blob: ceb100686e1da0b5a50ac2f3b791ea1e5fd36304 [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>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
alessiob3ec96df2017-05-22 06:57:06 -070016#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020017#include <type_traits>
18#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Yves Gerey988cc082018-10-23 12:03:01 +020020#include "absl/types/optional.h"
21#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/include/audio_util.h"
Per Åhgren200feba2019-03-06 04:16:46 +010024#include "modules/audio_processing/aec3/echo_canceller3.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020026#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/common.h"
29#include "modules/audio_processing/echo_cancellation_impl.h"
30#include "modules/audio_processing/echo_control_mobile_impl.h"
Sam Zackrissonf0d1c032019-03-27 13:28:08 +010031#include "modules/audio_processing/gain_control_config_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "modules/audio_processing/gain_control_for_experimental_agc.h"
33#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010034#include "modules/audio_processing/gain_controller2.h"
Per Åhgren0aefbf02019-08-23 21:29:17 +020035#include "modules/audio_processing/high_pass_filter.h"
Yves Gerey988cc082018-10-23 12:03:01 +020036#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020037#include "modules/audio_processing/level_estimator_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010038#include "modules/audio_processing/logging/apm_data_dumper.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020039#include "modules/audio_processing/noise_suppression_impl.h"
Sam Zackrisson23513132019-01-11 15:10:32 +010040#include "modules/audio_processing/noise_suppression_proxy.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020041#include "modules/audio_processing/residual_echo_detector.h"
42#include "modules/audio_processing/transient/transient_suppressor.h"
Sam Zackrisson0824c6f2019-10-07 14:03:56 +020043#include "modules/audio_processing/voice_detection.h"
Steve Anton10542f22019-01-11 09:11:00 -080044#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "rtc_base/ref_counted_object.h"
49#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020051#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000053
Michael Graczyk86c6d332015-07-23 11:41:39 -070054#define RETURN_ON_ERR(expr) \
55 do { \
56 int err = (expr); \
57 if (err != kNoError) { \
58 return err; \
59 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000060 } while (0)
61
niklase@google.com470e71d2011-07-07 08:21:25 +000062namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070063
kwibergd59d3bb2016-09-13 07:49:33 -070064constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020065constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070066
Michael Graczyk86c6d332015-07-23 11:41:39 -070067namespace {
68
69static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
70 switch (layout) {
71 case AudioProcessing::kMono:
72 case AudioProcessing::kStereo:
73 return false;
74 case AudioProcessing::kMonoAndKeyboard:
75 case AudioProcessing::kStereoAndKeyboard:
76 return true;
77 }
78
kwiberg9e2be5f2016-09-14 05:23:22 -070079 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070080 return false;
81}
aluebsdf6416a2016-03-16 18:26:35 -070082
peah2ace3f92016-09-10 04:42:27 -070083bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070084 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
85 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
86}
87
Per Åhgrenc8626b62019-08-23 15:49:51 +020088// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020089int SuitableProcessRate(int minimum_rate,
90 int max_splitting_rate,
91 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020092 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020093 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020094 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070095 if (rate >= uppermost_native_rate) {
96 return uppermost_native_rate;
97 }
98 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070099 return rate;
100 }
101 }
peah2ace3f92016-09-10 04:42:27 -0700102 RTC_NOTREACHED();
103 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700104}
105
Sam Zackrisson23513132019-01-11 15:10:32 +0100106NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
107 AudioProcessing::Config::NoiseSuppression::Level level) {
108 using NsConfig = AudioProcessing::Config::NoiseSuppression;
109 switch (level) {
110 case NsConfig::kLow:
111 return NoiseSuppression::kLow;
112 case NsConfig::kModerate:
113 return NoiseSuppression::kModerate;
114 case NsConfig::kHigh:
115 return NoiseSuppression::kHigh;
116 case NsConfig::kVeryHigh:
117 return NoiseSuppression::kVeryHigh;
118 default:
119 RTC_NOTREACHED();
120 }
121}
122
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100123GainControl::Mode Agc1ConfigModeToInterfaceMode(
124 AudioProcessing::Config::GainController1::Mode mode) {
125 using Agc1Config = AudioProcessing::Config::GainController1;
126 switch (mode) {
127 case Agc1Config::kAdaptiveAnalog:
128 return GainControl::kAdaptiveAnalog;
129 case Agc1Config::kAdaptiveDigital:
130 return GainControl::kAdaptiveDigital;
131 case Agc1Config::kFixedDigital:
132 return GainControl::kFixedDigital;
133 }
134}
135
peah9e6a2902017-05-15 07:19:21 -0700136// Maximum lengths that frame of samples being passed from the render side to
137// the capture side can have (does not apply to AEC3).
138static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
139static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
140
peah764e3642016-10-22 05:04:30 -0700141// Maximum number of frames to buffer in the render queue.
142// TODO(peah): Decrease this once we properly handle hugely unbalanced
143// reverse and forward call numbers.
144static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700145} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000146
147// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000148static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000149
Sam Zackrisson0beac582017-09-25 12:04:02 +0200150AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100151 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200152 bool render_pre_processor_enabled,
153 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100154 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200155 render_pre_processor_enabled_(render_pre_processor_enabled),
156 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700157
158bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200159 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700160 bool echo_canceller_enabled,
161 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700162 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700163 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700164 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700165 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200166 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200167 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200168 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700169 bool level_estimator_enabled,
170 bool transient_suppressor_enabled) {
171 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200172 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700173 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
174 changed |=
175 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700176 changed |=
177 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700178 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
179 changed |=
peah2ace3f92016-09-10 04:42:27 -0700180 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200181 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200182 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200183 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700184 changed |= (level_estimator_enabled != level_estimator_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200185 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700186 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
187 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200188 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700189 echo_canceller_enabled_ = echo_canceller_enabled;
190 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700191 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700192 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700193 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700194 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200195 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200196 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700197 level_estimator_enabled_ = level_estimator_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200198 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700199 transient_suppressor_enabled_ = transient_suppressor_enabled;
200 }
201
202 changed |= first_update_;
203 first_update_ = false;
204 return changed;
205}
206
207bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
208 const {
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200209 return CaptureMultiBandProcessingActive() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700210}
211
212bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
213 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200214 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700215 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200216 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700217}
218
peah23ac8b42017-05-23 05:33:56 -0700219bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
220 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200221 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
222 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700223}
224
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200225bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
226 return capture_analyzer_enabled_;
227}
228
peah2ace3f92016-09-10 04:42:27 -0700229bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
230 const {
231 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800232 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200233 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700234}
235
Alex Loiko5825aa62017-12-18 16:02:40 +0100236bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
237 const {
238 return render_pre_processor_enabled_;
239}
240
peah2ace3f92016-09-10 04:42:27 -0700241bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
242 const {
peah2ace3f92016-09-10 04:42:27 -0700243 return false;
peah2ace3f92016-09-10 04:42:27 -0700244}
245
Per Åhgren0aefbf02019-08-23 21:29:17 +0200246bool AudioProcessingImpl::ApmSubmoduleStates::HighPassFilteringRequired()
247 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200248 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
249 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
250}
251
solenberg5e465c32015-12-08 13:22:33 -0800252struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800253 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800254 // Accessed externally of APM without any lock acquired.
Sam Zackrisson23513132019-01-11 15:10:32 +0100255 // TODO(bugs.webrtc.org/9947): Move these submodules into private_submodules_
256 // when their pointer-to-submodule API functions are gone.
kwiberg88788ad2016-02-19 07:04:49 -0800257 std::unique_ptr<LevelEstimatorImpl> level_estimator;
258 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
Sam Zackrisson23513132019-01-11 15:10:32 +0100259 std::unique_ptr<NoiseSuppressionProxy> noise_suppression_proxy;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100260 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800261 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800262 gain_control_for_experimental_agc;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100263 std::unique_ptr<GainControlConfigProxy> gain_control_config_proxy;
solenberg5e465c32015-12-08 13:22:33 -0800264
265 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800266 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800267};
268
269struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200270 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100271 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200272 rtc::scoped_refptr<EchoDetector> echo_detector,
273 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200274 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100275 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200276 render_pre_processor(std::move(render_pre_processor)),
277 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800278 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800279 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700280 std::unique_ptr<GainController2> gain_controller2;
Per Åhgren0aefbf02019-08-23 21:29:17 +0200281 std::unique_ptr<HighPassFilter> high_pass_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200282 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100283 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100284 std::unique_ptr<EchoControl> echo_controller;
285 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100286 std::unique_ptr<CustomProcessing> capture_post_processor;
287 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200288 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200289 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100290 std::unique_ptr<LevelEstimatorImpl> output_level_estimator;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200291 std::unique_ptr<VoiceDetection> voice_detector;
solenberg5e465c32015-12-08 13:22:33 -0800292};
293
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100294AudioProcessingBuilder::AudioProcessingBuilder() = default;
295AudioProcessingBuilder::~AudioProcessingBuilder() = default;
296
297AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
298 std::unique_ptr<CustomProcessing> capture_post_processing) {
299 capture_post_processing_ = std::move(capture_post_processing);
300 return *this;
301}
302
303AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
304 std::unique_ptr<CustomProcessing> render_pre_processing) {
305 render_pre_processing_ = std::move(render_pre_processing);
306 return *this;
307}
308
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200309AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
310 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
311 capture_analyzer_ = std::move(capture_analyzer);
312 return *this;
313}
314
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100315AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
316 std::unique_ptr<EchoControlFactory> echo_control_factory) {
317 echo_control_factory_ = std::move(echo_control_factory);
318 return *this;
319}
320
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100321AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200322 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100323 echo_detector_ = std::move(echo_detector);
324 return *this;
325}
326
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100327AudioProcessing* AudioProcessingBuilder::Create() {
328 webrtc::Config config;
329 return Create(config);
330}
331
332AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100333 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
334 config, std::move(capture_post_processing_),
335 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200336 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100337 if (apm->Initialize() != AudioProcessing::kNoError) {
338 delete apm;
339 apm = nullptr;
340 }
341 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100342}
343
peah88ac8532016-09-12 16:47:25 -0700344AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200345 : AudioProcessingImpl(config,
346 /*capture_post_processor=*/nullptr,
347 /*render_pre_processor=*/nullptr,
348 /*echo_control_factory=*/nullptr,
349 /*echo_detector=*/nullptr,
350 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000351
Per Åhgren13735822018-02-12 21:42:56 +0100352int AudioProcessingImpl::instance_count_ = 0;
353
Sam Zackrisson0beac582017-09-25 12:04:02 +0200354AudioProcessingImpl::AudioProcessingImpl(
355 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100356 std::unique_ptr<CustomProcessing> capture_post_processor,
357 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200358 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200359 rtc::scoped_refptr<EchoDetector> echo_detector,
360 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100361 : data_dumper_(
362 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200363 capture_runtime_settings_(kRuntimeSettingQueueSize),
364 render_runtime_settings_(kRuntimeSettingQueueSize),
365 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
366 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200367 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200368 submodule_states_(!!capture_post_processor,
369 !!render_pre_processor,
370 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800371 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200372 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200373 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100374 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200375 std::move(echo_detector),
376 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800377 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800378 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000379#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200380 /* enabled= */ false,
381 /* enabled_agc2_level_estimator= */ false,
382 /* digital_adaptive_disabled= */ false,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200383 /* analyze_before_aec= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000384#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200385 config.Get<ExperimentalAgc>().enabled,
386 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200387 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200388 config.Get<ExperimentalAgc>().analyze_before_aec,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000389#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200390 !field_trial::IsEnabled(
391 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
392 !field_trial::IsEnabled(
393 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700394#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200395 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700396#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200397 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700398#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200399 capture_nonlocked_() {
Sam Zackrisson421c8592019-02-11 13:39:46 +0100400 // Mark Echo Controller enabled if a factory is injected.
401 capture_nonlocked_.echo_controller_enabled =
402 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000403
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100404 public_submodules_->gain_control.reset(new GainControlImpl());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100405 public_submodules_->level_estimator.reset(
406 new LevelEstimatorImpl(&crit_capture_));
407 public_submodules_->noise_suppression.reset(
408 new NoiseSuppressionImpl(&crit_capture_));
409 public_submodules_->noise_suppression_proxy.reset(new NoiseSuppressionProxy(
410 this, public_submodules_->noise_suppression.get()));
Sam Zackrisson421c8592019-02-11 13:39:46 +0100411 public_submodules_->gain_control_for_experimental_agc.reset(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100412 new GainControlForExperimentalAgc(
413 public_submodules_->gain_control.get()));
414 public_submodules_->gain_control_config_proxy.reset(
415 new GainControlConfigProxy(&crit_capture_, this, agc1()));
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200416
Sam Zackrisson421c8592019-02-11 13:39:46 +0100417 // If no echo detector is injected, use the ResidualEchoDetector.
418 if (!private_submodules_->echo_detector) {
419 private_submodules_->echo_detector =
420 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800421 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000422
Sam Zackrisson421c8592019-02-11 13:39:46 +0100423 // TODO(alessiob): Move the injected gain controller once injection is
424 // implemented.
425 private_submodules_->gain_controller2.reset(new GainController2());
426
427 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
428 << !!private_submodules_->capture_analyzer
429 << "\nCapture post processor activated: "
430 << !!private_submodules_->capture_post_processor
431 << "\nRender pre processor activated: "
432 << !!private_submodules_->render_pre_processor;
433
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000434 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000435}
436
437AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800438 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800439 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800440 private_submodules_->agc_manager.reset();
441 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800442 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000443}
444
niklase@google.com470e71d2011-07-07 08:21:25 +0000445int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800446 // Run in a single-threaded manner during initialization.
447 rtc::CritScope cs_render(&crit_render_);
448 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000449 return InitializeLocked();
450}
451
peahde65ddc2016-09-16 15:02:15 -0700452int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
453 int capture_output_sample_rate_hz,
454 int render_input_sample_rate_hz,
455 ChannelLayout capture_input_layout,
456 ChannelLayout capture_output_layout,
457 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700458 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700459 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
460 LayoutHasKeyboard(capture_input_layout)},
461 {capture_output_sample_rate_hz,
462 ChannelsFromLayout(capture_output_layout),
463 LayoutHasKeyboard(capture_output_layout)},
464 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
465 LayoutHasKeyboard(render_input_layout)},
466 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
467 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700468
469 return Initialize(processing_config);
470}
471
472int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800473 // Run in a single-threaded manner during initialization.
474 rtc::CritScope cs_render(&crit_render_);
475 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700476 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000477}
478
peahdf3efa82015-11-28 12:35:15 -0800479int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800480 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800481 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200482 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800483 return kNoError;
484 }
peahdf3efa82015-11-28 12:35:15 -0800485
486 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800487 return InitializeLocked(processing_config);
488}
489
niklase@google.com470e71d2011-07-07 08:21:25 +0000490int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200491 UpdateActiveSubmoduleStates();
492
Per Åhgrend47941e2019-08-22 11:51:13 +0200493 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800494 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200495 ? formats_.render_processing_format.sample_rate_hz()
496 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800497 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
498 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200499 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800500 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200501 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700502 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200503 render_audiobuffer_sample_rate_hz,
504 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700505 if (formats_.api_format.reverse_input_stream() !=
506 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800507 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800508 formats_.api_format.reverse_input_stream().num_channels(),
509 formats_.api_format.reverse_input_stream().num_frames(),
510 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800511 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700512 } else {
peahdf3efa82015-11-28 12:35:15 -0800513 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700514 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700515 } else {
peahdf3efa82015-11-28 12:35:15 -0800516 render_.render_audio.reset(nullptr);
517 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700518 }
peahce4d9152017-05-19 01:28:05 -0700519
Per Åhgrend47941e2019-08-22 11:51:13 +0200520 capture_.capture_audio.reset(new AudioBuffer(
521 formats_.api_format.input_stream().sample_rate_hz(),
522 formats_.api_format.input_stream().num_channels(),
523 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
524 formats_.api_format.output_stream().num_channels(),
525 formats_.api_format.output_stream().sample_rate_hz(),
526 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000527
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200528 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
529 formats_.api_format.output_stream().sample_rate_hz() &&
530 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
531 capture_.capture_fullband_audio.reset(
532 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
533 formats_.api_format.input_stream().num_channels(),
534 formats_.api_format.output_stream().sample_rate_hz(),
535 formats_.api_format.output_stream().num_channels(),
536 formats_.api_format.output_stream().sample_rate_hz(),
537 formats_.api_format.output_stream().num_channels()));
538 } else {
539 capture_.capture_fullband_audio.reset();
540 }
541
peah764e3642016-10-22 05:04:30 -0700542 AllocateRenderQueue();
543
peah135259a2016-10-28 03:12:11 -0700544 public_submodules_->gain_control->Initialize(num_proc_channels(),
545 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700546 if (constants_.use_experimental_agc) {
547 if (!private_submodules_->agc_manager.get()) {
548 private_submodules_->agc_manager.reset(new AgcManagerDirect(
549 public_submodules_->gain_control.get(),
550 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200551 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
552 constants_.use_experimental_agc_agc2_level_estimation,
553 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700554 }
555 private_submodules_->agc_manager->Initialize();
556 private_submodules_->agc_manager->SetCaptureMuted(
557 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700558 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700559 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200560 InitializeTransient();
Per Åhgren0aefbf02019-08-23 21:29:17 +0200561 InitializeHighPassFilter();
peahde65ddc2016-09-16 15:02:15 -0700562 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
563 proc_sample_rate_hz());
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200564 InitializeVoiceDetector();
peahde65ddc2016-09-16 15:02:15 -0700565 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700566 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200567 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700568 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200569 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200570 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100571 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800572
aleloi868f32f2017-05-23 07:20:05 -0700573 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200574 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700575 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000576 return kNoError;
577}
578
Michael Graczyk86c6d332015-07-23 11:41:39 -0700579int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200580 UpdateActiveSubmoduleStates();
581
Michael Graczyk86c6d332015-07-23 11:41:39 -0700582 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700583 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
584 return kBadSampleRateError;
585 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000586 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700587
Peter Kasting69558702016-01-12 16:26:35 -0800588 const size_t num_in_channels = config.input_stream().num_channels();
589 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590
591 // Need at least one input channel.
592 // Need either one output channel or as many outputs as there are inputs.
593 if (num_in_channels == 0 ||
594 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700595 return kBadNumberChannelsError;
596 }
597
peahdf3efa82015-11-28 12:35:15 -0800598 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000599
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200600 // Choose maximum rate to use for the split filtering.
601 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
602 config_.pipeline.maximum_internal_processing_rate == 32000);
603 int max_splitting_rate = 48000;
604 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
605 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
606 }
607
Per Åhgrenc8626b62019-08-23 15:49:51 +0200608 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700609 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700610 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200611 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700612 submodule_states_.CaptureMultiBandSubModulesActive() ||
613 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200614 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000615
peahde65ddc2016-09-16 15:02:15 -0700616 capture_nonlocked_.capture_processing_format =
617 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700618
peah2ce640f2017-04-07 03:57:48 -0700619 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200620 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200621 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700622 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
623 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200624 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700625 submodule_states_.CaptureMultiBandSubModulesActive() ||
626 submodule_states_.RenderMultiBandSubModulesActive());
627 } else {
628 render_processing_rate = capture_processing_rate;
629 }
630
peahde65ddc2016-09-16 15:02:15 -0700631 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700632 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700633 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
634 kSampleRate8kHz) {
635 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000636 } else {
peahde65ddc2016-09-16 15:02:15 -0700637 render_processing_rate =
638 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000639 }
640
Per Åhgrenc8626b62019-08-23 15:49:51 +0200641 RTC_DCHECK_NE(8000, render_processing_rate);
642
peahce4d9152017-05-19 01:28:05 -0700643 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200644 // By default, downmix the render stream to mono for analysis. This has been
645 // demonstrated to work well for AEC in most practical scenarios.
646 const bool experimental_multi_channel_render =
647 config_.pipeline.experimental_multi_channel &&
648 constants_.experimental_multi_channel_render_support;
649 int render_processing_num_channels =
650 experimental_multi_channel_render
651 ? formats_.api_format.reverse_input_stream().num_channels()
652 : 1;
653 formats_.render_processing_format =
654 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700655 } else {
656 formats_.render_processing_format = StreamConfig(
657 formats_.api_format.reverse_input_stream().sample_rate_hz(),
658 formats_.api_format.reverse_input_stream().num_channels());
659 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000660
peahde65ddc2016-09-16 15:02:15 -0700661 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
662 kSampleRate32kHz ||
663 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
664 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800665 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000666 } else {
peahdf3efa82015-11-28 12:35:15 -0800667 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700668 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000669 }
670
671 return InitializeLocked();
672}
673
peah88ac8532016-09-12 16:47:25 -0700674void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700675 // Run in a single-threaded manner when applying the settings.
676 rtc::CritScope cs_render(&crit_render_);
677 rtc::CritScope cs_capture(&crit_capture_);
678
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200679 const bool pipeline_config_changed =
680 config_.pipeline.experimental_multi_channel !=
681 config.pipeline.experimental_multi_channel;
682
Per Åhgren200feba2019-03-06 04:16:46 +0100683 const bool aec_config_changed =
684 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
685 config_.echo_canceller.use_legacy_aec !=
686 config.echo_canceller.use_legacy_aec ||
687 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
688 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
689 config_.echo_canceller.legacy_moderate_suppression_level !=
690 config.echo_canceller.legacy_moderate_suppression_level);
691
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100692 const bool agc1_config_changed =
693 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
694 config_.gain_controller1.mode != config.gain_controller1.mode ||
695 config_.gain_controller1.target_level_dbfs !=
696 config.gain_controller1.target_level_dbfs ||
697 config_.gain_controller1.compression_gain_db !=
698 config.gain_controller1.compression_gain_db ||
699 config_.gain_controller1.enable_limiter !=
700 config.gain_controller1.enable_limiter ||
701 config_.gain_controller1.analog_level_minimum !=
702 config.gain_controller1.analog_level_minimum ||
703 config_.gain_controller1.analog_level_maximum !=
704 config.gain_controller1.analog_level_maximum;
705
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200706 const bool voice_detection_config_changed =
707 config_.voice_detection.enabled != config.voice_detection.enabled;
708
Yves Gerey499bc6c2018-10-10 18:29:07 +0200709 config_ = config;
710
Per Åhgren200feba2019-03-06 04:16:46 +0100711 if (aec_config_changed) {
712 InitializeEchoController();
713 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200714
Sam Zackrisson23513132019-01-11 15:10:32 +0100715 public_submodules_->noise_suppression->Enable(
716 config.noise_suppression.enabled);
717 public_submodules_->noise_suppression->set_level(
718 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
719
Per Åhgren0aefbf02019-08-23 21:29:17 +0200720 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800721
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG(LS_INFO) << "Highpass filter activated: "
723 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800724
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100725 if (agc1_config_changed) {
726 ApplyAgc1Config(config_.gain_controller1);
727 }
728
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100729 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700730 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100731 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
732 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100733 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100734 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700735 config_.gain_controller2 = AudioProcessing::Config::GainController2();
736 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200737 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200738 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200739 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100740 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
741 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200742 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
743 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100744
745 if (config_.level_estimation.enabled &&
746 !private_submodules_->output_level_estimator) {
747 private_submodules_->output_level_estimator.reset(
748 new LevelEstimatorImpl(&crit_capture_));
749 private_submodules_->output_level_estimator->Enable(true);
750 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100751
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200752 if (voice_detection_config_changed) {
753 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100754 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200755
756 // Reinitialization must happen after all submodule configuration to avoid
757 // additional reinitializations on the next capture / render processing call.
758 if (pipeline_config_changed) {
759 InitializeLocked(formats_.api_format);
760 }
peah88ac8532016-09-12 16:47:25 -0700761}
762
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100763void AudioProcessingImpl::ApplyAgc1Config(
764 const Config::GainController1& config) {
765 GainControl* agc = agc1();
766 int error = agc->Enable(config.enabled);
767 RTC_DCHECK_EQ(kNoError, error);
768 error = agc->set_mode(Agc1ConfigModeToInterfaceMode(config.mode));
769 RTC_DCHECK_EQ(kNoError, error);
770 error = agc->set_target_level_dbfs(config.target_level_dbfs);
771 RTC_DCHECK_EQ(kNoError, error);
772 error = agc->set_compression_gain_db(config.compression_gain_db);
773 RTC_DCHECK_EQ(kNoError, error);
774 error = agc->enable_limiter(config.enable_limiter);
775 RTC_DCHECK_EQ(kNoError, error);
776 error = agc->set_analog_level_limits(config.analog_level_minimum,
777 config.analog_level_maximum);
778 RTC_DCHECK_EQ(kNoError, error);
779}
780
781GainControl* AudioProcessingImpl::agc1() {
782 if (constants_.use_experimental_agc) {
783 return public_submodules_->gain_control_for_experimental_agc.get();
784 }
785 return public_submodules_->gain_control.get();
786}
787
788const GainControl* AudioProcessingImpl::agc1() const {
789 if (constants_.use_experimental_agc) {
790 return public_submodules_->gain_control_for_experimental_agc.get();
791 }
792 return public_submodules_->gain_control.get();
793}
794
peah88ac8532016-09-12 16:47:25 -0700795void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800796 // Run in a single-threaded manner when setting the extra options.
797 rtc::CritScope cs_render(&crit_render_);
798 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000799
Per Åhgrenf204faf2019-04-25 15:18:06 +0200800 capture_nonlocked_.use_aec2_extended_filter =
801 config.Get<ExtendedFilter>().enabled;
802 capture_nonlocked_.use_aec2_delay_agnostic =
803 config.Get<DelayAgnostic>().enabled;
804 capture_nonlocked_.use_aec2_refined_adaptive_filter =
805 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800806
peahdf3efa82015-11-28 12:35:15 -0800807 if (capture_.transient_suppressor_enabled !=
808 config.Get<ExperimentalNs>().enabled) {
809 capture_.transient_suppressor_enabled =
810 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000811 InitializeTransient();
812 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000813}
814
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000815int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800816 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700817 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200820int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
821 return capture_.capture_fullband_audio
822 ? capture_.capture_fullband_audio->num_frames() * 100
823 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
824}
825
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000826int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800827 // Used as callback from submodules, hence locking is not allowed.
828 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000829}
830
Peter Kasting69558702016-01-12 16:26:35 -0800831size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800832 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700833 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000834}
835
Peter Kasting69558702016-01-12 16:26:35 -0800836size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800837 // Used as callback from submodules, hence locking is not allowed.
838 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000839}
840
Peter Kasting69558702016-01-12 16:26:35 -0800841size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800842 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200843 const bool experimental_multi_channel_capture =
844 config_.pipeline.experimental_multi_channel &&
845 constants_.experimental_multi_channel_capture_support;
846 if (capture_nonlocked_.echo_controller_enabled &&
847 !experimental_multi_channel_capture) {
848 return 1;
849 }
850 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800851}
852
Peter Kasting69558702016-01-12 16:26:35 -0800853size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800854 // Used as callback from submodules, hence locking is not allowed.
855 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000856}
857
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000858void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800859 rtc::CritScope cs(&crit_capture_);
860 capture_.output_will_be_muted = muted;
861 if (private_submodules_->agc_manager.get()) {
862 private_submodules_->agc_manager->SetCaptureMuted(
863 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000864 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000865}
866
Alessio Bazzicac054e782018-04-16 12:10:09 +0200867void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200868 switch (setting.type()) {
869 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
870 render_runtime_settings_enqueuer_.Enqueue(setting);
871 return;
872 case RuntimeSetting::Type::kNotSpecified:
873 RTC_NOTREACHED();
874 return;
875 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100876 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200877 case RuntimeSetting::Type::kCaptureFixedPostGain:
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200878 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200879 capture_runtime_settings_enqueuer_.Enqueue(setting);
880 return;
881 }
882 // The language allows the enum to have a non-enumerator
883 // value. Check that this doesn't happen.
884 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200885}
886
887AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
888 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200889 : runtime_settings_(*runtime_settings) {
890 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200891}
892
893AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
894 default;
895
896void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
897 RuntimeSetting setting) {
898 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200899 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200900 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200901 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200902 RTC_LOG(LS_ERROR)
903 << "The runtime settings queue is full. Oldest setting discarded.";
904 }
905 if (remaining_attempts == 0)
906 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
907}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000908
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000909int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700910 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000911 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000912 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000913 int output_sample_rate_hz,
914 ChannelLayout output_layout,
915 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800916 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800917 StreamConfig input_stream;
918 StreamConfig output_stream;
919 {
920 // Access the formats_.api_format.input_stream beneath the capture lock.
921 // The lock must be released as it is later required in the call
922 // to ProcessStream(,,,);
923 rtc::CritScope cs(&crit_capture_);
924 input_stream = formats_.api_format.input_stream();
925 output_stream = formats_.api_format.output_stream();
926 }
927
Michael Graczyk86c6d332015-07-23 11:41:39 -0700928 input_stream.set_sample_rate_hz(input_sample_rate_hz);
929 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
930 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700931 output_stream.set_sample_rate_hz(output_sample_rate_hz);
932 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
933 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
934
935 if (samples_per_channel != input_stream.num_frames()) {
936 return kBadDataLengthError;
937 }
938 return ProcessStream(src, input_stream, output_stream, dest);
939}
940
941int AudioProcessingImpl::ProcessStream(const float* const* src,
942 const StreamConfig& input_config,
943 const StreamConfig& output_config,
944 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800945 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800946 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700947 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800948 {
949 // Acquire the capture lock in order to safely call the function
950 // that retrieves the render side data. This function accesses apm
951 // getters that need the capture lock held when being called.
952 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700953 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800954
955 if (!src || !dest) {
956 return kNullPointerError;
957 }
958
959 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700960 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000961 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000962
Oskar Sundbom4b276482019-05-23 14:28:00 +0200963 if (processing_config.input_stream() != input_config) {
964 processing_config.input_stream() = input_config;
965 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800966 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200967
968 if (processing_config.output_stream() != output_config) {
969 processing_config.output_stream() = output_config;
970 reinitialization_required = true;
971 }
972
973 if (reinitialization_required) {
974 // Reinitialize.
975 rtc::CritScope cs_render(&crit_render_);
976 rtc::CritScope cs_capture(&crit_capture_);
977 RETURN_ON_ERR(InitializeLocked(processing_config));
978 }
979
peahdf3efa82015-11-28 12:35:15 -0800980 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700981 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
982 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000983
aleloi868f32f2017-05-23 07:20:05 -0700984 if (aec_dump_) {
985 RecordUnprocessedCaptureStream(src);
986 }
987
Per Åhgrena1351272019-08-15 12:15:46 +0200988 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800989 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700990 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200991 if (capture_.capture_fullband_audio) {
992 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
993 dest);
994 } else {
995 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
996 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000997
aleloi868f32f2017-05-23 07:20:05 -0700998 if (aec_dump_) {
999 RecordProcessedCaptureStream(dest);
1000 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001001 return kNoError;
1002}
1003
Alex Loiko73ec0192018-05-15 10:52:28 +02001004void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001005 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +02001006 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001007 if (aec_dump_) {
1008 aec_dump_->WriteRuntimeSetting(setting);
1009 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001010 switch (setting.type()) {
1011 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +02001012 if (config_.pre_amplifier.enabled) {
1013 float value;
1014 setting.GetFloat(&value);
1015 private_submodules_->pre_amplifier->SetGainFactor(value);
1016 }
1017 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001018 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001019 case RuntimeSetting::Type::kCaptureCompressionGain: {
1020 float value;
1021 setting.GetFloat(&value);
1022 int int_value = static_cast<int>(value + .5f);
1023 config_.gain_controller1.compression_gain_db = int_value;
1024 int error = agc1()->set_compression_gain_db(int_value);
1025 RTC_DCHECK_EQ(kNoError, error);
1026 break;
1027 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001028 case RuntimeSetting::Type::kCaptureFixedPostGain: {
1029 if (config_.gain_controller2.enabled) {
1030 float value;
1031 setting.GetFloat(&value);
1032 config_.gain_controller2.fixed_digital.gain_db = value;
1033 private_submodules_->gain_controller2->ApplyConfig(
1034 config_.gain_controller2);
1035 }
1036 break;
1037 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001038 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1039 int value;
1040 setting.GetInt(&value);
1041 capture_.playout_volume = value;
1042 break;
1043 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001044 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1045 RTC_NOTREACHED();
1046 break;
1047 case RuntimeSetting::Type::kNotSpecified:
1048 RTC_NOTREACHED();
1049 break;
1050 }
1051 }
1052}
1053
1054void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1055 RuntimeSetting setting;
1056 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001057 if (aec_dump_) {
1058 aec_dump_->WriteRuntimeSetting(setting);
1059 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001060 switch (setting.type()) {
1061 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1062 if (private_submodules_->render_pre_processor) {
1063 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
1064 }
1065 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001066 case RuntimeSetting::Type::kCapturePreGain: // fall-through
1067 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001068 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001069 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001070 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +02001071 RTC_NOTREACHED();
1072 break;
1073 }
1074 }
1075}
1076
peah9e6a2902017-05-15 07:19:21 -07001077void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001078 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001079
1080 // Insert the samples into the queue.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001081 if (private_submodules_->echo_cancellation) {
1082 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001083 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1084 num_reverse_channels(),
1085 &aec_render_queue_buffer_);
1086
Per Åhgrenf204faf2019-04-25 15:18:06 +02001087 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1088 // The data queue is full and needs to be emptied.
1089 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001090
Per Åhgrenf204faf2019-04-25 15:18:06 +02001091 // Retry the insert (should always work).
1092 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1093 RTC_DCHECK(result);
1094 }
peaha0624602016-10-25 04:45:24 -07001095 }
1096
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001097 if (private_submodules_->echo_control_mobile) {
1098 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1099 num_reverse_channels(),
1100 &aecm_render_queue_buffer_);
1101 RTC_DCHECK(aecm_render_signal_queue_);
1102 // Insert the samples into the queue.
1103 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1104 // The data queue is full and needs to be emptied.
1105 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001106
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001107 // Retry the insert (should always work).
1108 bool result =
1109 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1110 RTC_DCHECK(result);
1111 }
peah764e3642016-10-22 05:04:30 -07001112 }
peah701d6282016-10-25 05:42:20 -07001113
1114 if (!constants_.use_experimental_agc) {
1115 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
1116 // Insert the samples into the queue.
1117 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1118 // The data queue is full and needs to be emptied.
1119 EmptyQueuedRenderAudio();
1120
1121 // Retry the insert (should always work).
1122 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1123 RTC_DCHECK(result);
1124 }
1125 }
peah9e6a2902017-05-15 07:19:21 -07001126}
ivoc9f4a4a02016-10-28 05:39:16 -07001127
peah9e6a2902017-05-15 07:19:21 -07001128void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001129 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1130
1131 // Insert the samples into the queue.
1132 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1133 // The data queue is full and needs to be emptied.
1134 EmptyQueuedRenderAudio();
1135
1136 // Retry the insert (should always work).
1137 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1138 RTC_DCHECK(result);
1139 }
peah764e3642016-10-22 05:04:30 -07001140}
1141
1142void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001143 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001144 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001145
ivoc9f4a4a02016-10-28 05:39:16 -07001146 const size_t new_red_render_queue_element_max_size =
1147 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1148
peaha0624602016-10-25 04:45:24 -07001149 // Reallocate the queues if the queue item sizes are too small to fit the
1150 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001151
1152 if (agc_render_queue_element_max_size_ <
1153 new_agc_render_queue_element_max_size) {
1154 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1155
1156 std::vector<int16_t> template_queue_element(
1157 agc_render_queue_element_max_size_);
1158
1159 agc_render_signal_queue_.reset(
1160 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1161 kMaxNumFramesToBuffer, template_queue_element,
1162 RenderQueueItemVerifier<int16_t>(
1163 agc_render_queue_element_max_size_)));
1164
1165 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1166 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1167 } else {
1168 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001169 }
ivoc9f4a4a02016-10-28 05:39:16 -07001170
1171 if (red_render_queue_element_max_size_ <
1172 new_red_render_queue_element_max_size) {
1173 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1174
1175 std::vector<float> template_queue_element(
1176 red_render_queue_element_max_size_);
1177
1178 red_render_signal_queue_.reset(
1179 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1180 kMaxNumFramesToBuffer, template_queue_element,
1181 RenderQueueItemVerifier<float>(
1182 red_render_queue_element_max_size_)));
1183
1184 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1185 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1186 } else {
1187 red_render_signal_queue_->Clear();
1188 }
peah764e3642016-10-22 05:04:30 -07001189}
1190
1191void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1192 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001193 if (private_submodules_->echo_cancellation) {
1194 RTC_DCHECK(aec_render_signal_queue_);
1195 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
1196 private_submodules_->echo_cancellation->ProcessRenderAudio(
1197 aec_capture_queue_buffer_);
1198 }
peaha0624602016-10-25 04:45:24 -07001199 }
1200
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001201 if (private_submodules_->echo_control_mobile) {
1202 RTC_DCHECK(aecm_render_signal_queue_);
1203 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
1204 private_submodules_->echo_control_mobile->ProcessRenderAudio(
1205 aecm_capture_queue_buffer_);
1206 }
peah701d6282016-10-25 05:42:20 -07001207 }
1208
1209 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1210 public_submodules_->gain_control->ProcessRenderAudio(
1211 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001212 }
ivoc9f4a4a02016-10-28 05:39:16 -07001213
1214 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001215 RTC_DCHECK(private_submodules_->echo_detector);
1216 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001217 red_capture_queue_buffer_);
1218 }
peah764e3642016-10-22 05:04:30 -07001219}
1220
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001221int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001222 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001223 {
1224 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001225 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001226 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001227 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001228 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001229 }
peahfa6228e2015-11-16 16:27:42 -08001230
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001231 if (!frame) {
1232 return kNullPointerError;
1233 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001234 // Must be a native rate.
1235 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1236 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001237 frame->sample_rate_hz_ != kSampleRate32kHz &&
1238 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001239 return kBadSampleRateError;
1240 }
peah192164e2015-11-17 02:16:45 -08001241
peahdf3efa82015-11-28 12:35:15 -08001242 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001243 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001244 {
1245 // Aquire lock for the access of api_format.
1246 // The lock is released immediately due to the conditional
1247 // reinitialization.
1248 rtc::CritScope cs_capture(&crit_capture_);
1249 // TODO(ajm): The input and output rates and channels are currently
1250 // constrained to be identical in the int16 interface.
1251 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001252
1253 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001254 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001255
Oskar Sundbom4b276482019-05-23 14:28:00 +02001256 reinitialization_required =
1257 reinitialization_required ||
1258 processing_config.input_stream().sample_rate_hz() !=
1259 frame->sample_rate_hz_ ||
1260 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1261 processing_config.output_stream().sample_rate_hz() !=
1262 frame->sample_rate_hz_ ||
1263 processing_config.output_stream().num_channels() != frame->num_channels_;
1264
1265 if (reinitialization_required) {
1266 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1267 processing_config.input_stream().set_num_channels(frame->num_channels_);
1268 processing_config.output_stream().set_sample_rate_hz(
1269 frame->sample_rate_hz_);
1270 processing_config.output_stream().set_num_channels(frame->num_channels_);
1271
1272 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001273 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001274 rtc::CritScope cs_capture(&crit_capture_);
1275 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001276 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001277
peahdf3efa82015-11-28 12:35:15 -08001278 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001279 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001280 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001281 return kBadDataLengthError;
1282 }
1283
aleloi868f32f2017-05-23 07:20:05 -07001284 if (aec_dump_) {
1285 RecordUnprocessedCaptureStream(*frame);
1286 }
1287
Per Åhgrend47941e2019-08-22 11:51:13 +02001288 capture_.capture_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001289 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001290 if (submodule_states_.CaptureMultiBandProcessingActive() ||
1291 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001292 if (capture_.capture_fullband_audio) {
1293 capture_.capture_fullband_audio->CopyTo(frame);
1294 } else {
1295 capture_.capture_audio->CopyTo(frame);
1296 }
Per Åhgrena1351272019-08-15 12:15:46 +02001297 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001298 if (capture_.stats.voice_detected) {
1299 frame->vad_activity_ = *capture_.stats.voice_detected
1300 ? AudioFrame::kVadActive
1301 : AudioFrame::kVadPassive;
1302 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001303
aleloi868f32f2017-05-23 07:20:05 -07001304 if (aec_dump_) {
1305 RecordProcessedCaptureStream(*frame);
1306 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001307
1308 return kNoError;
1309}
1310
peahde65ddc2016-09-16 15:02:15 -07001311int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001312 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001313
peahb58a1582016-03-15 09:34:24 -07001314 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001315 // TODO(peah): Simplify once the public API Enable functions for these
1316 // are moved to APM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001317 RTC_DCHECK_LE(!!private_submodules_->echo_controller +
1318 !!private_submodules_->echo_cancellation +
1319 !!private_submodules_->echo_control_mobile,
1320 1);
peahb58a1582016-03-15 09:34:24 -07001321
peahde65ddc2016-09-16 15:02:15 -07001322 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001323
Alex Loikob5c9a792018-04-16 16:31:22 +02001324 if (private_submodules_->pre_amplifier) {
1325 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001326 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001327 capture_buffer->num_frames()));
1328 }
1329
Per Åhgren928146f2019-08-20 09:19:21 +02001330 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001331 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001332 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001333 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1334 if (log_rms) {
1335 capture_rms_interval_counter_ = 0;
1336 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001337 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1338 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1339 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1340 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001341 }
1342
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001343 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001344 // Detect and flag any change in the analog gain.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001345 int analog_mic_level = agc1()->stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001346 capture_.echo_path_gain_change =
1347 capture_.prev_analog_mic_level != analog_mic_level &&
1348 capture_.prev_analog_mic_level != -1;
1349 capture_.prev_analog_mic_level = analog_mic_level;
1350
Per Åhgrend2650d12018-10-02 17:00:59 +02001351 // Detect and flag any change in the pre-amplifier gain.
1352 if (private_submodules_->pre_amplifier) {
1353 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1354 capture_.echo_path_gain_change =
1355 capture_.echo_path_gain_change ||
1356 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001357 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001358 capture_.prev_pre_amp_gain = pre_amp_gain;
1359 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001360
1361 // Detect volume change.
1362 capture_.echo_path_gain_change =
1363 capture_.echo_path_gain_change ||
1364 (capture_.prev_playout_volume != capture_.playout_volume &&
1365 capture_.prev_playout_volume >= 0);
1366 capture_.prev_playout_volume = capture_.playout_volume;
1367
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001368 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001369 }
1370
peahbe615622016-02-13 16:40:47 -08001371 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001372 public_submodules_->gain_control->is_enabled()) {
1373 private_submodules_->agc_manager->AnalyzePreProcess(
Per Åhgren928146f2019-08-20 09:19:21 +02001374 capture_buffer->channels_f()[0], capture_buffer->num_channels(),
peahde65ddc2016-09-16 15:02:15 -07001375 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001376
1377 if (constants_.use_experimental_agc_process_before_aec) {
1378 private_submodules_->agc_manager->Process(
Per Åhgrend47941e2019-08-22 11:51:13 +02001379 capture_buffer->channels_const()[0],
Alex Loikod9342442018-09-10 13:59:41 +02001380 capture_nonlocked_.capture_processing_format.num_frames(),
1381 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1382 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001383 }
1384
peah2ace3f92016-09-10 04:42:27 -07001385 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1386 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001387 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1388 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001389 }
1390
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001391 const bool experimental_multi_channel_capture =
1392 config_.pipeline.experimental_multi_channel &&
1393 constants_.experimental_multi_channel_capture_support;
1394 if (private_submodules_->echo_controller &&
1395 !experimental_multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001396 // Force down-mixing of the number of channels after the detection of
1397 // capture signal saturation.
1398 // TODO(peah): Look into ensuring that this kind of tampering with the
1399 // AudioBuffer functionality should not be needed.
1400 capture_buffer->set_num_channels(1);
1401 }
1402
Per Åhgren0aefbf02019-08-23 21:29:17 +02001403 if (private_submodules_->high_pass_filter) {
1404 private_submodules_->high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001405 }
peahde65ddc2016-09-16 15:02:15 -07001406 RETURN_ON_ERR(
1407 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1408 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001409
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001410 if (private_submodules_->echo_control_mobile) {
1411 // Ensure that the stream delay was set before the call to the
1412 // AECM ProcessCaptureAudio function.
1413 if (!was_stream_delay_set()) {
1414 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001415 }
1416
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001417 if (public_submodules_->noise_suppression->is_enabled()) {
Per Åhgrena1351272019-08-15 12:15:46 +02001418 private_submodules_->echo_control_mobile->CopyLowPassReference(
1419 capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001420 }
peahe0eae3c2016-12-14 01:16:23 -08001421
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001422 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001423
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001424 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001425 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001426 } else {
1427 if (private_submodules_->echo_controller) {
1428 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1429
1430 if (was_stream_delay_set()) {
1431 private_submodules_->echo_controller->SetAudioBufferDelay(
1432 stream_delay_ms());
1433 }
1434
1435 private_submodules_->echo_controller->ProcessCapture(
1436 capture_buffer, capture_.echo_path_gain_change);
1437 } else if (private_submodules_->echo_cancellation) {
1438 // Ensure that the stream delay was set before the call to the
1439 // AEC ProcessCaptureAudio function.
1440 if (!was_stream_delay_set()) {
1441 return AudioProcessing::kStreamParameterNotSetError;
1442 }
1443
1444 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
1445 capture_buffer, stream_delay_ms()));
1446 }
1447
1448 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
Per Åhgren46537a32017-06-07 10:08:10 +02001449 }
ivoc9f4a4a02016-10-28 05:39:16 -07001450
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001451 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001452 capture_.stats.voice_detected =
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001453 private_submodules_->voice_detector->ProcessCaptureAudio(
1454 capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001455 } else {
1456 capture_.stats.voice_detected = absl::nullopt;
1457 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001458
peahbe615622016-02-13 16:40:47 -08001459 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001460 public_submodules_->gain_control->is_enabled() &&
1461 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001462 private_submodules_->agc_manager->Process(
Per Åhgren928146f2019-08-20 09:19:21 +02001463 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
peahde65ddc2016-09-16 15:02:15 -07001464 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001465 }
Per Åhgren200feba2019-03-06 04:16:46 +01001466 // TODO(peah): Add reporting from AEC3 whether there is echo.
peahb8fbb542016-03-15 02:28:08 -07001467 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001468 capture_buffer,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001469 private_submodules_->echo_cancellation &&
1470 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001471
peah2ace3f92016-09-10 04:42:27 -07001472 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1473 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001474 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1475 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001476 }
1477
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001478 if (capture_.capture_fullband_audio) {
1479 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1480 capture_buffer = capture_.capture_fullband_audio.get();
1481 }
1482
peah9e6a2902017-05-15 07:19:21 -07001483 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001484 RTC_DCHECK(private_submodules_->echo_detector);
1485 private_submodules_->echo_detector->AnalyzeCaptureAudio(
Per Åhgrend47941e2019-08-22 11:51:13 +02001486 rtc::ArrayView<const float>(capture_buffer->channels()[0],
peah9e6a2902017-05-15 07:19:21 -07001487 capture_buffer->num_frames()));
1488 }
1489
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001490 // TODO(aluebs): Investigate if the transient suppression placement should be
1491 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001492 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001493 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001494 private_submodules_->agc_manager.get()
1495 ? private_submodules_->agc_manager->voice_probability()
1496 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001497
peahdf3efa82015-11-28 12:35:15 -08001498 public_submodules_->transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001499 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001500 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001501 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001502 capture_buffer->num_frames_per_band(),
1503 capture_.keyboard_info.keyboard_data,
1504 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001505 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001506 }
1507
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001508 // Experimental APM sub-module that analyzes |capture_buffer|.
1509 if (private_submodules_->capture_analyzer) {
1510 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1511 }
1512
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001513 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001514 private_submodules_->gain_controller2->NotifyAnalogLevel(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001515 agc1()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001516 private_submodules_->gain_controller2->Process(capture_buffer);
1517 }
1518
Sam Zackrisson0beac582017-09-25 12:04:02 +02001519 if (private_submodules_->capture_post_processor) {
1520 private_submodules_->capture_post_processor->Process(capture_buffer);
1521 }
1522
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001523 // The level estimator operates on the recombined data.
Per Åhgrend47941e2019-08-22 11:51:13 +02001524 public_submodules_->level_estimator->ProcessStream(*capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001525 if (config_.level_estimation.enabled) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001526 private_submodules_->output_level_estimator->ProcessStream(*capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001527 capture_.stats.output_rms_dbfs =
1528 private_submodules_->output_level_estimator->RMS();
1529 } else {
1530 capture_.stats.output_rms_dbfs = absl::nullopt;
1531 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001532
Per Åhgren928146f2019-08-20 09:19:21 +02001533 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001534 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001535 capture_nonlocked_.capture_processing_format.num_frames()));
1536 if (log_rms) {
1537 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1538 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1539 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1540 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1541 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1542 }
1543
peahdf3efa82015-11-28 12:35:15 -08001544 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001545 return kNoError;
1546}
1547
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001548int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001549 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001550 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001551 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001552 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001553 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001554 const StreamConfig reverse_config = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001555 sample_rate_hz,
1556 ChannelsFromLayout(layout),
1557 LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001558 };
1559 if (samples_per_channel != reverse_config.num_frames()) {
1560 return kBadDataLengthError;
1561 }
peahdf3efa82015-11-28 12:35:15 -08001562 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001563}
1564
peahde65ddc2016-09-16 15:02:15 -07001565int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1566 const StreamConfig& input_config,
1567 const StreamConfig& output_config,
1568 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001569 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001570 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001571 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001572 if (submodule_states_.RenderMultiBandProcessingActive() ||
1573 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001574 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1575 dest);
peah2ace3f92016-09-10 04:42:27 -07001576 } else if (formats_.api_format.reverse_input_stream() !=
1577 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001578 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1579 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001580 } else {
peahde65ddc2016-09-16 15:02:15 -07001581 CopyAudioIfNeeded(src, input_config.num_frames(),
1582 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001583 }
1584
1585 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001586}
1587
peahdf3efa82015-11-28 12:35:15 -08001588int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001589 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001590 const StreamConfig& input_config,
1591 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001592 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001593 return kNullPointerError;
1594 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001595
peahde65ddc2016-09-16 15:02:15 -07001596 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001597 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001598 }
1599
peahdf3efa82015-11-28 12:35:15 -08001600 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001601 processing_config.reverse_input_stream() = input_config;
1602 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001603
peahdf3efa82015-11-28 12:35:15 -08001604 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001605 RTC_DCHECK_EQ(input_config.num_frames(),
1606 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001607
aleloi868f32f2017-05-23 07:20:05 -07001608 if (aec_dump_) {
1609 const size_t channel_size =
1610 formats_.api_format.reverse_input_stream().num_frames();
1611 const size_t num_channels =
1612 formats_.api_format.reverse_input_stream().num_channels();
1613 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001614 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001615 }
peahdf3efa82015-11-28 12:35:15 -08001616 render_.render_audio->CopyFrom(src,
1617 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001618 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001619}
1620
1621int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001622 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001623 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001624 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001625 return kNullPointerError;
1626 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001627 // Must be a native rate.
1628 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1629 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001630 frame->sample_rate_hz_ != kSampleRate32kHz &&
1631 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001632 return kBadSampleRateError;
1633 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001634
Michael Graczyk86c6d332015-07-23 11:41:39 -07001635 if (frame->num_channels_ <= 0) {
1636 return kBadNumberChannelsError;
1637 }
1638
peahdf3efa82015-11-28 12:35:15 -08001639 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001640 processing_config.reverse_input_stream().set_sample_rate_hz(
1641 frame->sample_rate_hz_);
1642 processing_config.reverse_input_stream().set_num_channels(
1643 frame->num_channels_);
1644 processing_config.reverse_output_stream().set_sample_rate_hz(
1645 frame->sample_rate_hz_);
1646 processing_config.reverse_output_stream().set_num_channels(
1647 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001648
peahdf3efa82015-11-28 12:35:15 -08001649 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001650 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001651 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001652 return kBadDataLengthError;
1653 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001654
aleloi868f32f2017-05-23 07:20:05 -07001655 if (aec_dump_) {
1656 aec_dump_->WriteRenderStreamMessage(*frame);
1657 }
1658
Per Åhgrend47941e2019-08-22 11:51:13 +02001659 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001660 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001661 if (submodule_states_.RenderMultiBandProcessingActive() ||
1662 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001663 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001664 }
aluebsb0319552016-03-17 20:39:53 -07001665 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001666}
niklase@google.com470e71d2011-07-07 08:21:25 +00001667
peahde65ddc2016-09-16 15:02:15 -07001668int AudioProcessingImpl::ProcessRenderStreamLocked() {
1669 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001670
Alex Loiko73ec0192018-05-15 10:52:28 +02001671 HandleRenderRuntimeSettings();
1672
Alex Loiko5825aa62017-12-18 16:02:40 +01001673 if (private_submodules_->render_pre_processor) {
1674 private_submodules_->render_pre_processor->Process(render_buffer);
1675 }
1676
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001677 QueueNonbandedRenderAudio(render_buffer);
1678
peah2ace3f92016-09-10 04:42:27 -07001679 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001680 SampleRateSupportsMultiBand(
1681 formats_.render_processing_format.sample_rate_hz())) {
1682 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001683 }
1684
peahce4d9152017-05-19 01:28:05 -07001685 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1686 QueueBandedRenderAudio(render_buffer);
1687 }
1688
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001689 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001690 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001691 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001692 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001693
peah2ace3f92016-09-10 04:42:27 -07001694 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001695 SampleRateSupportsMultiBand(
1696 formats_.render_processing_format.sample_rate_hz())) {
1697 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001698 }
1699
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001700 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001701}
1702
1703int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001704 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001705 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001706 capture_.was_stream_delay_set = true;
1707 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001708
niklase@google.com470e71d2011-07-07 08:21:25 +00001709 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001710 delay = 0;
1711 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001712 }
1713
1714 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1715 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001716 delay = 500;
1717 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001718 }
1719
peahdf3efa82015-11-28 12:35:15 -08001720 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001721 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001722}
1723
1724int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001725 // Used as callback from submodules, hence locking is not allowed.
1726 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001727}
1728
1729bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001730 // Used as callback from submodules, hence locking is not allowed.
1731 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001732}
1733
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001734void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001735 rtc::CritScope cs(&crit_capture_);
1736 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001737}
1738
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001739void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001740 rtc::CritScope cs(&crit_capture_);
1741 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001742}
1743
1744int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001745 rtc::CritScope cs(&crit_capture_);
1746 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001747}
1748
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001749void AudioProcessingImpl::set_stream_analog_level(int level) {
1750 rtc::CritScope cs_capture(&crit_capture_);
1751 int error = agc1()->set_stream_analog_level(level);
1752 RTC_DCHECK_EQ(kNoError, error);
1753}
1754
1755int AudioProcessingImpl::recommended_stream_analog_level() const {
1756 rtc::CritScope cs_capture(&crit_capture_);
1757 return agc1()->stream_analog_level();
1758}
1759
aleloi868f32f2017-05-23 07:20:05 -07001760void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1761 RTC_DCHECK(aec_dump);
1762 rtc::CritScope cs_render(&crit_render_);
1763 rtc::CritScope cs_capture(&crit_capture_);
1764
1765 // The previously attached AecDump will be destroyed with the
1766 // 'aec_dump' parameter, which is after locks are released.
1767 aec_dump_.swap(aec_dump);
1768 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001769 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001770}
1771
1772void AudioProcessingImpl::DetachAecDump() {
1773 // The d-tor of a task-queue based AecDump blocks until all pending
1774 // tasks are done. This construction avoids blocking while holding
1775 // the render and capture locks.
1776 std::unique_ptr<AecDump> aec_dump = nullptr;
1777 {
1778 rtc::CritScope cs_render(&crit_render_);
1779 rtc::CritScope cs_capture(&crit_capture_);
1780 aec_dump = std::move(aec_dump_);
1781 }
1782}
1783
Sam Zackrisson4d364492018-03-02 16:03:21 +01001784void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1785 std::unique_ptr<AudioGenerator> audio_generator) {
1786 // TODO(bugs.webrtc.org/8882) Stub.
1787 // Reset internal audio generator with audio_generator.
1788}
1789
1790void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1791 // TODO(bugs.webrtc.org/8882) Stub.
1792 // Delete audio generator, if one is attached.
1793}
1794
Ivo Creusen56d46092017-11-24 17:29:59 +01001795AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001796 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001797 rtc::CritScope cs_capture(&crit_capture_);
1798 if (!has_remote_tracks) {
1799 return capture_.stats;
1800 }
1801 AudioProcessingStats stats = capture_.stats;
1802 EchoCancellationImpl::Metrics metrics;
1803 if (private_submodules_->echo_controller) {
1804 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1805 stats.echo_return_loss = ec_metrics.echo_return_loss;
1806 stats.echo_return_loss_enhancement =
1807 ec_metrics.echo_return_loss_enhancement;
1808 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001809 }
1810 if (config_.residual_echo_detector.enabled) {
1811 RTC_DCHECK(private_submodules_->echo_detector);
1812 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1813 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1814 stats.residual_echo_likelihood_recent_max =
1815 ed_metrics.echo_likelihood_recent_max;
1816 }
Ivo Creusenae026092017-11-20 13:07:16 +01001817 return stats;
1818}
1819
niklase@google.com470e71d2011-07-07 08:21:25 +00001820GainControl* AudioProcessingImpl::gain_control() const {
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001821 return public_submodules_->gain_control_config_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001822}
1823
niklase@google.com470e71d2011-07-07 08:21:25 +00001824LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001825 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001826}
1827
1828NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001829 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001830}
1831
peah8271d042016-11-22 07:24:52 -08001832void AudioProcessingImpl::MutateConfig(
1833 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1834 rtc::CritScope cs_render(&crit_render_);
1835 rtc::CritScope cs_capture(&crit_capture_);
1836 mutator(&config_);
1837 ApplyConfig(config_);
1838}
1839
1840AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1841 rtc::CritScope cs_render(&crit_render_);
1842 rtc::CritScope cs_capture(&crit_capture_);
1843 return config_;
1844}
1845
peah2ace3f92016-09-10 04:42:27 -07001846bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1847 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001848 config_.high_pass_filter.enabled,
Per Åhgrend547d862019-05-03 15:48:47 +02001849 !!private_submodules_->echo_cancellation,
1850 !!private_submodules_->echo_control_mobile,
ivoc9f4a4a02016-10-28 05:39:16 -07001851 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001852 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001853 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001854 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001855 capture_nonlocked_.echo_controller_enabled,
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001856 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001857 public_submodules_->level_estimator->is_enabled(),
1858 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001859}
1860
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001861void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001862 if (capture_.transient_suppressor_enabled) {
1863 if (!public_submodules_->transient_suppressor.get()) {
1864 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001865 }
peahdf3efa82015-11-28 12:35:15 -08001866 public_submodules_->transient_suppressor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001867 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1868 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001869 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001870}
1871
Per Åhgren0aefbf02019-08-23 21:29:17 +02001872void AudioProcessingImpl::InitializeHighPassFilter() {
1873 if (submodule_states_.HighPassFilteringRequired()) {
1874 private_submodules_->high_pass_filter.reset(
1875 new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001876 } else {
Per Åhgren0aefbf02019-08-23 21:29:17 +02001877 private_submodules_->high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001878 }
1879}
alessiob3ec96df2017-05-22 06:57:06 -07001880
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001881void AudioProcessingImpl::InitializeVoiceDetector() {
1882 if (config_.voice_detection.enabled) {
1883 private_submodules_->voice_detector = std::make_unique<VoiceDetection>(
1884 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1885 } else {
1886 private_submodules_->voice_detector.reset();
1887 }
1888}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001889void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001890 bool use_echo_controller =
1891 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001892 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001893 !config_.echo_canceller.use_legacy_aec);
1894
1895 if (use_echo_controller) {
1896 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001897 if (echo_control_factory_) {
1898 private_submodules_->echo_controller =
1899 echo_control_factory_->Create(proc_sample_rate_hz());
1900 } else {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001901 private_submodules_->echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001902 EchoCanceller3Config(), proc_sample_rate_hz(), num_reverse_channels(),
1903 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001904 }
1905
1906 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001907
Per Åhgrenf204faf2019-04-25 15:18:06 +02001908 private_submodules_->echo_cancellation.reset();
1909 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001910 private_submodules_->echo_control_mobile.reset();
1911 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001912 return;
peahe0eae3c2016-12-14 01:16:23 -08001913 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001914
1915 private_submodules_->echo_controller.reset();
1916 capture_nonlocked_.echo_controller_enabled = false;
1917
1918 if (!config_.echo_canceller.enabled) {
1919 private_submodules_->echo_cancellation.reset();
1920 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001921 private_submodules_->echo_control_mobile.reset();
1922 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001923 return;
1924 }
1925
1926 if (config_.echo_canceller.mobile_mode) {
1927 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001928 size_t max_element_size =
1929 std::max(static_cast<size_t>(1),
1930 kMaxAllowedValuesOfSamplesPerBand *
1931 EchoControlMobileImpl::NumCancellersRequired(
1932 num_output_channels(), num_reverse_channels()));
1933
1934 std::vector<int16_t> template_queue_element(max_element_size);
1935
1936 aecm_render_signal_queue_.reset(
1937 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1938 kMaxNumFramesToBuffer, template_queue_element,
1939 RenderQueueItemVerifier<int16_t>(max_element_size)));
1940
1941 aecm_render_queue_buffer_.resize(max_element_size);
1942 aecm_capture_queue_buffer_.resize(max_element_size);
1943
1944 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
1945
1946 private_submodules_->echo_control_mobile->Initialize(
1947 proc_split_sample_rate_hz(), num_reverse_channels(),
1948 num_output_channels());
1949
Per Åhgrenf204faf2019-04-25 15:18:06 +02001950 private_submodules_->echo_cancellation.reset();
1951 aec_render_signal_queue_.reset();
1952 return;
1953 }
1954
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001955 private_submodules_->echo_control_mobile.reset();
1956 aecm_render_signal_queue_.reset();
1957
Per Åhgrenf204faf2019-04-25 15:18:06 +02001958 // Create and activate AEC2.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001959 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
1960 private_submodules_->echo_cancellation->SetExtraOptions(
1961 capture_nonlocked_.use_aec2_extended_filter,
1962 capture_nonlocked_.use_aec2_delay_agnostic,
1963 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1964
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001965 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001966 std::max(static_cast<size_t>(1),
1967 kMaxAllowedValuesOfSamplesPerBand *
1968 EchoCancellationImpl::NumCancellersRequired(
1969 num_output_channels(), num_reverse_channels()));
1970
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001971 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001972
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001973 aec_render_signal_queue_.reset(
1974 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1975 kMaxNumFramesToBuffer, template_queue_element,
1976 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001977
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001978 aec_render_queue_buffer_.resize(element_max_size);
1979 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001980
1981 private_submodules_->echo_cancellation->Initialize(
1982 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1983 num_proc_channels());
1984
Per Åhgrenf204faf2019-04-25 15:18:06 +02001985 private_submodules_->echo_cancellation->set_suppression_level(
1986 config_.echo_canceller.legacy_moderate_suppression_level
1987 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1988 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001989}
peah8271d042016-11-22 07:24:52 -08001990
alessiob3ec96df2017-05-22 06:57:06 -07001991void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001992 if (config_.gain_controller2.enabled) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001993 private_submodules_->gain_controller2->Initialize(
1994 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001995 }
1996}
1997
Alex Loikob5c9a792018-04-16 16:31:22 +02001998void AudioProcessingImpl::InitializePreAmplifier() {
1999 if (config_.pre_amplifier.enabled) {
2000 private_submodules_->pre_amplifier.reset(
2001 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
2002 } else {
2003 private_submodules_->pre_amplifier.reset();
2004 }
2005}
2006
ivoc9f4a4a02016-10-28 05:39:16 -07002007void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01002008 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01002009 private_submodules_->echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002010 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02002011 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07002012}
2013
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002014void AudioProcessingImpl::InitializeAnalyzer() {
2015 if (private_submodules_->capture_analyzer) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002016 private_submodules_->capture_analyzer->Initialize(
2017 proc_fullband_sample_rate_hz(), num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002018 }
2019}
2020
Sam Zackrisson0beac582017-09-25 12:04:02 +02002021void AudioProcessingImpl::InitializePostProcessor() {
2022 if (private_submodules_->capture_post_processor) {
2023 private_submodules_->capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002024 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002025 }
2026}
2027
Alex Loiko5825aa62017-12-18 16:02:40 +01002028void AudioProcessingImpl::InitializePreProcessor() {
2029 if (private_submodules_->render_pre_processor) {
2030 private_submodules_->render_pre_processor->Initialize(
2031 formats_.render_processing_format.sample_rate_hz(),
2032 formats_.render_processing_format.num_channels());
2033 }
2034}
2035
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002036void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002037
aleloi868f32f2017-05-23 07:20:05 -07002038void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2039 if (!aec_dump_) {
2040 return;
2041 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002042
2043 std::string experiments_description = "";
2044 if (private_submodules_->echo_cancellation) {
2045 experiments_description +=
2046 private_submodules_->echo_cancellation->GetExperimentsDescription();
2047 }
aleloi868f32f2017-05-23 07:20:05 -07002048 // TODO(peah): Add semicolon-separated concatenations of experiment
2049 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002050 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2051 experiments_description += "AgcClippingLevelExperiment;";
2052 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002053 if (capture_nonlocked_.echo_controller_enabled) {
2054 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002055 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002056 if (config_.gain_controller2.enabled) {
2057 experiments_description += "GainController2;";
2058 }
aleloi868f32f2017-05-23 07:20:05 -07002059
2060 InternalAPMConfig apm_config;
2061
Per Åhgren200feba2019-03-06 04:16:46 +01002062 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002063 apm_config.aec_delay_agnostic_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002064 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002065 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002066 apm_config.aec_drift_compensation_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002067 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002068 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002069 apm_config.aec_extended_filter_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002070 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002071 private_submodules_->echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002072 apm_config.aec_suppression_level =
2073 private_submodules_->echo_cancellation
2074 ? static_cast<int>(
2075 private_submodules_->echo_cancellation->suppression_level())
2076 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002077
Per Åhgrend547d862019-05-03 15:48:47 +02002078 apm_config.aecm_enabled = !!private_submodules_->echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002079 apm_config.aecm_comfort_noise_enabled =
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002080 private_submodules_->echo_control_mobile &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002081 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002082 apm_config.aecm_routing_mode =
2083 private_submodules_->echo_control_mobile
2084 ? static_cast<int>(
2085 private_submodules_->echo_control_mobile->routing_mode())
2086 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002087
2088 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2089 apm_config.agc_mode =
2090 static_cast<int>(public_submodules_->gain_control->mode());
2091 apm_config.agc_limiter_enabled =
2092 public_submodules_->gain_control->is_limiter_enabled();
2093 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2094
2095 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2096
2097 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2098 apm_config.ns_level =
2099 static_cast<int>(public_submodules_->noise_suppression->level());
2100
2101 apm_config.transient_suppression_enabled =
2102 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002103 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002104 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2105 apm_config.pre_amplifier_fixed_gain_factor =
2106 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002107
2108 if (!forced && apm_config == apm_config_for_aec_dump_) {
2109 return;
2110 }
2111 aec_dump_->WriteConfig(apm_config);
2112 apm_config_for_aec_dump_ = apm_config;
2113}
2114
2115void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2116 const float* const* src) {
2117 RTC_DCHECK(aec_dump_);
2118 WriteAecDumpConfigMessage(false);
2119
2120 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2121 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2122 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002123 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002124 RecordAudioProcessingState();
2125}
2126
2127void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2128 const AudioFrame& capture_frame) {
2129 RTC_DCHECK(aec_dump_);
2130 WriteAecDumpConfigMessage(false);
2131
2132 aec_dump_->AddCaptureStreamInput(capture_frame);
2133 RecordAudioProcessingState();
2134}
2135
2136void AudioProcessingImpl::RecordProcessedCaptureStream(
2137 const float* const* processed_capture_stream) {
2138 RTC_DCHECK(aec_dump_);
2139
2140 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2141 const size_t num_channels =
2142 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002143 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2144 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002145 aec_dump_->WriteCaptureStreamMessage();
2146}
2147
2148void AudioProcessingImpl::RecordProcessedCaptureStream(
2149 const AudioFrame& processed_capture_frame) {
2150 RTC_DCHECK(aec_dump_);
2151
2152 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2153 aec_dump_->WriteCaptureStreamMessage();
2154}
2155
2156void AudioProcessingImpl::RecordAudioProcessingState() {
2157 RTC_DCHECK(aec_dump_);
2158 AecDump::AudioProcessingState audio_proc_state;
2159 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2160 audio_proc_state.drift =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002161 private_submodules_->echo_cancellation
2162 ? private_submodules_->echo_cancellation->stream_drift_samples()
2163 : 0;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002164 audio_proc_state.level = agc1()->stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002165 audio_proc_state.keypress = capture_.key_pressed;
2166 aec_dump_->AddAudioProcessingState(audio_proc_state);
2167}
2168
kwiberg83ffe452016-08-29 14:46:07 -07002169AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002170 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002171 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002172 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002173 output_will_be_muted(false),
2174 key_pressed(false),
2175 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002176 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002177 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002178 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002179 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002180 prev_pre_amp_gain(-1.f),
2181 playout_volume(-1),
2182 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002183
2184AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2185
Per Åhgrena1351272019-08-15 12:15:46 +02002186void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2187 const float* const* data,
2188 const StreamConfig& stream_config) {
2189 if (stream_config.has_keyboard()) {
2190 keyboard_data = data[stream_config.num_channels()];
2191 } else {
2192 keyboard_data = NULL;
2193 }
2194 num_keyboard_frames = stream_config.num_frames();
2195}
2196
kwiberg83ffe452016-08-29 14:46:07 -07002197AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2198
2199AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2200
niklase@google.com470e71d2011-07-07 08:21:25 +00002201} // namespace webrtc