blob: 4d24ee662dddf61a7e341dd4b96bb9966a14ed41 [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_cancellation.reset(new EchoCancellationImpl());
433 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
434 // TODO(alessiob): Move the injected gain controller once injection is
435 // implemented.
436 private_submodules_->gain_controller2.reset(new GainController2());
437
438 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
439 << !!private_submodules_->capture_analyzer
440 << "\nCapture post processor activated: "
441 << !!private_submodules_->capture_post_processor
442 << "\nRender pre processor activated: "
443 << !!private_submodules_->render_pre_processor;
444
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000445 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000446}
447
448AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800449 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800450 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800451 private_submodules_->agc_manager.reset();
452 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800453 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000454}
455
niklase@google.com470e71d2011-07-07 08:21:25 +0000456int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800457 // Run in a single-threaded manner during initialization.
458 rtc::CritScope cs_render(&crit_render_);
459 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000460 return InitializeLocked();
461}
462
peahde65ddc2016-09-16 15:02:15 -0700463int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
464 int capture_output_sample_rate_hz,
465 int render_input_sample_rate_hz,
466 ChannelLayout capture_input_layout,
467 ChannelLayout capture_output_layout,
468 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700469 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700470 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
471 LayoutHasKeyboard(capture_input_layout)},
472 {capture_output_sample_rate_hz,
473 ChannelsFromLayout(capture_output_layout),
474 LayoutHasKeyboard(capture_output_layout)},
475 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
476 LayoutHasKeyboard(render_input_layout)},
477 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
478 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700479
480 return Initialize(processing_config);
481}
482
483int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800484 // Run in a single-threaded manner during initialization.
485 rtc::CritScope cs_render(&crit_render_);
486 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700487 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000488}
489
peahdf3efa82015-11-28 12:35:15 -0800490int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800491 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700492 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800493}
494
peahdf3efa82015-11-28 12:35:15 -0800495int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700496 const ProcessingConfig& processing_config,
497 bool force_initialization) {
498 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800499}
500
peah192164e2015-11-17 02:16:45 -0800501// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800502// their current values (needs to be called while holding the crit_render_lock).
503int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700504 const ProcessingConfig& processing_config,
505 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800506 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700507 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800508 return kNoError;
509 }
peahdf3efa82015-11-28 12:35:15 -0800510
511 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800512 return InitializeLocked(processing_config);
513}
514
niklase@google.com470e71d2011-07-07 08:21:25 +0000515int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200516 UpdateActiveSubmoduleStates();
517
peahde65ddc2016-09-16 15:02:15 -0700518 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800519 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700520 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800521 : formats_.api_format.reverse_output_stream().num_frames();
522 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
523 render_.render_audio.reset(new AudioBuffer(
524 formats_.api_format.reverse_input_stream().num_frames(),
525 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700526 formats_.render_processing_format.num_frames(),
527 formats_.render_processing_format.num_channels(),
528 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700529 if (formats_.api_format.reverse_input_stream() !=
530 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800531 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800532 formats_.api_format.reverse_input_stream().num_channels(),
533 formats_.api_format.reverse_input_stream().num_frames(),
534 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800535 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700536 } else {
peahdf3efa82015-11-28 12:35:15 -0800537 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700538 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700539 } else {
peahdf3efa82015-11-28 12:35:15 -0800540 render_.render_audio.reset(nullptr);
541 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700542 }
peahce4d9152017-05-19 01:28:05 -0700543
peahdf3efa82015-11-28 12:35:15 -0800544 capture_.capture_audio.reset(
545 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
546 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700547 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200548 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800549 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000550
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100551 private_submodules_->echo_cancellation->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700552 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
553 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700554 AllocateRenderQueue();
555
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100556 int success = private_submodules_->echo_cancellation->enable_metrics(true);
ivoc3e9a5372016-10-28 07:55:33 -0700557 RTC_DCHECK_EQ(0, success);
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100558 success = private_submodules_->echo_cancellation->enable_delay_logging(true);
ivoc3e9a5372016-10-28 07:55:33 -0700559 RTC_DCHECK_EQ(0, success);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100560 private_submodules_->echo_control_mobile->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700561 proc_split_sample_rate_hz(), num_reverse_channels(),
562 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700563
564 public_submodules_->gain_control->Initialize(num_proc_channels(),
565 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700566 if (constants_.use_experimental_agc) {
567 if (!private_submodules_->agc_manager.get()) {
568 private_submodules_->agc_manager.reset(new AgcManagerDirect(
569 public_submodules_->gain_control.get(),
570 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200571 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
572 constants_.use_experimental_agc_agc2_level_estimation,
573 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700574 }
575 private_submodules_->agc_manager->Initialize();
576 private_submodules_->agc_manager->SetCaptureMuted(
577 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700578 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700579 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200580 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800581 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700582 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
583 proc_sample_rate_hz());
584 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100585 if (private_submodules_->voice_detector) {
586 private_submodules_->voice_detector->Initialize(
587 proc_split_sample_rate_hz());
588 }
peahde65ddc2016-09-16 15:02:15 -0700589 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700590 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200591 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700592 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200593 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200594 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100595 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800596
aleloi868f32f2017-05-23 07:20:05 -0700597 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200598 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700599 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000600 return kNoError;
601}
602
Michael Graczyk86c6d332015-07-23 11:41:39 -0700603int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200604 UpdateActiveSubmoduleStates();
605
Michael Graczyk86c6d332015-07-23 11:41:39 -0700606 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700607 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
608 return kBadSampleRateError;
609 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000610 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700611
Peter Kasting69558702016-01-12 16:26:35 -0800612 const size_t num_in_channels = config.input_stream().num_channels();
613 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700614
615 // Need at least one input channel.
616 // Need either one output channel or as many outputs as there are inputs.
617 if (num_in_channels == 0 ||
618 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700619 return kBadNumberChannelsError;
620 }
621
peahdf3efa82015-11-28 12:35:15 -0800622 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000623
peahde65ddc2016-09-16 15:02:15 -0700624 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700625 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700626 formats_.api_format.output_stream().sample_rate_hz()),
627 submodule_states_.CaptureMultiBandSubModulesActive() ||
628 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000629
peahde65ddc2016-09-16 15:02:15 -0700630 capture_nonlocked_.capture_processing_format =
631 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700632
peah2ce640f2017-04-07 03:57:48 -0700633 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200634 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700635 render_processing_rate = FindNativeProcessRateToUse(
636 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
637 formats_.api_format.reverse_output_stream().sample_rate_hz()),
638 submodule_states_.CaptureMultiBandSubModulesActive() ||
639 submodule_states_.RenderMultiBandSubModulesActive());
640 } else {
641 render_processing_rate = capture_processing_rate;
642 }
643
aluebseb3603b2016-04-20 15:27:58 -0700644 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
645 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700646 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200647 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700648 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
649 ? kSampleRate32kHz
650 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700651 }
peah2ce640f2017-04-07 03:57:48 -0700652
peahde65ddc2016-09-16 15:02:15 -0700653 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700654 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700655 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
656 kSampleRate8kHz) {
657 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000658 } else {
peahde65ddc2016-09-16 15:02:15 -0700659 render_processing_rate =
660 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000661 }
662
peahde65ddc2016-09-16 15:02:15 -0700663 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000664 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700665 if (submodule_states_.RenderMultiBandSubModulesActive()) {
666 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
667 } else {
668 formats_.render_processing_format = StreamConfig(
669 formats_.api_format.reverse_input_stream().sample_rate_hz(),
670 formats_.api_format.reverse_input_stream().num_channels());
671 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000672
peahde65ddc2016-09-16 15:02:15 -0700673 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
674 kSampleRate32kHz ||
675 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
676 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800677 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000678 } else {
peahdf3efa82015-11-28 12:35:15 -0800679 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700680 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000681 }
682
683 return InitializeLocked();
684}
685
peah88ac8532016-09-12 16:47:25 -0700686void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700687 // Run in a single-threaded manner when applying the settings.
688 rtc::CritScope cs_render(&crit_render_);
689 rtc::CritScope cs_capture(&crit_capture_);
690
Per Åhgren200feba2019-03-06 04:16:46 +0100691 const bool aec_config_changed =
692 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
693 config_.echo_canceller.use_legacy_aec !=
694 config.echo_canceller.use_legacy_aec ||
695 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
696 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
697 config_.echo_canceller.legacy_moderate_suppression_level !=
698 config.echo_canceller.legacy_moderate_suppression_level);
699
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100700 const bool agc1_config_changed =
701 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
702 config_.gain_controller1.mode != config.gain_controller1.mode ||
703 config_.gain_controller1.target_level_dbfs !=
704 config.gain_controller1.target_level_dbfs ||
705 config_.gain_controller1.compression_gain_db !=
706 config.gain_controller1.compression_gain_db ||
707 config_.gain_controller1.enable_limiter !=
708 config.gain_controller1.enable_limiter ||
709 config_.gain_controller1.analog_level_minimum !=
710 config.gain_controller1.analog_level_minimum ||
711 config_.gain_controller1.analog_level_maximum !=
712 config.gain_controller1.analog_level_maximum;
713
Yves Gerey499bc6c2018-10-10 18:29:07 +0200714 config_ = config;
715
Per Åhgren200feba2019-03-06 04:16:46 +0100716 if (aec_config_changed) {
717 InitializeEchoController();
718 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200719
Sam Zackrisson23513132019-01-11 15:10:32 +0100720 public_submodules_->noise_suppression->Enable(
721 config.noise_suppression.enabled);
722 public_submodules_->noise_suppression->set_level(
723 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
724
peah8271d042016-11-22 07:24:52 -0800725 InitializeLowCutFilter();
726
Mirko Bonadei675513b2017-11-09 11:09:25 +0100727 RTC_LOG(LS_INFO) << "Highpass filter activated: "
728 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800729
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100730 if (agc1_config_changed) {
731 ApplyAgc1Config(config_.gain_controller1);
732 }
733
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100734 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700735 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100736 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
737 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100739 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700740 config_.gain_controller2 = AudioProcessing::Config::GainController2();
741 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200742 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200743 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200744 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100745 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
746 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200747 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
748 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100749
750 if (config_.level_estimation.enabled &&
751 !private_submodules_->output_level_estimator) {
752 private_submodules_->output_level_estimator.reset(
753 new LevelEstimatorImpl(&crit_capture_));
754 private_submodules_->output_level_estimator->Enable(true);
755 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100756
757 if (config_.voice_detection.enabled && !private_submodules_->voice_detector) {
758 private_submodules_->voice_detector.reset(
759 new VoiceDetectionImpl(&crit_capture_));
760 private_submodules_->voice_detector->Enable(true);
761 private_submodules_->voice_detector->set_likelihood(
762 VoiceDetection::kVeryLowLikelihood);
763 private_submodules_->voice_detector->Initialize(
764 proc_split_sample_rate_hz());
765 }
peah88ac8532016-09-12 16:47:25 -0700766}
767
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100768void AudioProcessingImpl::ApplyAgc1Config(
769 const Config::GainController1& config) {
770 GainControl* agc = agc1();
771 int error = agc->Enable(config.enabled);
772 RTC_DCHECK_EQ(kNoError, error);
773 error = agc->set_mode(Agc1ConfigModeToInterfaceMode(config.mode));
774 RTC_DCHECK_EQ(kNoError, error);
775 error = agc->set_target_level_dbfs(config.target_level_dbfs);
776 RTC_DCHECK_EQ(kNoError, error);
777 error = agc->set_compression_gain_db(config.compression_gain_db);
778 RTC_DCHECK_EQ(kNoError, error);
779 error = agc->enable_limiter(config.enable_limiter);
780 RTC_DCHECK_EQ(kNoError, error);
781 error = agc->set_analog_level_limits(config.analog_level_minimum,
782 config.analog_level_maximum);
783 RTC_DCHECK_EQ(kNoError, error);
784}
785
786GainControl* AudioProcessingImpl::agc1() {
787 if (constants_.use_experimental_agc) {
788 return public_submodules_->gain_control_for_experimental_agc.get();
789 }
790 return public_submodules_->gain_control.get();
791}
792
793const GainControl* AudioProcessingImpl::agc1() const {
794 if (constants_.use_experimental_agc) {
795 return public_submodules_->gain_control_for_experimental_agc.get();
796 }
797 return public_submodules_->gain_control.get();
798}
799
peah88ac8532016-09-12 16:47:25 -0700800void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800801 // Run in a single-threaded manner when setting the extra options.
802 rtc::CritScope cs_render(&crit_render_);
803 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000804
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100805 private_submodules_->echo_cancellation->SetExtraOptions(config);
peahb624d8c2016-03-05 03:01:14 -0800806
peahdf3efa82015-11-28 12:35:15 -0800807 if (capture_.transient_suppressor_enabled !=
808 config.Get<ExperimentalNs>().enabled) {
809 capture_.transient_suppressor_enabled =
810 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000811 InitializeTransient();
812 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000813}
814
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000815int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800816 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700817 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000820int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800821 // Used as callback from submodules, hence locking is not allowed.
822 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000823}
824
Peter Kasting69558702016-01-12 16:26:35 -0800825size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800826 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700827 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000828}
829
Peter Kasting69558702016-01-12 16:26:35 -0800830size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800831 // Used as callback from submodules, hence locking is not allowed.
832 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000833}
834
Peter Kasting69558702016-01-12 16:26:35 -0800835size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800836 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200837 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800838}
839
Peter Kasting69558702016-01-12 16:26:35 -0800840size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800841 // Used as callback from submodules, hence locking is not allowed.
842 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000843}
844
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000845void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800846 rtc::CritScope cs(&crit_capture_);
847 capture_.output_will_be_muted = muted;
848 if (private_submodules_->agc_manager.get()) {
849 private_submodules_->agc_manager->SetCaptureMuted(
850 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000851 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000852}
853
Alessio Bazzicac054e782018-04-16 12:10:09 +0200854void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200855 switch (setting.type()) {
856 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
857 render_runtime_settings_enqueuer_.Enqueue(setting);
858 return;
859 case RuntimeSetting::Type::kNotSpecified:
860 RTC_NOTREACHED();
861 return;
862 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100863 case RuntimeSetting::Type::kCaptureCompressionGain:
Alex Loiko73ec0192018-05-15 10:52:28 +0200864 capture_runtime_settings_enqueuer_.Enqueue(setting);
865 return;
866 }
867 // The language allows the enum to have a non-enumerator
868 // value. Check that this doesn't happen.
869 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200870}
871
872AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
873 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200874 : runtime_settings_(*runtime_settings) {
875 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200876}
877
878AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
879 default;
880
881void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
882 RuntimeSetting setting) {
883 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200884 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200885 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200886 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200887 RTC_LOG(LS_ERROR)
888 << "The runtime settings queue is full. Oldest setting discarded.";
889 }
890 if (remaining_attempts == 0)
891 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
892}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000893
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000894int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700895 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000896 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000897 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000898 int output_sample_rate_hz,
899 ChannelLayout output_layout,
900 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800901 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800902 StreamConfig input_stream;
903 StreamConfig output_stream;
904 {
905 // Access the formats_.api_format.input_stream beneath the capture lock.
906 // The lock must be released as it is later required in the call
907 // to ProcessStream(,,,);
908 rtc::CritScope cs(&crit_capture_);
909 input_stream = formats_.api_format.input_stream();
910 output_stream = formats_.api_format.output_stream();
911 }
912
Michael Graczyk86c6d332015-07-23 11:41:39 -0700913 input_stream.set_sample_rate_hz(input_sample_rate_hz);
914 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
915 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700916 output_stream.set_sample_rate_hz(output_sample_rate_hz);
917 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
918 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
919
920 if (samples_per_channel != input_stream.num_frames()) {
921 return kBadDataLengthError;
922 }
923 return ProcessStream(src, input_stream, output_stream, dest);
924}
925
926int AudioProcessingImpl::ProcessStream(const float* const* src,
927 const StreamConfig& input_config,
928 const StreamConfig& output_config,
929 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800930 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800931 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700932 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800933 {
934 // Acquire the capture lock in order to safely call the function
935 // that retrieves the render side data. This function accesses apm
936 // getters that need the capture lock held when being called.
937 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700938 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800939
940 if (!src || !dest) {
941 return kNullPointerError;
942 }
943
944 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700945 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000946 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000947
Michael Graczyk86c6d332015-07-23 11:41:39 -0700948 processing_config.input_stream() = input_config;
949 processing_config.output_stream() = output_config;
950
peahdf3efa82015-11-28 12:35:15 -0800951 {
952 // Do conditional reinitialization.
953 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700954 RETURN_ON_ERR(
955 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800956 }
957 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700958 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
959 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000960
aleloi868f32f2017-05-23 07:20:05 -0700961 if (aec_dump_) {
962 RecordUnprocessedCaptureStream(src);
963 }
964
peahdf3efa82015-11-28 12:35:15 -0800965 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700966 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800967 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000968
aleloi868f32f2017-05-23 07:20:05 -0700969 if (aec_dump_) {
970 RecordProcessedCaptureStream(dest);
971 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000972 return kNoError;
973}
974
Alex Loiko73ec0192018-05-15 10:52:28 +0200975void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200976 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200977 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200978 if (aec_dump_) {
979 aec_dump_->WriteRuntimeSetting(setting);
980 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200981 switch (setting.type()) {
982 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200983 if (config_.pre_amplifier.enabled) {
984 float value;
985 setting.GetFloat(&value);
986 private_submodules_->pre_amplifier->SetGainFactor(value);
987 }
988 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200989 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100990 case RuntimeSetting::Type::kCaptureCompressionGain: {
991 float value;
992 setting.GetFloat(&value);
993 int int_value = static_cast<int>(value + .5f);
994 config_.gain_controller1.compression_gain_db = int_value;
995 int error = agc1()->set_compression_gain_db(int_value);
996 RTC_DCHECK_EQ(kNoError, error);
997 break;
998 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200999 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1000 RTC_NOTREACHED();
1001 break;
1002 case RuntimeSetting::Type::kNotSpecified:
1003 RTC_NOTREACHED();
1004 break;
1005 }
1006 }
1007}
1008
1009void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1010 RuntimeSetting setting;
1011 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001012 if (aec_dump_) {
1013 aec_dump_->WriteRuntimeSetting(setting);
1014 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001015 switch (setting.type()) {
1016 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1017 if (private_submodules_->render_pre_processor) {
1018 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
1019 }
1020 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001021 case RuntimeSetting::Type::kCapturePreGain: // fall-through
1022 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001023 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +02001024 RTC_NOTREACHED();
1025 break;
1026 }
1027 }
1028}
1029
peah9e6a2902017-05-15 07:19:21 -07001030void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -07001031 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1032 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -07001033 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001034
kwibergaf476c72016-11-28 15:21:39 -08001035 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001036
1037 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -07001038 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001039 // The data queue is full and needs to be emptied.
1040 EmptyQueuedRenderAudio();
1041
1042 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -07001043 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001044 RTC_DCHECK(result);
1045 }
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_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -07001091 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001092 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -07001093 EchoCancellationImpl::NumCancellersRequired(
1094 num_output_channels(), num_reverse_channels()));
1095
peah701d6282016-10-25 05:42:20 -07001096 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001097 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001098 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001099 EchoControlMobileImpl::NumCancellersRequired(
1100 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001101
peah701d6282016-10-25 05:42:20 -07001102 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001103 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001104
ivoc9f4a4a02016-10-28 05:39:16 -07001105 const size_t new_red_render_queue_element_max_size =
1106 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1107
peaha0624602016-10-25 04:45:24 -07001108 // Reallocate the queues if the queue item sizes are too small to fit the
1109 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001110 if (aec_render_queue_element_max_size_ <
1111 new_aec_render_queue_element_max_size) {
1112 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001113
peaha0624602016-10-25 04:45:24 -07001114 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001115 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001116
peah701d6282016-10-25 05:42:20 -07001117 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001118 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1119 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001120 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001121 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001122
peah701d6282016-10-25 05:42:20 -07001123 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1124 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001125 } else {
peah701d6282016-10-25 05:42:20 -07001126 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001127 }
1128
peah701d6282016-10-25 05:42:20 -07001129 if (aecm_render_queue_element_max_size_ <
1130 new_aecm_render_queue_element_max_size) {
1131 aecm_render_queue_element_max_size_ =
1132 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001133
1134 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001135 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001136
peah701d6282016-10-25 05:42:20 -07001137 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001138 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1139 kMaxNumFramesToBuffer, template_queue_element,
1140 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001141 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001142
peah701d6282016-10-25 05:42:20 -07001143 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1144 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001145 } else {
peah701d6282016-10-25 05:42:20 -07001146 aecm_render_signal_queue_->Clear();
1147 }
1148
1149 if (agc_render_queue_element_max_size_ <
1150 new_agc_render_queue_element_max_size) {
1151 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1152
1153 std::vector<int16_t> template_queue_element(
1154 agc_render_queue_element_max_size_);
1155
1156 agc_render_signal_queue_.reset(
1157 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1158 kMaxNumFramesToBuffer, template_queue_element,
1159 RenderQueueItemVerifier<int16_t>(
1160 agc_render_queue_element_max_size_)));
1161
1162 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1163 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1164 } else {
1165 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001166 }
ivoc9f4a4a02016-10-28 05:39:16 -07001167
1168 if (red_render_queue_element_max_size_ <
1169 new_red_render_queue_element_max_size) {
1170 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1171
1172 std::vector<float> template_queue_element(
1173 red_render_queue_element_max_size_);
1174
1175 red_render_signal_queue_.reset(
1176 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1177 kMaxNumFramesToBuffer, template_queue_element,
1178 RenderQueueItemVerifier<float>(
1179 red_render_queue_element_max_size_)));
1180
1181 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1182 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1183 } else {
1184 red_render_signal_queue_->Clear();
1185 }
peah764e3642016-10-22 05:04:30 -07001186}
1187
1188void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1189 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001190 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001191 private_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001192 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001193 }
1194
peah701d6282016-10-25 05:42:20 -07001195 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001196 private_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001197 aecm_capture_queue_buffer_);
1198 }
1199
1200 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1201 public_submodules_->gain_control->ProcessRenderAudio(
1202 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001203 }
ivoc9f4a4a02016-10-28 05:39:16 -07001204
1205 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001206 RTC_DCHECK(private_submodules_->echo_detector);
1207 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001208 red_capture_queue_buffer_);
1209 }
peah764e3642016-10-22 05:04:30 -07001210}
1211
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001212int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001213 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001214 {
1215 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001216 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001217 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001218 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001219 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001220 }
peahfa6228e2015-11-16 16:27:42 -08001221
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001222 if (!frame) {
1223 return kNullPointerError;
1224 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001225 // Must be a native rate.
1226 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1227 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001228 frame->sample_rate_hz_ != kSampleRate32kHz &&
1229 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001230 return kBadSampleRateError;
1231 }
peah192164e2015-11-17 02:16:45 -08001232
peahdf3efa82015-11-28 12:35:15 -08001233 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001234 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001235 {
1236 // Aquire lock for the access of api_format.
1237 // The lock is released immediately due to the conditional
1238 // reinitialization.
1239 rtc::CritScope cs_capture(&crit_capture_);
1240 // TODO(ajm): The input and output rates and channels are currently
1241 // constrained to be identical in the int16 interface.
1242 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001243
1244 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001245 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001246 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1247 processing_config.input_stream().set_num_channels(frame->num_channels_);
1248 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1249 processing_config.output_stream().set_num_channels(frame->num_channels_);
1250
peahdf3efa82015-11-28 12:35:15 -08001251 {
1252 // Do conditional reinitialization.
1253 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001254 RETURN_ON_ERR(
1255 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001256 }
1257 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001258 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001259 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001260 return kBadDataLengthError;
1261 }
1262
aleloi868f32f2017-05-23 07:20:05 -07001263 if (aec_dump_) {
1264 RecordUnprocessedCaptureStream(*frame);
1265 }
1266
peahdf3efa82015-11-28 12:35:15 -08001267 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001268 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001269 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001270 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1271 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001272
aleloi868f32f2017-05-23 07:20:05 -07001273 if (aec_dump_) {
1274 RecordProcessedCaptureStream(*frame);
1275 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001276
1277 return kNoError;
1278}
1279
peahde65ddc2016-09-16 15:02:15 -07001280int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001281 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001282
peahb58a1582016-03-15 09:34:24 -07001283 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001284 // TODO(peah): Simplify once the public API Enable functions for these
1285 // are moved to APM.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001286 RTC_DCHECK(!(private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001287 private_submodules_->echo_control_mobile->is_enabled()));
peahb58a1582016-03-15 09:34:24 -07001288
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001289 MaybeUpdateHistograms();
1290
peahde65ddc2016-09-16 15:02:15 -07001291 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001292
Alex Loikob5c9a792018-04-16 16:31:22 +02001293 if (private_submodules_->pre_amplifier) {
1294 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1295 capture_buffer->channels_f(), capture_buffer->num_channels(),
1296 capture_buffer->num_frames()));
1297 }
1298
peah1b08dc32016-12-20 13:45:58 -08001299 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001300 capture_buffer->channels_const()[0],
1301 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001302 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1303 if (log_rms) {
1304 capture_rms_interval_counter_ = 0;
1305 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001306 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1307 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1308 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1309 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001310 }
1311
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001312 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001313 // Detect and flag any change in the analog gain.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001314 int analog_mic_level = agc1()->stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001315 capture_.echo_path_gain_change =
1316 capture_.prev_analog_mic_level != analog_mic_level &&
1317 capture_.prev_analog_mic_level != -1;
1318 capture_.prev_analog_mic_level = analog_mic_level;
1319
Per Åhgrend2650d12018-10-02 17:00:59 +02001320 // Detect and flag any change in the pre-amplifier gain.
1321 if (private_submodules_->pre_amplifier) {
1322 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1323 capture_.echo_path_gain_change =
1324 capture_.echo_path_gain_change ||
1325 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001326 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001327 capture_.prev_pre_amp_gain = pre_amp_gain;
1328 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001329 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001330 }
1331
peahbe615622016-02-13 16:40:47 -08001332 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001333 public_submodules_->gain_control->is_enabled()) {
1334 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001335 capture_buffer->channels()[0], capture_buffer->num_channels(),
1336 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001337
1338 if (constants_.use_experimental_agc_process_before_aec) {
1339 private_submodules_->agc_manager->Process(
1340 capture_buffer->channels()[0],
1341 capture_nonlocked_.capture_processing_format.num_frames(),
1342 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1343 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001344 }
1345
peah2ace3f92016-09-10 04:42:27 -07001346 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1347 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001348 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1349 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001350 }
1351
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001352 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001353 // Force down-mixing of the number of channels after the detection of
1354 // capture signal saturation.
1355 // TODO(peah): Look into ensuring that this kind of tampering with the
1356 // AudioBuffer functionality should not be needed.
1357 capture_buffer->set_num_channels(1);
1358 }
1359
peahe0eae3c2016-12-14 01:16:23 -08001360 // TODO(peah): Move the AEC3 low-cut filter to this place.
1361 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001362 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001363 private_submodules_->low_cut_filter->Process(capture_buffer);
1364 }
peahde65ddc2016-09-16 15:02:15 -07001365 RETURN_ON_ERR(
1366 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1367 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001368
1369 // Ensure that the stream delay was set before the call to the
1370 // AEC ProcessCaptureAudio function.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001371 if (private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001372 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001373 return AudioProcessing::kStreamParameterNotSetError;
1374 }
1375
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001376 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001377 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1378
Per Åhgrend0fa8202018-04-18 09:35:13 +02001379 if (was_stream_delay_set()) {
1380 private_submodules_->echo_controller->SetAudioBufferDelay(
1381 stream_delay_ms());
1382 }
1383
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001384 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001385 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001386 } else {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001387 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
peah61202ac2017-02-06 03:39:42 -08001388 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001389 }
1390
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001391 if (private_submodules_->echo_control_mobile->is_enabled() &&
peahdf3efa82015-11-28 12:35:15 -08001392 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001393 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001394 }
peahde65ddc2016-09-16 15:02:15 -07001395 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001396
1397 // Ensure that the stream delay was set before the call to the
1398 // AECM ProcessCaptureAudio function.
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001399 if (private_submodules_->echo_control_mobile->is_enabled() &&
peah253534d2016-03-15 04:32:28 -07001400 !was_stream_delay_set()) {
1401 return AudioProcessing::kStreamParameterNotSetError;
1402 }
1403
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001404 if (!(private_submodules_->echo_controller ||
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001405 private_submodules_->echo_cancellation->is_enabled())) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001406 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001407 capture_buffer, stream_delay_ms()));
1408 }
ivoc9f4a4a02016-10-28 05:39:16 -07001409
peahde65ddc2016-09-16 15:02:15 -07001410 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001411 if (config_.voice_detection.enabled) {
1412 private_submodules_->voice_detector->ProcessCaptureAudio(capture_buffer);
1413 capture_.stats.voice_detected =
1414 private_submodules_->voice_detector->stream_has_voice();
1415 } else {
1416 capture_.stats.voice_detected = absl::nullopt;
1417 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001418
peahbe615622016-02-13 16:40:47 -08001419 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001420 public_submodules_->gain_control->is_enabled() &&
1421 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001422 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001423 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1424 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001425 }
Per Åhgren200feba2019-03-06 04:16:46 +01001426 // TODO(peah): Add reporting from AEC3 whether there is echo.
peahb8fbb542016-03-15 02:28:08 -07001427 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001428 capture_buffer,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001429 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001430
peah2ace3f92016-09-10 04:42:27 -07001431 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1432 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001433 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1434 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001435 }
1436
peah9e6a2902017-05-15 07:19:21 -07001437 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001438 RTC_DCHECK(private_submodules_->echo_detector);
1439 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001440 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1441 capture_buffer->num_frames()));
1442 }
1443
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001444 // TODO(aluebs): Investigate if the transient suppression placement should be
1445 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001446 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001447 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001448 private_submodules_->agc_manager.get()
1449 ? private_submodules_->agc_manager->voice_probability()
1450 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001451
peahdf3efa82015-11-28 12:35:15 -08001452 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001453 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1454 capture_buffer->num_channels(),
1455 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1456 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1457 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001458 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001459 }
1460
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001461 // Experimental APM sub-module that analyzes |capture_buffer|.
1462 if (private_submodules_->capture_analyzer) {
1463 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1464 }
1465
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001466 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001467 private_submodules_->gain_controller2->NotifyAnalogLevel(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001468 agc1()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001469 private_submodules_->gain_controller2->Process(capture_buffer);
1470 }
1471
Sam Zackrisson0beac582017-09-25 12:04:02 +02001472 if (private_submodules_->capture_post_processor) {
1473 private_submodules_->capture_post_processor->Process(capture_buffer);
1474 }
1475
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001476 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001477 public_submodules_->level_estimator->ProcessStream(capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001478 if (config_.level_estimation.enabled) {
1479 private_submodules_->output_level_estimator->ProcessStream(capture_buffer);
1480 capture_.stats.output_rms_dbfs =
1481 private_submodules_->output_level_estimator->RMS();
1482 } else {
1483 capture_.stats.output_rms_dbfs = absl::nullopt;
1484 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001485
peah1b08dc32016-12-20 13:45:58 -08001486 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1487 capture_buffer->channels_const()[0],
1488 capture_nonlocked_.capture_processing_format.num_frames()));
1489 if (log_rms) {
1490 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1491 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1492 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1493 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1494 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1495 }
1496
peahdf3efa82015-11-28 12:35:15 -08001497 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001498 return kNoError;
1499}
1500
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001501int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001502 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001503 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001504 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001505 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001506 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001507 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001508 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001509 };
1510 if (samples_per_channel != reverse_config.num_frames()) {
1511 return kBadDataLengthError;
1512 }
peahdf3efa82015-11-28 12:35:15 -08001513 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001514}
1515
peahde65ddc2016-09-16 15:02:15 -07001516int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1517 const StreamConfig& input_config,
1518 const StreamConfig& output_config,
1519 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001520 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001521 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001522 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001523 if (submodule_states_.RenderMultiBandProcessingActive() ||
1524 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001525 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1526 dest);
peah2ace3f92016-09-10 04:42:27 -07001527 } else if (formats_.api_format.reverse_input_stream() !=
1528 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001529 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1530 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001531 } else {
peahde65ddc2016-09-16 15:02:15 -07001532 CopyAudioIfNeeded(src, input_config.num_frames(),
1533 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001534 }
1535
1536 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001537}
1538
peahdf3efa82015-11-28 12:35:15 -08001539int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001540 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001541 const StreamConfig& input_config,
1542 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001543 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001544 return kNullPointerError;
1545 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001546
peahde65ddc2016-09-16 15:02:15 -07001547 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001548 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001549 }
1550
peahdf3efa82015-11-28 12:35:15 -08001551 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001552 processing_config.reverse_input_stream() = input_config;
1553 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001554
peahdf3efa82015-11-28 12:35:15 -08001555 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001556 RTC_DCHECK_EQ(input_config.num_frames(),
1557 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001558
aleloi868f32f2017-05-23 07:20:05 -07001559 if (aec_dump_) {
1560 const size_t channel_size =
1561 formats_.api_format.reverse_input_stream().num_frames();
1562 const size_t num_channels =
1563 formats_.api_format.reverse_input_stream().num_channels();
1564 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001565 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001566 }
peahdf3efa82015-11-28 12:35:15 -08001567 render_.render_audio->CopyFrom(src,
1568 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001569 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001570}
1571
1572int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001573 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001574 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001575 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001576 return kNullPointerError;
1577 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001578 // Must be a native rate.
1579 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1580 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001581 frame->sample_rate_hz_ != kSampleRate32kHz &&
1582 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001583 return kBadSampleRateError;
1584 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001585
Michael Graczyk86c6d332015-07-23 11:41:39 -07001586 if (frame->num_channels_ <= 0) {
1587 return kBadNumberChannelsError;
1588 }
1589
peahdf3efa82015-11-28 12:35:15 -08001590 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001591 processing_config.reverse_input_stream().set_sample_rate_hz(
1592 frame->sample_rate_hz_);
1593 processing_config.reverse_input_stream().set_num_channels(
1594 frame->num_channels_);
1595 processing_config.reverse_output_stream().set_sample_rate_hz(
1596 frame->sample_rate_hz_);
1597 processing_config.reverse_output_stream().set_num_channels(
1598 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001599
peahdf3efa82015-11-28 12:35:15 -08001600 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001601 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001602 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001603 return kBadDataLengthError;
1604 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001605
aleloi868f32f2017-05-23 07:20:05 -07001606 if (aec_dump_) {
1607 aec_dump_->WriteRenderStreamMessage(*frame);
1608 }
1609
peahdf3efa82015-11-28 12:35:15 -08001610 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001611 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001612 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001613 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1614 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001615 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001616}
niklase@google.com470e71d2011-07-07 08:21:25 +00001617
peahde65ddc2016-09-16 15:02:15 -07001618int AudioProcessingImpl::ProcessRenderStreamLocked() {
1619 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001620
Alex Loiko73ec0192018-05-15 10:52:28 +02001621 HandleRenderRuntimeSettings();
1622
Alex Loiko5825aa62017-12-18 16:02:40 +01001623 if (private_submodules_->render_pre_processor) {
1624 private_submodules_->render_pre_processor->Process(render_buffer);
1625 }
1626
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001627 QueueNonbandedRenderAudio(render_buffer);
1628
peah2ace3f92016-09-10 04:42:27 -07001629 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001630 SampleRateSupportsMultiBand(
1631 formats_.render_processing_format.sample_rate_hz())) {
1632 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001633 }
1634
peahce4d9152017-05-19 01:28:05 -07001635 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1636 QueueBandedRenderAudio(render_buffer);
1637 }
1638
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001639 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001640 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001641 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001642 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001643
peah2ace3f92016-09-10 04:42:27 -07001644 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001645 SampleRateSupportsMultiBand(
1646 formats_.render_processing_format.sample_rate_hz())) {
1647 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001648 }
1649
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001650 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001651}
1652
1653int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001654 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001655 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001656 capture_.was_stream_delay_set = true;
1657 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001658
niklase@google.com470e71d2011-07-07 08:21:25 +00001659 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001660 delay = 0;
1661 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001662 }
1663
1664 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1665 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001666 delay = 500;
1667 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001668 }
1669
peahdf3efa82015-11-28 12:35:15 -08001670 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001671 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001672}
1673
1674int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001675 // Used as callback from submodules, hence locking is not allowed.
1676 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001677}
1678
1679bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001680 // Used as callback from submodules, hence locking is not allowed.
1681 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001682}
1683
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001684void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001685 rtc::CritScope cs(&crit_capture_);
1686 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001687}
1688
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001689void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001690 rtc::CritScope cs(&crit_capture_);
1691 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001692}
1693
1694int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001695 rtc::CritScope cs(&crit_capture_);
1696 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001697}
1698
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001699void AudioProcessingImpl::set_stream_analog_level(int level) {
1700 rtc::CritScope cs_capture(&crit_capture_);
1701 int error = agc1()->set_stream_analog_level(level);
1702 RTC_DCHECK_EQ(kNoError, error);
1703}
1704
1705int AudioProcessingImpl::recommended_stream_analog_level() const {
1706 rtc::CritScope cs_capture(&crit_capture_);
1707 return agc1()->stream_analog_level();
1708}
1709
aleloi868f32f2017-05-23 07:20:05 -07001710void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1711 RTC_DCHECK(aec_dump);
1712 rtc::CritScope cs_render(&crit_render_);
1713 rtc::CritScope cs_capture(&crit_capture_);
1714
1715 // The previously attached AecDump will be destroyed with the
1716 // 'aec_dump' parameter, which is after locks are released.
1717 aec_dump_.swap(aec_dump);
1718 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001719 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001720}
1721
1722void AudioProcessingImpl::DetachAecDump() {
1723 // The d-tor of a task-queue based AecDump blocks until all pending
1724 // tasks are done. This construction avoids blocking while holding
1725 // the render and capture locks.
1726 std::unique_ptr<AecDump> aec_dump = nullptr;
1727 {
1728 rtc::CritScope cs_render(&crit_render_);
1729 rtc::CritScope cs_capture(&crit_capture_);
1730 aec_dump = std::move(aec_dump_);
1731 }
1732}
1733
Sam Zackrisson4d364492018-03-02 16:03:21 +01001734void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1735 std::unique_ptr<AudioGenerator> audio_generator) {
1736 // TODO(bugs.webrtc.org/8882) Stub.
1737 // Reset internal audio generator with audio_generator.
1738}
1739
1740void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1741 // TODO(bugs.webrtc.org/8882) Stub.
1742 // Delete audio generator, if one is attached.
1743}
1744
Ivo Creusen56d46092017-11-24 17:29:59 +01001745AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001746 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001747 rtc::CritScope cs_capture(&crit_capture_);
1748 if (!has_remote_tracks) {
1749 return capture_.stats;
1750 }
1751 AudioProcessingStats stats = capture_.stats;
1752 EchoCancellationImpl::Metrics metrics;
1753 if (private_submodules_->echo_controller) {
1754 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1755 stats.echo_return_loss = ec_metrics.echo_return_loss;
1756 stats.echo_return_loss_enhancement =
1757 ec_metrics.echo_return_loss_enhancement;
1758 stats.delay_ms = ec_metrics.delay_ms;
1759 } else if (private_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1760 Error::kNoError) {
1761 if (metrics.divergent_filter_fraction != -1.0f) {
1762 stats.divergent_filter_fraction =
1763 absl::optional<double>(metrics.divergent_filter_fraction);
1764 }
1765 if (metrics.echo_return_loss.instant != -100) {
1766 stats.echo_return_loss =
1767 absl::optional<double>(metrics.echo_return_loss.instant);
1768 }
1769 if (metrics.echo_return_loss_enhancement.instant != -100) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001770 stats.echo_return_loss_enhancement =
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001771 absl::optional<double>(metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001772 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001773 }
1774 if (config_.residual_echo_detector.enabled) {
1775 RTC_DCHECK(private_submodules_->echo_detector);
1776 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1777 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1778 stats.residual_echo_likelihood_recent_max =
1779 ed_metrics.echo_likelihood_recent_max;
1780 }
1781 int delay_median, delay_std;
1782 float fraction_poor_delays;
1783 if (private_submodules_->echo_cancellation->GetDelayMetrics(
1784 &delay_median, &delay_std, &fraction_poor_delays) ==
1785 Error::kNoError) {
1786 if (delay_median >= 0) {
1787 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001788 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001789 if (delay_std >= 0) {
1790 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001791 }
1792 }
1793 return stats;
1794}
1795
niklase@google.com470e71d2011-07-07 08:21:25 +00001796GainControl* AudioProcessingImpl::gain_control() const {
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001797 return public_submodules_->gain_control_config_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001798}
1799
niklase@google.com470e71d2011-07-07 08:21:25 +00001800LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001801 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001802}
1803
1804NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001805 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001806}
1807
1808VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001809 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001810}
1811
peah8271d042016-11-22 07:24:52 -08001812void AudioProcessingImpl::MutateConfig(
1813 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1814 rtc::CritScope cs_render(&crit_render_);
1815 rtc::CritScope cs_capture(&crit_capture_);
1816 mutator(&config_);
1817 ApplyConfig(config_);
1818}
1819
1820AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1821 rtc::CritScope cs_render(&crit_render_);
1822 rtc::CritScope cs_capture(&crit_capture_);
1823 return config_;
1824}
1825
peah2ace3f92016-09-10 04:42:27 -07001826bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1827 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001828 config_.high_pass_filter.enabled,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001829 private_submodules_->echo_cancellation->is_enabled(),
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001830 private_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001831 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001832 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001833 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001834 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001835 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001836 public_submodules_->voice_detection->is_enabled(),
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001837 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001838 public_submodules_->level_estimator->is_enabled(),
1839 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001840}
1841
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001842void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001843 if (capture_.transient_suppressor_enabled) {
1844 if (!public_submodules_->transient_suppressor.get()) {
1845 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001846 }
peahdf3efa82015-11-28 12:35:15 -08001847 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001848 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1849 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001850 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001851}
1852
peah8271d042016-11-22 07:24:52 -08001853void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001854 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001855 private_submodules_->low_cut_filter.reset(
1856 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1857 } else {
1858 private_submodules_->low_cut_filter.reset();
1859 }
1860}
alessiob3ec96df2017-05-22 06:57:06 -07001861
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001862void AudioProcessingImpl::InitializeEchoController() {
Per Åhgren200feba2019-03-06 04:16:46 +01001863 if (echo_control_factory_ ||
1864 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
1865 !config_.echo_canceller.use_legacy_aec)) {
1866 if (echo_control_factory_) {
1867 private_submodules_->echo_controller =
1868 echo_control_factory_->Create(proc_sample_rate_hz());
1869 } else {
1870 private_submodules_->echo_controller = absl::make_unique<EchoCanceller3>(
1871 EchoCanceller3Config(), proc_sample_rate_hz(), true);
1872 }
1873
1874 capture_nonlocked_.echo_controller_enabled = true;
peahe0eae3c2016-12-14 01:16:23 -08001875 } else {
Per Åhgren200feba2019-03-06 04:16:46 +01001876 private_submodules_->echo_cancellation->Enable(
1877 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
1878 private_submodules_->echo_control_mobile->Enable(
1879 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
1880
1881 private_submodules_->echo_cancellation->set_suppression_level(
1882 config_.echo_canceller.legacy_moderate_suppression_level
1883 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1884 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
1885
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001886 private_submodules_->echo_controller.reset();
Per Åhgren200feba2019-03-06 04:16:46 +01001887 capture_nonlocked_.echo_controller_enabled = false;
peahe0eae3c2016-12-14 01:16:23 -08001888 }
1889}
peah8271d042016-11-22 07:24:52 -08001890
alessiob3ec96df2017-05-22 06:57:06 -07001891void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001892 if (config_.gain_controller2.enabled) {
1893 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001894 }
1895}
1896
Alex Loikob5c9a792018-04-16 16:31:22 +02001897void AudioProcessingImpl::InitializePreAmplifier() {
1898 if (config_.pre_amplifier.enabled) {
1899 private_submodules_->pre_amplifier.reset(
1900 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1901 } else {
1902 private_submodules_->pre_amplifier.reset();
1903 }
1904}
1905
ivoc9f4a4a02016-10-28 05:39:16 -07001906void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001907 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001908 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001909 proc_sample_rate_hz(), 1,
1910 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001911}
1912
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001913void AudioProcessingImpl::InitializeAnalyzer() {
1914 if (private_submodules_->capture_analyzer) {
1915 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1916 num_proc_channels());
1917 }
1918}
1919
Sam Zackrisson0beac582017-09-25 12:04:02 +02001920void AudioProcessingImpl::InitializePostProcessor() {
1921 if (private_submodules_->capture_post_processor) {
1922 private_submodules_->capture_post_processor->Initialize(
1923 proc_sample_rate_hz(), num_proc_channels());
1924 }
1925}
1926
Alex Loiko5825aa62017-12-18 16:02:40 +01001927void AudioProcessingImpl::InitializePreProcessor() {
1928 if (private_submodules_->render_pre_processor) {
1929 private_submodules_->render_pre_processor->Initialize(
1930 formats_.render_processing_format.sample_rate_hz(),
1931 formats_.render_processing_format.num_channels());
1932 }
1933}
1934
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001935void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001936 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001937
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001938 if (private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001939 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1940 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001941 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001942 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001943 capture_.stream_delay_jumps = 0;
1944 }
1945 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001946 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001947 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001948 }
1949
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001950 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001951 const int diff_stream_delay_ms =
1952 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1953 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1954 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001955 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1956 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001957 if (capture_.stream_delay_jumps == -1) {
1958 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001959 }
peahdf3efa82015-11-28 12:35:15 -08001960 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001961 }
peahdf3efa82015-11-28 12:35:15 -08001962 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001963
1964 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001965 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001966 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001967 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001968 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001969 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001970 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001971 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001972 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001973 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001974 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001975 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1976 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1977 100);
peahdf3efa82015-11-28 12:35:15 -08001978 if (capture_.aec_system_delay_jumps == -1) {
1979 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001980 }
peahdf3efa82015-11-28 12:35:15 -08001981 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001982 }
peahdf3efa82015-11-28 12:35:15 -08001983 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001984 }
1985}
1986
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001987void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001988 // Run in a single-threaded manner.
1989 rtc::CritScope cs_render(&crit_render_);
1990 rtc::CritScope cs_capture(&crit_capture_);
1991
1992 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001993 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001994 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001995 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001996 }
peahdf3efa82015-11-28 12:35:15 -08001997 capture_.stream_delay_jumps = -1;
1998 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001999
peahdf3efa82015-11-28 12:35:15 -08002000 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08002001 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
2002 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002003 }
peahdf3efa82015-11-28 12:35:15 -08002004 capture_.aec_system_delay_jumps = -1;
2005 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002006}
2007
aleloi868f32f2017-05-23 07:20:05 -07002008void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2009 if (!aec_dump_) {
2010 return;
2011 }
2012 std::string experiments_description =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002013 private_submodules_->echo_cancellation->GetExperimentsDescription();
aleloi868f32f2017-05-23 07:20:05 -07002014 // TODO(peah): Add semicolon-separated concatenations of experiment
2015 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002016 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2017 experiments_description += "AgcClippingLevelExperiment;";
2018 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002019 if (capture_nonlocked_.echo_controller_enabled) {
2020 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002021 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002022 if (config_.gain_controller2.enabled) {
2023 experiments_description += "GainController2;";
2024 }
aleloi868f32f2017-05-23 07:20:05 -07002025
2026 InternalAPMConfig apm_config;
2027
Per Åhgren200feba2019-03-06 04:16:46 +01002028 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002029 apm_config.aec_delay_agnostic_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002030 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002031 apm_config.aec_drift_compensation_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002032 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002033 apm_config.aec_extended_filter_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002034 private_submodules_->echo_cancellation->is_extended_filter_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002035 apm_config.aec_suppression_level = static_cast<int>(
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002036 private_submodules_->echo_cancellation->suppression_level());
aleloi868f32f2017-05-23 07:20:05 -07002037
2038 apm_config.aecm_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002039 private_submodules_->echo_control_mobile->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002040 apm_config.aecm_comfort_noise_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002041 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
2042 apm_config.aecm_routing_mode = static_cast<int>(
2043 private_submodules_->echo_control_mobile->routing_mode());
aleloi868f32f2017-05-23 07:20:05 -07002044
2045 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2046 apm_config.agc_mode =
2047 static_cast<int>(public_submodules_->gain_control->mode());
2048 apm_config.agc_limiter_enabled =
2049 public_submodules_->gain_control->is_limiter_enabled();
2050 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2051
2052 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2053
2054 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2055 apm_config.ns_level =
2056 static_cast<int>(public_submodules_->noise_suppression->level());
2057
2058 apm_config.transient_suppression_enabled =
2059 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002060 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002061 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2062 apm_config.pre_amplifier_fixed_gain_factor =
2063 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002064
2065 if (!forced && apm_config == apm_config_for_aec_dump_) {
2066 return;
2067 }
2068 aec_dump_->WriteConfig(apm_config);
2069 apm_config_for_aec_dump_ = apm_config;
2070}
2071
2072void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2073 const float* const* src) {
2074 RTC_DCHECK(aec_dump_);
2075 WriteAecDumpConfigMessage(false);
2076
2077 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2078 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2079 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002080 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002081 RecordAudioProcessingState();
2082}
2083
2084void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2085 const AudioFrame& capture_frame) {
2086 RTC_DCHECK(aec_dump_);
2087 WriteAecDumpConfigMessage(false);
2088
2089 aec_dump_->AddCaptureStreamInput(capture_frame);
2090 RecordAudioProcessingState();
2091}
2092
2093void AudioProcessingImpl::RecordProcessedCaptureStream(
2094 const float* const* processed_capture_stream) {
2095 RTC_DCHECK(aec_dump_);
2096
2097 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2098 const size_t num_channels =
2099 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002100 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2101 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002102 aec_dump_->WriteCaptureStreamMessage();
2103}
2104
2105void AudioProcessingImpl::RecordProcessedCaptureStream(
2106 const AudioFrame& processed_capture_frame) {
2107 RTC_DCHECK(aec_dump_);
2108
2109 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2110 aec_dump_->WriteCaptureStreamMessage();
2111}
2112
2113void AudioProcessingImpl::RecordAudioProcessingState() {
2114 RTC_DCHECK(aec_dump_);
2115 AecDump::AudioProcessingState audio_proc_state;
2116 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2117 audio_proc_state.drift =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002118 private_submodules_->echo_cancellation->stream_drift_samples();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002119 audio_proc_state.level = agc1()->stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002120 audio_proc_state.keypress = capture_.key_pressed;
2121 aec_dump_->AddAudioProcessingState(audio_proc_state);
2122}
2123
kwiberg83ffe452016-08-29 14:46:07 -07002124AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002125 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002126 : aec_system_delay_jumps(-1),
2127 delay_offset_ms(0),
2128 was_stream_delay_set(false),
2129 last_stream_delay_ms(0),
2130 last_aec_system_delay_ms(0),
2131 stream_delay_jumps(-1),
2132 output_will_be_muted(false),
2133 key_pressed(false),
2134 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002135 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002136 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002137 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002138 prev_analog_mic_level(-1),
2139 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002140
2141AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2142
2143AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2144
2145AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2146
niklase@google.com470e71d2011-07-07 08:21:25 +00002147} // namespace webrtc