blob: 564a9804e8dd3fa2a39674495162ce25d6657bac [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 {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200209 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700210}
211
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200212bool AudioProcessingImpl::ApmSubmoduleStates::
213 CaptureMultiBandProcessingPresent() const {
214 // If echo controller is present, assume it performs active processing.
215 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
216}
217
218bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive(
219 bool ec_processing_active) const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200220 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700221 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200222 adaptive_gain_controller_enabled_ ||
223 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700224}
225
peah23ac8b42017-05-23 05:33:56 -0700226bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
227 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200228 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
229 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700230}
231
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200232bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
233 return capture_analyzer_enabled_;
234}
235
peah2ace3f92016-09-10 04:42:27 -0700236bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
237 const {
238 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800239 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200240 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700241}
242
Alex Loiko5825aa62017-12-18 16:02:40 +0100243bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
244 const {
245 return render_pre_processor_enabled_;
246}
247
peah2ace3f92016-09-10 04:42:27 -0700248bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
249 const {
peah2ace3f92016-09-10 04:42:27 -0700250 return false;
peah2ace3f92016-09-10 04:42:27 -0700251}
252
Per Åhgren0aefbf02019-08-23 21:29:17 +0200253bool AudioProcessingImpl::ApmSubmoduleStates::HighPassFilteringRequired()
254 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200255 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
256 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
257}
258
solenberg5e465c32015-12-08 13:22:33 -0800259struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800260 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800261 // Accessed externally of APM without any lock acquired.
Sam Zackrisson23513132019-01-11 15:10:32 +0100262 // TODO(bugs.webrtc.org/9947): Move these submodules into private_submodules_
263 // when their pointer-to-submodule API functions are gone.
kwiberg88788ad2016-02-19 07:04:49 -0800264 std::unique_ptr<LevelEstimatorImpl> level_estimator;
265 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
Sam Zackrisson23513132019-01-11 15:10:32 +0100266 std::unique_ptr<NoiseSuppressionProxy> noise_suppression_proxy;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100267 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800268 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800269 gain_control_for_experimental_agc;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100270 std::unique_ptr<GainControlConfigProxy> gain_control_config_proxy;
solenberg5e465c32015-12-08 13:22:33 -0800271
272 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800273 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800274};
275
276struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200277 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100278 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200279 rtc::scoped_refptr<EchoDetector> echo_detector,
280 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200281 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100282 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200283 render_pre_processor(std::move(render_pre_processor)),
284 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800285 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800286 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700287 std::unique_ptr<GainController2> gain_controller2;
Per Åhgren0aefbf02019-08-23 21:29:17 +0200288 std::unique_ptr<HighPassFilter> high_pass_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200289 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100290 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100291 std::unique_ptr<EchoControl> echo_controller;
292 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100293 std::unique_ptr<CustomProcessing> capture_post_processor;
294 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200295 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200296 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100297 std::unique_ptr<LevelEstimatorImpl> output_level_estimator;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200298 std::unique_ptr<VoiceDetection> voice_detector;
solenberg5e465c32015-12-08 13:22:33 -0800299};
300
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100301AudioProcessingBuilder::AudioProcessingBuilder() = default;
302AudioProcessingBuilder::~AudioProcessingBuilder() = default;
303
304AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
305 std::unique_ptr<CustomProcessing> capture_post_processing) {
306 capture_post_processing_ = std::move(capture_post_processing);
307 return *this;
308}
309
310AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
311 std::unique_ptr<CustomProcessing> render_pre_processing) {
312 render_pre_processing_ = std::move(render_pre_processing);
313 return *this;
314}
315
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200316AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
317 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
318 capture_analyzer_ = std::move(capture_analyzer);
319 return *this;
320}
321
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100322AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
323 std::unique_ptr<EchoControlFactory> echo_control_factory) {
324 echo_control_factory_ = std::move(echo_control_factory);
325 return *this;
326}
327
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100328AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200329 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100330 echo_detector_ = std::move(echo_detector);
331 return *this;
332}
333
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100334AudioProcessing* AudioProcessingBuilder::Create() {
335 webrtc::Config config;
336 return Create(config);
337}
338
339AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100340 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
341 config, std::move(capture_post_processing_),
342 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200343 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100344 if (apm->Initialize() != AudioProcessing::kNoError) {
345 delete apm;
346 apm = nullptr;
347 }
348 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100349}
350
peah88ac8532016-09-12 16:47:25 -0700351AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200352 : AudioProcessingImpl(config,
353 /*capture_post_processor=*/nullptr,
354 /*render_pre_processor=*/nullptr,
355 /*echo_control_factory=*/nullptr,
356 /*echo_detector=*/nullptr,
357 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000358
Per Åhgren13735822018-02-12 21:42:56 +0100359int AudioProcessingImpl::instance_count_ = 0;
360
Sam Zackrisson0beac582017-09-25 12:04:02 +0200361AudioProcessingImpl::AudioProcessingImpl(
362 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100363 std::unique_ptr<CustomProcessing> capture_post_processor,
364 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200365 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200366 rtc::scoped_refptr<EchoDetector> echo_detector,
367 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100368 : data_dumper_(
369 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200370 capture_runtime_settings_(kRuntimeSettingQueueSize),
371 render_runtime_settings_(kRuntimeSettingQueueSize),
372 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
373 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200374 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200375 submodule_states_(!!capture_post_processor,
376 !!render_pre_processor,
377 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800378 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200379 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200380 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100381 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200382 std::move(echo_detector),
383 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800384 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800385 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000386#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200387 /* enabled= */ false,
388 /* enabled_agc2_level_estimator= */ false,
389 /* digital_adaptive_disabled= */ false,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200390 /* analyze_before_aec= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000391#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200392 config.Get<ExperimentalAgc>().enabled,
393 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200394 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200395 config.Get<ExperimentalAgc>().analyze_before_aec,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000396#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200397 !field_trial::IsEnabled(
398 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
399 !field_trial::IsEnabled(
400 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700401#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200402 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700403#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200404 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700405#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200406 capture_nonlocked_() {
Sam Zackrisson421c8592019-02-11 13:39:46 +0100407 // Mark Echo Controller enabled if a factory is injected.
408 capture_nonlocked_.echo_controller_enabled =
409 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000410
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100411 public_submodules_->gain_control.reset(new GainControlImpl());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100412 public_submodules_->level_estimator.reset(
413 new LevelEstimatorImpl(&crit_capture_));
414 public_submodules_->noise_suppression.reset(
415 new NoiseSuppressionImpl(&crit_capture_));
416 public_submodules_->noise_suppression_proxy.reset(new NoiseSuppressionProxy(
417 this, public_submodules_->noise_suppression.get()));
Sam Zackrisson421c8592019-02-11 13:39:46 +0100418 public_submodules_->gain_control_for_experimental_agc.reset(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100419 new GainControlForExperimentalAgc(
420 public_submodules_->gain_control.get()));
421 public_submodules_->gain_control_config_proxy.reset(
422 new GainControlConfigProxy(&crit_capture_, this, agc1()));
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200423
Sam Zackrisson421c8592019-02-11 13:39:46 +0100424 // If no echo detector is injected, use the ResidualEchoDetector.
425 if (!private_submodules_->echo_detector) {
426 private_submodules_->echo_detector =
427 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800428 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000429
Sam Zackrisson421c8592019-02-11 13:39:46 +0100430 // TODO(alessiob): Move the injected gain controller once injection is
431 // implemented.
432 private_submodules_->gain_controller2.reset(new GainController2());
433
434 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
435 << !!private_submodules_->capture_analyzer
436 << "\nCapture post processor activated: "
437 << !!private_submodules_->capture_post_processor
438 << "\nRender pre processor activated: "
439 << !!private_submodules_->render_pre_processor;
440
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000441 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000442}
443
444AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800445 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800446 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800447 private_submodules_->agc_manager.reset();
448 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800449 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000450}
451
niklase@google.com470e71d2011-07-07 08:21:25 +0000452int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800453 // Run in a single-threaded manner during initialization.
454 rtc::CritScope cs_render(&crit_render_);
455 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000456 return InitializeLocked();
457}
458
peahde65ddc2016-09-16 15:02:15 -0700459int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
460 int capture_output_sample_rate_hz,
461 int render_input_sample_rate_hz,
462 ChannelLayout capture_input_layout,
463 ChannelLayout capture_output_layout,
464 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700465 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700466 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
467 LayoutHasKeyboard(capture_input_layout)},
468 {capture_output_sample_rate_hz,
469 ChannelsFromLayout(capture_output_layout),
470 LayoutHasKeyboard(capture_output_layout)},
471 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
472 LayoutHasKeyboard(render_input_layout)},
473 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
474 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700475
476 return Initialize(processing_config);
477}
478
479int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800480 // Run in a single-threaded manner during initialization.
481 rtc::CritScope cs_render(&crit_render_);
482 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700483 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000484}
485
peahdf3efa82015-11-28 12:35:15 -0800486int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800487 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800488 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200489 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800490 return kNoError;
491 }
peahdf3efa82015-11-28 12:35:15 -0800492
493 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800494 return InitializeLocked(processing_config);
495}
496
niklase@google.com470e71d2011-07-07 08:21:25 +0000497int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200498 UpdateActiveSubmoduleStates();
499
Per Åhgrend47941e2019-08-22 11:51:13 +0200500 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800501 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200502 ? formats_.render_processing_format.sample_rate_hz()
503 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800504 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
505 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200506 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800507 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200508 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700509 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200510 render_audiobuffer_sample_rate_hz,
511 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700512 if (formats_.api_format.reverse_input_stream() !=
513 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800514 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800515 formats_.api_format.reverse_input_stream().num_channels(),
516 formats_.api_format.reverse_input_stream().num_frames(),
517 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800518 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700519 } else {
peahdf3efa82015-11-28 12:35:15 -0800520 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700521 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700522 } else {
peahdf3efa82015-11-28 12:35:15 -0800523 render_.render_audio.reset(nullptr);
524 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700525 }
peahce4d9152017-05-19 01:28:05 -0700526
Per Åhgrend47941e2019-08-22 11:51:13 +0200527 capture_.capture_audio.reset(new AudioBuffer(
528 formats_.api_format.input_stream().sample_rate_hz(),
529 formats_.api_format.input_stream().num_channels(),
530 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
531 formats_.api_format.output_stream().num_channels(),
532 formats_.api_format.output_stream().sample_rate_hz(),
533 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000534
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200535 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
536 formats_.api_format.output_stream().sample_rate_hz() &&
537 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
538 capture_.capture_fullband_audio.reset(
539 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
540 formats_.api_format.input_stream().num_channels(),
541 formats_.api_format.output_stream().sample_rate_hz(),
542 formats_.api_format.output_stream().num_channels(),
543 formats_.api_format.output_stream().sample_rate_hz(),
544 formats_.api_format.output_stream().num_channels()));
545 } else {
546 capture_.capture_fullband_audio.reset();
547 }
548
peah764e3642016-10-22 05:04:30 -0700549 AllocateRenderQueue();
550
peah135259a2016-10-28 03:12:11 -0700551 public_submodules_->gain_control->Initialize(num_proc_channels(),
552 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700553 if (constants_.use_experimental_agc) {
554 if (!private_submodules_->agc_manager.get()) {
555 private_submodules_->agc_manager.reset(new AgcManagerDirect(
556 public_submodules_->gain_control.get(),
557 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200558 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
559 constants_.use_experimental_agc_agc2_level_estimation,
560 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700561 }
562 private_submodules_->agc_manager->Initialize();
563 private_submodules_->agc_manager->SetCaptureMuted(
564 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700565 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700566 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200567 InitializeTransient();
Per Åhgren0aefbf02019-08-23 21:29:17 +0200568 InitializeHighPassFilter();
peahde65ddc2016-09-16 15:02:15 -0700569 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
570 proc_sample_rate_hz());
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200571 InitializeVoiceDetector();
peahde65ddc2016-09-16 15:02:15 -0700572 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700573 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200574 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700575 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200576 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200577 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100578 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800579
aleloi868f32f2017-05-23 07:20:05 -0700580 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200581 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700582 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000583 return kNoError;
584}
585
Michael Graczyk86c6d332015-07-23 11:41:39 -0700586int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200587 UpdateActiveSubmoduleStates();
588
Michael Graczyk86c6d332015-07-23 11:41:39 -0700589 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
591 return kBadSampleRateError;
592 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000593 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700594
Peter Kasting69558702016-01-12 16:26:35 -0800595 const size_t num_in_channels = config.input_stream().num_channels();
596 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700597
598 // Need at least one input channel.
599 // Need either one output channel or as many outputs as there are inputs.
600 if (num_in_channels == 0 ||
601 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700602 return kBadNumberChannelsError;
603 }
604
peahdf3efa82015-11-28 12:35:15 -0800605 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000606
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200607 // Choose maximum rate to use for the split filtering.
608 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
609 config_.pipeline.maximum_internal_processing_rate == 32000);
610 int max_splitting_rate = 48000;
611 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
612 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
613 }
614
Per Åhgrenc8626b62019-08-23 15:49:51 +0200615 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700616 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700617 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200618 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700619 submodule_states_.CaptureMultiBandSubModulesActive() ||
620 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200621 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000622
peahde65ddc2016-09-16 15:02:15 -0700623 capture_nonlocked_.capture_processing_format =
624 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700625
peah2ce640f2017-04-07 03:57:48 -0700626 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200627 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200628 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700629 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
630 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200631 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700632 submodule_states_.CaptureMultiBandSubModulesActive() ||
633 submodule_states_.RenderMultiBandSubModulesActive());
634 } else {
635 render_processing_rate = capture_processing_rate;
636 }
637
peahde65ddc2016-09-16 15:02:15 -0700638 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700639 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700640 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
641 kSampleRate8kHz) {
642 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000643 } else {
peahde65ddc2016-09-16 15:02:15 -0700644 render_processing_rate =
645 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000646 }
647
Per Åhgrenc8626b62019-08-23 15:49:51 +0200648 RTC_DCHECK_NE(8000, render_processing_rate);
649
peahce4d9152017-05-19 01:28:05 -0700650 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200651 // By default, downmix the render stream to mono for analysis. This has been
652 // demonstrated to work well for AEC in most practical scenarios.
653 const bool experimental_multi_channel_render =
654 config_.pipeline.experimental_multi_channel &&
655 constants_.experimental_multi_channel_render_support;
656 int render_processing_num_channels =
657 experimental_multi_channel_render
658 ? formats_.api_format.reverse_input_stream().num_channels()
659 : 1;
660 formats_.render_processing_format =
661 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700662 } else {
663 formats_.render_processing_format = StreamConfig(
664 formats_.api_format.reverse_input_stream().sample_rate_hz(),
665 formats_.api_format.reverse_input_stream().num_channels());
666 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000667
peahde65ddc2016-09-16 15:02:15 -0700668 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
669 kSampleRate32kHz ||
670 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
671 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800672 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000673 } else {
peahdf3efa82015-11-28 12:35:15 -0800674 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700675 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000676 }
677
678 return InitializeLocked();
679}
680
peah88ac8532016-09-12 16:47:25 -0700681void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700682 // Run in a single-threaded manner when applying the settings.
683 rtc::CritScope cs_render(&crit_render_);
684 rtc::CritScope cs_capture(&crit_capture_);
685
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200686 const bool pipeline_config_changed =
687 config_.pipeline.experimental_multi_channel !=
688 config.pipeline.experimental_multi_channel;
689
Per Åhgren200feba2019-03-06 04:16:46 +0100690 const bool aec_config_changed =
691 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
692 config_.echo_canceller.use_legacy_aec !=
693 config.echo_canceller.use_legacy_aec ||
694 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
695 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
696 config_.echo_canceller.legacy_moderate_suppression_level !=
697 config.echo_canceller.legacy_moderate_suppression_level);
698
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100699 const bool agc1_config_changed =
700 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
701 config_.gain_controller1.mode != config.gain_controller1.mode ||
702 config_.gain_controller1.target_level_dbfs !=
703 config.gain_controller1.target_level_dbfs ||
704 config_.gain_controller1.compression_gain_db !=
705 config.gain_controller1.compression_gain_db ||
706 config_.gain_controller1.enable_limiter !=
707 config.gain_controller1.enable_limiter ||
708 config_.gain_controller1.analog_level_minimum !=
709 config.gain_controller1.analog_level_minimum ||
710 config_.gain_controller1.analog_level_maximum !=
711 config.gain_controller1.analog_level_maximum;
712
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200713 const bool voice_detection_config_changed =
714 config_.voice_detection.enabled != config.voice_detection.enabled;
715
Yves Gerey499bc6c2018-10-10 18:29:07 +0200716 config_ = config;
717
Per Åhgren200feba2019-03-06 04:16:46 +0100718 if (aec_config_changed) {
719 InitializeEchoController();
720 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200721
Sam Zackrisson23513132019-01-11 15:10:32 +0100722 public_submodules_->noise_suppression->Enable(
723 config.noise_suppression.enabled);
724 public_submodules_->noise_suppression->set_level(
725 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
726
Per Åhgren0aefbf02019-08-23 21:29:17 +0200727 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800728
Mirko Bonadei675513b2017-11-09 11:09:25 +0100729 RTC_LOG(LS_INFO) << "Highpass filter activated: "
730 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800731
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100732 if (agc1_config_changed) {
733 ApplyAgc1Config(config_.gain_controller1);
734 }
735
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100736 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700737 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100738 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
739 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100740 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100741 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700742 config_.gain_controller2 = AudioProcessing::Config::GainController2();
743 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200744 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200745 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200746 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100747 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
748 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200749 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
750 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100751
752 if (config_.level_estimation.enabled &&
753 !private_submodules_->output_level_estimator) {
754 private_submodules_->output_level_estimator.reset(
755 new LevelEstimatorImpl(&crit_capture_));
756 private_submodules_->output_level_estimator->Enable(true);
757 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100758
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200759 if (voice_detection_config_changed) {
760 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100761 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200762
763 // Reinitialization must happen after all submodule configuration to avoid
764 // additional reinitializations on the next capture / render processing call.
765 if (pipeline_config_changed) {
766 InitializeLocked(formats_.api_format);
767 }
peah88ac8532016-09-12 16:47:25 -0700768}
769
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100770void AudioProcessingImpl::ApplyAgc1Config(
771 const Config::GainController1& config) {
772 GainControl* agc = agc1();
773 int error = agc->Enable(config.enabled);
774 RTC_DCHECK_EQ(kNoError, error);
775 error = agc->set_mode(Agc1ConfigModeToInterfaceMode(config.mode));
776 RTC_DCHECK_EQ(kNoError, error);
777 error = agc->set_target_level_dbfs(config.target_level_dbfs);
778 RTC_DCHECK_EQ(kNoError, error);
779 error = agc->set_compression_gain_db(config.compression_gain_db);
780 RTC_DCHECK_EQ(kNoError, error);
781 error = agc->enable_limiter(config.enable_limiter);
782 RTC_DCHECK_EQ(kNoError, error);
783 error = agc->set_analog_level_limits(config.analog_level_minimum,
784 config.analog_level_maximum);
785 RTC_DCHECK_EQ(kNoError, error);
786}
787
788GainControl* AudioProcessingImpl::agc1() {
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
795const GainControl* AudioProcessingImpl::agc1() const {
796 if (constants_.use_experimental_agc) {
797 return public_submodules_->gain_control_for_experimental_agc.get();
798 }
799 return public_submodules_->gain_control.get();
800}
801
peah88ac8532016-09-12 16:47:25 -0700802void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800803 // Run in a single-threaded manner when setting the extra options.
804 rtc::CritScope cs_render(&crit_render_);
805 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000806
Per Åhgrenf204faf2019-04-25 15:18:06 +0200807 capture_nonlocked_.use_aec2_extended_filter =
808 config.Get<ExtendedFilter>().enabled;
809 capture_nonlocked_.use_aec2_delay_agnostic =
810 config.Get<DelayAgnostic>().enabled;
811 capture_nonlocked_.use_aec2_refined_adaptive_filter =
812 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800813
peahdf3efa82015-11-28 12:35:15 -0800814 if (capture_.transient_suppressor_enabled !=
815 config.Get<ExperimentalNs>().enabled) {
816 capture_.transient_suppressor_enabled =
817 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000818 InitializeTransient();
819 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000820}
821
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000822int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800823 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700824 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000825}
826
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200827int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
828 return capture_.capture_fullband_audio
829 ? capture_.capture_fullband_audio->num_frames() * 100
830 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
831}
832
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000833int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800834 // Used as callback from submodules, hence locking is not allowed.
835 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000836}
837
Peter Kasting69558702016-01-12 16:26:35 -0800838size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800839 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700840 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000841}
842
Peter Kasting69558702016-01-12 16:26:35 -0800843size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800844 // Used as callback from submodules, hence locking is not allowed.
845 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000846}
847
Peter Kasting69558702016-01-12 16:26:35 -0800848size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800849 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200850 const bool experimental_multi_channel_capture =
851 config_.pipeline.experimental_multi_channel &&
852 constants_.experimental_multi_channel_capture_support;
853 if (capture_nonlocked_.echo_controller_enabled &&
854 !experimental_multi_channel_capture) {
855 return 1;
856 }
857 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800858}
859
Peter Kasting69558702016-01-12 16:26:35 -0800860size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800861 // Used as callback from submodules, hence locking is not allowed.
862 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000863}
864
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000865void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800866 rtc::CritScope cs(&crit_capture_);
867 capture_.output_will_be_muted = muted;
868 if (private_submodules_->agc_manager.get()) {
869 private_submodules_->agc_manager->SetCaptureMuted(
870 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000871 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000872}
873
Alessio Bazzicac054e782018-04-16 12:10:09 +0200874void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200875 switch (setting.type()) {
876 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
877 render_runtime_settings_enqueuer_.Enqueue(setting);
878 return;
879 case RuntimeSetting::Type::kNotSpecified:
880 RTC_NOTREACHED();
881 return;
882 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100883 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200884 case RuntimeSetting::Type::kCaptureFixedPostGain:
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200885 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200886 capture_runtime_settings_enqueuer_.Enqueue(setting);
887 return;
888 }
889 // The language allows the enum to have a non-enumerator
890 // value. Check that this doesn't happen.
891 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200892}
893
894AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
895 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200896 : runtime_settings_(*runtime_settings) {
897 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200898}
899
900AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
901 default;
902
903void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
904 RuntimeSetting setting) {
905 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200906 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200907 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200908 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200909 RTC_LOG(LS_ERROR)
910 << "The runtime settings queue is full. Oldest setting discarded.";
911 }
912 if (remaining_attempts == 0)
913 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
914}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000915
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000916int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700917 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000918 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000919 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000920 int output_sample_rate_hz,
921 ChannelLayout output_layout,
922 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800923 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800924 StreamConfig input_stream;
925 StreamConfig output_stream;
926 {
927 // Access the formats_.api_format.input_stream beneath the capture lock.
928 // The lock must be released as it is later required in the call
929 // to ProcessStream(,,,);
930 rtc::CritScope cs(&crit_capture_);
931 input_stream = formats_.api_format.input_stream();
932 output_stream = formats_.api_format.output_stream();
933 }
934
Michael Graczyk86c6d332015-07-23 11:41:39 -0700935 input_stream.set_sample_rate_hz(input_sample_rate_hz);
936 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
937 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700938 output_stream.set_sample_rate_hz(output_sample_rate_hz);
939 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
940 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
941
942 if (samples_per_channel != input_stream.num_frames()) {
943 return kBadDataLengthError;
944 }
945 return ProcessStream(src, input_stream, output_stream, dest);
946}
947
948int AudioProcessingImpl::ProcessStream(const float* const* src,
949 const StreamConfig& input_config,
950 const StreamConfig& output_config,
951 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800952 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800953 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700954 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800955 {
956 // Acquire the capture lock in order to safely call the function
957 // that retrieves the render side data. This function accesses apm
958 // getters that need the capture lock held when being called.
959 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700960 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800961
962 if (!src || !dest) {
963 return kNullPointerError;
964 }
965
966 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700967 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000968 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000969
Oskar Sundbom4b276482019-05-23 14:28:00 +0200970 if (processing_config.input_stream() != input_config) {
971 processing_config.input_stream() = input_config;
972 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800973 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200974
975 if (processing_config.output_stream() != output_config) {
976 processing_config.output_stream() = output_config;
977 reinitialization_required = true;
978 }
979
980 if (reinitialization_required) {
981 // Reinitialize.
982 rtc::CritScope cs_render(&crit_render_);
983 rtc::CritScope cs_capture(&crit_capture_);
984 RETURN_ON_ERR(InitializeLocked(processing_config));
985 }
986
peahdf3efa82015-11-28 12:35:15 -0800987 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700988 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
989 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000990
aleloi868f32f2017-05-23 07:20:05 -0700991 if (aec_dump_) {
992 RecordUnprocessedCaptureStream(src);
993 }
994
Per Åhgrena1351272019-08-15 12:15:46 +0200995 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800996 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200997 if (capture_.capture_fullband_audio) {
998 capture_.capture_fullband_audio->CopyFrom(
999 src, formats_.api_format.input_stream());
1000 }
peahde65ddc2016-09-16 15:02:15 -07001001 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001002 if (capture_.capture_fullband_audio) {
1003 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1004 dest);
1005 } else {
1006 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1007 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001008
aleloi868f32f2017-05-23 07:20:05 -07001009 if (aec_dump_) {
1010 RecordProcessedCaptureStream(dest);
1011 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001012 return kNoError;
1013}
1014
Alex Loiko73ec0192018-05-15 10:52:28 +02001015void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001016 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +02001017 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001018 if (aec_dump_) {
1019 aec_dump_->WriteRuntimeSetting(setting);
1020 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001021 switch (setting.type()) {
1022 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +02001023 if (config_.pre_amplifier.enabled) {
1024 float value;
1025 setting.GetFloat(&value);
1026 private_submodules_->pre_amplifier->SetGainFactor(value);
1027 }
1028 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001029 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001030 case RuntimeSetting::Type::kCaptureCompressionGain: {
1031 float value;
1032 setting.GetFloat(&value);
1033 int int_value = static_cast<int>(value + .5f);
1034 config_.gain_controller1.compression_gain_db = int_value;
1035 int error = agc1()->set_compression_gain_db(int_value);
1036 RTC_DCHECK_EQ(kNoError, error);
1037 break;
1038 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001039 case RuntimeSetting::Type::kCaptureFixedPostGain: {
1040 if (config_.gain_controller2.enabled) {
1041 float value;
1042 setting.GetFloat(&value);
1043 config_.gain_controller2.fixed_digital.gain_db = value;
1044 private_submodules_->gain_controller2->ApplyConfig(
1045 config_.gain_controller2);
1046 }
1047 break;
1048 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001049 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1050 int value;
1051 setting.GetInt(&value);
1052 capture_.playout_volume = value;
1053 break;
1054 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001055 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1056 RTC_NOTREACHED();
1057 break;
1058 case RuntimeSetting::Type::kNotSpecified:
1059 RTC_NOTREACHED();
1060 break;
1061 }
1062 }
1063}
1064
1065void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1066 RuntimeSetting setting;
1067 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001068 if (aec_dump_) {
1069 aec_dump_->WriteRuntimeSetting(setting);
1070 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001071 switch (setting.type()) {
1072 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1073 if (private_submodules_->render_pre_processor) {
1074 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
1075 }
1076 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001077 case RuntimeSetting::Type::kCapturePreGain: // fall-through
1078 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001079 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001080 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001081 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +02001082 RTC_NOTREACHED();
1083 break;
1084 }
1085 }
1086}
1087
peah9e6a2902017-05-15 07:19:21 -07001088void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001089 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001090
1091 // Insert the samples into the queue.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001092 if (private_submodules_->echo_cancellation) {
1093 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001094 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1095 num_reverse_channels(),
1096 &aec_render_queue_buffer_);
1097
Per Åhgrenf204faf2019-04-25 15:18:06 +02001098 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1099 // The data queue is full and needs to be emptied.
1100 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001101
Per Åhgrenf204faf2019-04-25 15:18:06 +02001102 // Retry the insert (should always work).
1103 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1104 RTC_DCHECK(result);
1105 }
peaha0624602016-10-25 04:45:24 -07001106 }
1107
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001108 if (private_submodules_->echo_control_mobile) {
1109 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1110 num_reverse_channels(),
1111 &aecm_render_queue_buffer_);
1112 RTC_DCHECK(aecm_render_signal_queue_);
1113 // Insert the samples into the queue.
1114 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1115 // The data queue is full and needs to be emptied.
1116 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001117
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001118 // Retry the insert (should always work).
1119 bool result =
1120 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1121 RTC_DCHECK(result);
1122 }
peah764e3642016-10-22 05:04:30 -07001123 }
peah701d6282016-10-25 05:42:20 -07001124
1125 if (!constants_.use_experimental_agc) {
1126 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
1127 // Insert the samples into the queue.
1128 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1129 // The data queue is full and needs to be emptied.
1130 EmptyQueuedRenderAudio();
1131
1132 // Retry the insert (should always work).
1133 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1134 RTC_DCHECK(result);
1135 }
1136 }
peah9e6a2902017-05-15 07:19:21 -07001137}
ivoc9f4a4a02016-10-28 05:39:16 -07001138
peah9e6a2902017-05-15 07:19:21 -07001139void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001140 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1141
1142 // Insert the samples into the queue.
1143 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1144 // The data queue is full and needs to be emptied.
1145 EmptyQueuedRenderAudio();
1146
1147 // Retry the insert (should always work).
1148 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1149 RTC_DCHECK(result);
1150 }
peah764e3642016-10-22 05:04:30 -07001151}
1152
1153void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001154 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001155 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001156
ivoc9f4a4a02016-10-28 05:39:16 -07001157 const size_t new_red_render_queue_element_max_size =
1158 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1159
peaha0624602016-10-25 04:45:24 -07001160 // Reallocate the queues if the queue item sizes are too small to fit the
1161 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001162
1163 if (agc_render_queue_element_max_size_ <
1164 new_agc_render_queue_element_max_size) {
1165 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1166
1167 std::vector<int16_t> template_queue_element(
1168 agc_render_queue_element_max_size_);
1169
1170 agc_render_signal_queue_.reset(
1171 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1172 kMaxNumFramesToBuffer, template_queue_element,
1173 RenderQueueItemVerifier<int16_t>(
1174 agc_render_queue_element_max_size_)));
1175
1176 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1177 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1178 } else {
1179 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001180 }
ivoc9f4a4a02016-10-28 05:39:16 -07001181
1182 if (red_render_queue_element_max_size_ <
1183 new_red_render_queue_element_max_size) {
1184 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1185
1186 std::vector<float> template_queue_element(
1187 red_render_queue_element_max_size_);
1188
1189 red_render_signal_queue_.reset(
1190 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1191 kMaxNumFramesToBuffer, template_queue_element,
1192 RenderQueueItemVerifier<float>(
1193 red_render_queue_element_max_size_)));
1194
1195 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1196 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1197 } else {
1198 red_render_signal_queue_->Clear();
1199 }
peah764e3642016-10-22 05:04:30 -07001200}
1201
1202void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1203 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001204 if (private_submodules_->echo_cancellation) {
1205 RTC_DCHECK(aec_render_signal_queue_);
1206 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
1207 private_submodules_->echo_cancellation->ProcessRenderAudio(
1208 aec_capture_queue_buffer_);
1209 }
peaha0624602016-10-25 04:45:24 -07001210 }
1211
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001212 if (private_submodules_->echo_control_mobile) {
1213 RTC_DCHECK(aecm_render_signal_queue_);
1214 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
1215 private_submodules_->echo_control_mobile->ProcessRenderAudio(
1216 aecm_capture_queue_buffer_);
1217 }
peah701d6282016-10-25 05:42:20 -07001218 }
1219
1220 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1221 public_submodules_->gain_control->ProcessRenderAudio(
1222 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001223 }
ivoc9f4a4a02016-10-28 05:39:16 -07001224
1225 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001226 RTC_DCHECK(private_submodules_->echo_detector);
1227 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001228 red_capture_queue_buffer_);
1229 }
peah764e3642016-10-22 05:04:30 -07001230}
1231
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001232int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001233 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001234 {
1235 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001236 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001237 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001238 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001239 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001240 }
peahfa6228e2015-11-16 16:27:42 -08001241
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001242 if (!frame) {
1243 return kNullPointerError;
1244 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001245 // Must be a native rate.
1246 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1247 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001248 frame->sample_rate_hz_ != kSampleRate32kHz &&
1249 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001250 return kBadSampleRateError;
1251 }
peah192164e2015-11-17 02:16:45 -08001252
peahdf3efa82015-11-28 12:35:15 -08001253 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001254 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001255 {
1256 // Aquire lock for the access of api_format.
1257 // The lock is released immediately due to the conditional
1258 // reinitialization.
1259 rtc::CritScope cs_capture(&crit_capture_);
1260 // TODO(ajm): The input and output rates and channels are currently
1261 // constrained to be identical in the int16 interface.
1262 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001263
1264 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001265 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001266
Oskar Sundbom4b276482019-05-23 14:28:00 +02001267 reinitialization_required =
1268 reinitialization_required ||
1269 processing_config.input_stream().sample_rate_hz() !=
1270 frame->sample_rate_hz_ ||
1271 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1272 processing_config.output_stream().sample_rate_hz() !=
1273 frame->sample_rate_hz_ ||
1274 processing_config.output_stream().num_channels() != frame->num_channels_;
1275
1276 if (reinitialization_required) {
1277 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1278 processing_config.input_stream().set_num_channels(frame->num_channels_);
1279 processing_config.output_stream().set_sample_rate_hz(
1280 frame->sample_rate_hz_);
1281 processing_config.output_stream().set_num_channels(frame->num_channels_);
1282
1283 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001284 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001285 rtc::CritScope cs_capture(&crit_capture_);
1286 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001287 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001288
peahdf3efa82015-11-28 12:35:15 -08001289 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001290 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001291 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001292 return kBadDataLengthError;
1293 }
1294
aleloi868f32f2017-05-23 07:20:05 -07001295 if (aec_dump_) {
1296 RecordUnprocessedCaptureStream(*frame);
1297 }
1298
Per Åhgrend47941e2019-08-22 11:51:13 +02001299 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001300 if (capture_.capture_fullband_audio) {
1301 capture_.capture_fullband_audio->CopyFrom(frame);
1302 }
peahde65ddc2016-09-16 15:02:15 -07001303 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001304 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001305 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001306 if (capture_.capture_fullband_audio) {
1307 capture_.capture_fullband_audio->CopyTo(frame);
1308 } else {
1309 capture_.capture_audio->CopyTo(frame);
1310 }
Per Åhgrena1351272019-08-15 12:15:46 +02001311 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001312 if (capture_.stats.voice_detected) {
1313 frame->vad_activity_ = *capture_.stats.voice_detected
1314 ? AudioFrame::kVadActive
1315 : AudioFrame::kVadPassive;
1316 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001317
aleloi868f32f2017-05-23 07:20:05 -07001318 if (aec_dump_) {
1319 RecordProcessedCaptureStream(*frame);
1320 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001321
1322 return kNoError;
1323}
1324
peahde65ddc2016-09-16 15:02:15 -07001325int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001326 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001327
peahb58a1582016-03-15 09:34:24 -07001328 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001329 // TODO(peah): Simplify once the public API Enable functions for these
1330 // are moved to APM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001331 RTC_DCHECK_LE(!!private_submodules_->echo_controller +
1332 !!private_submodules_->echo_cancellation +
1333 !!private_submodules_->echo_control_mobile,
1334 1);
peahb58a1582016-03-15 09:34:24 -07001335
peahde65ddc2016-09-16 15:02:15 -07001336 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001337
Alex Loikob5c9a792018-04-16 16:31:22 +02001338 if (private_submodules_->pre_amplifier) {
1339 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001340 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001341 capture_buffer->num_frames()));
1342 }
1343
Per Åhgren928146f2019-08-20 09:19:21 +02001344 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001345 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001346 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001347 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1348 if (log_rms) {
1349 capture_rms_interval_counter_ = 0;
1350 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001351 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1352 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1353 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1354 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001355 }
1356
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001357 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001358 // Detect and flag any change in the analog gain.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001359 int analog_mic_level = agc1()->stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001360 capture_.echo_path_gain_change =
1361 capture_.prev_analog_mic_level != analog_mic_level &&
1362 capture_.prev_analog_mic_level != -1;
1363 capture_.prev_analog_mic_level = analog_mic_level;
1364
Per Åhgrend2650d12018-10-02 17:00:59 +02001365 // Detect and flag any change in the pre-amplifier gain.
1366 if (private_submodules_->pre_amplifier) {
1367 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1368 capture_.echo_path_gain_change =
1369 capture_.echo_path_gain_change ||
1370 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001371 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001372 capture_.prev_pre_amp_gain = pre_amp_gain;
1373 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001374
1375 // Detect volume change.
1376 capture_.echo_path_gain_change =
1377 capture_.echo_path_gain_change ||
1378 (capture_.prev_playout_volume != capture_.playout_volume &&
1379 capture_.prev_playout_volume >= 0);
1380 capture_.prev_playout_volume = capture_.playout_volume;
1381
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001382 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001383 }
1384
peahbe615622016-02-13 16:40:47 -08001385 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001386 public_submodules_->gain_control->is_enabled()) {
1387 private_submodules_->agc_manager->AnalyzePreProcess(
Per Åhgren928146f2019-08-20 09:19:21 +02001388 capture_buffer->channels_f()[0], capture_buffer->num_channels(),
peahde65ddc2016-09-16 15:02:15 -07001389 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001390
1391 if (constants_.use_experimental_agc_process_before_aec) {
1392 private_submodules_->agc_manager->Process(
Per Åhgrend47941e2019-08-22 11:51:13 +02001393 capture_buffer->channels_const()[0],
Alex Loikod9342442018-09-10 13:59:41 +02001394 capture_nonlocked_.capture_processing_format.num_frames(),
1395 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1396 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001397 }
1398
peah2ace3f92016-09-10 04:42:27 -07001399 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1400 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001401 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1402 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001403 }
1404
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001405 const bool experimental_multi_channel_capture =
1406 config_.pipeline.experimental_multi_channel &&
1407 constants_.experimental_multi_channel_capture_support;
1408 if (private_submodules_->echo_controller &&
1409 !experimental_multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001410 // Force down-mixing of the number of channels after the detection of
1411 // capture signal saturation.
1412 // TODO(peah): Look into ensuring that this kind of tampering with the
1413 // AudioBuffer functionality should not be needed.
1414 capture_buffer->set_num_channels(1);
1415 }
1416
Per Åhgren0aefbf02019-08-23 21:29:17 +02001417 if (private_submodules_->high_pass_filter) {
1418 private_submodules_->high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001419 }
peahde65ddc2016-09-16 15:02:15 -07001420 RETURN_ON_ERR(
1421 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1422 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001423
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001424 if (private_submodules_->echo_control_mobile) {
1425 // Ensure that the stream delay was set before the call to the
1426 // AECM ProcessCaptureAudio function.
1427 if (!was_stream_delay_set()) {
1428 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001429 }
1430
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001431 if (public_submodules_->noise_suppression->is_enabled()) {
Per Åhgrena1351272019-08-15 12:15:46 +02001432 private_submodules_->echo_control_mobile->CopyLowPassReference(
1433 capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001434 }
peahe0eae3c2016-12-14 01:16:23 -08001435
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001436 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001437
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001438 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001439 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001440 } else {
1441 if (private_submodules_->echo_controller) {
1442 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1443
1444 if (was_stream_delay_set()) {
1445 private_submodules_->echo_controller->SetAudioBufferDelay(
1446 stream_delay_ms());
1447 }
1448
1449 private_submodules_->echo_controller->ProcessCapture(
1450 capture_buffer, capture_.echo_path_gain_change);
1451 } else if (private_submodules_->echo_cancellation) {
1452 // Ensure that the stream delay was set before the call to the
1453 // AEC ProcessCaptureAudio function.
1454 if (!was_stream_delay_set()) {
1455 return AudioProcessing::kStreamParameterNotSetError;
1456 }
1457
1458 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
1459 capture_buffer, stream_delay_ms()));
1460 }
1461
1462 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
Per Åhgren46537a32017-06-07 10:08:10 +02001463 }
ivoc9f4a4a02016-10-28 05:39:16 -07001464
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001465 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001466 capture_.stats.voice_detected =
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001467 private_submodules_->voice_detector->ProcessCaptureAudio(
1468 capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001469 } else {
1470 capture_.stats.voice_detected = absl::nullopt;
1471 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001472
peahbe615622016-02-13 16:40:47 -08001473 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001474 public_submodules_->gain_control->is_enabled() &&
1475 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001476 private_submodules_->agc_manager->Process(
Per Åhgren928146f2019-08-20 09:19:21 +02001477 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
peahde65ddc2016-09-16 15:02:15 -07001478 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001479 }
Per Åhgren200feba2019-03-06 04:16:46 +01001480 // TODO(peah): Add reporting from AEC3 whether there is echo.
peahb8fbb542016-03-15 02:28:08 -07001481 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001482 capture_buffer,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001483 private_submodules_->echo_cancellation &&
1484 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001485
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001486 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001487 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001488 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1489 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001490 }
1491
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001492 if (capture_.capture_fullband_audio) {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001493 const auto& ec = private_submodules_->echo_controller;
1494 bool ec_active = ec ? ec->ActiveProcessing() : false;
1495 // Only update the fullband buffer if the multiband processing has changed
1496 // the signal. Keep the original signal otherwise.
1497 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1498 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1499 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001500 capture_buffer = capture_.capture_fullband_audio.get();
1501 }
1502
peah9e6a2902017-05-15 07:19:21 -07001503 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001504 RTC_DCHECK(private_submodules_->echo_detector);
1505 private_submodules_->echo_detector->AnalyzeCaptureAudio(
Per Åhgrend47941e2019-08-22 11:51:13 +02001506 rtc::ArrayView<const float>(capture_buffer->channels()[0],
peah9e6a2902017-05-15 07:19:21 -07001507 capture_buffer->num_frames()));
1508 }
1509
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001510 // TODO(aluebs): Investigate if the transient suppression placement should be
1511 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001512 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001513 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001514 private_submodules_->agc_manager.get()
1515 ? private_submodules_->agc_manager->voice_probability()
1516 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001517
peahdf3efa82015-11-28 12:35:15 -08001518 public_submodules_->transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001519 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001520 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001521 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001522 capture_buffer->num_frames_per_band(),
1523 capture_.keyboard_info.keyboard_data,
1524 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001525 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001526 }
1527
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001528 // Experimental APM sub-module that analyzes |capture_buffer|.
1529 if (private_submodules_->capture_analyzer) {
1530 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1531 }
1532
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001533 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001534 private_submodules_->gain_controller2->NotifyAnalogLevel(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001535 agc1()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001536 private_submodules_->gain_controller2->Process(capture_buffer);
1537 }
1538
Sam Zackrisson0beac582017-09-25 12:04:02 +02001539 if (private_submodules_->capture_post_processor) {
1540 private_submodules_->capture_post_processor->Process(capture_buffer);
1541 }
1542
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001543 // The level estimator operates on the recombined data.
Per Åhgrend47941e2019-08-22 11:51:13 +02001544 public_submodules_->level_estimator->ProcessStream(*capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001545 if (config_.level_estimation.enabled) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001546 private_submodules_->output_level_estimator->ProcessStream(*capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001547 capture_.stats.output_rms_dbfs =
1548 private_submodules_->output_level_estimator->RMS();
1549 } else {
1550 capture_.stats.output_rms_dbfs = absl::nullopt;
1551 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001552
Per Åhgren928146f2019-08-20 09:19:21 +02001553 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001554 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001555 capture_nonlocked_.capture_processing_format.num_frames()));
1556 if (log_rms) {
1557 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1558 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1559 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1560 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1561 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1562 }
1563
peahdf3efa82015-11-28 12:35:15 -08001564 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001565 return kNoError;
1566}
1567
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001568int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001569 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001570 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001571 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001572 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001573 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001574 const StreamConfig reverse_config = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001575 sample_rate_hz,
1576 ChannelsFromLayout(layout),
1577 LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001578 };
1579 if (samples_per_channel != reverse_config.num_frames()) {
1580 return kBadDataLengthError;
1581 }
peahdf3efa82015-11-28 12:35:15 -08001582 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001583}
1584
peahde65ddc2016-09-16 15:02:15 -07001585int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1586 const StreamConfig& input_config,
1587 const StreamConfig& output_config,
1588 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001589 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001590 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001591 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001592 if (submodule_states_.RenderMultiBandProcessingActive() ||
1593 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001594 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1595 dest);
peah2ace3f92016-09-10 04:42:27 -07001596 } else if (formats_.api_format.reverse_input_stream() !=
1597 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001598 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1599 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001600 } else {
peahde65ddc2016-09-16 15:02:15 -07001601 CopyAudioIfNeeded(src, input_config.num_frames(),
1602 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001603 }
1604
1605 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001606}
1607
peahdf3efa82015-11-28 12:35:15 -08001608int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001609 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001610 const StreamConfig& input_config,
1611 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001612 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001613 return kNullPointerError;
1614 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001615
peahde65ddc2016-09-16 15:02:15 -07001616 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001617 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001618 }
1619
peahdf3efa82015-11-28 12:35:15 -08001620 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001621 processing_config.reverse_input_stream() = input_config;
1622 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001623
peahdf3efa82015-11-28 12:35:15 -08001624 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001625 RTC_DCHECK_EQ(input_config.num_frames(),
1626 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001627
aleloi868f32f2017-05-23 07:20:05 -07001628 if (aec_dump_) {
1629 const size_t channel_size =
1630 formats_.api_format.reverse_input_stream().num_frames();
1631 const size_t num_channels =
1632 formats_.api_format.reverse_input_stream().num_channels();
1633 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001634 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001635 }
peahdf3efa82015-11-28 12:35:15 -08001636 render_.render_audio->CopyFrom(src,
1637 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001638 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001639}
1640
1641int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001642 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001643 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001644 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001645 return kNullPointerError;
1646 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001647 // Must be a native rate.
1648 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1649 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001650 frame->sample_rate_hz_ != kSampleRate32kHz &&
1651 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001652 return kBadSampleRateError;
1653 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001654
Michael Graczyk86c6d332015-07-23 11:41:39 -07001655 if (frame->num_channels_ <= 0) {
1656 return kBadNumberChannelsError;
1657 }
1658
peahdf3efa82015-11-28 12:35:15 -08001659 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001660 processing_config.reverse_input_stream().set_sample_rate_hz(
1661 frame->sample_rate_hz_);
1662 processing_config.reverse_input_stream().set_num_channels(
1663 frame->num_channels_);
1664 processing_config.reverse_output_stream().set_sample_rate_hz(
1665 frame->sample_rate_hz_);
1666 processing_config.reverse_output_stream().set_num_channels(
1667 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001668
peahdf3efa82015-11-28 12:35:15 -08001669 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001670 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001671 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001672 return kBadDataLengthError;
1673 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001674
aleloi868f32f2017-05-23 07:20:05 -07001675 if (aec_dump_) {
1676 aec_dump_->WriteRenderStreamMessage(*frame);
1677 }
1678
Per Åhgrend47941e2019-08-22 11:51:13 +02001679 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001680 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001681 if (submodule_states_.RenderMultiBandProcessingActive() ||
1682 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001683 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001684 }
aluebsb0319552016-03-17 20:39:53 -07001685 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001686}
niklase@google.com470e71d2011-07-07 08:21:25 +00001687
peahde65ddc2016-09-16 15:02:15 -07001688int AudioProcessingImpl::ProcessRenderStreamLocked() {
1689 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001690
Alex Loiko73ec0192018-05-15 10:52:28 +02001691 HandleRenderRuntimeSettings();
1692
Alex Loiko5825aa62017-12-18 16:02:40 +01001693 if (private_submodules_->render_pre_processor) {
1694 private_submodules_->render_pre_processor->Process(render_buffer);
1695 }
1696
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001697 QueueNonbandedRenderAudio(render_buffer);
1698
peah2ace3f92016-09-10 04:42:27 -07001699 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001700 SampleRateSupportsMultiBand(
1701 formats_.render_processing_format.sample_rate_hz())) {
1702 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001703 }
1704
peahce4d9152017-05-19 01:28:05 -07001705 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1706 QueueBandedRenderAudio(render_buffer);
1707 }
1708
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001709 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001710 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001711 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001712 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001713
peah2ace3f92016-09-10 04:42:27 -07001714 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001715 SampleRateSupportsMultiBand(
1716 formats_.render_processing_format.sample_rate_hz())) {
1717 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001718 }
1719
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001720 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001721}
1722
1723int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001724 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001725 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001726 capture_.was_stream_delay_set = true;
1727 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001728
niklase@google.com470e71d2011-07-07 08:21:25 +00001729 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001730 delay = 0;
1731 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001732 }
1733
1734 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1735 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001736 delay = 500;
1737 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001738 }
1739
peahdf3efa82015-11-28 12:35:15 -08001740 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001741 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
1744int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001745 // Used as callback from submodules, hence locking is not allowed.
1746 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001747}
1748
1749bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001750 // Used as callback from submodules, hence locking is not allowed.
1751 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001752}
1753
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001754void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001755 rtc::CritScope cs(&crit_capture_);
1756 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001757}
1758
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001759void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001760 rtc::CritScope cs(&crit_capture_);
1761 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001762}
1763
1764int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001765 rtc::CritScope cs(&crit_capture_);
1766 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001767}
1768
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001769void AudioProcessingImpl::set_stream_analog_level(int level) {
1770 rtc::CritScope cs_capture(&crit_capture_);
1771 int error = agc1()->set_stream_analog_level(level);
1772 RTC_DCHECK_EQ(kNoError, error);
1773}
1774
1775int AudioProcessingImpl::recommended_stream_analog_level() const {
1776 rtc::CritScope cs_capture(&crit_capture_);
1777 return agc1()->stream_analog_level();
1778}
1779
aleloi868f32f2017-05-23 07:20:05 -07001780void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1781 RTC_DCHECK(aec_dump);
1782 rtc::CritScope cs_render(&crit_render_);
1783 rtc::CritScope cs_capture(&crit_capture_);
1784
1785 // The previously attached AecDump will be destroyed with the
1786 // 'aec_dump' parameter, which is after locks are released.
1787 aec_dump_.swap(aec_dump);
1788 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001789 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001790}
1791
1792void AudioProcessingImpl::DetachAecDump() {
1793 // The d-tor of a task-queue based AecDump blocks until all pending
1794 // tasks are done. This construction avoids blocking while holding
1795 // the render and capture locks.
1796 std::unique_ptr<AecDump> aec_dump = nullptr;
1797 {
1798 rtc::CritScope cs_render(&crit_render_);
1799 rtc::CritScope cs_capture(&crit_capture_);
1800 aec_dump = std::move(aec_dump_);
1801 }
1802}
1803
Sam Zackrisson4d364492018-03-02 16:03:21 +01001804void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1805 std::unique_ptr<AudioGenerator> audio_generator) {
1806 // TODO(bugs.webrtc.org/8882) Stub.
1807 // Reset internal audio generator with audio_generator.
1808}
1809
1810void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1811 // TODO(bugs.webrtc.org/8882) Stub.
1812 // Delete audio generator, if one is attached.
1813}
1814
Ivo Creusen56d46092017-11-24 17:29:59 +01001815AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001816 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001817 rtc::CritScope cs_capture(&crit_capture_);
1818 if (!has_remote_tracks) {
1819 return capture_.stats;
1820 }
1821 AudioProcessingStats stats = capture_.stats;
1822 EchoCancellationImpl::Metrics metrics;
1823 if (private_submodules_->echo_controller) {
1824 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1825 stats.echo_return_loss = ec_metrics.echo_return_loss;
1826 stats.echo_return_loss_enhancement =
1827 ec_metrics.echo_return_loss_enhancement;
1828 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001829 }
1830 if (config_.residual_echo_detector.enabled) {
1831 RTC_DCHECK(private_submodules_->echo_detector);
1832 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1833 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1834 stats.residual_echo_likelihood_recent_max =
1835 ed_metrics.echo_likelihood_recent_max;
1836 }
Ivo Creusenae026092017-11-20 13:07:16 +01001837 return stats;
1838}
1839
niklase@google.com470e71d2011-07-07 08:21:25 +00001840GainControl* AudioProcessingImpl::gain_control() const {
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001841 return public_submodules_->gain_control_config_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001842}
1843
niklase@google.com470e71d2011-07-07 08:21:25 +00001844LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001845 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001846}
1847
1848NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001849 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001850}
1851
peah8271d042016-11-22 07:24:52 -08001852void AudioProcessingImpl::MutateConfig(
1853 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1854 rtc::CritScope cs_render(&crit_render_);
1855 rtc::CritScope cs_capture(&crit_capture_);
1856 mutator(&config_);
1857 ApplyConfig(config_);
1858}
1859
1860AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1861 rtc::CritScope cs_render(&crit_render_);
1862 rtc::CritScope cs_capture(&crit_capture_);
1863 return config_;
1864}
1865
peah2ace3f92016-09-10 04:42:27 -07001866bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1867 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001868 config_.high_pass_filter.enabled,
Per Åhgrend547d862019-05-03 15:48:47 +02001869 !!private_submodules_->echo_cancellation,
1870 !!private_submodules_->echo_control_mobile,
ivoc9f4a4a02016-10-28 05:39:16 -07001871 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001872 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001873 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001874 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001875 capture_nonlocked_.echo_controller_enabled,
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001876 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001877 public_submodules_->level_estimator->is_enabled(),
1878 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001879}
1880
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001881void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001882 if (capture_.transient_suppressor_enabled) {
1883 if (!public_submodules_->transient_suppressor.get()) {
1884 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001885 }
peahdf3efa82015-11-28 12:35:15 -08001886 public_submodules_->transient_suppressor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001887 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1888 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001889 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001890}
1891
Per Åhgren0aefbf02019-08-23 21:29:17 +02001892void AudioProcessingImpl::InitializeHighPassFilter() {
1893 if (submodule_states_.HighPassFilteringRequired()) {
1894 private_submodules_->high_pass_filter.reset(
1895 new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001896 } else {
Per Åhgren0aefbf02019-08-23 21:29:17 +02001897 private_submodules_->high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001898 }
1899}
alessiob3ec96df2017-05-22 06:57:06 -07001900
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001901void AudioProcessingImpl::InitializeVoiceDetector() {
1902 if (config_.voice_detection.enabled) {
1903 private_submodules_->voice_detector = std::make_unique<VoiceDetection>(
1904 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1905 } else {
1906 private_submodules_->voice_detector.reset();
1907 }
1908}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001909void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001910 bool use_echo_controller =
1911 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001912 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001913 !config_.echo_canceller.use_legacy_aec);
1914
1915 if (use_echo_controller) {
1916 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001917 if (echo_control_factory_) {
1918 private_submodules_->echo_controller =
1919 echo_control_factory_->Create(proc_sample_rate_hz());
1920 } else {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001921 private_submodules_->echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001922 EchoCanceller3Config(), proc_sample_rate_hz(), num_reverse_channels(),
1923 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001924 }
1925
1926 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001927
Per Åhgrenf204faf2019-04-25 15:18:06 +02001928 private_submodules_->echo_cancellation.reset();
1929 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001930 private_submodules_->echo_control_mobile.reset();
1931 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001932 return;
peahe0eae3c2016-12-14 01:16:23 -08001933 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001934
1935 private_submodules_->echo_controller.reset();
1936 capture_nonlocked_.echo_controller_enabled = false;
1937
1938 if (!config_.echo_canceller.enabled) {
1939 private_submodules_->echo_cancellation.reset();
1940 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001941 private_submodules_->echo_control_mobile.reset();
1942 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001943 return;
1944 }
1945
1946 if (config_.echo_canceller.mobile_mode) {
1947 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001948 size_t max_element_size =
1949 std::max(static_cast<size_t>(1),
1950 kMaxAllowedValuesOfSamplesPerBand *
1951 EchoControlMobileImpl::NumCancellersRequired(
1952 num_output_channels(), num_reverse_channels()));
1953
1954 std::vector<int16_t> template_queue_element(max_element_size);
1955
1956 aecm_render_signal_queue_.reset(
1957 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1958 kMaxNumFramesToBuffer, template_queue_element,
1959 RenderQueueItemVerifier<int16_t>(max_element_size)));
1960
1961 aecm_render_queue_buffer_.resize(max_element_size);
1962 aecm_capture_queue_buffer_.resize(max_element_size);
1963
1964 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
1965
1966 private_submodules_->echo_control_mobile->Initialize(
1967 proc_split_sample_rate_hz(), num_reverse_channels(),
1968 num_output_channels());
1969
Per Åhgrenf204faf2019-04-25 15:18:06 +02001970 private_submodules_->echo_cancellation.reset();
1971 aec_render_signal_queue_.reset();
1972 return;
1973 }
1974
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001975 private_submodules_->echo_control_mobile.reset();
1976 aecm_render_signal_queue_.reset();
1977
Per Åhgrenf204faf2019-04-25 15:18:06 +02001978 // Create and activate AEC2.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001979 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
1980 private_submodules_->echo_cancellation->SetExtraOptions(
1981 capture_nonlocked_.use_aec2_extended_filter,
1982 capture_nonlocked_.use_aec2_delay_agnostic,
1983 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1984
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001985 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001986 std::max(static_cast<size_t>(1),
1987 kMaxAllowedValuesOfSamplesPerBand *
1988 EchoCancellationImpl::NumCancellersRequired(
1989 num_output_channels(), num_reverse_channels()));
1990
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001991 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001992
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001993 aec_render_signal_queue_.reset(
1994 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1995 kMaxNumFramesToBuffer, template_queue_element,
1996 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001997
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001998 aec_render_queue_buffer_.resize(element_max_size);
1999 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02002000
2001 private_submodules_->echo_cancellation->Initialize(
2002 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
2003 num_proc_channels());
2004
Per Åhgrenf204faf2019-04-25 15:18:06 +02002005 private_submodules_->echo_cancellation->set_suppression_level(
2006 config_.echo_canceller.legacy_moderate_suppression_level
2007 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
2008 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08002009}
peah8271d042016-11-22 07:24:52 -08002010
alessiob3ec96df2017-05-22 06:57:06 -07002011void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002012 if (config_.gain_controller2.enabled) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002013 private_submodules_->gain_controller2->Initialize(
2014 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002015 }
2016}
2017
Alex Loikob5c9a792018-04-16 16:31:22 +02002018void AudioProcessingImpl::InitializePreAmplifier() {
2019 if (config_.pre_amplifier.enabled) {
2020 private_submodules_->pre_amplifier.reset(
2021 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
2022 } else {
2023 private_submodules_->pre_amplifier.reset();
2024 }
2025}
2026
ivoc9f4a4a02016-10-28 05:39:16 -07002027void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01002028 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01002029 private_submodules_->echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002030 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02002031 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07002032}
2033
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002034void AudioProcessingImpl::InitializeAnalyzer() {
2035 if (private_submodules_->capture_analyzer) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002036 private_submodules_->capture_analyzer->Initialize(
2037 proc_fullband_sample_rate_hz(), num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002038 }
2039}
2040
Sam Zackrisson0beac582017-09-25 12:04:02 +02002041void AudioProcessingImpl::InitializePostProcessor() {
2042 if (private_submodules_->capture_post_processor) {
2043 private_submodules_->capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002044 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002045 }
2046}
2047
Alex Loiko5825aa62017-12-18 16:02:40 +01002048void AudioProcessingImpl::InitializePreProcessor() {
2049 if (private_submodules_->render_pre_processor) {
2050 private_submodules_->render_pre_processor->Initialize(
2051 formats_.render_processing_format.sample_rate_hz(),
2052 formats_.render_processing_format.num_channels());
2053 }
2054}
2055
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002056void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002057
aleloi868f32f2017-05-23 07:20:05 -07002058void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2059 if (!aec_dump_) {
2060 return;
2061 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002062
2063 std::string experiments_description = "";
2064 if (private_submodules_->echo_cancellation) {
2065 experiments_description +=
2066 private_submodules_->echo_cancellation->GetExperimentsDescription();
2067 }
aleloi868f32f2017-05-23 07:20:05 -07002068 // TODO(peah): Add semicolon-separated concatenations of experiment
2069 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002070 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2071 experiments_description += "AgcClippingLevelExperiment;";
2072 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002073 if (capture_nonlocked_.echo_controller_enabled) {
2074 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002075 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002076 if (config_.gain_controller2.enabled) {
2077 experiments_description += "GainController2;";
2078 }
aleloi868f32f2017-05-23 07:20:05 -07002079
2080 InternalAPMConfig apm_config;
2081
Per Åhgren200feba2019-03-06 04:16:46 +01002082 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002083 apm_config.aec_delay_agnostic_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002084 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002085 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002086 apm_config.aec_drift_compensation_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002087 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002088 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002089 apm_config.aec_extended_filter_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002090 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002091 private_submodules_->echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002092 apm_config.aec_suppression_level =
2093 private_submodules_->echo_cancellation
2094 ? static_cast<int>(
2095 private_submodules_->echo_cancellation->suppression_level())
2096 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002097
Per Åhgrend547d862019-05-03 15:48:47 +02002098 apm_config.aecm_enabled = !!private_submodules_->echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002099 apm_config.aecm_comfort_noise_enabled =
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002100 private_submodules_->echo_control_mobile &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002101 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002102 apm_config.aecm_routing_mode =
2103 private_submodules_->echo_control_mobile
2104 ? static_cast<int>(
2105 private_submodules_->echo_control_mobile->routing_mode())
2106 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002107
2108 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2109 apm_config.agc_mode =
2110 static_cast<int>(public_submodules_->gain_control->mode());
2111 apm_config.agc_limiter_enabled =
2112 public_submodules_->gain_control->is_limiter_enabled();
2113 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2114
2115 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2116
2117 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2118 apm_config.ns_level =
2119 static_cast<int>(public_submodules_->noise_suppression->level());
2120
2121 apm_config.transient_suppression_enabled =
2122 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002123 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002124 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2125 apm_config.pre_amplifier_fixed_gain_factor =
2126 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002127
2128 if (!forced && apm_config == apm_config_for_aec_dump_) {
2129 return;
2130 }
2131 aec_dump_->WriteConfig(apm_config);
2132 apm_config_for_aec_dump_ = apm_config;
2133}
2134
2135void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2136 const float* const* src) {
2137 RTC_DCHECK(aec_dump_);
2138 WriteAecDumpConfigMessage(false);
2139
2140 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2141 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2142 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002143 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002144 RecordAudioProcessingState();
2145}
2146
2147void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2148 const AudioFrame& capture_frame) {
2149 RTC_DCHECK(aec_dump_);
2150 WriteAecDumpConfigMessage(false);
2151
2152 aec_dump_->AddCaptureStreamInput(capture_frame);
2153 RecordAudioProcessingState();
2154}
2155
2156void AudioProcessingImpl::RecordProcessedCaptureStream(
2157 const float* const* processed_capture_stream) {
2158 RTC_DCHECK(aec_dump_);
2159
2160 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2161 const size_t num_channels =
2162 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002163 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2164 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002165 aec_dump_->WriteCaptureStreamMessage();
2166}
2167
2168void AudioProcessingImpl::RecordProcessedCaptureStream(
2169 const AudioFrame& processed_capture_frame) {
2170 RTC_DCHECK(aec_dump_);
2171
2172 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2173 aec_dump_->WriteCaptureStreamMessage();
2174}
2175
2176void AudioProcessingImpl::RecordAudioProcessingState() {
2177 RTC_DCHECK(aec_dump_);
2178 AecDump::AudioProcessingState audio_proc_state;
2179 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2180 audio_proc_state.drift =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002181 private_submodules_->echo_cancellation
2182 ? private_submodules_->echo_cancellation->stream_drift_samples()
2183 : 0;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002184 audio_proc_state.level = agc1()->stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002185 audio_proc_state.keypress = capture_.key_pressed;
2186 aec_dump_->AddAudioProcessingState(audio_proc_state);
2187}
2188
kwiberg83ffe452016-08-29 14:46:07 -07002189AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002190 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002191 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002192 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002193 output_will_be_muted(false),
2194 key_pressed(false),
2195 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002196 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002197 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002198 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002199 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002200 prev_pre_amp_gain(-1.f),
2201 playout_volume(-1),
2202 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002203
2204AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2205
Per Åhgrena1351272019-08-15 12:15:46 +02002206void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2207 const float* const* data,
2208 const StreamConfig& stream_config) {
2209 if (stream_config.has_keyboard()) {
2210 keyboard_data = data[stream_config.num_channels()];
2211 } else {
2212 keyboard_data = NULL;
2213 }
2214 num_keyboard_frames = stream_config.num_frames();
2215}
2216
kwiberg83ffe452016-08-29 14:46:07 -07002217AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2218
2219AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2220
niklase@google.com470e71d2011-07-07 08:21:25 +00002221} // namespace webrtc