blob: 6950623523354df15259eebe3bf55673c048be5f [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <type_traits>
17#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000018
Per Åhgren200feba2019-03-06 04:16:46 +010019#include "absl/memory/memory.h"
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"
Yves Gerey988cc082018-10-23 12:03:01 +020035#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020036#include "modules/audio_processing/level_estimator_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010037#include "modules/audio_processing/logging/apm_data_dumper.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020038#include "modules/audio_processing/low_cut_filter.h"
39#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"
43#include "modules/audio_processing/voice_detection_impl.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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000052
Michael Graczyk86c6d332015-07-23 11:41:39 -070053#define RETURN_ON_ERR(expr) \
54 do { \
55 int err = (expr); \
56 if (err != kNoError) { \
57 return err; \
58 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000059 } while (0)
60
niklase@google.com470e71d2011-07-07 08:21:25 +000061namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070062
kwibergd59d3bb2016-09-13 07:49:33 -070063constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020064constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070065
Michael Graczyk86c6d332015-07-23 11:41:39 -070066namespace {
67
68static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
69 switch (layout) {
70 case AudioProcessing::kMono:
71 case AudioProcessing::kStereo:
72 return false;
73 case AudioProcessing::kMonoAndKeyboard:
74 case AudioProcessing::kStereoAndKeyboard:
75 return true;
76 }
77
kwiberg9e2be5f2016-09-14 05:23:22 -070078 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070079 return false;
80}
aluebsdf6416a2016-03-16 18:26:35 -070081
peah2ace3f92016-09-10 04:42:27 -070082bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070083 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
84 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
85}
86
peah2ace3f92016-09-10 04:42:27 -070087int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
88#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070089 constexpr int kMaxSplittingNativeProcessRate =
90 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070091#else
kwibergd59d3bb2016-09-13 07:49:33 -070092 constexpr int kMaxSplittingNativeProcessRate =
93 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070094#endif
kwibergd59d3bb2016-09-13 07:49:33 -070095 static_assert(
96 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
97 "");
peah2ace3f92016-09-10 04:42:27 -070098 const int uppermost_native_rate = band_splitting_required
99 ? kMaxSplittingNativeProcessRate
100 : AudioProcessing::kSampleRate48kHz;
101
102 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
103 if (rate >= uppermost_native_rate) {
104 return uppermost_native_rate;
105 }
106 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700107 return rate;
108 }
109 }
peah2ace3f92016-09-10 04:42:27 -0700110 RTC_NOTREACHED();
111 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700112}
113
Sam Zackrisson23513132019-01-11 15:10:32 +0100114NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
115 AudioProcessing::Config::NoiseSuppression::Level level) {
116 using NsConfig = AudioProcessing::Config::NoiseSuppression;
117 switch (level) {
118 case NsConfig::kLow:
119 return NoiseSuppression::kLow;
120 case NsConfig::kModerate:
121 return NoiseSuppression::kModerate;
122 case NsConfig::kHigh:
123 return NoiseSuppression::kHigh;
124 case NsConfig::kVeryHigh:
125 return NoiseSuppression::kVeryHigh;
126 default:
127 RTC_NOTREACHED();
128 }
129}
130
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100131GainControl::Mode Agc1ConfigModeToInterfaceMode(
132 AudioProcessing::Config::GainController1::Mode mode) {
133 using Agc1Config = AudioProcessing::Config::GainController1;
134 switch (mode) {
135 case Agc1Config::kAdaptiveAnalog:
136 return GainControl::kAdaptiveAnalog;
137 case Agc1Config::kAdaptiveDigital:
138 return GainControl::kAdaptiveDigital;
139 case Agc1Config::kFixedDigital:
140 return GainControl::kFixedDigital;
141 }
142}
143
peah9e6a2902017-05-15 07:19:21 -0700144// Maximum lengths that frame of samples being passed from the render side to
145// the capture side can have (does not apply to AEC3).
146static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
147static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
148
peah764e3642016-10-22 05:04:30 -0700149// Maximum number of frames to buffer in the render queue.
150// TODO(peah): Decrease this once we properly handle hugely unbalanced
151// reverse and forward call numbers.
152static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700153} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000154
155// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000156static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000157
Sam Zackrisson0beac582017-09-25 12:04:02 +0200158AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100159 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200160 bool render_pre_processor_enabled,
161 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100162 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200163 render_pre_processor_enabled_(render_pre_processor_enabled),
164 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700165
166bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200167 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700168 bool echo_canceller_enabled,
169 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700170 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700171 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700172 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700173 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200174 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200175 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700176 bool voice_activity_detector_enabled,
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100177 bool private_voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700178 bool level_estimator_enabled,
179 bool transient_suppressor_enabled) {
180 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200181 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700182 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
183 changed |=
184 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700185 changed |=
186 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700187 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
188 changed |=
peah2ace3f92016-09-10 04:42:27 -0700189 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700190 changed |=
191 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200192 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200193 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700194 changed |= (level_estimator_enabled != level_estimator_enabled_);
195 changed |=
196 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100197 changed |=
198 (private_voice_detector_enabled != private_voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700199 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
200 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200201 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700202 echo_canceller_enabled_ = echo_canceller_enabled;
203 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700204 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700205 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700206 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700207 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200208 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200209 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700210 level_estimator_enabled_ = level_estimator_enabled;
211 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100212 private_voice_detector_enabled_ = private_voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700213 transient_suppressor_enabled_ = transient_suppressor_enabled;
214 }
215
216 changed |= first_update_;
217 first_update_ = false;
218 return changed;
219}
220
221bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
222 const {
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100223 return CaptureMultiBandProcessingActive() ||
224 voice_activity_detector_enabled_ || private_voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700225}
226
227bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
228 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200229 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700230 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200231 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700232}
233
peah23ac8b42017-05-23 05:33:56 -0700234bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
235 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200236 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
237 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700238}
239
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200240bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
241 return capture_analyzer_enabled_;
242}
243
peah2ace3f92016-09-10 04:42:27 -0700244bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
245 const {
246 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800247 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200248 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700249}
250
Alex Loiko5825aa62017-12-18 16:02:40 +0100251bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
252 const {
253 return render_pre_processor_enabled_;
254}
255
peah2ace3f92016-09-10 04:42:27 -0700256bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
257 const {
peah2ace3f92016-09-10 04:42:27 -0700258 return false;
peah2ace3f92016-09-10 04:42:27 -0700259}
260
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200261bool AudioProcessingImpl::ApmSubmoduleStates::LowCutFilteringRequired() const {
262 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
263 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
264}
265
solenberg5e465c32015-12-08 13:22:33 -0800266struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800267 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800268 // Accessed externally of APM without any lock acquired.
Sam Zackrisson23513132019-01-11 15:10:32 +0100269 // TODO(bugs.webrtc.org/9947): Move these submodules into private_submodules_
270 // when their pointer-to-submodule API functions are gone.
kwiberg88788ad2016-02-19 07:04:49 -0800271 std::unique_ptr<LevelEstimatorImpl> level_estimator;
272 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
Sam Zackrisson23513132019-01-11 15:10:32 +0100273 std::unique_ptr<NoiseSuppressionProxy> noise_suppression_proxy;
kwiberg88788ad2016-02-19 07:04:49 -0800274 std::unique_ptr<VoiceDetectionImpl> voice_detection;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100275 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800276 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800277 gain_control_for_experimental_agc;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100278 std::unique_ptr<GainControlConfigProxy> gain_control_config_proxy;
solenberg5e465c32015-12-08 13:22:33 -0800279
280 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800281 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800282};
283
284struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200285 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100286 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200287 rtc::scoped_refptr<EchoDetector> echo_detector,
288 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200289 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100290 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200291 render_pre_processor(std::move(render_pre_processor)),
292 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800293 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800294 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700295 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800296 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200297 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100298 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100299 std::unique_ptr<EchoControl> echo_controller;
300 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100301 std::unique_ptr<CustomProcessing> capture_post_processor;
302 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200303 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200304 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100305 std::unique_ptr<LevelEstimatorImpl> output_level_estimator;
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100306 std::unique_ptr<VoiceDetectionImpl> voice_detector;
solenberg5e465c32015-12-08 13:22:33 -0800307};
308
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100309AudioProcessingBuilder::AudioProcessingBuilder() = default;
310AudioProcessingBuilder::~AudioProcessingBuilder() = default;
311
312AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
313 std::unique_ptr<CustomProcessing> capture_post_processing) {
314 capture_post_processing_ = std::move(capture_post_processing);
315 return *this;
316}
317
318AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
319 std::unique_ptr<CustomProcessing> render_pre_processing) {
320 render_pre_processing_ = std::move(render_pre_processing);
321 return *this;
322}
323
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200324AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
325 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
326 capture_analyzer_ = std::move(capture_analyzer);
327 return *this;
328}
329
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100330AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
331 std::unique_ptr<EchoControlFactory> echo_control_factory) {
332 echo_control_factory_ = std::move(echo_control_factory);
333 return *this;
334}
335
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100336AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200337 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100338 echo_detector_ = std::move(echo_detector);
339 return *this;
340}
341
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100342AudioProcessing* AudioProcessingBuilder::Create() {
343 webrtc::Config config;
344 return Create(config);
345}
346
347AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100348 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
349 config, std::move(capture_post_processing_),
350 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200351 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100352 if (apm->Initialize() != AudioProcessing::kNoError) {
353 delete apm;
354 apm = nullptr;
355 }
356 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100357}
358
peah88ac8532016-09-12 16:47:25 -0700359AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200360 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
361}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000362
Per Åhgren13735822018-02-12 21:42:56 +0100363int AudioProcessingImpl::instance_count_ = 0;
364
Sam Zackrisson0beac582017-09-25 12:04:02 +0200365AudioProcessingImpl::AudioProcessingImpl(
366 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100367 std::unique_ptr<CustomProcessing> capture_post_processor,
368 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200369 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200370 rtc::scoped_refptr<EchoDetector> echo_detector,
371 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100372 : data_dumper_(
373 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200374 capture_runtime_settings_(kRuntimeSettingQueueSize),
375 render_runtime_settings_(kRuntimeSettingQueueSize),
376 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
377 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200378 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200379 submodule_states_(!!capture_post_processor,
380 !!render_pre_processor,
381 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800382 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200383 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200384 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100385 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200386 std::move(echo_detector),
387 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800388 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800389 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000390#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200391 /* enabled= */ false,
392 /* enabled_agc2_level_estimator= */ false,
393 /* digital_adaptive_disabled= */ false,
394 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000395#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200396 config.Get<ExperimentalAgc>().enabled,
397 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200398 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
399 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000400#endif
andrew1c7075f2015-06-24 18:14:14 -0700401#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200402 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700403#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200404 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700405#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200406 capture_nonlocked_() {
Sam Zackrisson421c8592019-02-11 13:39:46 +0100407 // Mark Echo Controller enabled if a factory is injected.
408 capture_nonlocked_.echo_controller_enabled =
409 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000410
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100411 public_submodules_->gain_control.reset(new GainControlImpl());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100412 public_submodules_->level_estimator.reset(
413 new LevelEstimatorImpl(&crit_capture_));
414 public_submodules_->noise_suppression.reset(
415 new NoiseSuppressionImpl(&crit_capture_));
416 public_submodules_->noise_suppression_proxy.reset(new NoiseSuppressionProxy(
417 this, public_submodules_->noise_suppression.get()));
418 public_submodules_->voice_detection.reset(
419 new VoiceDetectionImpl(&crit_capture_));
420 public_submodules_->gain_control_for_experimental_agc.reset(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100421 new GainControlForExperimentalAgc(
422 public_submodules_->gain_control.get()));
423 public_submodules_->gain_control_config_proxy.reset(
424 new GainControlConfigProxy(&crit_capture_, this, agc1()));
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200425
Sam Zackrisson421c8592019-02-11 13:39:46 +0100426 // If no echo detector is injected, use the ResidualEchoDetector.
427 if (!private_submodules_->echo_detector) {
428 private_submodules_->echo_detector =
429 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800430 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000431
Sam Zackrisson421c8592019-02-11 13:39:46 +0100432 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
433 // TODO(alessiob): Move the injected gain controller once injection is
434 // implemented.
435 private_submodules_->gain_controller2.reset(new GainController2());
436
437 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
438 << !!private_submodules_->capture_analyzer
439 << "\nCapture post processor activated: "
440 << !!private_submodules_->capture_post_processor
441 << "\nRender pre processor activated: "
442 << !!private_submodules_->render_pre_processor;
443
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000444 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000445}
446
447AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800448 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800449 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800450 private_submodules_->agc_manager.reset();
451 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800452 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000453}
454
niklase@google.com470e71d2011-07-07 08:21:25 +0000455int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800456 // Run in a single-threaded manner during initialization.
457 rtc::CritScope cs_render(&crit_render_);
458 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000459 return InitializeLocked();
460}
461
peahde65ddc2016-09-16 15:02:15 -0700462int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
463 int capture_output_sample_rate_hz,
464 int render_input_sample_rate_hz,
465 ChannelLayout capture_input_layout,
466 ChannelLayout capture_output_layout,
467 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700468 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700469 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
470 LayoutHasKeyboard(capture_input_layout)},
471 {capture_output_sample_rate_hz,
472 ChannelsFromLayout(capture_output_layout),
473 LayoutHasKeyboard(capture_output_layout)},
474 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
475 LayoutHasKeyboard(render_input_layout)},
476 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
477 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700478
479 return Initialize(processing_config);
480}
481
482int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800483 // Run in a single-threaded manner during initialization.
484 rtc::CritScope cs_render(&crit_render_);
485 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700486 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000487}
488
peahdf3efa82015-11-28 12:35:15 -0800489int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800490 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700491 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800492}
493
peahdf3efa82015-11-28 12:35:15 -0800494int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700495 const ProcessingConfig& processing_config,
496 bool force_initialization) {
497 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800498}
499
peah192164e2015-11-17 02:16:45 -0800500// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800501// their current values (needs to be called while holding the crit_render_lock).
502int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700503 const ProcessingConfig& processing_config,
504 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800505 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700506 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800507 return kNoError;
508 }
peahdf3efa82015-11-28 12:35:15 -0800509
510 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800511 return InitializeLocked(processing_config);
512}
513
niklase@google.com470e71d2011-07-07 08:21:25 +0000514int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200515 UpdateActiveSubmoduleStates();
516
peahde65ddc2016-09-16 15:02:15 -0700517 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800518 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700519 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800520 : formats_.api_format.reverse_output_stream().num_frames();
521 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
522 render_.render_audio.reset(new AudioBuffer(
523 formats_.api_format.reverse_input_stream().num_frames(),
524 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700525 formats_.render_processing_format.num_frames(),
526 formats_.render_processing_format.num_channels(),
527 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700528 if (formats_.api_format.reverse_input_stream() !=
529 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800530 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800531 formats_.api_format.reverse_input_stream().num_channels(),
532 formats_.api_format.reverse_input_stream().num_frames(),
533 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800534 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700535 } else {
peahdf3efa82015-11-28 12:35:15 -0800536 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700537 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700538 } else {
peahdf3efa82015-11-28 12:35:15 -0800539 render_.render_audio.reset(nullptr);
540 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700541 }
peahce4d9152017-05-19 01:28:05 -0700542
peahdf3efa82015-11-28 12:35:15 -0800543 capture_.capture_audio.reset(
544 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
545 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700546 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200547 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800548 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000549
peah764e3642016-10-22 05:04:30 -0700550 AllocateRenderQueue();
551
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100552 private_submodules_->echo_control_mobile->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700553 proc_split_sample_rate_hz(), num_reverse_channels(),
554 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700555
556 public_submodules_->gain_control->Initialize(num_proc_channels(),
557 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700558 if (constants_.use_experimental_agc) {
559 if (!private_submodules_->agc_manager.get()) {
560 private_submodules_->agc_manager.reset(new AgcManagerDirect(
561 public_submodules_->gain_control.get(),
562 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200563 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
564 constants_.use_experimental_agc_agc2_level_estimation,
565 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700566 }
567 private_submodules_->agc_manager->Initialize();
568 private_submodules_->agc_manager->SetCaptureMuted(
569 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700570 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700571 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200572 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800573 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700574 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
575 proc_sample_rate_hz());
576 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100577 if (private_submodules_->voice_detector) {
578 private_submodules_->voice_detector->Initialize(
579 proc_split_sample_rate_hz());
580 }
peahde65ddc2016-09-16 15:02:15 -0700581 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700582 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200583 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700584 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200585 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200586 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100587 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800588
aleloi868f32f2017-05-23 07:20:05 -0700589 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200590 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700591 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000592 return kNoError;
593}
594
Michael Graczyk86c6d332015-07-23 11:41:39 -0700595int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200596 UpdateActiveSubmoduleStates();
597
Michael Graczyk86c6d332015-07-23 11:41:39 -0700598 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700599 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
600 return kBadSampleRateError;
601 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000602 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700603
Peter Kasting69558702016-01-12 16:26:35 -0800604 const size_t num_in_channels = config.input_stream().num_channels();
605 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700606
607 // Need at least one input channel.
608 // Need either one output channel or as many outputs as there are inputs.
609 if (num_in_channels == 0 ||
610 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700611 return kBadNumberChannelsError;
612 }
613
peahdf3efa82015-11-28 12:35:15 -0800614 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000615
peahde65ddc2016-09-16 15:02:15 -0700616 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700617 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700618 formats_.api_format.output_stream().sample_rate_hz()),
619 submodule_states_.CaptureMultiBandSubModulesActive() ||
620 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000621
peahde65ddc2016-09-16 15:02:15 -0700622 capture_nonlocked_.capture_processing_format =
623 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700624
peah2ce640f2017-04-07 03:57:48 -0700625 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200626 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700627 render_processing_rate = FindNativeProcessRateToUse(
628 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
629 formats_.api_format.reverse_output_stream().sample_rate_hz()),
630 submodule_states_.CaptureMultiBandSubModulesActive() ||
631 submodule_states_.RenderMultiBandSubModulesActive());
632 } else {
633 render_processing_rate = capture_processing_rate;
634 }
635
aluebseb3603b2016-04-20 15:27:58 -0700636 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
637 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700638 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200639 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700640 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
641 ? kSampleRate32kHz
642 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700643 }
peah2ce640f2017-04-07 03:57:48 -0700644
peahde65ddc2016-09-16 15:02:15 -0700645 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700646 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700647 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
648 kSampleRate8kHz) {
649 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000650 } else {
peahde65ddc2016-09-16 15:02:15 -0700651 render_processing_rate =
652 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000653 }
654
peahde65ddc2016-09-16 15:02:15 -0700655 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000656 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700657 if (submodule_states_.RenderMultiBandSubModulesActive()) {
658 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
659 } else {
660 formats_.render_processing_format = StreamConfig(
661 formats_.api_format.reverse_input_stream().sample_rate_hz(),
662 formats_.api_format.reverse_input_stream().num_channels());
663 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000664
peahde65ddc2016-09-16 15:02:15 -0700665 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
666 kSampleRate32kHz ||
667 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
668 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800669 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000670 } else {
peahdf3efa82015-11-28 12:35:15 -0800671 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700672 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000673 }
674
675 return InitializeLocked();
676}
677
peah88ac8532016-09-12 16:47:25 -0700678void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700679 // Run in a single-threaded manner when applying the settings.
680 rtc::CritScope cs_render(&crit_render_);
681 rtc::CritScope cs_capture(&crit_capture_);
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
Yves Gerey499bc6c2018-10-10 18:29:07 +0200706 config_ = config;
707
Per Åhgren200feba2019-03-06 04:16:46 +0100708 if (aec_config_changed) {
709 InitializeEchoController();
710 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200711
Sam Zackrisson23513132019-01-11 15:10:32 +0100712 public_submodules_->noise_suppression->Enable(
713 config.noise_suppression.enabled);
714 public_submodules_->noise_suppression->set_level(
715 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
716
peah8271d042016-11-22 07:24:52 -0800717 InitializeLowCutFilter();
718
Mirko Bonadei675513b2017-11-09 11:09:25 +0100719 RTC_LOG(LS_INFO) << "Highpass filter activated: "
720 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800721
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100722 if (agc1_config_changed) {
723 ApplyAgc1Config(config_.gain_controller1);
724 }
725
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100726 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700727 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100728 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
729 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100730 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100731 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700732 config_.gain_controller2 = AudioProcessing::Config::GainController2();
733 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200734 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200735 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200736 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100737 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
738 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200739 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
740 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100741
742 if (config_.level_estimation.enabled &&
743 !private_submodules_->output_level_estimator) {
744 private_submodules_->output_level_estimator.reset(
745 new LevelEstimatorImpl(&crit_capture_));
746 private_submodules_->output_level_estimator->Enable(true);
747 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100748
749 if (config_.voice_detection.enabled && !private_submodules_->voice_detector) {
750 private_submodules_->voice_detector.reset(
751 new VoiceDetectionImpl(&crit_capture_));
752 private_submodules_->voice_detector->Enable(true);
753 private_submodules_->voice_detector->set_likelihood(
754 VoiceDetection::kVeryLowLikelihood);
755 private_submodules_->voice_detector->Initialize(
756 proc_split_sample_rate_hz());
757 }
peah88ac8532016-09-12 16:47:25 -0700758}
759
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100760void AudioProcessingImpl::ApplyAgc1Config(
761 const Config::GainController1& config) {
762 GainControl* agc = agc1();
763 int error = agc->Enable(config.enabled);
764 RTC_DCHECK_EQ(kNoError, error);
765 error = agc->set_mode(Agc1ConfigModeToInterfaceMode(config.mode));
766 RTC_DCHECK_EQ(kNoError, error);
767 error = agc->set_target_level_dbfs(config.target_level_dbfs);
768 RTC_DCHECK_EQ(kNoError, error);
769 error = agc->set_compression_gain_db(config.compression_gain_db);
770 RTC_DCHECK_EQ(kNoError, error);
771 error = agc->enable_limiter(config.enable_limiter);
772 RTC_DCHECK_EQ(kNoError, error);
773 error = agc->set_analog_level_limits(config.analog_level_minimum,
774 config.analog_level_maximum);
775 RTC_DCHECK_EQ(kNoError, error);
776}
777
778GainControl* AudioProcessingImpl::agc1() {
779 if (constants_.use_experimental_agc) {
780 return public_submodules_->gain_control_for_experimental_agc.get();
781 }
782 return public_submodules_->gain_control.get();
783}
784
785const GainControl* AudioProcessingImpl::agc1() const {
786 if (constants_.use_experimental_agc) {
787 return public_submodules_->gain_control_for_experimental_agc.get();
788 }
789 return public_submodules_->gain_control.get();
790}
791
peah88ac8532016-09-12 16:47:25 -0700792void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800793 // Run in a single-threaded manner when setting the extra options.
794 rtc::CritScope cs_render(&crit_render_);
795 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000796
Per Åhgrenf204faf2019-04-25 15:18:06 +0200797 capture_nonlocked_.use_aec2_extended_filter =
798 config.Get<ExtendedFilter>().enabled;
799 capture_nonlocked_.use_aec2_delay_agnostic =
800 config.Get<DelayAgnostic>().enabled;
801 capture_nonlocked_.use_aec2_refined_adaptive_filter =
802 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800803
peahdf3efa82015-11-28 12:35:15 -0800804 if (capture_.transient_suppressor_enabled !=
805 config.Get<ExperimentalNs>().enabled) {
806 capture_.transient_suppressor_enabled =
807 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000808 InitializeTransient();
809 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000810}
811
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000812int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800813 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700814 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000815}
816
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000817int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800818 // Used as callback from submodules, hence locking is not allowed.
819 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000820}
821
Peter Kasting69558702016-01-12 16:26:35 -0800822size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800823 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700824 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000825}
826
Peter Kasting69558702016-01-12 16:26:35 -0800827size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800828 // Used as callback from submodules, hence locking is not allowed.
829 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000830}
831
Peter Kasting69558702016-01-12 16:26:35 -0800832size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800833 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200834 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800835}
836
Peter Kasting69558702016-01-12 16:26:35 -0800837size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800838 // Used as callback from submodules, hence locking is not allowed.
839 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000840}
841
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000842void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800843 rtc::CritScope cs(&crit_capture_);
844 capture_.output_will_be_muted = muted;
845 if (private_submodules_->agc_manager.get()) {
846 private_submodules_->agc_manager->SetCaptureMuted(
847 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000848 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000849}
850
Alessio Bazzicac054e782018-04-16 12:10:09 +0200851void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200852 switch (setting.type()) {
853 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
854 render_runtime_settings_enqueuer_.Enqueue(setting);
855 return;
856 case RuntimeSetting::Type::kNotSpecified:
857 RTC_NOTREACHED();
858 return;
859 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100860 case RuntimeSetting::Type::kCaptureCompressionGain:
Alex Loiko73ec0192018-05-15 10:52:28 +0200861 capture_runtime_settings_enqueuer_.Enqueue(setting);
862 return;
863 }
864 // The language allows the enum to have a non-enumerator
865 // value. Check that this doesn't happen.
866 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200867}
868
869AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
870 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200871 : runtime_settings_(*runtime_settings) {
872 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200873}
874
875AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
876 default;
877
878void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
879 RuntimeSetting setting) {
880 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200881 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200882 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200883 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200884 RTC_LOG(LS_ERROR)
885 << "The runtime settings queue is full. Oldest setting discarded.";
886 }
887 if (remaining_attempts == 0)
888 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
889}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000890
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000891int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700892 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000893 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000894 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000895 int output_sample_rate_hz,
896 ChannelLayout output_layout,
897 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800898 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800899 StreamConfig input_stream;
900 StreamConfig output_stream;
901 {
902 // Access the formats_.api_format.input_stream beneath the capture lock.
903 // The lock must be released as it is later required in the call
904 // to ProcessStream(,,,);
905 rtc::CritScope cs(&crit_capture_);
906 input_stream = formats_.api_format.input_stream();
907 output_stream = formats_.api_format.output_stream();
908 }
909
Michael Graczyk86c6d332015-07-23 11:41:39 -0700910 input_stream.set_sample_rate_hz(input_sample_rate_hz);
911 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
912 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700913 output_stream.set_sample_rate_hz(output_sample_rate_hz);
914 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
915 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
916
917 if (samples_per_channel != input_stream.num_frames()) {
918 return kBadDataLengthError;
919 }
920 return ProcessStream(src, input_stream, output_stream, dest);
921}
922
923int AudioProcessingImpl::ProcessStream(const float* const* src,
924 const StreamConfig& input_config,
925 const StreamConfig& output_config,
926 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800927 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800928 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700929 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800930 {
931 // Acquire the capture lock in order to safely call the function
932 // that retrieves the render side data. This function accesses apm
933 // getters that need the capture lock held when being called.
934 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700935 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800936
937 if (!src || !dest) {
938 return kNullPointerError;
939 }
940
941 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700942 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000943 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000944
Michael Graczyk86c6d332015-07-23 11:41:39 -0700945 processing_config.input_stream() = input_config;
946 processing_config.output_stream() = output_config;
947
peahdf3efa82015-11-28 12:35:15 -0800948 {
949 // Do conditional reinitialization.
950 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700951 RETURN_ON_ERR(
952 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800953 }
954 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700955 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
956 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000957
aleloi868f32f2017-05-23 07:20:05 -0700958 if (aec_dump_) {
959 RecordUnprocessedCaptureStream(src);
960 }
961
peahdf3efa82015-11-28 12:35:15 -0800962 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700963 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800964 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000965
aleloi868f32f2017-05-23 07:20:05 -0700966 if (aec_dump_) {
967 RecordProcessedCaptureStream(dest);
968 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000969 return kNoError;
970}
971
Alex Loiko73ec0192018-05-15 10:52:28 +0200972void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200973 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200974 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200975 if (aec_dump_) {
976 aec_dump_->WriteRuntimeSetting(setting);
977 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200978 switch (setting.type()) {
979 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200980 if (config_.pre_amplifier.enabled) {
981 float value;
982 setting.GetFloat(&value);
983 private_submodules_->pre_amplifier->SetGainFactor(value);
984 }
985 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200986 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100987 case RuntimeSetting::Type::kCaptureCompressionGain: {
988 float value;
989 setting.GetFloat(&value);
990 int int_value = static_cast<int>(value + .5f);
991 config_.gain_controller1.compression_gain_db = int_value;
992 int error = agc1()->set_compression_gain_db(int_value);
993 RTC_DCHECK_EQ(kNoError, error);
994 break;
995 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200996 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
997 RTC_NOTREACHED();
998 break;
999 case RuntimeSetting::Type::kNotSpecified:
1000 RTC_NOTREACHED();
1001 break;
1002 }
1003 }
1004}
1005
1006void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1007 RuntimeSetting setting;
1008 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001009 if (aec_dump_) {
1010 aec_dump_->WriteRuntimeSetting(setting);
1011 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001012 switch (setting.type()) {
1013 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1014 if (private_submodules_->render_pre_processor) {
1015 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
1016 }
1017 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001018 case RuntimeSetting::Type::kCapturePreGain: // fall-through
1019 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001020 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +02001021 RTC_NOTREACHED();
1022 break;
1023 }
1024 }
1025}
1026
peah9e6a2902017-05-15 07:19:21 -07001027void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -07001028 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1029 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -07001030 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001031
kwibergaf476c72016-11-28 15:21:39 -08001032 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001033
1034 // Insert the samples into the queue.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001035 if (private_submodules_->echo_cancellation) {
1036 RTC_DCHECK(aec_render_signal_queue_);
1037 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1038 // The data queue is full and needs to be emptied.
1039 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001040
Per Åhgrenf204faf2019-04-25 15:18:06 +02001041 // Retry the insert (should always work).
1042 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1043 RTC_DCHECK(result);
1044 }
peaha0624602016-10-25 04:45:24 -07001045 }
1046
1047 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1048 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -07001049 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001050
1051 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -07001052 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001053 // The data queue is full and needs to be emptied.
1054 EmptyQueuedRenderAudio();
1055
1056 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -07001057 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001058 RTC_DCHECK(result);
1059 }
peah701d6282016-10-25 05:42:20 -07001060
1061 if (!constants_.use_experimental_agc) {
1062 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
1063 // Insert the samples into the queue.
1064 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1065 // The data queue is full and needs to be emptied.
1066 EmptyQueuedRenderAudio();
1067
1068 // Retry the insert (should always work).
1069 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1070 RTC_DCHECK(result);
1071 }
1072 }
peah9e6a2902017-05-15 07:19:21 -07001073}
ivoc9f4a4a02016-10-28 05:39:16 -07001074
peah9e6a2902017-05-15 07:19:21 -07001075void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001076 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1077
1078 // Insert the samples into the queue.
1079 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1080 // The data queue is full and needs to be emptied.
1081 EmptyQueuedRenderAudio();
1082
1083 // Retry the insert (should always work).
1084 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1085 RTC_DCHECK(result);
1086 }
peah764e3642016-10-22 05:04:30 -07001087}
1088
1089void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001090 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001091 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001092 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001093 EchoControlMobileImpl::NumCancellersRequired(
1094 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001095
peah701d6282016-10-25 05:42:20 -07001096 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001097 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001098
ivoc9f4a4a02016-10-28 05:39:16 -07001099 const size_t new_red_render_queue_element_max_size =
1100 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1101
peaha0624602016-10-25 04:45:24 -07001102 // Reallocate the queues if the queue item sizes are too small to fit the
1103 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001104 if (aecm_render_queue_element_max_size_ <
1105 new_aecm_render_queue_element_max_size) {
1106 aecm_render_queue_element_max_size_ =
1107 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001108
1109 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001110 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001111
peah701d6282016-10-25 05:42:20 -07001112 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001113 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1114 kMaxNumFramesToBuffer, template_queue_element,
1115 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001116 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001117
peah701d6282016-10-25 05:42:20 -07001118 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1119 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001120 } else {
peah701d6282016-10-25 05:42:20 -07001121 aecm_render_signal_queue_->Clear();
1122 }
1123
1124 if (agc_render_queue_element_max_size_ <
1125 new_agc_render_queue_element_max_size) {
1126 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1127
1128 std::vector<int16_t> template_queue_element(
1129 agc_render_queue_element_max_size_);
1130
1131 agc_render_signal_queue_.reset(
1132 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1133 kMaxNumFramesToBuffer, template_queue_element,
1134 RenderQueueItemVerifier<int16_t>(
1135 agc_render_queue_element_max_size_)));
1136
1137 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1138 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1139 } else {
1140 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001141 }
ivoc9f4a4a02016-10-28 05:39:16 -07001142
1143 if (red_render_queue_element_max_size_ <
1144 new_red_render_queue_element_max_size) {
1145 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1146
1147 std::vector<float> template_queue_element(
1148 red_render_queue_element_max_size_);
1149
1150 red_render_signal_queue_.reset(
1151 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1152 kMaxNumFramesToBuffer, template_queue_element,
1153 RenderQueueItemVerifier<float>(
1154 red_render_queue_element_max_size_)));
1155
1156 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1157 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1158 } else {
1159 red_render_signal_queue_->Clear();
1160 }
peah764e3642016-10-22 05:04:30 -07001161}
1162
1163void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1164 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001165 if (private_submodules_->echo_cancellation) {
1166 RTC_DCHECK(aec_render_signal_queue_);
1167 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
1168 private_submodules_->echo_cancellation->ProcessRenderAudio(
1169 aec_capture_queue_buffer_);
1170 }
peaha0624602016-10-25 04:45:24 -07001171 }
1172
peah701d6282016-10-25 05:42:20 -07001173 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001174 private_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001175 aecm_capture_queue_buffer_);
1176 }
1177
1178 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1179 public_submodules_->gain_control->ProcessRenderAudio(
1180 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001181 }
ivoc9f4a4a02016-10-28 05:39:16 -07001182
1183 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001184 RTC_DCHECK(private_submodules_->echo_detector);
1185 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001186 red_capture_queue_buffer_);
1187 }
peah764e3642016-10-22 05:04:30 -07001188}
1189
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001190int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001191 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001192 {
1193 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001194 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001195 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001196 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001197 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001198 }
peahfa6228e2015-11-16 16:27:42 -08001199
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001200 if (!frame) {
1201 return kNullPointerError;
1202 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001203 // Must be a native rate.
1204 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1205 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001206 frame->sample_rate_hz_ != kSampleRate32kHz &&
1207 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001208 return kBadSampleRateError;
1209 }
peah192164e2015-11-17 02:16:45 -08001210
peahdf3efa82015-11-28 12:35:15 -08001211 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001212 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001213 {
1214 // Aquire lock for the access of api_format.
1215 // The lock is released immediately due to the conditional
1216 // reinitialization.
1217 rtc::CritScope cs_capture(&crit_capture_);
1218 // TODO(ajm): The input and output rates and channels are currently
1219 // constrained to be identical in the int16 interface.
1220 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001221
1222 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001223 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001224 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1225 processing_config.input_stream().set_num_channels(frame->num_channels_);
1226 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1227 processing_config.output_stream().set_num_channels(frame->num_channels_);
1228
peahdf3efa82015-11-28 12:35:15 -08001229 {
1230 // Do conditional reinitialization.
1231 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001232 RETURN_ON_ERR(
1233 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001234 }
1235 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001236 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001237 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001238 return kBadDataLengthError;
1239 }
1240
aleloi868f32f2017-05-23 07:20:05 -07001241 if (aec_dump_) {
1242 RecordUnprocessedCaptureStream(*frame);
1243 }
1244
peahdf3efa82015-11-28 12:35:15 -08001245 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001246 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001247 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001248 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1249 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001250
aleloi868f32f2017-05-23 07:20:05 -07001251 if (aec_dump_) {
1252 RecordProcessedCaptureStream(*frame);
1253 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001254
1255 return kNoError;
1256}
1257
peahde65ddc2016-09-16 15:02:15 -07001258int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001259 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001260
peahb58a1582016-03-15 09:34:24 -07001261 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001262 // TODO(peah): Simplify once the public API Enable functions for these
1263 // are moved to APM.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001264 RTC_DCHECK(!((private_submodules_->echo_cancellation &&
1265 private_submodules_->echo_cancellation->is_enabled()) &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001266 private_submodules_->echo_control_mobile->is_enabled()));
peahb58a1582016-03-15 09:34:24 -07001267
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001268 MaybeUpdateHistograms();
1269
peahde65ddc2016-09-16 15:02:15 -07001270 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001271
Alex Loikob5c9a792018-04-16 16:31:22 +02001272 if (private_submodules_->pre_amplifier) {
1273 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1274 capture_buffer->channels_f(), capture_buffer->num_channels(),
1275 capture_buffer->num_frames()));
1276 }
1277
peah1b08dc32016-12-20 13:45:58 -08001278 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001279 capture_buffer->channels_const()[0],
1280 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001281 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1282 if (log_rms) {
1283 capture_rms_interval_counter_ = 0;
1284 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001285 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1286 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1287 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1288 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001289 }
1290
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001291 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001292 // Detect and flag any change in the analog gain.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001293 int analog_mic_level = agc1()->stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001294 capture_.echo_path_gain_change =
1295 capture_.prev_analog_mic_level != analog_mic_level &&
1296 capture_.prev_analog_mic_level != -1;
1297 capture_.prev_analog_mic_level = analog_mic_level;
1298
Per Åhgrend2650d12018-10-02 17:00:59 +02001299 // Detect and flag any change in the pre-amplifier gain.
1300 if (private_submodules_->pre_amplifier) {
1301 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1302 capture_.echo_path_gain_change =
1303 capture_.echo_path_gain_change ||
1304 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001305 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001306 capture_.prev_pre_amp_gain = pre_amp_gain;
1307 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001308 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001309 }
1310
peahbe615622016-02-13 16:40:47 -08001311 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001312 public_submodules_->gain_control->is_enabled()) {
1313 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001314 capture_buffer->channels()[0], capture_buffer->num_channels(),
1315 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001316
1317 if (constants_.use_experimental_agc_process_before_aec) {
1318 private_submodules_->agc_manager->Process(
1319 capture_buffer->channels()[0],
1320 capture_nonlocked_.capture_processing_format.num_frames(),
1321 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1322 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001323 }
1324
peah2ace3f92016-09-10 04:42:27 -07001325 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1326 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001327 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1328 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001329 }
1330
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001331 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001332 // Force down-mixing of the number of channels after the detection of
1333 // capture signal saturation.
1334 // TODO(peah): Look into ensuring that this kind of tampering with the
1335 // AudioBuffer functionality should not be needed.
1336 capture_buffer->set_num_channels(1);
1337 }
1338
peahe0eae3c2016-12-14 01:16:23 -08001339 // TODO(peah): Move the AEC3 low-cut filter to this place.
1340 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001341 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001342 private_submodules_->low_cut_filter->Process(capture_buffer);
1343 }
peahde65ddc2016-09-16 15:02:15 -07001344 RETURN_ON_ERR(
1345 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1346 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001347
1348 // Ensure that the stream delay was set before the call to the
1349 // AEC ProcessCaptureAudio function.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001350 if (private_submodules_->echo_cancellation &&
1351 private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001352 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001353 return AudioProcessing::kStreamParameterNotSetError;
1354 }
1355
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001356 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001357 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1358
Per Åhgrend0fa8202018-04-18 09:35:13 +02001359 if (was_stream_delay_set()) {
1360 private_submodules_->echo_controller->SetAudioBufferDelay(
1361 stream_delay_ms());
1362 }
1363
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001364 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001365 capture_buffer, capture_.echo_path_gain_change);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001366 } else if (private_submodules_->echo_cancellation) {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001367 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
peah61202ac2017-02-06 03:39:42 -08001368 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001369 }
1370
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001371 if (private_submodules_->echo_control_mobile->is_enabled() &&
peahdf3efa82015-11-28 12:35:15 -08001372 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001373 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001374 }
peahde65ddc2016-09-16 15:02:15 -07001375 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001376
1377 // Ensure that the stream delay was set before the call to the
1378 // AECM ProcessCaptureAudio function.
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001379 if (private_submodules_->echo_control_mobile->is_enabled() &&
peah253534d2016-03-15 04:32:28 -07001380 !was_stream_delay_set()) {
1381 return AudioProcessing::kStreamParameterNotSetError;
1382 }
1383
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001384 if (!(private_submodules_->echo_controller ||
Per Åhgrenf204faf2019-04-25 15:18:06 +02001385 (private_submodules_->echo_cancellation &&
1386 private_submodules_->echo_cancellation->is_enabled()))) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001387 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001388 capture_buffer, stream_delay_ms()));
1389 }
ivoc9f4a4a02016-10-28 05:39:16 -07001390
peahde65ddc2016-09-16 15:02:15 -07001391 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001392 if (config_.voice_detection.enabled) {
1393 private_submodules_->voice_detector->ProcessCaptureAudio(capture_buffer);
1394 capture_.stats.voice_detected =
1395 private_submodules_->voice_detector->stream_has_voice();
1396 } else {
1397 capture_.stats.voice_detected = absl::nullopt;
1398 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001399
peahbe615622016-02-13 16:40:47 -08001400 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001401 public_submodules_->gain_control->is_enabled() &&
1402 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001403 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001404 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1405 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001406 }
Per Åhgren200feba2019-03-06 04:16:46 +01001407 // TODO(peah): Add reporting from AEC3 whether there is echo.
peahb8fbb542016-03-15 02:28:08 -07001408 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001409 capture_buffer,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001410 private_submodules_->echo_cancellation &&
1411 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001412
peah2ace3f92016-09-10 04:42:27 -07001413 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1414 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001415 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1416 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001417 }
1418
peah9e6a2902017-05-15 07:19:21 -07001419 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001420 RTC_DCHECK(private_submodules_->echo_detector);
1421 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001422 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1423 capture_buffer->num_frames()));
1424 }
1425
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001426 // TODO(aluebs): Investigate if the transient suppression placement should be
1427 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001428 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001429 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001430 private_submodules_->agc_manager.get()
1431 ? private_submodules_->agc_manager->voice_probability()
1432 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001433
peahdf3efa82015-11-28 12:35:15 -08001434 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001435 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1436 capture_buffer->num_channels(),
1437 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1438 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1439 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001440 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001441 }
1442
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001443 // Experimental APM sub-module that analyzes |capture_buffer|.
1444 if (private_submodules_->capture_analyzer) {
1445 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1446 }
1447
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001448 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001449 private_submodules_->gain_controller2->NotifyAnalogLevel(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001450 agc1()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001451 private_submodules_->gain_controller2->Process(capture_buffer);
1452 }
1453
Sam Zackrisson0beac582017-09-25 12:04:02 +02001454 if (private_submodules_->capture_post_processor) {
1455 private_submodules_->capture_post_processor->Process(capture_buffer);
1456 }
1457
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001458 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001459 public_submodules_->level_estimator->ProcessStream(capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001460 if (config_.level_estimation.enabled) {
1461 private_submodules_->output_level_estimator->ProcessStream(capture_buffer);
1462 capture_.stats.output_rms_dbfs =
1463 private_submodules_->output_level_estimator->RMS();
1464 } else {
1465 capture_.stats.output_rms_dbfs = absl::nullopt;
1466 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001467
peah1b08dc32016-12-20 13:45:58 -08001468 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1469 capture_buffer->channels_const()[0],
1470 capture_nonlocked_.capture_processing_format.num_frames()));
1471 if (log_rms) {
1472 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1473 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1474 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1475 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1476 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1477 }
1478
peahdf3efa82015-11-28 12:35:15 -08001479 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001480 return kNoError;
1481}
1482
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001483int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001484 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001485 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001486 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001487 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001488 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001489 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001490 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001491 };
1492 if (samples_per_channel != reverse_config.num_frames()) {
1493 return kBadDataLengthError;
1494 }
peahdf3efa82015-11-28 12:35:15 -08001495 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001496}
1497
peahde65ddc2016-09-16 15:02:15 -07001498int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1499 const StreamConfig& input_config,
1500 const StreamConfig& output_config,
1501 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001502 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001503 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001504 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001505 if (submodule_states_.RenderMultiBandProcessingActive() ||
1506 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001507 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1508 dest);
peah2ace3f92016-09-10 04:42:27 -07001509 } else if (formats_.api_format.reverse_input_stream() !=
1510 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001511 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1512 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001513 } else {
peahde65ddc2016-09-16 15:02:15 -07001514 CopyAudioIfNeeded(src, input_config.num_frames(),
1515 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001516 }
1517
1518 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001519}
1520
peahdf3efa82015-11-28 12:35:15 -08001521int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001522 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001523 const StreamConfig& input_config,
1524 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001525 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001526 return kNullPointerError;
1527 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001528
peahde65ddc2016-09-16 15:02:15 -07001529 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001530 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001531 }
1532
peahdf3efa82015-11-28 12:35:15 -08001533 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001534 processing_config.reverse_input_stream() = input_config;
1535 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001536
peahdf3efa82015-11-28 12:35:15 -08001537 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001538 RTC_DCHECK_EQ(input_config.num_frames(),
1539 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001540
aleloi868f32f2017-05-23 07:20:05 -07001541 if (aec_dump_) {
1542 const size_t channel_size =
1543 formats_.api_format.reverse_input_stream().num_frames();
1544 const size_t num_channels =
1545 formats_.api_format.reverse_input_stream().num_channels();
1546 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001547 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001548 }
peahdf3efa82015-11-28 12:35:15 -08001549 render_.render_audio->CopyFrom(src,
1550 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001551 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001552}
1553
1554int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001555 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001556 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001557 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001558 return kNullPointerError;
1559 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001560 // Must be a native rate.
1561 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1562 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001563 frame->sample_rate_hz_ != kSampleRate32kHz &&
1564 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001565 return kBadSampleRateError;
1566 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001567
Michael Graczyk86c6d332015-07-23 11:41:39 -07001568 if (frame->num_channels_ <= 0) {
1569 return kBadNumberChannelsError;
1570 }
1571
peahdf3efa82015-11-28 12:35:15 -08001572 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001573 processing_config.reverse_input_stream().set_sample_rate_hz(
1574 frame->sample_rate_hz_);
1575 processing_config.reverse_input_stream().set_num_channels(
1576 frame->num_channels_);
1577 processing_config.reverse_output_stream().set_sample_rate_hz(
1578 frame->sample_rate_hz_);
1579 processing_config.reverse_output_stream().set_num_channels(
1580 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001581
peahdf3efa82015-11-28 12:35:15 -08001582 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001583 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001584 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001585 return kBadDataLengthError;
1586 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001587
aleloi868f32f2017-05-23 07:20:05 -07001588 if (aec_dump_) {
1589 aec_dump_->WriteRenderStreamMessage(*frame);
1590 }
1591
peahdf3efa82015-11-28 12:35:15 -08001592 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001593 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001594 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001595 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1596 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001597 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001598}
niklase@google.com470e71d2011-07-07 08:21:25 +00001599
peahde65ddc2016-09-16 15:02:15 -07001600int AudioProcessingImpl::ProcessRenderStreamLocked() {
1601 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001602
Alex Loiko73ec0192018-05-15 10:52:28 +02001603 HandleRenderRuntimeSettings();
1604
Alex Loiko5825aa62017-12-18 16:02:40 +01001605 if (private_submodules_->render_pre_processor) {
1606 private_submodules_->render_pre_processor->Process(render_buffer);
1607 }
1608
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001609 QueueNonbandedRenderAudio(render_buffer);
1610
peah2ace3f92016-09-10 04:42:27 -07001611 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001612 SampleRateSupportsMultiBand(
1613 formats_.render_processing_format.sample_rate_hz())) {
1614 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001615 }
1616
peahce4d9152017-05-19 01:28:05 -07001617 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1618 QueueBandedRenderAudio(render_buffer);
1619 }
1620
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001621 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001622 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001623 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001624 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001625
peah2ace3f92016-09-10 04:42:27 -07001626 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001627 SampleRateSupportsMultiBand(
1628 formats_.render_processing_format.sample_rate_hz())) {
1629 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001630 }
1631
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001632 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001633}
1634
1635int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001636 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001637 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001638 capture_.was_stream_delay_set = true;
1639 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001640
niklase@google.com470e71d2011-07-07 08:21:25 +00001641 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001642 delay = 0;
1643 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001644 }
1645
1646 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1647 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001648 delay = 500;
1649 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001650 }
1651
peahdf3efa82015-11-28 12:35:15 -08001652 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001653 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001654}
1655
1656int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001657 // Used as callback from submodules, hence locking is not allowed.
1658 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001659}
1660
1661bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001662 // Used as callback from submodules, hence locking is not allowed.
1663 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001664}
1665
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001666void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001667 rtc::CritScope cs(&crit_capture_);
1668 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001669}
1670
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001671void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001672 rtc::CritScope cs(&crit_capture_);
1673 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001674}
1675
1676int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001677 rtc::CritScope cs(&crit_capture_);
1678 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001679}
1680
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001681void AudioProcessingImpl::set_stream_analog_level(int level) {
1682 rtc::CritScope cs_capture(&crit_capture_);
1683 int error = agc1()->set_stream_analog_level(level);
1684 RTC_DCHECK_EQ(kNoError, error);
1685}
1686
1687int AudioProcessingImpl::recommended_stream_analog_level() const {
1688 rtc::CritScope cs_capture(&crit_capture_);
1689 return agc1()->stream_analog_level();
1690}
1691
aleloi868f32f2017-05-23 07:20:05 -07001692void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1693 RTC_DCHECK(aec_dump);
1694 rtc::CritScope cs_render(&crit_render_);
1695 rtc::CritScope cs_capture(&crit_capture_);
1696
1697 // The previously attached AecDump will be destroyed with the
1698 // 'aec_dump' parameter, which is after locks are released.
1699 aec_dump_.swap(aec_dump);
1700 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001701 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001702}
1703
1704void AudioProcessingImpl::DetachAecDump() {
1705 // The d-tor of a task-queue based AecDump blocks until all pending
1706 // tasks are done. This construction avoids blocking while holding
1707 // the render and capture locks.
1708 std::unique_ptr<AecDump> aec_dump = nullptr;
1709 {
1710 rtc::CritScope cs_render(&crit_render_);
1711 rtc::CritScope cs_capture(&crit_capture_);
1712 aec_dump = std::move(aec_dump_);
1713 }
1714}
1715
Sam Zackrisson4d364492018-03-02 16:03:21 +01001716void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1717 std::unique_ptr<AudioGenerator> audio_generator) {
1718 // TODO(bugs.webrtc.org/8882) Stub.
1719 // Reset internal audio generator with audio_generator.
1720}
1721
1722void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1723 // TODO(bugs.webrtc.org/8882) Stub.
1724 // Delete audio generator, if one is attached.
1725}
1726
Ivo Creusen56d46092017-11-24 17:29:59 +01001727AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001728 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001729 rtc::CritScope cs_capture(&crit_capture_);
1730 if (!has_remote_tracks) {
1731 return capture_.stats;
1732 }
1733 AudioProcessingStats stats = capture_.stats;
1734 EchoCancellationImpl::Metrics metrics;
1735 if (private_submodules_->echo_controller) {
1736 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1737 stats.echo_return_loss = ec_metrics.echo_return_loss;
1738 stats.echo_return_loss_enhancement =
1739 ec_metrics.echo_return_loss_enhancement;
1740 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001741 }
1742 if (config_.residual_echo_detector.enabled) {
1743 RTC_DCHECK(private_submodules_->echo_detector);
1744 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1745 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1746 stats.residual_echo_likelihood_recent_max =
1747 ed_metrics.echo_likelihood_recent_max;
1748 }
Ivo Creusenae026092017-11-20 13:07:16 +01001749 return stats;
1750}
1751
niklase@google.com470e71d2011-07-07 08:21:25 +00001752GainControl* AudioProcessingImpl::gain_control() const {
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001753 return public_submodules_->gain_control_config_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001754}
1755
niklase@google.com470e71d2011-07-07 08:21:25 +00001756LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001757 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001758}
1759
1760NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001761 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001762}
1763
1764VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001765 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001766}
1767
peah8271d042016-11-22 07:24:52 -08001768void AudioProcessingImpl::MutateConfig(
1769 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1770 rtc::CritScope cs_render(&crit_render_);
1771 rtc::CritScope cs_capture(&crit_capture_);
1772 mutator(&config_);
1773 ApplyConfig(config_);
1774}
1775
1776AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1777 rtc::CritScope cs_render(&crit_render_);
1778 rtc::CritScope cs_capture(&crit_capture_);
1779 return config_;
1780}
1781
peah2ace3f92016-09-10 04:42:27 -07001782bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1783 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001784 config_.high_pass_filter.enabled,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001785 private_submodules_->echo_cancellation &&
1786 private_submodules_->echo_cancellation->is_enabled(),
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001787 private_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001788 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001789 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001790 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001791 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001792 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001793 public_submodules_->voice_detection->is_enabled(),
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001794 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001795 public_submodules_->level_estimator->is_enabled(),
1796 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001797}
1798
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001799void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001800 if (capture_.transient_suppressor_enabled) {
1801 if (!public_submodules_->transient_suppressor.get()) {
1802 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001803 }
peahdf3efa82015-11-28 12:35:15 -08001804 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001805 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1806 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001807 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001808}
1809
peah8271d042016-11-22 07:24:52 -08001810void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001811 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001812 private_submodules_->low_cut_filter.reset(
1813 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1814 } else {
1815 private_submodules_->low_cut_filter.reset();
1816 }
1817}
alessiob3ec96df2017-05-22 06:57:06 -07001818
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001819void AudioProcessingImpl::InitializeEchoController() {
Per Åhgren200feba2019-03-06 04:16:46 +01001820 if (echo_control_factory_ ||
1821 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
1822 !config_.echo_canceller.use_legacy_aec)) {
1823 if (echo_control_factory_) {
1824 private_submodules_->echo_controller =
1825 echo_control_factory_->Create(proc_sample_rate_hz());
1826 } else {
1827 private_submodules_->echo_controller = absl::make_unique<EchoCanceller3>(
1828 EchoCanceller3Config(), proc_sample_rate_hz(), true);
1829 }
1830
1831 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001832
Per Åhgrenf204faf2019-04-25 15:18:06 +02001833 private_submodules_->echo_cancellation.reset();
1834 aec_render_signal_queue_.reset();
1835 private_submodules_->echo_control_mobile->Enable(false);
1836 return;
peahe0eae3c2016-12-14 01:16:23 -08001837 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001838
1839 private_submodules_->echo_controller.reset();
1840 capture_nonlocked_.echo_controller_enabled = false;
1841
1842 if (!config_.echo_canceller.enabled) {
1843 private_submodules_->echo_cancellation.reset();
1844 aec_render_signal_queue_.reset();
1845 private_submodules_->echo_control_mobile->Enable(false);
1846 return;
1847 }
1848
1849 if (config_.echo_canceller.mobile_mode) {
1850 // Create and activate AECM.
1851 // TODO(peah): Add an on-demand creation of AECmobile similar to AEC2.
1852 private_submodules_->echo_control_mobile->Enable(true);
1853
1854 private_submodules_->echo_cancellation.reset();
1855 aec_render_signal_queue_.reset();
1856 return;
1857 }
1858
1859 // Create and activate AEC2.
1860 private_submodules_->echo_control_mobile->Enable(false);
1861 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
1862 private_submodules_->echo_cancellation->SetExtraOptions(
1863 capture_nonlocked_.use_aec2_extended_filter,
1864 capture_nonlocked_.use_aec2_delay_agnostic,
1865 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1866
1867 const size_t new_aec_render_queue_element_max_size =
1868 std::max(static_cast<size_t>(1),
1869 kMaxAllowedValuesOfSamplesPerBand *
1870 EchoCancellationImpl::NumCancellersRequired(
1871 num_output_channels(), num_reverse_channels()));
1872
1873 // Reallocate the queues if the queue item sizes are too small to fit the
1874 // data to put in the queues.
1875 if (aec_render_queue_element_max_size_ <
1876 new_aec_render_queue_element_max_size ||
1877 !aec_render_signal_queue_) {
1878 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
1879
1880 std::vector<float> template_queue_element(
1881 aec_render_queue_element_max_size_);
1882
1883 aec_render_signal_queue_.reset(
1884 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1885 kMaxNumFramesToBuffer, template_queue_element,
1886 RenderQueueItemVerifier<float>(
1887 aec_render_queue_element_max_size_)));
1888
1889 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1890 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
1891 } else {
1892 aec_render_signal_queue_->Clear();
1893 }
1894
1895 private_submodules_->echo_cancellation->Initialize(
1896 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1897 num_proc_channels());
1898
1899 private_submodules_->echo_cancellation->Enable(true);
1900
1901 private_submodules_->echo_cancellation->set_suppression_level(
1902 config_.echo_canceller.legacy_moderate_suppression_level
1903 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1904 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
1905
1906 private_submodules_->echo_controller.reset();
1907 capture_nonlocked_.echo_controller_enabled = false;
peahe0eae3c2016-12-14 01:16:23 -08001908}
peah8271d042016-11-22 07:24:52 -08001909
alessiob3ec96df2017-05-22 06:57:06 -07001910void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001911 if (config_.gain_controller2.enabled) {
1912 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001913 }
1914}
1915
Alex Loikob5c9a792018-04-16 16:31:22 +02001916void AudioProcessingImpl::InitializePreAmplifier() {
1917 if (config_.pre_amplifier.enabled) {
1918 private_submodules_->pre_amplifier.reset(
1919 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1920 } else {
1921 private_submodules_->pre_amplifier.reset();
1922 }
1923}
1924
ivoc9f4a4a02016-10-28 05:39:16 -07001925void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001926 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001927 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001928 proc_sample_rate_hz(), 1,
1929 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001930}
1931
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001932void AudioProcessingImpl::InitializeAnalyzer() {
1933 if (private_submodules_->capture_analyzer) {
1934 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1935 num_proc_channels());
1936 }
1937}
1938
Sam Zackrisson0beac582017-09-25 12:04:02 +02001939void AudioProcessingImpl::InitializePostProcessor() {
1940 if (private_submodules_->capture_post_processor) {
1941 private_submodules_->capture_post_processor->Initialize(
1942 proc_sample_rate_hz(), num_proc_channels());
1943 }
1944}
1945
Alex Loiko5825aa62017-12-18 16:02:40 +01001946void AudioProcessingImpl::InitializePreProcessor() {
1947 if (private_submodules_->render_pre_processor) {
1948 private_submodules_->render_pre_processor->Initialize(
1949 formats_.render_processing_format.sample_rate_hz(),
1950 formats_.render_processing_format.num_channels());
1951 }
1952}
1953
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001954void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001955 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001956
Per Åhgrenf204faf2019-04-25 15:18:06 +02001957 if (private_submodules_->echo_cancellation &&
1958 private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001959 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1960 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001961 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001962 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001963 capture_.stream_delay_jumps = 0;
1964 }
1965 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001966 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001967 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001968 }
1969
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001970 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001971 const int diff_stream_delay_ms =
1972 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1973 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1974 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001975 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1976 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001977 if (capture_.stream_delay_jumps == -1) {
1978 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001979 }
peahdf3efa82015-11-28 12:35:15 -08001980 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001981 }
peahdf3efa82015-11-28 12:35:15 -08001982 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001983
1984 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001985 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001986 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001987 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001988 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001989 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001990 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001991 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001992 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001993 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001994 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001995 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1996 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1997 100);
peahdf3efa82015-11-28 12:35:15 -08001998 if (capture_.aec_system_delay_jumps == -1) {
1999 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002000 }
peahdf3efa82015-11-28 12:35:15 -08002001 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02002002 }
peahdf3efa82015-11-28 12:35:15 -08002003 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02002004 }
2005}
2006
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002007void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08002008 // Run in a single-threaded manner.
2009 rtc::CritScope cs_render(&crit_render_);
2010 rtc::CritScope cs_capture(&crit_capture_);
2011
2012 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08002013 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002014 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08002015 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002016 }
peahdf3efa82015-11-28 12:35:15 -08002017 capture_.stream_delay_jumps = -1;
2018 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002019
peahdf3efa82015-11-28 12:35:15 -08002020 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08002021 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
2022 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002023 }
peahdf3efa82015-11-28 12:35:15 -08002024 capture_.aec_system_delay_jumps = -1;
2025 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002026}
2027
aleloi868f32f2017-05-23 07:20:05 -07002028void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2029 if (!aec_dump_) {
2030 return;
2031 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002032
2033 std::string experiments_description = "";
2034 if (private_submodules_->echo_cancellation) {
2035 experiments_description +=
2036 private_submodules_->echo_cancellation->GetExperimentsDescription();
2037 }
aleloi868f32f2017-05-23 07:20:05 -07002038 // TODO(peah): Add semicolon-separated concatenations of experiment
2039 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002040 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2041 experiments_description += "AgcClippingLevelExperiment;";
2042 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002043 if (capture_nonlocked_.echo_controller_enabled) {
2044 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002045 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002046 if (config_.gain_controller2.enabled) {
2047 experiments_description += "GainController2;";
2048 }
aleloi868f32f2017-05-23 07:20:05 -07002049
2050 InternalAPMConfig apm_config;
2051
Per Åhgren200feba2019-03-06 04:16:46 +01002052 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002053 apm_config.aec_delay_agnostic_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002054 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002055 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002056 apm_config.aec_drift_compensation_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002057 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002058 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002059 apm_config.aec_extended_filter_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002060 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002061 private_submodules_->echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002062 apm_config.aec_suppression_level =
2063 private_submodules_->echo_cancellation
2064 ? static_cast<int>(
2065 private_submodules_->echo_cancellation->suppression_level())
2066 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002067
2068 apm_config.aecm_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002069 private_submodules_->echo_control_mobile->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002070 apm_config.aecm_comfort_noise_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002071 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
2072 apm_config.aecm_routing_mode = static_cast<int>(
2073 private_submodules_->echo_control_mobile->routing_mode());
aleloi868f32f2017-05-23 07:20:05 -07002074
2075 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2076 apm_config.agc_mode =
2077 static_cast<int>(public_submodules_->gain_control->mode());
2078 apm_config.agc_limiter_enabled =
2079 public_submodules_->gain_control->is_limiter_enabled();
2080 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2081
2082 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2083
2084 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2085 apm_config.ns_level =
2086 static_cast<int>(public_submodules_->noise_suppression->level());
2087
2088 apm_config.transient_suppression_enabled =
2089 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002090 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002091 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2092 apm_config.pre_amplifier_fixed_gain_factor =
2093 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002094
2095 if (!forced && apm_config == apm_config_for_aec_dump_) {
2096 return;
2097 }
2098 aec_dump_->WriteConfig(apm_config);
2099 apm_config_for_aec_dump_ = apm_config;
2100}
2101
2102void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2103 const float* const* src) {
2104 RTC_DCHECK(aec_dump_);
2105 WriteAecDumpConfigMessage(false);
2106
2107 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2108 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2109 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002110 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002111 RecordAudioProcessingState();
2112}
2113
2114void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2115 const AudioFrame& capture_frame) {
2116 RTC_DCHECK(aec_dump_);
2117 WriteAecDumpConfigMessage(false);
2118
2119 aec_dump_->AddCaptureStreamInput(capture_frame);
2120 RecordAudioProcessingState();
2121}
2122
2123void AudioProcessingImpl::RecordProcessedCaptureStream(
2124 const float* const* processed_capture_stream) {
2125 RTC_DCHECK(aec_dump_);
2126
2127 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2128 const size_t num_channels =
2129 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002130 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2131 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002132 aec_dump_->WriteCaptureStreamMessage();
2133}
2134
2135void AudioProcessingImpl::RecordProcessedCaptureStream(
2136 const AudioFrame& processed_capture_frame) {
2137 RTC_DCHECK(aec_dump_);
2138
2139 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2140 aec_dump_->WriteCaptureStreamMessage();
2141}
2142
2143void AudioProcessingImpl::RecordAudioProcessingState() {
2144 RTC_DCHECK(aec_dump_);
2145 AecDump::AudioProcessingState audio_proc_state;
2146 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2147 audio_proc_state.drift =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002148 private_submodules_->echo_cancellation
2149 ? private_submodules_->echo_cancellation->stream_drift_samples()
2150 : 0;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002151 audio_proc_state.level = agc1()->stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002152 audio_proc_state.keypress = capture_.key_pressed;
2153 aec_dump_->AddAudioProcessingState(audio_proc_state);
2154}
2155
kwiberg83ffe452016-08-29 14:46:07 -07002156AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002157 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002158 : aec_system_delay_jumps(-1),
2159 delay_offset_ms(0),
2160 was_stream_delay_set(false),
2161 last_stream_delay_ms(0),
2162 last_aec_system_delay_ms(0),
2163 stream_delay_jumps(-1),
2164 output_will_be_muted(false),
2165 key_pressed(false),
2166 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002167 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002168 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002169 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002170 prev_analog_mic_level(-1),
2171 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002172
2173AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2174
2175AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2176
2177AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2178
niklase@google.com470e71d2011-07-07 08:21:25 +00002179} // namespace webrtc