blob: 0582eceb5e029a7a1bea7cdc3ecc46d2e69463aa [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"
saza6787f232019-10-11 19:31:07 +020037#include "modules/audio_processing/level_estimator.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 transient_suppressor_enabled) {
170 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200171 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700172 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
173 changed |=
174 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700175 changed |=
176 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700177 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
178 changed |=
peah2ace3f92016-09-10 04:42:27 -0700179 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200180 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200181 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200182 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200183 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700184 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
185 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200186 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700187 echo_canceller_enabled_ = echo_canceller_enabled;
188 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700189 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700190 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700191 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700192 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200193 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200194 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200195 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700196 transient_suppressor_enabled_ = transient_suppressor_enabled;
197 }
198
199 changed |= first_update_;
200 first_update_ = false;
201 return changed;
202}
203
204bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
205 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200206 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700207}
208
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200209bool AudioProcessingImpl::ApmSubmoduleStates::
210 CaptureMultiBandProcessingPresent() const {
211 // If echo controller is present, assume it performs active processing.
212 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
213}
214
215bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive(
216 bool ec_processing_active) const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200217 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700218 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200219 adaptive_gain_controller_enabled_ ||
220 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700221}
222
peah23ac8b42017-05-23 05:33:56 -0700223bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
224 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200225 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
226 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700227}
228
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200229bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
230 return capture_analyzer_enabled_;
231}
232
peah2ace3f92016-09-10 04:42:27 -0700233bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
234 const {
235 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800236 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200237 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700238}
239
Alex Loiko5825aa62017-12-18 16:02:40 +0100240bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
241 const {
242 return render_pre_processor_enabled_;
243}
244
peah2ace3f92016-09-10 04:42:27 -0700245bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
246 const {
peah2ace3f92016-09-10 04:42:27 -0700247 return false;
peah2ace3f92016-09-10 04:42:27 -0700248}
249
Per Åhgren0aefbf02019-08-23 21:29:17 +0200250bool AudioProcessingImpl::ApmSubmoduleStates::HighPassFilteringRequired()
251 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200252 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
253 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
254}
255
solenberg5e465c32015-12-08 13:22:33 -0800256struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800257 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800258 // Accessed externally of APM without any lock acquired.
Sam Zackrisson23513132019-01-11 15:10:32 +0100259 // TODO(bugs.webrtc.org/9947): Move these submodules into private_submodules_
260 // when their pointer-to-submodule API functions are gone.
kwiberg88788ad2016-02-19 07:04:49 -0800261 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
Sam Zackrisson23513132019-01-11 15:10:32 +0100262 std::unique_ptr<NoiseSuppressionProxy> noise_suppression_proxy;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100263 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800264 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800265 gain_control_for_experimental_agc;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100266 std::unique_ptr<GainControlConfigProxy> gain_control_config_proxy;
solenberg5e465c32015-12-08 13:22:33 -0800267
268 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800269 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800270};
271
272struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200273 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100274 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200275 rtc::scoped_refptr<EchoDetector> echo_detector,
276 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200277 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100278 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200279 render_pre_processor(std::move(render_pre_processor)),
280 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800281 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800282 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700283 std::unique_ptr<GainController2> gain_controller2;
Per Åhgren0aefbf02019-08-23 21:29:17 +0200284 std::unique_ptr<HighPassFilter> high_pass_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200285 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100286 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100287 std::unique_ptr<EchoControl> echo_controller;
288 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100289 std::unique_ptr<CustomProcessing> capture_post_processor;
290 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200291 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200292 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
saza6787f232019-10-11 19:31:07 +0200293 std::unique_ptr<LevelEstimator> output_level_estimator;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200294 std::unique_ptr<VoiceDetection> voice_detector;
solenberg5e465c32015-12-08 13:22:33 -0800295};
296
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100297AudioProcessingBuilder::AudioProcessingBuilder() = default;
298AudioProcessingBuilder::~AudioProcessingBuilder() = default;
299
300AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
301 std::unique_ptr<CustomProcessing> capture_post_processing) {
302 capture_post_processing_ = std::move(capture_post_processing);
303 return *this;
304}
305
306AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
307 std::unique_ptr<CustomProcessing> render_pre_processing) {
308 render_pre_processing_ = std::move(render_pre_processing);
309 return *this;
310}
311
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200312AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
313 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
314 capture_analyzer_ = std::move(capture_analyzer);
315 return *this;
316}
317
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100318AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
319 std::unique_ptr<EchoControlFactory> echo_control_factory) {
320 echo_control_factory_ = std::move(echo_control_factory);
321 return *this;
322}
323
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100324AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200325 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100326 echo_detector_ = std::move(echo_detector);
327 return *this;
328}
329
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100330AudioProcessing* AudioProcessingBuilder::Create() {
331 webrtc::Config config;
332 return Create(config);
333}
334
335AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100336 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
337 config, std::move(capture_post_processing_),
338 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200339 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100340 if (apm->Initialize() != AudioProcessing::kNoError) {
341 delete apm;
342 apm = nullptr;
343 }
344 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100345}
346
peah88ac8532016-09-12 16:47:25 -0700347AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200348 : AudioProcessingImpl(config,
349 /*capture_post_processor=*/nullptr,
350 /*render_pre_processor=*/nullptr,
351 /*echo_control_factory=*/nullptr,
352 /*echo_detector=*/nullptr,
353 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000354
Per Åhgren13735822018-02-12 21:42:56 +0100355int AudioProcessingImpl::instance_count_ = 0;
356
Sam Zackrisson0beac582017-09-25 12:04:02 +0200357AudioProcessingImpl::AudioProcessingImpl(
358 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100359 std::unique_ptr<CustomProcessing> capture_post_processor,
360 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200361 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200362 rtc::scoped_refptr<EchoDetector> echo_detector,
363 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100364 : data_dumper_(
365 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200366 capture_runtime_settings_(kRuntimeSettingQueueSize),
367 render_runtime_settings_(kRuntimeSettingQueueSize),
368 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
369 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200370 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200371 submodule_states_(!!capture_post_processor,
372 !!render_pre_processor,
373 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800374 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200375 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200376 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100377 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200378 std::move(echo_detector),
379 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800380 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800381 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000382#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200383 /* enabled= */ false,
384 /* enabled_agc2_level_estimator= */ false,
385 /* digital_adaptive_disabled= */ false,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200386 /* analyze_before_aec= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000387#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200388 config.Get<ExperimentalAgc>().enabled,
389 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200390 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200391 config.Get<ExperimentalAgc>().analyze_before_aec,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000392#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200393 !field_trial::IsEnabled(
394 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
395 !field_trial::IsEnabled(
396 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700397#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200398 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700399#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200400 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700401#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200402 capture_nonlocked_() {
Sam Zackrisson421c8592019-02-11 13:39:46 +0100403 // Mark Echo Controller enabled if a factory is injected.
404 capture_nonlocked_.echo_controller_enabled =
405 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000406
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100407 public_submodules_->gain_control.reset(new GainControlImpl());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100408 public_submodules_->noise_suppression.reset(
409 new NoiseSuppressionImpl(&crit_capture_));
410 public_submodules_->noise_suppression_proxy.reset(new NoiseSuppressionProxy(
411 this, public_submodules_->noise_suppression.get()));
Sam Zackrisson421c8592019-02-11 13:39:46 +0100412 public_submodules_->gain_control_for_experimental_agc.reset(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100413 new GainControlForExperimentalAgc(
414 public_submodules_->gain_control.get()));
415 public_submodules_->gain_control_config_proxy.reset(
416 new GainControlConfigProxy(&crit_capture_, this, agc1()));
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200417
Sam Zackrisson421c8592019-02-11 13:39:46 +0100418 // If no echo detector is injected, use the ResidualEchoDetector.
419 if (!private_submodules_->echo_detector) {
420 private_submodules_->echo_detector =
421 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800422 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000423
Sam Zackrisson421c8592019-02-11 13:39:46 +0100424 // TODO(alessiob): Move the injected gain controller once injection is
425 // implemented.
426 private_submodules_->gain_controller2.reset(new GainController2());
427
428 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
429 << !!private_submodules_->capture_analyzer
430 << "\nCapture post processor activated: "
431 << !!private_submodules_->capture_post_processor
432 << "\nRender pre processor activated: "
433 << !!private_submodules_->render_pre_processor;
434
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000435 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000436}
437
438AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800439 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800440 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800441 private_submodules_->agc_manager.reset();
442 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800443 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000444}
445
niklase@google.com470e71d2011-07-07 08:21:25 +0000446int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800447 // Run in a single-threaded manner during initialization.
448 rtc::CritScope cs_render(&crit_render_);
449 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000450 return InitializeLocked();
451}
452
peahde65ddc2016-09-16 15:02:15 -0700453int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
454 int capture_output_sample_rate_hz,
455 int render_input_sample_rate_hz,
456 ChannelLayout capture_input_layout,
457 ChannelLayout capture_output_layout,
458 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700459 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700460 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
461 LayoutHasKeyboard(capture_input_layout)},
462 {capture_output_sample_rate_hz,
463 ChannelsFromLayout(capture_output_layout),
464 LayoutHasKeyboard(capture_output_layout)},
465 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
466 LayoutHasKeyboard(render_input_layout)},
467 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
468 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700469
470 return Initialize(processing_config);
471}
472
473int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800474 // Run in a single-threaded manner during initialization.
475 rtc::CritScope cs_render(&crit_render_);
476 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700477 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000478}
479
peahdf3efa82015-11-28 12:35:15 -0800480int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800481 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800482 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200483 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800484 return kNoError;
485 }
peahdf3efa82015-11-28 12:35:15 -0800486
487 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800488 return InitializeLocked(processing_config);
489}
490
niklase@google.com470e71d2011-07-07 08:21:25 +0000491int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200492 UpdateActiveSubmoduleStates();
493
Per Åhgrend47941e2019-08-22 11:51:13 +0200494 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800495 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200496 ? formats_.render_processing_format.sample_rate_hz()
497 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800498 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
499 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200500 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800501 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200502 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700503 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200504 render_audiobuffer_sample_rate_hz,
505 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700506 if (formats_.api_format.reverse_input_stream() !=
507 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800508 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800509 formats_.api_format.reverse_input_stream().num_channels(),
510 formats_.api_format.reverse_input_stream().num_frames(),
511 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800512 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700513 } else {
peahdf3efa82015-11-28 12:35:15 -0800514 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700515 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700516 } else {
peahdf3efa82015-11-28 12:35:15 -0800517 render_.render_audio.reset(nullptr);
518 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700519 }
peahce4d9152017-05-19 01:28:05 -0700520
Per Åhgrend47941e2019-08-22 11:51:13 +0200521 capture_.capture_audio.reset(new AudioBuffer(
522 formats_.api_format.input_stream().sample_rate_hz(),
523 formats_.api_format.input_stream().num_channels(),
524 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
525 formats_.api_format.output_stream().num_channels(),
526 formats_.api_format.output_stream().sample_rate_hz(),
527 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000528
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200529 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
530 formats_.api_format.output_stream().sample_rate_hz() &&
531 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
532 capture_.capture_fullband_audio.reset(
533 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
534 formats_.api_format.input_stream().num_channels(),
535 formats_.api_format.output_stream().sample_rate_hz(),
536 formats_.api_format.output_stream().num_channels(),
537 formats_.api_format.output_stream().sample_rate_hz(),
538 formats_.api_format.output_stream().num_channels()));
539 } else {
540 capture_.capture_fullband_audio.reset();
541 }
542
peah764e3642016-10-22 05:04:30 -0700543 AllocateRenderQueue();
544
peah135259a2016-10-28 03:12:11 -0700545 public_submodules_->gain_control->Initialize(num_proc_channels(),
546 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700547 if (constants_.use_experimental_agc) {
548 if (!private_submodules_->agc_manager.get()) {
549 private_submodules_->agc_manager.reset(new AgcManagerDirect(
550 public_submodules_->gain_control.get(),
551 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200552 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
553 constants_.use_experimental_agc_agc2_level_estimation,
554 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700555 }
556 private_submodules_->agc_manager->Initialize();
557 private_submodules_->agc_manager->SetCaptureMuted(
558 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700559 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700560 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200561 InitializeTransient();
Per Åhgren0aefbf02019-08-23 21:29:17 +0200562 InitializeHighPassFilter();
peahde65ddc2016-09-16 15:02:15 -0700563 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
564 proc_sample_rate_hz());
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200565 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700566 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200567 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700568 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200569 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200570 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100571 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800572
aleloi868f32f2017-05-23 07:20:05 -0700573 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200574 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700575 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000576 return kNoError;
577}
578
Michael Graczyk86c6d332015-07-23 11:41:39 -0700579int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200580 UpdateActiveSubmoduleStates();
581
Michael Graczyk86c6d332015-07-23 11:41:39 -0700582 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700583 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
584 return kBadSampleRateError;
585 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000586 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700587
Peter Kasting69558702016-01-12 16:26:35 -0800588 const size_t num_in_channels = config.input_stream().num_channels();
589 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590
591 // Need at least one input channel.
592 // Need either one output channel or as many outputs as there are inputs.
593 if (num_in_channels == 0 ||
594 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700595 return kBadNumberChannelsError;
596 }
597
peahdf3efa82015-11-28 12:35:15 -0800598 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000599
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200600 // Choose maximum rate to use for the split filtering.
601 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
602 config_.pipeline.maximum_internal_processing_rate == 32000);
603 int max_splitting_rate = 48000;
604 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
605 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
606 }
607
Per Åhgrenc8626b62019-08-23 15:49:51 +0200608 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700609 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700610 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200611 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700612 submodule_states_.CaptureMultiBandSubModulesActive() ||
613 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200614 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000615
peahde65ddc2016-09-16 15:02:15 -0700616 capture_nonlocked_.capture_processing_format =
617 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700618
peah2ce640f2017-04-07 03:57:48 -0700619 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200620 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200621 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700622 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
623 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200624 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700625 submodule_states_.CaptureMultiBandSubModulesActive() ||
626 submodule_states_.RenderMultiBandSubModulesActive());
627 } else {
628 render_processing_rate = capture_processing_rate;
629 }
630
peahde65ddc2016-09-16 15:02:15 -0700631 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700632 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700633 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
634 kSampleRate8kHz) {
635 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000636 } else {
peahde65ddc2016-09-16 15:02:15 -0700637 render_processing_rate =
638 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000639 }
640
Per Åhgrenc8626b62019-08-23 15:49:51 +0200641 RTC_DCHECK_NE(8000, render_processing_rate);
642
peahce4d9152017-05-19 01:28:05 -0700643 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200644 // By default, downmix the render stream to mono for analysis. This has been
645 // demonstrated to work well for AEC in most practical scenarios.
646 const bool experimental_multi_channel_render =
647 config_.pipeline.experimental_multi_channel &&
648 constants_.experimental_multi_channel_render_support;
649 int render_processing_num_channels =
650 experimental_multi_channel_render
651 ? formats_.api_format.reverse_input_stream().num_channels()
652 : 1;
653 formats_.render_processing_format =
654 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700655 } else {
656 formats_.render_processing_format = StreamConfig(
657 formats_.api_format.reverse_input_stream().sample_rate_hz(),
658 formats_.api_format.reverse_input_stream().num_channels());
659 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000660
peahde65ddc2016-09-16 15:02:15 -0700661 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
662 kSampleRate32kHz ||
663 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
664 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800665 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000666 } else {
peahdf3efa82015-11-28 12:35:15 -0800667 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700668 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000669 }
670
671 return InitializeLocked();
672}
673
peah88ac8532016-09-12 16:47:25 -0700674void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700675 // Run in a single-threaded manner when applying the settings.
676 rtc::CritScope cs_render(&crit_render_);
677 rtc::CritScope cs_capture(&crit_capture_);
678
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200679 const bool pipeline_config_changed =
680 config_.pipeline.experimental_multi_channel !=
681 config.pipeline.experimental_multi_channel;
682
Per Åhgren200feba2019-03-06 04:16:46 +0100683 const bool aec_config_changed =
684 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
685 config_.echo_canceller.use_legacy_aec !=
686 config.echo_canceller.use_legacy_aec ||
687 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
688 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
689 config_.echo_canceller.legacy_moderate_suppression_level !=
690 config.echo_canceller.legacy_moderate_suppression_level);
691
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100692 const bool agc1_config_changed =
693 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
694 config_.gain_controller1.mode != config.gain_controller1.mode ||
695 config_.gain_controller1.target_level_dbfs !=
696 config.gain_controller1.target_level_dbfs ||
697 config_.gain_controller1.compression_gain_db !=
698 config.gain_controller1.compression_gain_db ||
699 config_.gain_controller1.enable_limiter !=
700 config.gain_controller1.enable_limiter ||
701 config_.gain_controller1.analog_level_minimum !=
702 config.gain_controller1.analog_level_minimum ||
703 config_.gain_controller1.analog_level_maximum !=
704 config.gain_controller1.analog_level_maximum;
705
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200706 const bool voice_detection_config_changed =
707 config_.voice_detection.enabled != config.voice_detection.enabled;
708
Yves Gerey499bc6c2018-10-10 18:29:07 +0200709 config_ = config;
710
Per Åhgren200feba2019-03-06 04:16:46 +0100711 if (aec_config_changed) {
712 InitializeEchoController();
713 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200714
Sam Zackrisson23513132019-01-11 15:10:32 +0100715 public_submodules_->noise_suppression->Enable(
716 config.noise_suppression.enabled);
717 public_submodules_->noise_suppression->set_level(
718 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
719
Per Åhgren0aefbf02019-08-23 21:29:17 +0200720 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800721
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG(LS_INFO) << "Highpass filter activated: "
723 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800724
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100725 if (agc1_config_changed) {
726 ApplyAgc1Config(config_.gain_controller1);
727 }
728
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100729 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700730 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100731 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
732 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100733 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100734 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700735 config_.gain_controller2 = AudioProcessing::Config::GainController2();
736 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200737 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200738 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200739 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100740 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
741 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200742 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
743 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100744
745 if (config_.level_estimation.enabled &&
746 !private_submodules_->output_level_estimator) {
saza6787f232019-10-11 19:31:07 +0200747 private_submodules_->output_level_estimator =
748 std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100749 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100750
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200751 if (voice_detection_config_changed) {
752 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100753 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200754
755 // Reinitialization must happen after all submodule configuration to avoid
756 // additional reinitializations on the next capture / render processing call.
757 if (pipeline_config_changed) {
758 InitializeLocked(formats_.api_format);
759 }
peah88ac8532016-09-12 16:47:25 -0700760}
761
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100762void AudioProcessingImpl::ApplyAgc1Config(
763 const Config::GainController1& config) {
764 GainControl* agc = agc1();
765 int error = agc->Enable(config.enabled);
766 RTC_DCHECK_EQ(kNoError, error);
767 error = agc->set_mode(Agc1ConfigModeToInterfaceMode(config.mode));
768 RTC_DCHECK_EQ(kNoError, error);
769 error = agc->set_target_level_dbfs(config.target_level_dbfs);
770 RTC_DCHECK_EQ(kNoError, error);
771 error = agc->set_compression_gain_db(config.compression_gain_db);
772 RTC_DCHECK_EQ(kNoError, error);
773 error = agc->enable_limiter(config.enable_limiter);
774 RTC_DCHECK_EQ(kNoError, error);
775 error = agc->set_analog_level_limits(config.analog_level_minimum,
776 config.analog_level_maximum);
777 RTC_DCHECK_EQ(kNoError, error);
778}
779
780GainControl* AudioProcessingImpl::agc1() {
781 if (constants_.use_experimental_agc) {
782 return public_submodules_->gain_control_for_experimental_agc.get();
783 }
784 return public_submodules_->gain_control.get();
785}
786
787const GainControl* AudioProcessingImpl::agc1() const {
788 if (constants_.use_experimental_agc) {
789 return public_submodules_->gain_control_for_experimental_agc.get();
790 }
791 return public_submodules_->gain_control.get();
792}
793
peah88ac8532016-09-12 16:47:25 -0700794void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800795 // Run in a single-threaded manner when setting the extra options.
796 rtc::CritScope cs_render(&crit_render_);
797 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000798
Per Åhgrenf204faf2019-04-25 15:18:06 +0200799 capture_nonlocked_.use_aec2_extended_filter =
800 config.Get<ExtendedFilter>().enabled;
801 capture_nonlocked_.use_aec2_delay_agnostic =
802 config.Get<DelayAgnostic>().enabled;
803 capture_nonlocked_.use_aec2_refined_adaptive_filter =
804 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800805
peahdf3efa82015-11-28 12:35:15 -0800806 if (capture_.transient_suppressor_enabled !=
807 config.Get<ExperimentalNs>().enabled) {
808 capture_.transient_suppressor_enabled =
809 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000810 InitializeTransient();
811 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000812}
813
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000814int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800815 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700816 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000817}
818
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200819int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
820 return capture_.capture_fullband_audio
821 ? capture_.capture_fullband_audio->num_frames() * 100
822 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
823}
824
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000825int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800826 // Used as callback from submodules, hence locking is not allowed.
827 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000828}
829
Peter Kasting69558702016-01-12 16:26:35 -0800830size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800831 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700832 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000833}
834
Peter Kasting69558702016-01-12 16:26:35 -0800835size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800836 // Used as callback from submodules, hence locking is not allowed.
837 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000838}
839
Peter Kasting69558702016-01-12 16:26:35 -0800840size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800841 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200842 const bool experimental_multi_channel_capture =
843 config_.pipeline.experimental_multi_channel &&
844 constants_.experimental_multi_channel_capture_support;
845 if (capture_nonlocked_.echo_controller_enabled &&
846 !experimental_multi_channel_capture) {
847 return 1;
848 }
849 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800850}
851
Peter Kasting69558702016-01-12 16:26:35 -0800852size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800853 // Used as callback from submodules, hence locking is not allowed.
854 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000855}
856
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000857void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800858 rtc::CritScope cs(&crit_capture_);
859 capture_.output_will_be_muted = muted;
860 if (private_submodules_->agc_manager.get()) {
861 private_submodules_->agc_manager->SetCaptureMuted(
862 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000863 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000864}
865
Alessio Bazzicac054e782018-04-16 12:10:09 +0200866void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200867 switch (setting.type()) {
868 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
869 render_runtime_settings_enqueuer_.Enqueue(setting);
870 return;
871 case RuntimeSetting::Type::kNotSpecified:
872 RTC_NOTREACHED();
873 return;
874 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100875 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200876 case RuntimeSetting::Type::kCaptureFixedPostGain:
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200877 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200878 capture_runtime_settings_enqueuer_.Enqueue(setting);
879 return;
880 }
881 // The language allows the enum to have a non-enumerator
882 // value. Check that this doesn't happen.
883 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200884}
885
886AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
887 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200888 : runtime_settings_(*runtime_settings) {
889 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200890}
891
892AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
893 default;
894
895void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
896 RuntimeSetting setting) {
897 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200898 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200899 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200900 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200901 RTC_LOG(LS_ERROR)
902 << "The runtime settings queue is full. Oldest setting discarded.";
903 }
904 if (remaining_attempts == 0)
905 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
906}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000907
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000908int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700909 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000910 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000911 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000912 int output_sample_rate_hz,
913 ChannelLayout output_layout,
914 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800915 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800916 StreamConfig input_stream;
917 StreamConfig output_stream;
918 {
919 // Access the formats_.api_format.input_stream beneath the capture lock.
920 // The lock must be released as it is later required in the call
921 // to ProcessStream(,,,);
922 rtc::CritScope cs(&crit_capture_);
923 input_stream = formats_.api_format.input_stream();
924 output_stream = formats_.api_format.output_stream();
925 }
926
Michael Graczyk86c6d332015-07-23 11:41:39 -0700927 input_stream.set_sample_rate_hz(input_sample_rate_hz);
928 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
929 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700930 output_stream.set_sample_rate_hz(output_sample_rate_hz);
931 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
932 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
933
934 if (samples_per_channel != input_stream.num_frames()) {
935 return kBadDataLengthError;
936 }
937 return ProcessStream(src, input_stream, output_stream, dest);
938}
939
940int AudioProcessingImpl::ProcessStream(const float* const* src,
941 const StreamConfig& input_config,
942 const StreamConfig& output_config,
943 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800944 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800945 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700946 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800947 {
948 // Acquire the capture lock in order to safely call the function
949 // that retrieves the render side data. This function accesses apm
950 // getters that need the capture lock held when being called.
951 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700952 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800953
954 if (!src || !dest) {
955 return kNullPointerError;
956 }
957
958 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700959 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000960 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000961
Oskar Sundbom4b276482019-05-23 14:28:00 +0200962 if (processing_config.input_stream() != input_config) {
963 processing_config.input_stream() = input_config;
964 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800965 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200966
967 if (processing_config.output_stream() != output_config) {
968 processing_config.output_stream() = output_config;
969 reinitialization_required = true;
970 }
971
972 if (reinitialization_required) {
973 // Reinitialize.
974 rtc::CritScope cs_render(&crit_render_);
975 rtc::CritScope cs_capture(&crit_capture_);
976 RETURN_ON_ERR(InitializeLocked(processing_config));
977 }
978
peahdf3efa82015-11-28 12:35:15 -0800979 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700980 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
981 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000982
aleloi868f32f2017-05-23 07:20:05 -0700983 if (aec_dump_) {
984 RecordUnprocessedCaptureStream(src);
985 }
986
Per Åhgrena1351272019-08-15 12:15:46 +0200987 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800988 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200989 if (capture_.capture_fullband_audio) {
990 capture_.capture_fullband_audio->CopyFrom(
991 src, formats_.api_format.input_stream());
992 }
peahde65ddc2016-09-16 15:02:15 -0700993 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200994 if (capture_.capture_fullband_audio) {
995 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
996 dest);
997 } else {
998 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
999 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001000
aleloi868f32f2017-05-23 07:20:05 -07001001 if (aec_dump_) {
1002 RecordProcessedCaptureStream(dest);
1003 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001004 return kNoError;
1005}
1006
Alex Loiko73ec0192018-05-15 10:52:28 +02001007void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001008 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +02001009 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001010 if (aec_dump_) {
1011 aec_dump_->WriteRuntimeSetting(setting);
1012 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001013 switch (setting.type()) {
1014 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +02001015 if (config_.pre_amplifier.enabled) {
1016 float value;
1017 setting.GetFloat(&value);
1018 private_submodules_->pre_amplifier->SetGainFactor(value);
1019 }
1020 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001021 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001022 case RuntimeSetting::Type::kCaptureCompressionGain: {
1023 float value;
1024 setting.GetFloat(&value);
1025 int int_value = static_cast<int>(value + .5f);
1026 config_.gain_controller1.compression_gain_db = int_value;
1027 int error = agc1()->set_compression_gain_db(int_value);
1028 RTC_DCHECK_EQ(kNoError, error);
1029 break;
1030 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001031 case RuntimeSetting::Type::kCaptureFixedPostGain: {
1032 if (config_.gain_controller2.enabled) {
1033 float value;
1034 setting.GetFloat(&value);
1035 config_.gain_controller2.fixed_digital.gain_db = value;
1036 private_submodules_->gain_controller2->ApplyConfig(
1037 config_.gain_controller2);
1038 }
1039 break;
1040 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001041 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1042 int value;
1043 setting.GetInt(&value);
1044 capture_.playout_volume = value;
1045 break;
1046 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001047 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1048 RTC_NOTREACHED();
1049 break;
1050 case RuntimeSetting::Type::kNotSpecified:
1051 RTC_NOTREACHED();
1052 break;
1053 }
1054 }
1055}
1056
1057void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1058 RuntimeSetting setting;
1059 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001060 if (aec_dump_) {
1061 aec_dump_->WriteRuntimeSetting(setting);
1062 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001063 switch (setting.type()) {
1064 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1065 if (private_submodules_->render_pre_processor) {
1066 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
1067 }
1068 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001069 case RuntimeSetting::Type::kCapturePreGain: // fall-through
1070 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001071 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001072 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001073 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +02001074 RTC_NOTREACHED();
1075 break;
1076 }
1077 }
1078}
1079
peah9e6a2902017-05-15 07:19:21 -07001080void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001081 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001082
1083 // Insert the samples into the queue.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001084 if (private_submodules_->echo_cancellation) {
1085 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001086 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1087 num_reverse_channels(),
1088 &aec_render_queue_buffer_);
1089
Per Åhgrenf204faf2019-04-25 15:18:06 +02001090 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1091 // The data queue is full and needs to be emptied.
1092 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001093
Per Åhgrenf204faf2019-04-25 15:18:06 +02001094 // Retry the insert (should always work).
1095 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1096 RTC_DCHECK(result);
1097 }
peaha0624602016-10-25 04:45:24 -07001098 }
1099
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001100 if (private_submodules_->echo_control_mobile) {
1101 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1102 num_reverse_channels(),
1103 &aecm_render_queue_buffer_);
1104 RTC_DCHECK(aecm_render_signal_queue_);
1105 // Insert the samples into the queue.
1106 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1107 // The data queue is full and needs to be emptied.
1108 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001109
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001110 // Retry the insert (should always work).
1111 bool result =
1112 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1113 RTC_DCHECK(result);
1114 }
peah764e3642016-10-22 05:04:30 -07001115 }
peah701d6282016-10-25 05:42:20 -07001116
1117 if (!constants_.use_experimental_agc) {
1118 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
1119 // Insert the samples into the queue.
1120 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1121 // The data queue is full and needs to be emptied.
1122 EmptyQueuedRenderAudio();
1123
1124 // Retry the insert (should always work).
1125 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1126 RTC_DCHECK(result);
1127 }
1128 }
peah9e6a2902017-05-15 07:19:21 -07001129}
ivoc9f4a4a02016-10-28 05:39:16 -07001130
peah9e6a2902017-05-15 07:19:21 -07001131void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001132 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1133
1134 // Insert the samples into the queue.
1135 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1136 // The data queue is full and needs to be emptied.
1137 EmptyQueuedRenderAudio();
1138
1139 // Retry the insert (should always work).
1140 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1141 RTC_DCHECK(result);
1142 }
peah764e3642016-10-22 05:04:30 -07001143}
1144
1145void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001146 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001147 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001148
ivoc9f4a4a02016-10-28 05:39:16 -07001149 const size_t new_red_render_queue_element_max_size =
1150 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1151
peaha0624602016-10-25 04:45:24 -07001152 // Reallocate the queues if the queue item sizes are too small to fit the
1153 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001154
1155 if (agc_render_queue_element_max_size_ <
1156 new_agc_render_queue_element_max_size) {
1157 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1158
1159 std::vector<int16_t> template_queue_element(
1160 agc_render_queue_element_max_size_);
1161
1162 agc_render_signal_queue_.reset(
1163 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1164 kMaxNumFramesToBuffer, template_queue_element,
1165 RenderQueueItemVerifier<int16_t>(
1166 agc_render_queue_element_max_size_)));
1167
1168 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1169 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1170 } else {
1171 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001172 }
ivoc9f4a4a02016-10-28 05:39:16 -07001173
1174 if (red_render_queue_element_max_size_ <
1175 new_red_render_queue_element_max_size) {
1176 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1177
1178 std::vector<float> template_queue_element(
1179 red_render_queue_element_max_size_);
1180
1181 red_render_signal_queue_.reset(
1182 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1183 kMaxNumFramesToBuffer, template_queue_element,
1184 RenderQueueItemVerifier<float>(
1185 red_render_queue_element_max_size_)));
1186
1187 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1188 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1189 } else {
1190 red_render_signal_queue_->Clear();
1191 }
peah764e3642016-10-22 05:04:30 -07001192}
1193
1194void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1195 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001196 if (private_submodules_->echo_cancellation) {
1197 RTC_DCHECK(aec_render_signal_queue_);
1198 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
1199 private_submodules_->echo_cancellation->ProcessRenderAudio(
1200 aec_capture_queue_buffer_);
1201 }
peaha0624602016-10-25 04:45:24 -07001202 }
1203
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001204 if (private_submodules_->echo_control_mobile) {
1205 RTC_DCHECK(aecm_render_signal_queue_);
1206 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
1207 private_submodules_->echo_control_mobile->ProcessRenderAudio(
1208 aecm_capture_queue_buffer_);
1209 }
peah701d6282016-10-25 05:42:20 -07001210 }
1211
1212 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1213 public_submodules_->gain_control->ProcessRenderAudio(
1214 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001215 }
ivoc9f4a4a02016-10-28 05:39:16 -07001216
1217 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001218 RTC_DCHECK(private_submodules_->echo_detector);
1219 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001220 red_capture_queue_buffer_);
1221 }
peah764e3642016-10-22 05:04:30 -07001222}
1223
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001224int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001225 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001226 {
1227 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001228 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001229 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001230 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001231 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001232 }
peahfa6228e2015-11-16 16:27:42 -08001233
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001234 if (!frame) {
1235 return kNullPointerError;
1236 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001237 // Must be a native rate.
1238 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1239 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001240 frame->sample_rate_hz_ != kSampleRate32kHz &&
1241 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001242 return kBadSampleRateError;
1243 }
peah192164e2015-11-17 02:16:45 -08001244
peahdf3efa82015-11-28 12:35:15 -08001245 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001246 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001247 {
1248 // Aquire lock for the access of api_format.
1249 // The lock is released immediately due to the conditional
1250 // reinitialization.
1251 rtc::CritScope cs_capture(&crit_capture_);
1252 // TODO(ajm): The input and output rates and channels are currently
1253 // constrained to be identical in the int16 interface.
1254 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001255
1256 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001257 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001258
Oskar Sundbom4b276482019-05-23 14:28:00 +02001259 reinitialization_required =
1260 reinitialization_required ||
1261 processing_config.input_stream().sample_rate_hz() !=
1262 frame->sample_rate_hz_ ||
1263 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1264 processing_config.output_stream().sample_rate_hz() !=
1265 frame->sample_rate_hz_ ||
1266 processing_config.output_stream().num_channels() != frame->num_channels_;
1267
1268 if (reinitialization_required) {
1269 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1270 processing_config.input_stream().set_num_channels(frame->num_channels_);
1271 processing_config.output_stream().set_sample_rate_hz(
1272 frame->sample_rate_hz_);
1273 processing_config.output_stream().set_num_channels(frame->num_channels_);
1274
1275 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001276 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001277 rtc::CritScope cs_capture(&crit_capture_);
1278 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001279 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001280
peahdf3efa82015-11-28 12:35:15 -08001281 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001282 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001283 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001284 return kBadDataLengthError;
1285 }
1286
aleloi868f32f2017-05-23 07:20:05 -07001287 if (aec_dump_) {
1288 RecordUnprocessedCaptureStream(*frame);
1289 }
1290
Per Åhgrend47941e2019-08-22 11:51:13 +02001291 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001292 if (capture_.capture_fullband_audio) {
1293 capture_.capture_fullband_audio->CopyFrom(frame);
1294 }
peahde65ddc2016-09-16 15:02:15 -07001295 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001296 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001297 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001298 if (capture_.capture_fullband_audio) {
1299 capture_.capture_fullband_audio->CopyTo(frame);
1300 } else {
1301 capture_.capture_audio->CopyTo(frame);
1302 }
Per Åhgrena1351272019-08-15 12:15:46 +02001303 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001304 if (capture_.stats.voice_detected) {
1305 frame->vad_activity_ = *capture_.stats.voice_detected
1306 ? AudioFrame::kVadActive
1307 : AudioFrame::kVadPassive;
1308 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001309
aleloi868f32f2017-05-23 07:20:05 -07001310 if (aec_dump_) {
1311 RecordProcessedCaptureStream(*frame);
1312 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001313
1314 return kNoError;
1315}
1316
peahde65ddc2016-09-16 15:02:15 -07001317int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001318 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001319
peahb58a1582016-03-15 09:34:24 -07001320 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001321 // TODO(peah): Simplify once the public API Enable functions for these
1322 // are moved to APM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001323 RTC_DCHECK_LE(!!private_submodules_->echo_controller +
1324 !!private_submodules_->echo_cancellation +
1325 !!private_submodules_->echo_control_mobile,
1326 1);
peahb58a1582016-03-15 09:34:24 -07001327
peahde65ddc2016-09-16 15:02:15 -07001328 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001329
Alex Loikob5c9a792018-04-16 16:31:22 +02001330 if (private_submodules_->pre_amplifier) {
1331 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001332 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001333 capture_buffer->num_frames()));
1334 }
1335
Per Åhgren928146f2019-08-20 09:19:21 +02001336 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001337 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001338 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001339 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1340 if (log_rms) {
1341 capture_rms_interval_counter_ = 0;
1342 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001343 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1344 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1345 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1346 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001347 }
1348
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001349 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001350 // Detect and flag any change in the analog gain.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001351 int analog_mic_level = agc1()->stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001352 capture_.echo_path_gain_change =
1353 capture_.prev_analog_mic_level != analog_mic_level &&
1354 capture_.prev_analog_mic_level != -1;
1355 capture_.prev_analog_mic_level = analog_mic_level;
1356
Per Åhgrend2650d12018-10-02 17:00:59 +02001357 // Detect and flag any change in the pre-amplifier gain.
1358 if (private_submodules_->pre_amplifier) {
1359 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1360 capture_.echo_path_gain_change =
1361 capture_.echo_path_gain_change ||
1362 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001363 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001364 capture_.prev_pre_amp_gain = pre_amp_gain;
1365 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001366
1367 // Detect volume change.
1368 capture_.echo_path_gain_change =
1369 capture_.echo_path_gain_change ||
1370 (capture_.prev_playout_volume != capture_.playout_volume &&
1371 capture_.prev_playout_volume >= 0);
1372 capture_.prev_playout_volume = capture_.playout_volume;
1373
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001374 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001375 }
1376
peahbe615622016-02-13 16:40:47 -08001377 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001378 public_submodules_->gain_control->is_enabled()) {
1379 private_submodules_->agc_manager->AnalyzePreProcess(
Per Åhgren928146f2019-08-20 09:19:21 +02001380 capture_buffer->channels_f()[0], capture_buffer->num_channels(),
peahde65ddc2016-09-16 15:02:15 -07001381 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001382
1383 if (constants_.use_experimental_agc_process_before_aec) {
1384 private_submodules_->agc_manager->Process(
Per Åhgrend47941e2019-08-22 11:51:13 +02001385 capture_buffer->channels_const()[0],
Alex Loikod9342442018-09-10 13:59:41 +02001386 capture_nonlocked_.capture_processing_format.num_frames(),
1387 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1388 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001389 }
1390
peah2ace3f92016-09-10 04:42:27 -07001391 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1392 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001393 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1394 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001395 }
1396
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001397 const bool experimental_multi_channel_capture =
1398 config_.pipeline.experimental_multi_channel &&
1399 constants_.experimental_multi_channel_capture_support;
1400 if (private_submodules_->echo_controller &&
1401 !experimental_multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001402 // Force down-mixing of the number of channels after the detection of
1403 // capture signal saturation.
1404 // TODO(peah): Look into ensuring that this kind of tampering with the
1405 // AudioBuffer functionality should not be needed.
1406 capture_buffer->set_num_channels(1);
1407 }
1408
Per Åhgren0aefbf02019-08-23 21:29:17 +02001409 if (private_submodules_->high_pass_filter) {
1410 private_submodules_->high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001411 }
peahde65ddc2016-09-16 15:02:15 -07001412 RETURN_ON_ERR(
1413 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1414 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001415
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001416 if (private_submodules_->echo_control_mobile) {
1417 // Ensure that the stream delay was set before the call to the
1418 // AECM ProcessCaptureAudio function.
1419 if (!was_stream_delay_set()) {
1420 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001421 }
1422
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001423 if (public_submodules_->noise_suppression->is_enabled()) {
Per Åhgrena1351272019-08-15 12:15:46 +02001424 private_submodules_->echo_control_mobile->CopyLowPassReference(
1425 capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001426 }
peahe0eae3c2016-12-14 01:16:23 -08001427
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001428 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001429
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001430 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001431 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001432 } else {
1433 if (private_submodules_->echo_controller) {
1434 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1435
1436 if (was_stream_delay_set()) {
1437 private_submodules_->echo_controller->SetAudioBufferDelay(
1438 stream_delay_ms());
1439 }
1440
1441 private_submodules_->echo_controller->ProcessCapture(
1442 capture_buffer, capture_.echo_path_gain_change);
1443 } else if (private_submodules_->echo_cancellation) {
1444 // Ensure that the stream delay was set before the call to the
1445 // AEC ProcessCaptureAudio function.
1446 if (!was_stream_delay_set()) {
1447 return AudioProcessing::kStreamParameterNotSetError;
1448 }
1449
1450 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
1451 capture_buffer, stream_delay_ms()));
1452 }
1453
1454 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
Per Åhgren46537a32017-06-07 10:08:10 +02001455 }
ivoc9f4a4a02016-10-28 05:39:16 -07001456
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001457 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001458 capture_.stats.voice_detected =
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001459 private_submodules_->voice_detector->ProcessCaptureAudio(
1460 capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001461 } else {
1462 capture_.stats.voice_detected = absl::nullopt;
1463 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001464
peahbe615622016-02-13 16:40:47 -08001465 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001466 public_submodules_->gain_control->is_enabled() &&
1467 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001468 private_submodules_->agc_manager->Process(
Per Åhgren928146f2019-08-20 09:19:21 +02001469 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
peahde65ddc2016-09-16 15:02:15 -07001470 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001471 }
Per Åhgren200feba2019-03-06 04:16:46 +01001472 // TODO(peah): Add reporting from AEC3 whether there is echo.
peahb8fbb542016-03-15 02:28:08 -07001473 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001474 capture_buffer,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001475 private_submodules_->echo_cancellation &&
1476 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001477
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001478 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001479 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001480 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1481 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001482 }
1483
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001484 if (capture_.capture_fullband_audio) {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001485 const auto& ec = private_submodules_->echo_controller;
1486 bool ec_active = ec ? ec->ActiveProcessing() : false;
1487 // Only update the fullband buffer if the multiband processing has changed
1488 // the signal. Keep the original signal otherwise.
1489 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1490 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1491 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001492 capture_buffer = capture_.capture_fullband_audio.get();
1493 }
1494
peah9e6a2902017-05-15 07:19:21 -07001495 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001496 RTC_DCHECK(private_submodules_->echo_detector);
1497 private_submodules_->echo_detector->AnalyzeCaptureAudio(
Per Åhgrend47941e2019-08-22 11:51:13 +02001498 rtc::ArrayView<const float>(capture_buffer->channels()[0],
peah9e6a2902017-05-15 07:19:21 -07001499 capture_buffer->num_frames()));
1500 }
1501
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001502 // TODO(aluebs): Investigate if the transient suppression placement should be
1503 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001504 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001505 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001506 private_submodules_->agc_manager.get()
1507 ? private_submodules_->agc_manager->voice_probability()
1508 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001509
peahdf3efa82015-11-28 12:35:15 -08001510 public_submodules_->transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001511 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001512 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001513 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001514 capture_buffer->num_frames_per_band(),
1515 capture_.keyboard_info.keyboard_data,
1516 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001517 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001518 }
1519
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001520 // Experimental APM sub-module that analyzes |capture_buffer|.
1521 if (private_submodules_->capture_analyzer) {
1522 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1523 }
1524
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001525 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001526 private_submodules_->gain_controller2->NotifyAnalogLevel(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001527 agc1()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001528 private_submodules_->gain_controller2->Process(capture_buffer);
1529 }
1530
Sam Zackrisson0beac582017-09-25 12:04:02 +02001531 if (private_submodules_->capture_post_processor) {
1532 private_submodules_->capture_post_processor->Process(capture_buffer);
1533 }
1534
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001535 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001536 if (config_.level_estimation.enabled) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001537 private_submodules_->output_level_estimator->ProcessStream(*capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001538 capture_.stats.output_rms_dbfs =
1539 private_submodules_->output_level_estimator->RMS();
1540 } else {
1541 capture_.stats.output_rms_dbfs = absl::nullopt;
1542 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001543
Per Åhgren928146f2019-08-20 09:19:21 +02001544 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001545 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001546 capture_nonlocked_.capture_processing_format.num_frames()));
1547 if (log_rms) {
1548 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1549 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1550 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1551 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1552 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1553 }
1554
peahdf3efa82015-11-28 12:35:15 -08001555 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001556 return kNoError;
1557}
1558
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001559int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001560 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001561 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001562 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001563 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001564 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001565 const StreamConfig reverse_config = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001566 sample_rate_hz,
1567 ChannelsFromLayout(layout),
1568 LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001569 };
1570 if (samples_per_channel != reverse_config.num_frames()) {
1571 return kBadDataLengthError;
1572 }
peahdf3efa82015-11-28 12:35:15 -08001573 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001574}
1575
peahde65ddc2016-09-16 15:02:15 -07001576int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1577 const StreamConfig& input_config,
1578 const StreamConfig& output_config,
1579 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001580 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001581 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001582 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001583 if (submodule_states_.RenderMultiBandProcessingActive() ||
1584 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001585 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1586 dest);
peah2ace3f92016-09-10 04:42:27 -07001587 } else if (formats_.api_format.reverse_input_stream() !=
1588 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001589 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1590 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001591 } else {
peahde65ddc2016-09-16 15:02:15 -07001592 CopyAudioIfNeeded(src, input_config.num_frames(),
1593 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001594 }
1595
1596 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001597}
1598
peahdf3efa82015-11-28 12:35:15 -08001599int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001600 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001601 const StreamConfig& input_config,
1602 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001603 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001604 return kNullPointerError;
1605 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001606
peahde65ddc2016-09-16 15:02:15 -07001607 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001608 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001609 }
1610
peahdf3efa82015-11-28 12:35:15 -08001611 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001612 processing_config.reverse_input_stream() = input_config;
1613 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001614
peahdf3efa82015-11-28 12:35:15 -08001615 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001616 RTC_DCHECK_EQ(input_config.num_frames(),
1617 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001618
aleloi868f32f2017-05-23 07:20:05 -07001619 if (aec_dump_) {
1620 const size_t channel_size =
1621 formats_.api_format.reverse_input_stream().num_frames();
1622 const size_t num_channels =
1623 formats_.api_format.reverse_input_stream().num_channels();
1624 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001625 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001626 }
peahdf3efa82015-11-28 12:35:15 -08001627 render_.render_audio->CopyFrom(src,
1628 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001629 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001630}
1631
1632int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001633 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001634 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001635 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001636 return kNullPointerError;
1637 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001638 // Must be a native rate.
1639 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1640 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001641 frame->sample_rate_hz_ != kSampleRate32kHz &&
1642 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001643 return kBadSampleRateError;
1644 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001645
Michael Graczyk86c6d332015-07-23 11:41:39 -07001646 if (frame->num_channels_ <= 0) {
1647 return kBadNumberChannelsError;
1648 }
1649
peahdf3efa82015-11-28 12:35:15 -08001650 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001651 processing_config.reverse_input_stream().set_sample_rate_hz(
1652 frame->sample_rate_hz_);
1653 processing_config.reverse_input_stream().set_num_channels(
1654 frame->num_channels_);
1655 processing_config.reverse_output_stream().set_sample_rate_hz(
1656 frame->sample_rate_hz_);
1657 processing_config.reverse_output_stream().set_num_channels(
1658 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001659
peahdf3efa82015-11-28 12:35:15 -08001660 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001661 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001662 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001663 return kBadDataLengthError;
1664 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001665
aleloi868f32f2017-05-23 07:20:05 -07001666 if (aec_dump_) {
1667 aec_dump_->WriteRenderStreamMessage(*frame);
1668 }
1669
Per Åhgrend47941e2019-08-22 11:51:13 +02001670 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001671 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001672 if (submodule_states_.RenderMultiBandProcessingActive() ||
1673 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001674 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001675 }
aluebsb0319552016-03-17 20:39:53 -07001676 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001677}
niklase@google.com470e71d2011-07-07 08:21:25 +00001678
peahde65ddc2016-09-16 15:02:15 -07001679int AudioProcessingImpl::ProcessRenderStreamLocked() {
1680 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001681
Alex Loiko73ec0192018-05-15 10:52:28 +02001682 HandleRenderRuntimeSettings();
1683
Alex Loiko5825aa62017-12-18 16:02:40 +01001684 if (private_submodules_->render_pre_processor) {
1685 private_submodules_->render_pre_processor->Process(render_buffer);
1686 }
1687
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001688 QueueNonbandedRenderAudio(render_buffer);
1689
peah2ace3f92016-09-10 04:42:27 -07001690 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001691 SampleRateSupportsMultiBand(
1692 formats_.render_processing_format.sample_rate_hz())) {
1693 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001694 }
1695
peahce4d9152017-05-19 01:28:05 -07001696 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1697 QueueBandedRenderAudio(render_buffer);
1698 }
1699
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001700 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001701 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001702 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001703 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001704
peah2ace3f92016-09-10 04:42:27 -07001705 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001706 SampleRateSupportsMultiBand(
1707 formats_.render_processing_format.sample_rate_hz())) {
1708 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001709 }
1710
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001711 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001712}
1713
1714int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001715 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001716 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001717 capture_.was_stream_delay_set = true;
1718 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001719
niklase@google.com470e71d2011-07-07 08:21:25 +00001720 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001721 delay = 0;
1722 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001723 }
1724
1725 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1726 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001727 delay = 500;
1728 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001729 }
1730
peahdf3efa82015-11-28 12:35:15 -08001731 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001732 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001733}
1734
1735int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001736 // Used as callback from submodules, hence locking is not allowed.
1737 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001738}
1739
1740bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001741 // Used as callback from submodules, hence locking is not allowed.
1742 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001743}
1744
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001745void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001746 rtc::CritScope cs(&crit_capture_);
1747 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001748}
1749
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001750void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001751 rtc::CritScope cs(&crit_capture_);
1752 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001753}
1754
1755int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001756 rtc::CritScope cs(&crit_capture_);
1757 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001758}
1759
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001760void AudioProcessingImpl::set_stream_analog_level(int level) {
1761 rtc::CritScope cs_capture(&crit_capture_);
1762 int error = agc1()->set_stream_analog_level(level);
1763 RTC_DCHECK_EQ(kNoError, error);
1764}
1765
1766int AudioProcessingImpl::recommended_stream_analog_level() const {
1767 rtc::CritScope cs_capture(&crit_capture_);
1768 return agc1()->stream_analog_level();
1769}
1770
aleloi868f32f2017-05-23 07:20:05 -07001771void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1772 RTC_DCHECK(aec_dump);
1773 rtc::CritScope cs_render(&crit_render_);
1774 rtc::CritScope cs_capture(&crit_capture_);
1775
1776 // The previously attached AecDump will be destroyed with the
1777 // 'aec_dump' parameter, which is after locks are released.
1778 aec_dump_.swap(aec_dump);
1779 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001780 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001781}
1782
1783void AudioProcessingImpl::DetachAecDump() {
1784 // The d-tor of a task-queue based AecDump blocks until all pending
1785 // tasks are done. This construction avoids blocking while holding
1786 // the render and capture locks.
1787 std::unique_ptr<AecDump> aec_dump = nullptr;
1788 {
1789 rtc::CritScope cs_render(&crit_render_);
1790 rtc::CritScope cs_capture(&crit_capture_);
1791 aec_dump = std::move(aec_dump_);
1792 }
1793}
1794
Sam Zackrisson4d364492018-03-02 16:03:21 +01001795void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1796 std::unique_ptr<AudioGenerator> audio_generator) {
1797 // TODO(bugs.webrtc.org/8882) Stub.
1798 // Reset internal audio generator with audio_generator.
1799}
1800
1801void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1802 // TODO(bugs.webrtc.org/8882) Stub.
1803 // Delete audio generator, if one is attached.
1804}
1805
Ivo Creusen56d46092017-11-24 17:29:59 +01001806AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001807 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001808 rtc::CritScope cs_capture(&crit_capture_);
1809 if (!has_remote_tracks) {
1810 return capture_.stats;
1811 }
1812 AudioProcessingStats stats = capture_.stats;
1813 EchoCancellationImpl::Metrics metrics;
1814 if (private_submodules_->echo_controller) {
1815 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1816 stats.echo_return_loss = ec_metrics.echo_return_loss;
1817 stats.echo_return_loss_enhancement =
1818 ec_metrics.echo_return_loss_enhancement;
1819 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001820 }
1821 if (config_.residual_echo_detector.enabled) {
1822 RTC_DCHECK(private_submodules_->echo_detector);
1823 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1824 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1825 stats.residual_echo_likelihood_recent_max =
1826 ed_metrics.echo_likelihood_recent_max;
1827 }
Ivo Creusenae026092017-11-20 13:07:16 +01001828 return stats;
1829}
1830
niklase@google.com470e71d2011-07-07 08:21:25 +00001831GainControl* AudioProcessingImpl::gain_control() const {
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001832 return public_submodules_->gain_control_config_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001833}
1834
niklase@google.com470e71d2011-07-07 08:21:25 +00001835NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001836 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001837}
1838
peah8271d042016-11-22 07:24:52 -08001839void AudioProcessingImpl::MutateConfig(
1840 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1841 rtc::CritScope cs_render(&crit_render_);
1842 rtc::CritScope cs_capture(&crit_capture_);
1843 mutator(&config_);
1844 ApplyConfig(config_);
1845}
1846
1847AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1848 rtc::CritScope cs_render(&crit_render_);
1849 rtc::CritScope cs_capture(&crit_capture_);
1850 return config_;
1851}
1852
peah2ace3f92016-09-10 04:42:27 -07001853bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1854 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001855 config_.high_pass_filter.enabled,
Per Åhgrend547d862019-05-03 15:48:47 +02001856 !!private_submodules_->echo_cancellation,
1857 !!private_submodules_->echo_control_mobile,
ivoc9f4a4a02016-10-28 05:39:16 -07001858 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001859 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001860 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001861 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001862 capture_nonlocked_.echo_controller_enabled,
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001863 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001864 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001865}
1866
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001867void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001868 if (capture_.transient_suppressor_enabled) {
1869 if (!public_submodules_->transient_suppressor.get()) {
1870 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001871 }
peahdf3efa82015-11-28 12:35:15 -08001872 public_submodules_->transient_suppressor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001873 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1874 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001875 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001876}
1877
Per Åhgren0aefbf02019-08-23 21:29:17 +02001878void AudioProcessingImpl::InitializeHighPassFilter() {
1879 if (submodule_states_.HighPassFilteringRequired()) {
1880 private_submodules_->high_pass_filter.reset(
1881 new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001882 } else {
Per Åhgren0aefbf02019-08-23 21:29:17 +02001883 private_submodules_->high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001884 }
1885}
alessiob3ec96df2017-05-22 06:57:06 -07001886
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001887void AudioProcessingImpl::InitializeVoiceDetector() {
1888 if (config_.voice_detection.enabled) {
1889 private_submodules_->voice_detector = std::make_unique<VoiceDetection>(
1890 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1891 } else {
1892 private_submodules_->voice_detector.reset();
1893 }
1894}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001895void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001896 bool use_echo_controller =
1897 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001898 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001899 !config_.echo_canceller.use_legacy_aec);
1900
1901 if (use_echo_controller) {
1902 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001903 if (echo_control_factory_) {
1904 private_submodules_->echo_controller =
1905 echo_control_factory_->Create(proc_sample_rate_hz());
1906 } else {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001907 private_submodules_->echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001908 EchoCanceller3Config(), proc_sample_rate_hz(), num_reverse_channels(),
1909 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001910 }
1911
1912 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001913
Per Åhgrenf204faf2019-04-25 15:18:06 +02001914 private_submodules_->echo_cancellation.reset();
1915 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001916 private_submodules_->echo_control_mobile.reset();
1917 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001918 return;
peahe0eae3c2016-12-14 01:16:23 -08001919 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001920
1921 private_submodules_->echo_controller.reset();
1922 capture_nonlocked_.echo_controller_enabled = false;
1923
1924 if (!config_.echo_canceller.enabled) {
1925 private_submodules_->echo_cancellation.reset();
1926 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001927 private_submodules_->echo_control_mobile.reset();
1928 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001929 return;
1930 }
1931
1932 if (config_.echo_canceller.mobile_mode) {
1933 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001934 size_t max_element_size =
1935 std::max(static_cast<size_t>(1),
1936 kMaxAllowedValuesOfSamplesPerBand *
1937 EchoControlMobileImpl::NumCancellersRequired(
1938 num_output_channels(), num_reverse_channels()));
1939
1940 std::vector<int16_t> template_queue_element(max_element_size);
1941
1942 aecm_render_signal_queue_.reset(
1943 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1944 kMaxNumFramesToBuffer, template_queue_element,
1945 RenderQueueItemVerifier<int16_t>(max_element_size)));
1946
1947 aecm_render_queue_buffer_.resize(max_element_size);
1948 aecm_capture_queue_buffer_.resize(max_element_size);
1949
1950 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
1951
1952 private_submodules_->echo_control_mobile->Initialize(
1953 proc_split_sample_rate_hz(), num_reverse_channels(),
1954 num_output_channels());
1955
Per Åhgrenf204faf2019-04-25 15:18:06 +02001956 private_submodules_->echo_cancellation.reset();
1957 aec_render_signal_queue_.reset();
1958 return;
1959 }
1960
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001961 private_submodules_->echo_control_mobile.reset();
1962 aecm_render_signal_queue_.reset();
1963
Per Åhgrenf204faf2019-04-25 15:18:06 +02001964 // Create and activate AEC2.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001965 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
1966 private_submodules_->echo_cancellation->SetExtraOptions(
1967 capture_nonlocked_.use_aec2_extended_filter,
1968 capture_nonlocked_.use_aec2_delay_agnostic,
1969 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1970
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001971 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001972 std::max(static_cast<size_t>(1),
1973 kMaxAllowedValuesOfSamplesPerBand *
1974 EchoCancellationImpl::NumCancellersRequired(
1975 num_output_channels(), num_reverse_channels()));
1976
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001977 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001978
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001979 aec_render_signal_queue_.reset(
1980 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1981 kMaxNumFramesToBuffer, template_queue_element,
1982 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001983
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001984 aec_render_queue_buffer_.resize(element_max_size);
1985 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001986
1987 private_submodules_->echo_cancellation->Initialize(
1988 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1989 num_proc_channels());
1990
Per Åhgrenf204faf2019-04-25 15:18:06 +02001991 private_submodules_->echo_cancellation->set_suppression_level(
1992 config_.echo_canceller.legacy_moderate_suppression_level
1993 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1994 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001995}
peah8271d042016-11-22 07:24:52 -08001996
alessiob3ec96df2017-05-22 06:57:06 -07001997void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001998 if (config_.gain_controller2.enabled) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001999 private_submodules_->gain_controller2->Initialize(
2000 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002001 }
2002}
2003
Alex Loikob5c9a792018-04-16 16:31:22 +02002004void AudioProcessingImpl::InitializePreAmplifier() {
2005 if (config_.pre_amplifier.enabled) {
2006 private_submodules_->pre_amplifier.reset(
2007 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
2008 } else {
2009 private_submodules_->pre_amplifier.reset();
2010 }
2011}
2012
ivoc9f4a4a02016-10-28 05:39:16 -07002013void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01002014 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01002015 private_submodules_->echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002016 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02002017 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07002018}
2019
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002020void AudioProcessingImpl::InitializeAnalyzer() {
2021 if (private_submodules_->capture_analyzer) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002022 private_submodules_->capture_analyzer->Initialize(
2023 proc_fullband_sample_rate_hz(), num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002024 }
2025}
2026
Sam Zackrisson0beac582017-09-25 12:04:02 +02002027void AudioProcessingImpl::InitializePostProcessor() {
2028 if (private_submodules_->capture_post_processor) {
2029 private_submodules_->capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002030 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002031 }
2032}
2033
Alex Loiko5825aa62017-12-18 16:02:40 +01002034void AudioProcessingImpl::InitializePreProcessor() {
2035 if (private_submodules_->render_pre_processor) {
2036 private_submodules_->render_pre_processor->Initialize(
2037 formats_.render_processing_format.sample_rate_hz(),
2038 formats_.render_processing_format.num_channels());
2039 }
2040}
2041
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002042void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002043
aleloi868f32f2017-05-23 07:20:05 -07002044void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2045 if (!aec_dump_) {
2046 return;
2047 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002048
2049 std::string experiments_description = "";
2050 if (private_submodules_->echo_cancellation) {
2051 experiments_description +=
2052 private_submodules_->echo_cancellation->GetExperimentsDescription();
2053 }
aleloi868f32f2017-05-23 07:20:05 -07002054 // TODO(peah): Add semicolon-separated concatenations of experiment
2055 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002056 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2057 experiments_description += "AgcClippingLevelExperiment;";
2058 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002059 if (capture_nonlocked_.echo_controller_enabled) {
2060 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002061 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002062 if (config_.gain_controller2.enabled) {
2063 experiments_description += "GainController2;";
2064 }
aleloi868f32f2017-05-23 07:20:05 -07002065
2066 InternalAPMConfig apm_config;
2067
Per Åhgren200feba2019-03-06 04:16:46 +01002068 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002069 apm_config.aec_delay_agnostic_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002070 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002071 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002072 apm_config.aec_drift_compensation_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002073 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002074 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002075 apm_config.aec_extended_filter_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002076 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002077 private_submodules_->echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002078 apm_config.aec_suppression_level =
2079 private_submodules_->echo_cancellation
2080 ? static_cast<int>(
2081 private_submodules_->echo_cancellation->suppression_level())
2082 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002083
Per Åhgrend547d862019-05-03 15:48:47 +02002084 apm_config.aecm_enabled = !!private_submodules_->echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002085 apm_config.aecm_comfort_noise_enabled =
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002086 private_submodules_->echo_control_mobile &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002087 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002088 apm_config.aecm_routing_mode =
2089 private_submodules_->echo_control_mobile
2090 ? static_cast<int>(
2091 private_submodules_->echo_control_mobile->routing_mode())
2092 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002093
2094 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2095 apm_config.agc_mode =
2096 static_cast<int>(public_submodules_->gain_control->mode());
2097 apm_config.agc_limiter_enabled =
2098 public_submodules_->gain_control->is_limiter_enabled();
2099 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2100
2101 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2102
2103 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2104 apm_config.ns_level =
2105 static_cast<int>(public_submodules_->noise_suppression->level());
2106
2107 apm_config.transient_suppression_enabled =
2108 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002109 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002110 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2111 apm_config.pre_amplifier_fixed_gain_factor =
2112 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002113
2114 if (!forced && apm_config == apm_config_for_aec_dump_) {
2115 return;
2116 }
2117 aec_dump_->WriteConfig(apm_config);
2118 apm_config_for_aec_dump_ = apm_config;
2119}
2120
2121void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2122 const float* const* src) {
2123 RTC_DCHECK(aec_dump_);
2124 WriteAecDumpConfigMessage(false);
2125
2126 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2127 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2128 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002129 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002130 RecordAudioProcessingState();
2131}
2132
2133void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2134 const AudioFrame& capture_frame) {
2135 RTC_DCHECK(aec_dump_);
2136 WriteAecDumpConfigMessage(false);
2137
2138 aec_dump_->AddCaptureStreamInput(capture_frame);
2139 RecordAudioProcessingState();
2140}
2141
2142void AudioProcessingImpl::RecordProcessedCaptureStream(
2143 const float* const* processed_capture_stream) {
2144 RTC_DCHECK(aec_dump_);
2145
2146 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2147 const size_t num_channels =
2148 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002149 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2150 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002151 aec_dump_->WriteCaptureStreamMessage();
2152}
2153
2154void AudioProcessingImpl::RecordProcessedCaptureStream(
2155 const AudioFrame& processed_capture_frame) {
2156 RTC_DCHECK(aec_dump_);
2157
2158 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2159 aec_dump_->WriteCaptureStreamMessage();
2160}
2161
2162void AudioProcessingImpl::RecordAudioProcessingState() {
2163 RTC_DCHECK(aec_dump_);
2164 AecDump::AudioProcessingState audio_proc_state;
2165 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2166 audio_proc_state.drift =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002167 private_submodules_->echo_cancellation
2168 ? private_submodules_->echo_cancellation->stream_drift_samples()
2169 : 0;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002170 audio_proc_state.level = agc1()->stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002171 audio_proc_state.keypress = capture_.key_pressed;
2172 aec_dump_->AddAudioProcessingState(audio_proc_state);
2173}
2174
kwiberg83ffe452016-08-29 14:46:07 -07002175AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002176 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002177 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002178 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002179 output_will_be_muted(false),
2180 key_pressed(false),
2181 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002182 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002183 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002184 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002185 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002186 prev_pre_amp_gain(-1.f),
2187 playout_volume(-1),
2188 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002189
2190AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2191
Per Åhgrena1351272019-08-15 12:15:46 +02002192void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2193 const float* const* data,
2194 const StreamConfig& stream_config) {
2195 if (stream_config.has_keyboard()) {
2196 keyboard_data = data[stream_config.num_channels()];
2197 } else {
2198 keyboard_data = NULL;
2199 }
2200 num_keyboard_frames = stream_config.num_frames();
2201}
2202
kwiberg83ffe452016-08-29 14:46:07 -07002203AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2204
2205AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2206
niklase@google.com470e71d2011-07-07 08:21:25 +00002207} // namespace webrtc