blob: 9ca81e69e336f562f9a3e62ab9203928ae28ca9b [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_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200190 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200191 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200192 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700193 changed |= (level_estimator_enabled != level_estimator_enabled_);
194 changed |=
195 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100196 changed |=
197 (private_voice_detector_enabled != private_voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700198 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
199 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200200 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700201 echo_canceller_enabled_ = echo_canceller_enabled;
202 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700203 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700204 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700205 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700206 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200207 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200208 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700209 level_estimator_enabled_ = level_estimator_enabled;
210 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100211 private_voice_detector_enabled_ = private_voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700212 transient_suppressor_enabled_ = transient_suppressor_enabled;
213 }
214
215 changed |= first_update_;
216 first_update_ = false;
217 return changed;
218}
219
220bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
221 const {
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100222 return CaptureMultiBandProcessingActive() ||
223 voice_activity_detector_enabled_ || private_voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700224}
225
226bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
227 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200228 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700229 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200230 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700231}
232
peah23ac8b42017-05-23 05:33:56 -0700233bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
234 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200235 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
236 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700237}
238
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200239bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
240 return capture_analyzer_enabled_;
241}
242
peah2ace3f92016-09-10 04:42:27 -0700243bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
244 const {
245 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800246 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200247 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700248}
249
Alex Loiko5825aa62017-12-18 16:02:40 +0100250bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
251 const {
252 return render_pre_processor_enabled_;
253}
254
peah2ace3f92016-09-10 04:42:27 -0700255bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
256 const {
peah2ace3f92016-09-10 04:42:27 -0700257 return false;
peah2ace3f92016-09-10 04:42:27 -0700258}
259
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200260bool AudioProcessingImpl::ApmSubmoduleStates::LowCutFilteringRequired() const {
261 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
262 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
263}
264
solenberg5e465c32015-12-08 13:22:33 -0800265struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800266 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800267 // Accessed externally of APM without any lock acquired.
Sam Zackrisson23513132019-01-11 15:10:32 +0100268 // TODO(bugs.webrtc.org/9947): Move these submodules into private_submodules_
269 // when their pointer-to-submodule API functions are gone.
kwiberg88788ad2016-02-19 07:04:49 -0800270 std::unique_ptr<LevelEstimatorImpl> level_estimator;
271 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
Sam Zackrisson23513132019-01-11 15:10:32 +0100272 std::unique_ptr<NoiseSuppressionProxy> noise_suppression_proxy;
kwiberg88788ad2016-02-19 07:04:49 -0800273 std::unique_ptr<VoiceDetectionImpl> voice_detection;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100274 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800275 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800276 gain_control_for_experimental_agc;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100277 std::unique_ptr<GainControlConfigProxy> gain_control_config_proxy;
solenberg5e465c32015-12-08 13:22:33 -0800278
279 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800280 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800281};
282
283struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200284 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100285 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200286 rtc::scoped_refptr<EchoDetector> echo_detector,
287 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200288 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100289 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200290 render_pre_processor(std::move(render_pre_processor)),
291 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800292 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800293 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700294 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800295 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200296 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100297 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100298 std::unique_ptr<EchoControl> echo_controller;
299 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100300 std::unique_ptr<CustomProcessing> capture_post_processor;
301 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200302 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200303 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100304 std::unique_ptr<LevelEstimatorImpl> output_level_estimator;
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100305 std::unique_ptr<VoiceDetectionImpl> voice_detector;
solenberg5e465c32015-12-08 13:22:33 -0800306};
307
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100308AudioProcessingBuilder::AudioProcessingBuilder() = default;
309AudioProcessingBuilder::~AudioProcessingBuilder() = default;
310
311AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
312 std::unique_ptr<CustomProcessing> capture_post_processing) {
313 capture_post_processing_ = std::move(capture_post_processing);
314 return *this;
315}
316
317AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
318 std::unique_ptr<CustomProcessing> render_pre_processing) {
319 render_pre_processing_ = std::move(render_pre_processing);
320 return *this;
321}
322
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200323AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
324 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
325 capture_analyzer_ = std::move(capture_analyzer);
326 return *this;
327}
328
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100329AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
330 std::unique_ptr<EchoControlFactory> echo_control_factory) {
331 echo_control_factory_ = std::move(echo_control_factory);
332 return *this;
333}
334
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100335AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200336 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100337 echo_detector_ = std::move(echo_detector);
338 return *this;
339}
340
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100341AudioProcessing* AudioProcessingBuilder::Create() {
342 webrtc::Config config;
343 return Create(config);
344}
345
346AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100347 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
348 config, std::move(capture_post_processing_),
349 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200350 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100351 if (apm->Initialize() != AudioProcessing::kNoError) {
352 delete apm;
353 apm = nullptr;
354 }
355 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100356}
357
peah88ac8532016-09-12 16:47:25 -0700358AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200359 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
360}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000361
Per Åhgren13735822018-02-12 21:42:56 +0100362int AudioProcessingImpl::instance_count_ = 0;
363
Sam Zackrisson0beac582017-09-25 12:04:02 +0200364AudioProcessingImpl::AudioProcessingImpl(
365 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100366 std::unique_ptr<CustomProcessing> capture_post_processor,
367 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200368 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200369 rtc::scoped_refptr<EchoDetector> echo_detector,
370 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100371 : data_dumper_(
372 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200373 capture_runtime_settings_(kRuntimeSettingQueueSize),
374 render_runtime_settings_(kRuntimeSettingQueueSize),
375 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
376 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200377 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200378 submodule_states_(!!capture_post_processor,
379 !!render_pre_processor,
380 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800381 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200382 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200383 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100384 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200385 std::move(echo_detector),
386 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800387 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800388 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000389#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200390 /* enabled= */ false,
391 /* enabled_agc2_level_estimator= */ false,
392 /* digital_adaptive_disabled= */ false,
393 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000394#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200395 config.Get<ExperimentalAgc>().enabled,
396 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200397 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
398 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000399#endif
andrew1c7075f2015-06-24 18:14:14 -0700400#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200401 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700402#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200403 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700404#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200405 capture_nonlocked_() {
Sam Zackrisson421c8592019-02-11 13:39:46 +0100406 // Mark Echo Controller enabled if a factory is injected.
407 capture_nonlocked_.echo_controller_enabled =
408 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000409
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100410 public_submodules_->gain_control.reset(new GainControlImpl());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100411 public_submodules_->level_estimator.reset(
412 new LevelEstimatorImpl(&crit_capture_));
413 public_submodules_->noise_suppression.reset(
414 new NoiseSuppressionImpl(&crit_capture_));
415 public_submodules_->noise_suppression_proxy.reset(new NoiseSuppressionProxy(
416 this, public_submodules_->noise_suppression.get()));
417 public_submodules_->voice_detection.reset(
418 new VoiceDetectionImpl(&crit_capture_));
419 public_submodules_->gain_control_for_experimental_agc.reset(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100420 new GainControlForExperimentalAgc(
421 public_submodules_->gain_control.get()));
422 public_submodules_->gain_control_config_proxy.reset(
423 new GainControlConfigProxy(&crit_capture_, this, agc1()));
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200424
Sam Zackrisson421c8592019-02-11 13:39:46 +0100425 // If no echo detector is injected, use the ResidualEchoDetector.
426 if (!private_submodules_->echo_detector) {
427 private_submodules_->echo_detector =
428 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800429 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000430
Sam Zackrisson421c8592019-02-11 13:39:46 +0100431 // TODO(alessiob): Move the injected gain controller once injection is
432 // implemented.
433 private_submodules_->gain_controller2.reset(new GainController2());
434
435 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
436 << !!private_submodules_->capture_analyzer
437 << "\nCapture post processor activated: "
438 << !!private_submodules_->capture_post_processor
439 << "\nRender pre processor activated: "
440 << !!private_submodules_->render_pre_processor;
441
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000442 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000443}
444
445AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800446 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800447 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800448 private_submodules_->agc_manager.reset();
449 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800450 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000451}
452
niklase@google.com470e71d2011-07-07 08:21:25 +0000453int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800454 // Run in a single-threaded manner during initialization.
455 rtc::CritScope cs_render(&crit_render_);
456 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000457 return InitializeLocked();
458}
459
peahde65ddc2016-09-16 15:02:15 -0700460int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
461 int capture_output_sample_rate_hz,
462 int render_input_sample_rate_hz,
463 ChannelLayout capture_input_layout,
464 ChannelLayout capture_output_layout,
465 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700466 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700467 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
468 LayoutHasKeyboard(capture_input_layout)},
469 {capture_output_sample_rate_hz,
470 ChannelsFromLayout(capture_output_layout),
471 LayoutHasKeyboard(capture_output_layout)},
472 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
473 LayoutHasKeyboard(render_input_layout)},
474 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
475 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700476
477 return Initialize(processing_config);
478}
479
480int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800481 // Run in a single-threaded manner during initialization.
482 rtc::CritScope cs_render(&crit_render_);
483 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700484 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000485}
486
peahdf3efa82015-11-28 12:35:15 -0800487int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800488 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700489 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800490}
491
peahdf3efa82015-11-28 12:35:15 -0800492int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700493 const ProcessingConfig& processing_config,
494 bool force_initialization) {
495 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800496}
497
peah192164e2015-11-17 02:16:45 -0800498// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800499// their current values (needs to be called while holding the crit_render_lock).
500int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700501 const ProcessingConfig& processing_config,
502 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800503 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700504 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800505 return kNoError;
506 }
peahdf3efa82015-11-28 12:35:15 -0800507
508 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800509 return InitializeLocked(processing_config);
510}
511
niklase@google.com470e71d2011-07-07 08:21:25 +0000512int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200513 UpdateActiveSubmoduleStates();
514
peahde65ddc2016-09-16 15:02:15 -0700515 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800516 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700517 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800518 : formats_.api_format.reverse_output_stream().num_frames();
519 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
520 render_.render_audio.reset(new AudioBuffer(
521 formats_.api_format.reverse_input_stream().num_frames(),
522 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700523 formats_.render_processing_format.num_frames(),
524 formats_.render_processing_format.num_channels(),
525 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700526 if (formats_.api_format.reverse_input_stream() !=
527 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800528 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800529 formats_.api_format.reverse_input_stream().num_channels(),
530 formats_.api_format.reverse_input_stream().num_frames(),
531 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800532 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700533 } else {
peahdf3efa82015-11-28 12:35:15 -0800534 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700535 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700536 } else {
peahdf3efa82015-11-28 12:35:15 -0800537 render_.render_audio.reset(nullptr);
538 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700539 }
peahce4d9152017-05-19 01:28:05 -0700540
peahdf3efa82015-11-28 12:35:15 -0800541 capture_.capture_audio.reset(
542 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
543 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700544 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200545 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800546 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000547
peah764e3642016-10-22 05:04:30 -0700548 AllocateRenderQueue();
549
peah135259a2016-10-28 03:12:11 -0700550 public_submodules_->gain_control->Initialize(num_proc_channels(),
551 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700552 if (constants_.use_experimental_agc) {
553 if (!private_submodules_->agc_manager.get()) {
554 private_submodules_->agc_manager.reset(new AgcManagerDirect(
555 public_submodules_->gain_control.get(),
556 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200557 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
558 constants_.use_experimental_agc_agc2_level_estimation,
559 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700560 }
561 private_submodules_->agc_manager->Initialize();
562 private_submodules_->agc_manager->SetCaptureMuted(
563 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700564 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700565 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200566 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800567 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700568 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
569 proc_sample_rate_hz());
570 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100571 if (private_submodules_->voice_detector) {
572 private_submodules_->voice_detector->Initialize(
573 proc_split_sample_rate_hz());
574 }
peahde65ddc2016-09-16 15:02:15 -0700575 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700576 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200577 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700578 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200579 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200580 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100581 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800582
aleloi868f32f2017-05-23 07:20:05 -0700583 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200584 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700585 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000586 return kNoError;
587}
588
Michael Graczyk86c6d332015-07-23 11:41:39 -0700589int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200590 UpdateActiveSubmoduleStates();
591
Michael Graczyk86c6d332015-07-23 11:41:39 -0700592 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700593 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
594 return kBadSampleRateError;
595 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000596 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700597
Peter Kasting69558702016-01-12 16:26:35 -0800598 const size_t num_in_channels = config.input_stream().num_channels();
599 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700600
601 // Need at least one input channel.
602 // Need either one output channel or as many outputs as there are inputs.
603 if (num_in_channels == 0 ||
604 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700605 return kBadNumberChannelsError;
606 }
607
peahdf3efa82015-11-28 12:35:15 -0800608 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000609
peahde65ddc2016-09-16 15:02:15 -0700610 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700611 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700612 formats_.api_format.output_stream().sample_rate_hz()),
613 submodule_states_.CaptureMultiBandSubModulesActive() ||
614 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000615
peahde65ddc2016-09-16 15:02:15 -0700616 capture_nonlocked_.capture_processing_format =
617 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700618
peah2ce640f2017-04-07 03:57:48 -0700619 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200620 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700621 render_processing_rate = FindNativeProcessRateToUse(
622 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
623 formats_.api_format.reverse_output_stream().sample_rate_hz()),
624 submodule_states_.CaptureMultiBandSubModulesActive() ||
625 submodule_states_.RenderMultiBandSubModulesActive());
626 } else {
627 render_processing_rate = capture_processing_rate;
628 }
629
aluebseb3603b2016-04-20 15:27:58 -0700630 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
631 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700632 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200633 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700634 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
635 ? kSampleRate32kHz
636 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700637 }
peah2ce640f2017-04-07 03:57:48 -0700638
peahde65ddc2016-09-16 15:02:15 -0700639 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700640 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700641 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
642 kSampleRate8kHz) {
643 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000644 } else {
peahde65ddc2016-09-16 15:02:15 -0700645 render_processing_rate =
646 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000647 }
648
peahde65ddc2016-09-16 15:02:15 -0700649 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000650 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700651 if (submodule_states_.RenderMultiBandSubModulesActive()) {
652 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
653 } else {
654 formats_.render_processing_format = StreamConfig(
655 formats_.api_format.reverse_input_stream().sample_rate_hz(),
656 formats_.api_format.reverse_input_stream().num_channels());
657 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000658
peahde65ddc2016-09-16 15:02:15 -0700659 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
660 kSampleRate32kHz ||
661 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
662 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800663 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000664 } else {
peahdf3efa82015-11-28 12:35:15 -0800665 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700666 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000667 }
668
669 return InitializeLocked();
670}
671
peah88ac8532016-09-12 16:47:25 -0700672void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700673 // Run in a single-threaded manner when applying the settings.
674 rtc::CritScope cs_render(&crit_render_);
675 rtc::CritScope cs_capture(&crit_capture_);
676
Per Åhgren200feba2019-03-06 04:16:46 +0100677 const bool aec_config_changed =
678 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
679 config_.echo_canceller.use_legacy_aec !=
680 config.echo_canceller.use_legacy_aec ||
681 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
682 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
683 config_.echo_canceller.legacy_moderate_suppression_level !=
684 config.echo_canceller.legacy_moderate_suppression_level);
685
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100686 const bool agc1_config_changed =
687 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
688 config_.gain_controller1.mode != config.gain_controller1.mode ||
689 config_.gain_controller1.target_level_dbfs !=
690 config.gain_controller1.target_level_dbfs ||
691 config_.gain_controller1.compression_gain_db !=
692 config.gain_controller1.compression_gain_db ||
693 config_.gain_controller1.enable_limiter !=
694 config.gain_controller1.enable_limiter ||
695 config_.gain_controller1.analog_level_minimum !=
696 config.gain_controller1.analog_level_minimum ||
697 config_.gain_controller1.analog_level_maximum !=
698 config.gain_controller1.analog_level_maximum;
699
Yves Gerey499bc6c2018-10-10 18:29:07 +0200700 config_ = config;
701
Per Åhgren200feba2019-03-06 04:16:46 +0100702 if (aec_config_changed) {
703 InitializeEchoController();
704 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200705
Sam Zackrisson23513132019-01-11 15:10:32 +0100706 public_submodules_->noise_suppression->Enable(
707 config.noise_suppression.enabled);
708 public_submodules_->noise_suppression->set_level(
709 NsConfigLevelToInterfaceLevel(config.noise_suppression.level));
710
peah8271d042016-11-22 07:24:52 -0800711 InitializeLowCutFilter();
712
Mirko Bonadei675513b2017-11-09 11:09:25 +0100713 RTC_LOG(LS_INFO) << "Highpass filter activated: "
714 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800715
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100716 if (agc1_config_changed) {
717 ApplyAgc1Config(config_.gain_controller1);
718 }
719
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100720 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700721 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100722 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
723 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100724 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100725 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700726 config_.gain_controller2 = AudioProcessing::Config::GainController2();
727 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200728 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200729 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200730 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100731 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
732 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200733 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
734 << config_.pre_amplifier.enabled;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100735
736 if (config_.level_estimation.enabled &&
737 !private_submodules_->output_level_estimator) {
738 private_submodules_->output_level_estimator.reset(
739 new LevelEstimatorImpl(&crit_capture_));
740 private_submodules_->output_level_estimator->Enable(true);
741 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100742
743 if (config_.voice_detection.enabled && !private_submodules_->voice_detector) {
744 private_submodules_->voice_detector.reset(
745 new VoiceDetectionImpl(&crit_capture_));
746 private_submodules_->voice_detector->Enable(true);
747 private_submodules_->voice_detector->set_likelihood(
748 VoiceDetection::kVeryLowLikelihood);
749 private_submodules_->voice_detector->Initialize(
750 proc_split_sample_rate_hz());
751 }
peah88ac8532016-09-12 16:47:25 -0700752}
753
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100754void AudioProcessingImpl::ApplyAgc1Config(
755 const Config::GainController1& config) {
756 GainControl* agc = agc1();
757 int error = agc->Enable(config.enabled);
758 RTC_DCHECK_EQ(kNoError, error);
759 error = agc->set_mode(Agc1ConfigModeToInterfaceMode(config.mode));
760 RTC_DCHECK_EQ(kNoError, error);
761 error = agc->set_target_level_dbfs(config.target_level_dbfs);
762 RTC_DCHECK_EQ(kNoError, error);
763 error = agc->set_compression_gain_db(config.compression_gain_db);
764 RTC_DCHECK_EQ(kNoError, error);
765 error = agc->enable_limiter(config.enable_limiter);
766 RTC_DCHECK_EQ(kNoError, error);
767 error = agc->set_analog_level_limits(config.analog_level_minimum,
768 config.analog_level_maximum);
769 RTC_DCHECK_EQ(kNoError, error);
770}
771
772GainControl* AudioProcessingImpl::agc1() {
773 if (constants_.use_experimental_agc) {
774 return public_submodules_->gain_control_for_experimental_agc.get();
775 }
776 return public_submodules_->gain_control.get();
777}
778
779const GainControl* AudioProcessingImpl::agc1() const {
780 if (constants_.use_experimental_agc) {
781 return public_submodules_->gain_control_for_experimental_agc.get();
782 }
783 return public_submodules_->gain_control.get();
784}
785
peah88ac8532016-09-12 16:47:25 -0700786void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800787 // Run in a single-threaded manner when setting the extra options.
788 rtc::CritScope cs_render(&crit_render_);
789 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000790
Per Åhgrenf204faf2019-04-25 15:18:06 +0200791 capture_nonlocked_.use_aec2_extended_filter =
792 config.Get<ExtendedFilter>().enabled;
793 capture_nonlocked_.use_aec2_delay_agnostic =
794 config.Get<DelayAgnostic>().enabled;
795 capture_nonlocked_.use_aec2_refined_adaptive_filter =
796 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800797
peahdf3efa82015-11-28 12:35:15 -0800798 if (capture_.transient_suppressor_enabled !=
799 config.Get<ExperimentalNs>().enabled) {
800 capture_.transient_suppressor_enabled =
801 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000802 InitializeTransient();
803 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000804}
805
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000806int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800807 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700808 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000809}
810
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000811int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800812 // Used as callback from submodules, hence locking is not allowed.
813 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000814}
815
Peter Kasting69558702016-01-12 16:26:35 -0800816size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800817 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700818 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000819}
820
Peter Kasting69558702016-01-12 16:26:35 -0800821size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800822 // Used as callback from submodules, hence locking is not allowed.
823 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000824}
825
Peter Kasting69558702016-01-12 16:26:35 -0800826size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800827 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200828 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800829}
830
Peter Kasting69558702016-01-12 16:26:35 -0800831size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800832 // Used as callback from submodules, hence locking is not allowed.
833 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000834}
835
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000836void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800837 rtc::CritScope cs(&crit_capture_);
838 capture_.output_will_be_muted = muted;
839 if (private_submodules_->agc_manager.get()) {
840 private_submodules_->agc_manager->SetCaptureMuted(
841 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000842 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000843}
844
Alessio Bazzicac054e782018-04-16 12:10:09 +0200845void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200846 switch (setting.type()) {
847 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
848 render_runtime_settings_enqueuer_.Enqueue(setting);
849 return;
850 case RuntimeSetting::Type::kNotSpecified:
851 RTC_NOTREACHED();
852 return;
853 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100854 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200855 case RuntimeSetting::Type::kCaptureFixedPostGain:
Alex Loiko73ec0192018-05-15 10:52:28 +0200856 capture_runtime_settings_enqueuer_.Enqueue(setting);
857 return;
858 }
859 // The language allows the enum to have a non-enumerator
860 // value. Check that this doesn't happen.
861 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200862}
863
864AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
865 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200866 : runtime_settings_(*runtime_settings) {
867 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200868}
869
870AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
871 default;
872
873void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
874 RuntimeSetting setting) {
875 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200876 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200877 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200878 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200879 RTC_LOG(LS_ERROR)
880 << "The runtime settings queue is full. Oldest setting discarded.";
881 }
882 if (remaining_attempts == 0)
883 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
884}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000885
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000886int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700887 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000888 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000889 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000890 int output_sample_rate_hz,
891 ChannelLayout output_layout,
892 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800893 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800894 StreamConfig input_stream;
895 StreamConfig output_stream;
896 {
897 // Access the formats_.api_format.input_stream beneath the capture lock.
898 // The lock must be released as it is later required in the call
899 // to ProcessStream(,,,);
900 rtc::CritScope cs(&crit_capture_);
901 input_stream = formats_.api_format.input_stream();
902 output_stream = formats_.api_format.output_stream();
903 }
904
Michael Graczyk86c6d332015-07-23 11:41:39 -0700905 input_stream.set_sample_rate_hz(input_sample_rate_hz);
906 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
907 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700908 output_stream.set_sample_rate_hz(output_sample_rate_hz);
909 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
910 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
911
912 if (samples_per_channel != input_stream.num_frames()) {
913 return kBadDataLengthError;
914 }
915 return ProcessStream(src, input_stream, output_stream, dest);
916}
917
918int AudioProcessingImpl::ProcessStream(const float* const* src,
919 const StreamConfig& input_config,
920 const StreamConfig& output_config,
921 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800922 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800923 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700924 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800925 {
926 // Acquire the capture lock in order to safely call the function
927 // that retrieves the render side data. This function accesses apm
928 // getters that need the capture lock held when being called.
929 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700930 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800931
932 if (!src || !dest) {
933 return kNullPointerError;
934 }
935
936 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700937 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000938 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000939
Michael Graczyk86c6d332015-07-23 11:41:39 -0700940 processing_config.input_stream() = input_config;
941 processing_config.output_stream() = output_config;
942
peahdf3efa82015-11-28 12:35:15 -0800943 {
944 // Do conditional reinitialization.
945 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700946 RETURN_ON_ERR(
947 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800948 }
949 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700950 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
951 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000952
aleloi868f32f2017-05-23 07:20:05 -0700953 if (aec_dump_) {
954 RecordUnprocessedCaptureStream(src);
955 }
956
peahdf3efa82015-11-28 12:35:15 -0800957 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700958 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800959 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000960
aleloi868f32f2017-05-23 07:20:05 -0700961 if (aec_dump_) {
962 RecordProcessedCaptureStream(dest);
963 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000964 return kNoError;
965}
966
Alex Loiko73ec0192018-05-15 10:52:28 +0200967void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200968 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200969 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200970 if (aec_dump_) {
971 aec_dump_->WriteRuntimeSetting(setting);
972 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200973 switch (setting.type()) {
974 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200975 if (config_.pre_amplifier.enabled) {
976 float value;
977 setting.GetFloat(&value);
978 private_submodules_->pre_amplifier->SetGainFactor(value);
979 }
980 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200981 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100982 case RuntimeSetting::Type::kCaptureCompressionGain: {
983 float value;
984 setting.GetFloat(&value);
985 int int_value = static_cast<int>(value + .5f);
986 config_.gain_controller1.compression_gain_db = int_value;
987 int error = agc1()->set_compression_gain_db(int_value);
988 RTC_DCHECK_EQ(kNoError, error);
989 break;
990 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200991 case RuntimeSetting::Type::kCaptureFixedPostGain: {
992 if (config_.gain_controller2.enabled) {
993 float value;
994 setting.GetFloat(&value);
995 config_.gain_controller2.fixed_digital.gain_db = value;
996 private_submodules_->gain_controller2->ApplyConfig(
997 config_.gain_controller2);
998 }
999 break;
1000 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001001 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1002 RTC_NOTREACHED();
1003 break;
1004 case RuntimeSetting::Type::kNotSpecified:
1005 RTC_NOTREACHED();
1006 break;
1007 }
1008 }
1009}
1010
1011void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1012 RuntimeSetting setting;
1013 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001014 if (aec_dump_) {
1015 aec_dump_->WriteRuntimeSetting(setting);
1016 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001017 switch (setting.type()) {
1018 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1019 if (private_submodules_->render_pre_processor) {
1020 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
1021 }
1022 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001023 case RuntimeSetting::Type::kCapturePreGain: // fall-through
1024 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001025 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001026 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +02001027 RTC_NOTREACHED();
1028 break;
1029 }
1030 }
1031}
1032
peah9e6a2902017-05-15 07:19:21 -07001033void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001034 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001035
1036 // Insert the samples into the queue.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001037 if (private_submodules_->echo_cancellation) {
1038 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001039 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1040 num_reverse_channels(),
1041 &aec_render_queue_buffer_);
1042
Per Åhgrenf204faf2019-04-25 15:18:06 +02001043 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1044 // The data queue is full and needs to be emptied.
1045 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001046
Per Åhgrenf204faf2019-04-25 15:18:06 +02001047 // Retry the insert (should always work).
1048 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1049 RTC_DCHECK(result);
1050 }
peaha0624602016-10-25 04:45:24 -07001051 }
1052
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001053 if (private_submodules_->echo_control_mobile) {
1054 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1055 num_reverse_channels(),
1056 &aecm_render_queue_buffer_);
1057 RTC_DCHECK(aecm_render_signal_queue_);
1058 // Insert the samples into the queue.
1059 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1060 // The data queue is full and needs to be emptied.
1061 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001062
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001063 // Retry the insert (should always work).
1064 bool result =
1065 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1066 RTC_DCHECK(result);
1067 }
peah764e3642016-10-22 05:04:30 -07001068 }
peah701d6282016-10-25 05:42:20 -07001069
1070 if (!constants_.use_experimental_agc) {
1071 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
1072 // Insert the samples into the queue.
1073 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1074 // The data queue is full and needs to be emptied.
1075 EmptyQueuedRenderAudio();
1076
1077 // Retry the insert (should always work).
1078 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1079 RTC_DCHECK(result);
1080 }
1081 }
peah9e6a2902017-05-15 07:19:21 -07001082}
ivoc9f4a4a02016-10-28 05:39:16 -07001083
peah9e6a2902017-05-15 07:19:21 -07001084void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001085 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1086
1087 // Insert the samples into the queue.
1088 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1089 // The data queue is full and needs to be emptied.
1090 EmptyQueuedRenderAudio();
1091
1092 // Retry the insert (should always work).
1093 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1094 RTC_DCHECK(result);
1095 }
peah764e3642016-10-22 05:04:30 -07001096}
1097
1098void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001099 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001100 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001101
ivoc9f4a4a02016-10-28 05:39:16 -07001102 const size_t new_red_render_queue_element_max_size =
1103 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1104
peaha0624602016-10-25 04:45:24 -07001105 // Reallocate the queues if the queue item sizes are too small to fit the
1106 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001107
1108 if (agc_render_queue_element_max_size_ <
1109 new_agc_render_queue_element_max_size) {
1110 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1111
1112 std::vector<int16_t> template_queue_element(
1113 agc_render_queue_element_max_size_);
1114
1115 agc_render_signal_queue_.reset(
1116 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1117 kMaxNumFramesToBuffer, template_queue_element,
1118 RenderQueueItemVerifier<int16_t>(
1119 agc_render_queue_element_max_size_)));
1120
1121 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1122 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1123 } else {
1124 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001125 }
ivoc9f4a4a02016-10-28 05:39:16 -07001126
1127 if (red_render_queue_element_max_size_ <
1128 new_red_render_queue_element_max_size) {
1129 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1130
1131 std::vector<float> template_queue_element(
1132 red_render_queue_element_max_size_);
1133
1134 red_render_signal_queue_.reset(
1135 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1136 kMaxNumFramesToBuffer, template_queue_element,
1137 RenderQueueItemVerifier<float>(
1138 red_render_queue_element_max_size_)));
1139
1140 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1141 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1142 } else {
1143 red_render_signal_queue_->Clear();
1144 }
peah764e3642016-10-22 05:04:30 -07001145}
1146
1147void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1148 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001149 if (private_submodules_->echo_cancellation) {
1150 RTC_DCHECK(aec_render_signal_queue_);
1151 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
1152 private_submodules_->echo_cancellation->ProcessRenderAudio(
1153 aec_capture_queue_buffer_);
1154 }
peaha0624602016-10-25 04:45:24 -07001155 }
1156
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001157 if (private_submodules_->echo_control_mobile) {
1158 RTC_DCHECK(aecm_render_signal_queue_);
1159 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
1160 private_submodules_->echo_control_mobile->ProcessRenderAudio(
1161 aecm_capture_queue_buffer_);
1162 }
peah701d6282016-10-25 05:42:20 -07001163 }
1164
1165 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1166 public_submodules_->gain_control->ProcessRenderAudio(
1167 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001168 }
ivoc9f4a4a02016-10-28 05:39:16 -07001169
1170 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001171 RTC_DCHECK(private_submodules_->echo_detector);
1172 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001173 red_capture_queue_buffer_);
1174 }
peah764e3642016-10-22 05:04:30 -07001175}
1176
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001177int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001178 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001179 {
1180 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001181 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001182 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001183 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001184 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001185 }
peahfa6228e2015-11-16 16:27:42 -08001186
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001187 if (!frame) {
1188 return kNullPointerError;
1189 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001190 // Must be a native rate.
1191 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1192 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001193 frame->sample_rate_hz_ != kSampleRate32kHz &&
1194 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001195 return kBadSampleRateError;
1196 }
peah192164e2015-11-17 02:16:45 -08001197
peahdf3efa82015-11-28 12:35:15 -08001198 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001199 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001200 {
1201 // Aquire lock for the access of api_format.
1202 // The lock is released immediately due to the conditional
1203 // reinitialization.
1204 rtc::CritScope cs_capture(&crit_capture_);
1205 // TODO(ajm): The input and output rates and channels are currently
1206 // constrained to be identical in the int16 interface.
1207 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001208
1209 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001210 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001211 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1212 processing_config.input_stream().set_num_channels(frame->num_channels_);
1213 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1214 processing_config.output_stream().set_num_channels(frame->num_channels_);
1215
peahdf3efa82015-11-28 12:35:15 -08001216 {
1217 // Do conditional reinitialization.
1218 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001219 RETURN_ON_ERR(
1220 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001221 }
1222 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001223 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001224 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001225 return kBadDataLengthError;
1226 }
1227
aleloi868f32f2017-05-23 07:20:05 -07001228 if (aec_dump_) {
1229 RecordUnprocessedCaptureStream(*frame);
1230 }
1231
peahdf3efa82015-11-28 12:35:15 -08001232 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001233 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001234 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001235 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1236 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001237
aleloi868f32f2017-05-23 07:20:05 -07001238 if (aec_dump_) {
1239 RecordProcessedCaptureStream(*frame);
1240 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001241
1242 return kNoError;
1243}
1244
peahde65ddc2016-09-16 15:02:15 -07001245int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001246 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001247
peahb58a1582016-03-15 09:34:24 -07001248 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001249 // TODO(peah): Simplify once the public API Enable functions for these
1250 // are moved to APM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001251 RTC_DCHECK_LE(!!private_submodules_->echo_controller +
1252 !!private_submodules_->echo_cancellation +
1253 !!private_submodules_->echo_control_mobile,
1254 1);
peahb58a1582016-03-15 09:34:24 -07001255
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001256 MaybeUpdateHistograms();
1257
peahde65ddc2016-09-16 15:02:15 -07001258 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001259
Alex Loikob5c9a792018-04-16 16:31:22 +02001260 if (private_submodules_->pre_amplifier) {
1261 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1262 capture_buffer->channels_f(), capture_buffer->num_channels(),
1263 capture_buffer->num_frames()));
1264 }
1265
peah1b08dc32016-12-20 13:45:58 -08001266 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001267 capture_buffer->channels_const()[0],
1268 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001269 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1270 if (log_rms) {
1271 capture_rms_interval_counter_ = 0;
1272 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001273 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1274 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1275 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1276 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001277 }
1278
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001279 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001280 // Detect and flag any change in the analog gain.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001281 int analog_mic_level = agc1()->stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001282 capture_.echo_path_gain_change =
1283 capture_.prev_analog_mic_level != analog_mic_level &&
1284 capture_.prev_analog_mic_level != -1;
1285 capture_.prev_analog_mic_level = analog_mic_level;
1286
Per Åhgrend2650d12018-10-02 17:00:59 +02001287 // Detect and flag any change in the pre-amplifier gain.
1288 if (private_submodules_->pre_amplifier) {
1289 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1290 capture_.echo_path_gain_change =
1291 capture_.echo_path_gain_change ||
1292 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001293 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001294 capture_.prev_pre_amp_gain = pre_amp_gain;
1295 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001296 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001297 }
1298
peahbe615622016-02-13 16:40:47 -08001299 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001300 public_submodules_->gain_control->is_enabled()) {
1301 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001302 capture_buffer->channels()[0], capture_buffer->num_channels(),
1303 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001304
1305 if (constants_.use_experimental_agc_process_before_aec) {
1306 private_submodules_->agc_manager->Process(
1307 capture_buffer->channels()[0],
1308 capture_nonlocked_.capture_processing_format.num_frames(),
1309 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1310 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001311 }
1312
peah2ace3f92016-09-10 04:42:27 -07001313 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1314 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001315 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1316 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001317 }
1318
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001319 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001320 // Force down-mixing of the number of channels after the detection of
1321 // capture signal saturation.
1322 // TODO(peah): Look into ensuring that this kind of tampering with the
1323 // AudioBuffer functionality should not be needed.
1324 capture_buffer->set_num_channels(1);
1325 }
1326
peahe0eae3c2016-12-14 01:16:23 -08001327 // TODO(peah): Move the AEC3 low-cut filter to this place.
1328 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001329 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001330 private_submodules_->low_cut_filter->Process(capture_buffer);
1331 }
peahde65ddc2016-09-16 15:02:15 -07001332 RETURN_ON_ERR(
1333 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1334 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001335
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001336 if (private_submodules_->echo_control_mobile) {
1337 // Ensure that the stream delay was set before the call to the
1338 // AECM ProcessCaptureAudio function.
1339 if (!was_stream_delay_set()) {
1340 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001341 }
1342
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001343 if (public_submodules_->noise_suppression->is_enabled()) {
1344 capture_buffer->CopyLowPassToReference();
1345 }
peahe0eae3c2016-12-14 01:16:23 -08001346
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001347 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001348
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001349 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001350 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001351 } else {
1352 if (private_submodules_->echo_controller) {
1353 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1354
1355 if (was_stream_delay_set()) {
1356 private_submodules_->echo_controller->SetAudioBufferDelay(
1357 stream_delay_ms());
1358 }
1359
1360 private_submodules_->echo_controller->ProcessCapture(
1361 capture_buffer, capture_.echo_path_gain_change);
1362 } else if (private_submodules_->echo_cancellation) {
1363 // Ensure that the stream delay was set before the call to the
1364 // AEC ProcessCaptureAudio function.
1365 if (!was_stream_delay_set()) {
1366 return AudioProcessing::kStreamParameterNotSetError;
1367 }
1368
1369 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
1370 capture_buffer, stream_delay_ms()));
1371 }
1372
1373 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
Per Åhgren46537a32017-06-07 10:08:10 +02001374 }
ivoc9f4a4a02016-10-28 05:39:16 -07001375
peahde65ddc2016-09-16 15:02:15 -07001376 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001377 if (config_.voice_detection.enabled) {
1378 private_submodules_->voice_detector->ProcessCaptureAudio(capture_buffer);
1379 capture_.stats.voice_detected =
1380 private_submodules_->voice_detector->stream_has_voice();
1381 } else {
1382 capture_.stats.voice_detected = absl::nullopt;
1383 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001384
peahbe615622016-02-13 16:40:47 -08001385 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001386 public_submodules_->gain_control->is_enabled() &&
1387 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001388 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001389 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1390 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001391 }
Per Åhgren200feba2019-03-06 04:16:46 +01001392 // TODO(peah): Add reporting from AEC3 whether there is echo.
peahb8fbb542016-03-15 02:28:08 -07001393 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001394 capture_buffer,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001395 private_submodules_->echo_cancellation &&
1396 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001397
peah2ace3f92016-09-10 04:42:27 -07001398 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1399 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001400 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1401 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001402 }
1403
peah9e6a2902017-05-15 07:19:21 -07001404 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001405 RTC_DCHECK(private_submodules_->echo_detector);
1406 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001407 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1408 capture_buffer->num_frames()));
1409 }
1410
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001411 // TODO(aluebs): Investigate if the transient suppression placement should be
1412 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001413 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001414 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001415 private_submodules_->agc_manager.get()
1416 ? private_submodules_->agc_manager->voice_probability()
1417 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001418
peahdf3efa82015-11-28 12:35:15 -08001419 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001420 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1421 capture_buffer->num_channels(),
1422 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1423 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1424 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001425 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001426 }
1427
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001428 // Experimental APM sub-module that analyzes |capture_buffer|.
1429 if (private_submodules_->capture_analyzer) {
1430 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1431 }
1432
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001433 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001434 private_submodules_->gain_controller2->NotifyAnalogLevel(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001435 agc1()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001436 private_submodules_->gain_controller2->Process(capture_buffer);
1437 }
1438
Sam Zackrisson0beac582017-09-25 12:04:02 +02001439 if (private_submodules_->capture_post_processor) {
1440 private_submodules_->capture_post_processor->Process(capture_buffer);
1441 }
1442
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001443 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001444 public_submodules_->level_estimator->ProcessStream(capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001445 if (config_.level_estimation.enabled) {
1446 private_submodules_->output_level_estimator->ProcessStream(capture_buffer);
1447 capture_.stats.output_rms_dbfs =
1448 private_submodules_->output_level_estimator->RMS();
1449 } else {
1450 capture_.stats.output_rms_dbfs = absl::nullopt;
1451 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001452
peah1b08dc32016-12-20 13:45:58 -08001453 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1454 capture_buffer->channels_const()[0],
1455 capture_nonlocked_.capture_processing_format.num_frames()));
1456 if (log_rms) {
1457 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1458 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1459 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1460 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1461 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1462 }
1463
peahdf3efa82015-11-28 12:35:15 -08001464 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001465 return kNoError;
1466}
1467
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001468int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001469 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001470 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001471 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001472 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001473 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001474 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001475 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001476 };
1477 if (samples_per_channel != reverse_config.num_frames()) {
1478 return kBadDataLengthError;
1479 }
peahdf3efa82015-11-28 12:35:15 -08001480 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001481}
1482
peahde65ddc2016-09-16 15:02:15 -07001483int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1484 const StreamConfig& input_config,
1485 const StreamConfig& output_config,
1486 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001487 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001488 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001489 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001490 if (submodule_states_.RenderMultiBandProcessingActive() ||
1491 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001492 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1493 dest);
peah2ace3f92016-09-10 04:42:27 -07001494 } else if (formats_.api_format.reverse_input_stream() !=
1495 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001496 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1497 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001498 } else {
peahde65ddc2016-09-16 15:02:15 -07001499 CopyAudioIfNeeded(src, input_config.num_frames(),
1500 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001501 }
1502
1503 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001504}
1505
peahdf3efa82015-11-28 12:35:15 -08001506int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001507 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001508 const StreamConfig& input_config,
1509 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001510 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001511 return kNullPointerError;
1512 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001513
peahde65ddc2016-09-16 15:02:15 -07001514 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001515 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001516 }
1517
peahdf3efa82015-11-28 12:35:15 -08001518 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001519 processing_config.reverse_input_stream() = input_config;
1520 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001521
peahdf3efa82015-11-28 12:35:15 -08001522 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001523 RTC_DCHECK_EQ(input_config.num_frames(),
1524 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001525
aleloi868f32f2017-05-23 07:20:05 -07001526 if (aec_dump_) {
1527 const size_t channel_size =
1528 formats_.api_format.reverse_input_stream().num_frames();
1529 const size_t num_channels =
1530 formats_.api_format.reverse_input_stream().num_channels();
1531 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001532 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001533 }
peahdf3efa82015-11-28 12:35:15 -08001534 render_.render_audio->CopyFrom(src,
1535 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001536 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001537}
1538
1539int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001540 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001541 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001542 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001543 return kNullPointerError;
1544 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001545 // Must be a native rate.
1546 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1547 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001548 frame->sample_rate_hz_ != kSampleRate32kHz &&
1549 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001550 return kBadSampleRateError;
1551 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001552
Michael Graczyk86c6d332015-07-23 11:41:39 -07001553 if (frame->num_channels_ <= 0) {
1554 return kBadNumberChannelsError;
1555 }
1556
peahdf3efa82015-11-28 12:35:15 -08001557 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001558 processing_config.reverse_input_stream().set_sample_rate_hz(
1559 frame->sample_rate_hz_);
1560 processing_config.reverse_input_stream().set_num_channels(
1561 frame->num_channels_);
1562 processing_config.reverse_output_stream().set_sample_rate_hz(
1563 frame->sample_rate_hz_);
1564 processing_config.reverse_output_stream().set_num_channels(
1565 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001566
peahdf3efa82015-11-28 12:35:15 -08001567 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001568 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001569 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001570 return kBadDataLengthError;
1571 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001572
aleloi868f32f2017-05-23 07:20:05 -07001573 if (aec_dump_) {
1574 aec_dump_->WriteRenderStreamMessage(*frame);
1575 }
1576
peahdf3efa82015-11-28 12:35:15 -08001577 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001578 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001579 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001580 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1581 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001582 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001583}
niklase@google.com470e71d2011-07-07 08:21:25 +00001584
peahde65ddc2016-09-16 15:02:15 -07001585int AudioProcessingImpl::ProcessRenderStreamLocked() {
1586 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001587
Alex Loiko73ec0192018-05-15 10:52:28 +02001588 HandleRenderRuntimeSettings();
1589
Alex Loiko5825aa62017-12-18 16:02:40 +01001590 if (private_submodules_->render_pre_processor) {
1591 private_submodules_->render_pre_processor->Process(render_buffer);
1592 }
1593
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001594 QueueNonbandedRenderAudio(render_buffer);
1595
peah2ace3f92016-09-10 04:42:27 -07001596 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001597 SampleRateSupportsMultiBand(
1598 formats_.render_processing_format.sample_rate_hz())) {
1599 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001600 }
1601
peahce4d9152017-05-19 01:28:05 -07001602 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1603 QueueBandedRenderAudio(render_buffer);
1604 }
1605
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001606 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001607 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001608 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001609 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001610
peah2ace3f92016-09-10 04:42:27 -07001611 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001612 SampleRateSupportsMultiBand(
1613 formats_.render_processing_format.sample_rate_hz())) {
1614 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001615 }
1616
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001617 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001618}
1619
1620int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001621 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001622 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001623 capture_.was_stream_delay_set = true;
1624 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001625
niklase@google.com470e71d2011-07-07 08:21:25 +00001626 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001627 delay = 0;
1628 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001629 }
1630
1631 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1632 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001633 delay = 500;
1634 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001635 }
1636
peahdf3efa82015-11-28 12:35:15 -08001637 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001638 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001639}
1640
1641int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001642 // Used as callback from submodules, hence locking is not allowed.
1643 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001644}
1645
1646bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001647 // Used as callback from submodules, hence locking is not allowed.
1648 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001649}
1650
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001651void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001652 rtc::CritScope cs(&crit_capture_);
1653 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001654}
1655
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001656void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001657 rtc::CritScope cs(&crit_capture_);
1658 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001659}
1660
1661int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001662 rtc::CritScope cs(&crit_capture_);
1663 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001664}
1665
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001666void AudioProcessingImpl::set_stream_analog_level(int level) {
1667 rtc::CritScope cs_capture(&crit_capture_);
1668 int error = agc1()->set_stream_analog_level(level);
1669 RTC_DCHECK_EQ(kNoError, error);
1670}
1671
1672int AudioProcessingImpl::recommended_stream_analog_level() const {
1673 rtc::CritScope cs_capture(&crit_capture_);
1674 return agc1()->stream_analog_level();
1675}
1676
aleloi868f32f2017-05-23 07:20:05 -07001677void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1678 RTC_DCHECK(aec_dump);
1679 rtc::CritScope cs_render(&crit_render_);
1680 rtc::CritScope cs_capture(&crit_capture_);
1681
1682 // The previously attached AecDump will be destroyed with the
1683 // 'aec_dump' parameter, which is after locks are released.
1684 aec_dump_.swap(aec_dump);
1685 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001686 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001687}
1688
1689void AudioProcessingImpl::DetachAecDump() {
1690 // The d-tor of a task-queue based AecDump blocks until all pending
1691 // tasks are done. This construction avoids blocking while holding
1692 // the render and capture locks.
1693 std::unique_ptr<AecDump> aec_dump = nullptr;
1694 {
1695 rtc::CritScope cs_render(&crit_render_);
1696 rtc::CritScope cs_capture(&crit_capture_);
1697 aec_dump = std::move(aec_dump_);
1698 }
1699}
1700
Sam Zackrisson4d364492018-03-02 16:03:21 +01001701void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1702 std::unique_ptr<AudioGenerator> audio_generator) {
1703 // TODO(bugs.webrtc.org/8882) Stub.
1704 // Reset internal audio generator with audio_generator.
1705}
1706
1707void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1708 // TODO(bugs.webrtc.org/8882) Stub.
1709 // Delete audio generator, if one is attached.
1710}
1711
Ivo Creusen56d46092017-11-24 17:29:59 +01001712AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001713 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001714 rtc::CritScope cs_capture(&crit_capture_);
1715 if (!has_remote_tracks) {
1716 return capture_.stats;
1717 }
1718 AudioProcessingStats stats = capture_.stats;
1719 EchoCancellationImpl::Metrics metrics;
1720 if (private_submodules_->echo_controller) {
1721 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1722 stats.echo_return_loss = ec_metrics.echo_return_loss;
1723 stats.echo_return_loss_enhancement =
1724 ec_metrics.echo_return_loss_enhancement;
1725 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001726 }
1727 if (config_.residual_echo_detector.enabled) {
1728 RTC_DCHECK(private_submodules_->echo_detector);
1729 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1730 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1731 stats.residual_echo_likelihood_recent_max =
1732 ed_metrics.echo_likelihood_recent_max;
1733 }
Ivo Creusenae026092017-11-20 13:07:16 +01001734 return stats;
1735}
1736
niklase@google.com470e71d2011-07-07 08:21:25 +00001737GainControl* AudioProcessingImpl::gain_control() const {
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001738 return public_submodules_->gain_control_config_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001739}
1740
niklase@google.com470e71d2011-07-07 08:21:25 +00001741LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001742 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001743}
1744
1745NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
Sam Zackrisson23513132019-01-11 15:10:32 +01001746 return public_submodules_->noise_suppression_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001747}
1748
1749VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001750 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001751}
1752
peah8271d042016-11-22 07:24:52 -08001753void AudioProcessingImpl::MutateConfig(
1754 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1755 rtc::CritScope cs_render(&crit_render_);
1756 rtc::CritScope cs_capture(&crit_capture_);
1757 mutator(&config_);
1758 ApplyConfig(config_);
1759}
1760
1761AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1762 rtc::CritScope cs_render(&crit_render_);
1763 rtc::CritScope cs_capture(&crit_capture_);
1764 return config_;
1765}
1766
peah2ace3f92016-09-10 04:42:27 -07001767bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1768 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001769 config_.high_pass_filter.enabled,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001770 private_submodules_->echo_cancellation &&
1771 private_submodules_->echo_cancellation->is_enabled(),
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001772 private_submodules_->echo_control_mobile &&
1773 private_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001774 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001775 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001776 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001777 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001778 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001779 public_submodules_->voice_detection->is_enabled(),
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001780 config_.voice_detection.enabled,
peah2ace3f92016-09-10 04:42:27 -07001781 public_submodules_->level_estimator->is_enabled(),
1782 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001783}
1784
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001785void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001786 if (capture_.transient_suppressor_enabled) {
1787 if (!public_submodules_->transient_suppressor.get()) {
1788 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001789 }
peahdf3efa82015-11-28 12:35:15 -08001790 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001791 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1792 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001793 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001794}
1795
peah8271d042016-11-22 07:24:52 -08001796void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001797 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001798 private_submodules_->low_cut_filter.reset(
1799 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1800 } else {
1801 private_submodules_->low_cut_filter.reset();
1802 }
1803}
alessiob3ec96df2017-05-22 06:57:06 -07001804
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001805void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001806 bool use_echo_controller =
1807 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001808 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001809 !config_.echo_canceller.use_legacy_aec);
1810
1811 if (use_echo_controller) {
1812 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001813 if (echo_control_factory_) {
1814 private_submodules_->echo_controller =
1815 echo_control_factory_->Create(proc_sample_rate_hz());
1816 } else {
1817 private_submodules_->echo_controller = absl::make_unique<EchoCanceller3>(
1818 EchoCanceller3Config(), proc_sample_rate_hz(), true);
1819 }
1820
1821 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001822
Per Åhgrenf204faf2019-04-25 15:18:06 +02001823 private_submodules_->echo_cancellation.reset();
1824 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001825 private_submodules_->echo_control_mobile.reset();
1826 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001827 return;
peahe0eae3c2016-12-14 01:16:23 -08001828 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001829
1830 private_submodules_->echo_controller.reset();
1831 capture_nonlocked_.echo_controller_enabled = false;
1832
1833 if (!config_.echo_canceller.enabled) {
1834 private_submodules_->echo_cancellation.reset();
1835 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001836 private_submodules_->echo_control_mobile.reset();
1837 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001838 return;
1839 }
1840
1841 if (config_.echo_canceller.mobile_mode) {
1842 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001843 size_t max_element_size =
1844 std::max(static_cast<size_t>(1),
1845 kMaxAllowedValuesOfSamplesPerBand *
1846 EchoControlMobileImpl::NumCancellersRequired(
1847 num_output_channels(), num_reverse_channels()));
1848
1849 std::vector<int16_t> template_queue_element(max_element_size);
1850
1851 aecm_render_signal_queue_.reset(
1852 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1853 kMaxNumFramesToBuffer, template_queue_element,
1854 RenderQueueItemVerifier<int16_t>(max_element_size)));
1855
1856 aecm_render_queue_buffer_.resize(max_element_size);
1857 aecm_capture_queue_buffer_.resize(max_element_size);
1858
1859 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
1860
1861 private_submodules_->echo_control_mobile->Initialize(
1862 proc_split_sample_rate_hz(), num_reverse_channels(),
1863 num_output_channels());
1864
Per Åhgrenf204faf2019-04-25 15:18:06 +02001865 private_submodules_->echo_control_mobile->Enable(true);
1866
1867 private_submodules_->echo_cancellation.reset();
1868 aec_render_signal_queue_.reset();
1869 return;
1870 }
1871
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001872 private_submodules_->echo_control_mobile.reset();
1873 aecm_render_signal_queue_.reset();
1874
Per Åhgrenf204faf2019-04-25 15:18:06 +02001875 // Create and activate AEC2.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001876 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
1877 private_submodules_->echo_cancellation->SetExtraOptions(
1878 capture_nonlocked_.use_aec2_extended_filter,
1879 capture_nonlocked_.use_aec2_delay_agnostic,
1880 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1881
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001882 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001883 std::max(static_cast<size_t>(1),
1884 kMaxAllowedValuesOfSamplesPerBand *
1885 EchoCancellationImpl::NumCancellersRequired(
1886 num_output_channels(), num_reverse_channels()));
1887
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001888 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001889
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001890 aec_render_signal_queue_.reset(
1891 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1892 kMaxNumFramesToBuffer, template_queue_element,
1893 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001894
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001895 aec_render_queue_buffer_.resize(element_max_size);
1896 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001897
1898 private_submodules_->echo_cancellation->Initialize(
1899 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1900 num_proc_channels());
1901
1902 private_submodules_->echo_cancellation->Enable(true);
1903
1904 private_submodules_->echo_cancellation->set_suppression_level(
1905 config_.echo_canceller.legacy_moderate_suppression_level
1906 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1907 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001908}
peah8271d042016-11-22 07:24:52 -08001909
alessiob3ec96df2017-05-22 06:57:06 -07001910void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001911 if (config_.gain_controller2.enabled) {
1912 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001913 }
1914}
1915
Alex Loikob5c9a792018-04-16 16:31:22 +02001916void AudioProcessingImpl::InitializePreAmplifier() {
1917 if (config_.pre_amplifier.enabled) {
1918 private_submodules_->pre_amplifier.reset(
1919 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1920 } else {
1921 private_submodules_->pre_amplifier.reset();
1922 }
1923}
1924
ivoc9f4a4a02016-10-28 05:39:16 -07001925void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001926 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001927 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001928 proc_sample_rate_hz(), 1,
1929 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001930}
1931
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001932void AudioProcessingImpl::InitializeAnalyzer() {
1933 if (private_submodules_->capture_analyzer) {
1934 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1935 num_proc_channels());
1936 }
1937}
1938
Sam Zackrisson0beac582017-09-25 12:04:02 +02001939void AudioProcessingImpl::InitializePostProcessor() {
1940 if (private_submodules_->capture_post_processor) {
1941 private_submodules_->capture_post_processor->Initialize(
1942 proc_sample_rate_hz(), num_proc_channels());
1943 }
1944}
1945
Alex Loiko5825aa62017-12-18 16:02:40 +01001946void AudioProcessingImpl::InitializePreProcessor() {
1947 if (private_submodules_->render_pre_processor) {
1948 private_submodules_->render_pre_processor->Initialize(
1949 formats_.render_processing_format.sample_rate_hz(),
1950 formats_.render_processing_format.num_channels());
1951 }
1952}
1953
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001954void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001955 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001956
Per Åhgrenf204faf2019-04-25 15:18:06 +02001957 if (private_submodules_->echo_cancellation &&
1958 private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001959 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1960 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001961 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001962 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001963 capture_.stream_delay_jumps = 0;
1964 }
1965 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001966 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001967 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001968 }
1969
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001970 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001971 const int diff_stream_delay_ms =
1972 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1973 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1974 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001975 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1976 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001977 if (capture_.stream_delay_jumps == -1) {
1978 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001979 }
peahdf3efa82015-11-28 12:35:15 -08001980 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001981 }
peahdf3efa82015-11-28 12:35:15 -08001982 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001983
1984 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001985 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001986 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001987 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001988 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001989 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001990 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001991 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001992 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001993 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001994 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001995 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1996 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1997 100);
peahdf3efa82015-11-28 12:35:15 -08001998 if (capture_.aec_system_delay_jumps == -1) {
1999 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002000 }
peahdf3efa82015-11-28 12:35:15 -08002001 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02002002 }
peahdf3efa82015-11-28 12:35:15 -08002003 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02002004 }
2005}
2006
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002007void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08002008 // Run in a single-threaded manner.
2009 rtc::CritScope cs_render(&crit_render_);
2010 rtc::CritScope cs_capture(&crit_capture_);
2011
2012 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08002013 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002014 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08002015 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002016 }
peahdf3efa82015-11-28 12:35:15 -08002017 capture_.stream_delay_jumps = -1;
2018 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002019
peahdf3efa82015-11-28 12:35:15 -08002020 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08002021 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
2022 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002023 }
peahdf3efa82015-11-28 12:35:15 -08002024 capture_.aec_system_delay_jumps = -1;
2025 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002026}
2027
aleloi868f32f2017-05-23 07:20:05 -07002028void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2029 if (!aec_dump_) {
2030 return;
2031 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002032
2033 std::string experiments_description = "";
2034 if (private_submodules_->echo_cancellation) {
2035 experiments_description +=
2036 private_submodules_->echo_cancellation->GetExperimentsDescription();
2037 }
aleloi868f32f2017-05-23 07:20:05 -07002038 // TODO(peah): Add semicolon-separated concatenations of experiment
2039 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002040 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2041 experiments_description += "AgcClippingLevelExperiment;";
2042 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002043 if (capture_nonlocked_.echo_controller_enabled) {
2044 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002045 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002046 if (config_.gain_controller2.enabled) {
2047 experiments_description += "GainController2;";
2048 }
aleloi868f32f2017-05-23 07:20:05 -07002049
2050 InternalAPMConfig apm_config;
2051
Per Åhgren200feba2019-03-06 04:16:46 +01002052 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002053 apm_config.aec_delay_agnostic_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002054 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002055 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002056 apm_config.aec_drift_compensation_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002057 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002058 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002059 apm_config.aec_extended_filter_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002060 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002061 private_submodules_->echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002062 apm_config.aec_suppression_level =
2063 private_submodules_->echo_cancellation
2064 ? static_cast<int>(
2065 private_submodules_->echo_cancellation->suppression_level())
2066 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002067
2068 apm_config.aecm_enabled =
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002069 private_submodules_->echo_control_mobile &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002070 private_submodules_->echo_control_mobile->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002071 apm_config.aecm_comfort_noise_enabled =
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002072 private_submodules_->echo_control_mobile &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002073 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002074 apm_config.aecm_routing_mode =
2075 private_submodules_->echo_control_mobile
2076 ? static_cast<int>(
2077 private_submodules_->echo_control_mobile->routing_mode())
2078 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002079
2080 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2081 apm_config.agc_mode =
2082 static_cast<int>(public_submodules_->gain_control->mode());
2083 apm_config.agc_limiter_enabled =
2084 public_submodules_->gain_control->is_limiter_enabled();
2085 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2086
2087 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2088
2089 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2090 apm_config.ns_level =
2091 static_cast<int>(public_submodules_->noise_suppression->level());
2092
2093 apm_config.transient_suppression_enabled =
2094 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002095 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002096 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2097 apm_config.pre_amplifier_fixed_gain_factor =
2098 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002099
2100 if (!forced && apm_config == apm_config_for_aec_dump_) {
2101 return;
2102 }
2103 aec_dump_->WriteConfig(apm_config);
2104 apm_config_for_aec_dump_ = apm_config;
2105}
2106
2107void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2108 const float* const* src) {
2109 RTC_DCHECK(aec_dump_);
2110 WriteAecDumpConfigMessage(false);
2111
2112 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2113 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2114 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002115 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002116 RecordAudioProcessingState();
2117}
2118
2119void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2120 const AudioFrame& capture_frame) {
2121 RTC_DCHECK(aec_dump_);
2122 WriteAecDumpConfigMessage(false);
2123
2124 aec_dump_->AddCaptureStreamInput(capture_frame);
2125 RecordAudioProcessingState();
2126}
2127
2128void AudioProcessingImpl::RecordProcessedCaptureStream(
2129 const float* const* processed_capture_stream) {
2130 RTC_DCHECK(aec_dump_);
2131
2132 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2133 const size_t num_channels =
2134 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002135 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2136 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002137 aec_dump_->WriteCaptureStreamMessage();
2138}
2139
2140void AudioProcessingImpl::RecordProcessedCaptureStream(
2141 const AudioFrame& processed_capture_frame) {
2142 RTC_DCHECK(aec_dump_);
2143
2144 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2145 aec_dump_->WriteCaptureStreamMessage();
2146}
2147
2148void AudioProcessingImpl::RecordAudioProcessingState() {
2149 RTC_DCHECK(aec_dump_);
2150 AecDump::AudioProcessingState audio_proc_state;
2151 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2152 audio_proc_state.drift =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002153 private_submodules_->echo_cancellation
2154 ? private_submodules_->echo_cancellation->stream_drift_samples()
2155 : 0;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002156 audio_proc_state.level = agc1()->stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002157 audio_proc_state.keypress = capture_.key_pressed;
2158 aec_dump_->AddAudioProcessingState(audio_proc_state);
2159}
2160
kwiberg83ffe452016-08-29 14:46:07 -07002161AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002162 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002163 : aec_system_delay_jumps(-1),
2164 delay_offset_ms(0),
2165 was_stream_delay_set(false),
2166 last_stream_delay_ms(0),
2167 last_aec_system_delay_ms(0),
2168 stream_delay_jumps(-1),
2169 output_will_be_muted(false),
2170 key_pressed(false),
2171 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002172 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002173 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002174 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002175 prev_analog_mic_level(-1),
2176 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002177
2178AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2179
2180AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2181
2182AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2183
niklase@google.com470e71d2011-07-07 08:21:25 +00002184} // namespace webrtc