blob: 760e81d1156b1331e7db639cd93cad5b2b3b38d1 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
alessiob3ec96df2017-05-22 06:57:06 -070016#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020017#include <type_traits>
18#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Yves Gerey988cc082018-10-23 12:03:01 +020020#include "absl/types/optional.h"
21#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/include/audio_util.h"
Per Åhgren200feba2019-03-06 04:16:46 +010024#include "modules/audio_processing/aec3/echo_canceller3.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020026#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/common.h"
29#include "modules/audio_processing/echo_cancellation_impl.h"
30#include "modules/audio_processing/echo_control_mobile_impl.h"
31#include "modules/audio_processing/gain_control_for_experimental_agc.h"
32#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010033#include "modules/audio_processing/gain_controller2.h"
Per Åhgren0aefbf02019-08-23 21:29:17 +020034#include "modules/audio_processing/high_pass_filter.h"
Yves Gerey988cc082018-10-23 12:03:01 +020035#include "modules/audio_processing/include/audio_frame_view.h"
saza6787f232019-10-11 19:31:07 +020036#include "modules/audio_processing/level_estimator.h"
Per Åhgren13735822018-02-12 21:42:56 +010037#include "modules/audio_processing/logging/apm_data_dumper.h"
saza0bad15f2019-10-16 11:46:11 +020038#include "modules/audio_processing/noise_suppression.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020039#include "modules/audio_processing/residual_echo_detector.h"
40#include "modules/audio_processing/transient/transient_suppressor.h"
Sam Zackrisson0824c6f2019-10-07 14:03:56 +020041#include "modules/audio_processing/voice_detection.h"
Steve Anton10542f22019-01-11 09:11:00 -080042#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080044#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "rtc_base/ref_counted_object.h"
47#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/trace_event.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020049#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000051
Michael Graczyk86c6d332015-07-23 11:41:39 -070052#define RETURN_ON_ERR(expr) \
53 do { \
54 int err = (expr); \
55 if (err != kNoError) { \
56 return err; \
57 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000058 } while (0)
59
niklase@google.com470e71d2011-07-07 08:21:25 +000060namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070061
kwibergd59d3bb2016-09-13 07:49:33 -070062constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020063constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070064
Michael Graczyk86c6d332015-07-23 11:41:39 -070065namespace {
66
67static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
68 switch (layout) {
69 case AudioProcessing::kMono:
70 case AudioProcessing::kStereo:
71 return false;
72 case AudioProcessing::kMonoAndKeyboard:
73 case AudioProcessing::kStereoAndKeyboard:
74 return true;
75 }
76
kwiberg9e2be5f2016-09-14 05:23:22 -070077 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070078 return false;
79}
aluebsdf6416a2016-03-16 18:26:35 -070080
peah2ace3f92016-09-10 04:42:27 -070081bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070082 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
83 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
84}
85
Per Åhgrenc8626b62019-08-23 15:49:51 +020086// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020087int SuitableProcessRate(int minimum_rate,
88 int max_splitting_rate,
89 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020090 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020091 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020092 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070093 if (rate >= uppermost_native_rate) {
94 return uppermost_native_rate;
95 }
96 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070097 return rate;
98 }
99 }
peah2ace3f92016-09-10 04:42:27 -0700100 RTC_NOTREACHED();
101 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700102}
103
Sam Zackrisson23513132019-01-11 15:10:32 +0100104NoiseSuppression::Level NsConfigLevelToInterfaceLevel(
105 AudioProcessing::Config::NoiseSuppression::Level level) {
106 using NsConfig = AudioProcessing::Config::NoiseSuppression;
107 switch (level) {
108 case NsConfig::kLow:
saza0bad15f2019-10-16 11:46:11 +0200109 return NoiseSuppression::Level::kLow;
Sam Zackrisson23513132019-01-11 15:10:32 +0100110 case NsConfig::kModerate:
saza0bad15f2019-10-16 11:46:11 +0200111 return NoiseSuppression::Level::kModerate;
Sam Zackrisson23513132019-01-11 15:10:32 +0100112 case NsConfig::kHigh:
saza0bad15f2019-10-16 11:46:11 +0200113 return NoiseSuppression::Level::kHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100114 case NsConfig::kVeryHigh:
saza0bad15f2019-10-16 11:46:11 +0200115 return NoiseSuppression::Level::kVeryHigh;
Sam Zackrisson23513132019-01-11 15:10:32 +0100116 default:
117 RTC_NOTREACHED();
118 }
119}
120
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100121GainControl::Mode Agc1ConfigModeToInterfaceMode(
122 AudioProcessing::Config::GainController1::Mode mode) {
123 using Agc1Config = AudioProcessing::Config::GainController1;
124 switch (mode) {
125 case Agc1Config::kAdaptiveAnalog:
126 return GainControl::kAdaptiveAnalog;
127 case Agc1Config::kAdaptiveDigital:
128 return GainControl::kAdaptiveDigital;
129 case Agc1Config::kFixedDigital:
130 return GainControl::kFixedDigital;
131 }
132}
133
peah9e6a2902017-05-15 07:19:21 -0700134// Maximum lengths that frame of samples being passed from the render side to
135// the capture side can have (does not apply to AEC3).
136static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
137static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
138
peah764e3642016-10-22 05:04:30 -0700139// Maximum number of frames to buffer in the render queue.
140// TODO(peah): Decrease this once we properly handle hugely unbalanced
141// reverse and forward call numbers.
142static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700143} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000144
145// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000146static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000147
Sam Zackrisson0beac582017-09-25 12:04:02 +0200148AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100149 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200150 bool render_pre_processor_enabled,
151 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100152 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200153 render_pre_processor_enabled_(render_pre_processor_enabled),
154 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700155
156bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200157 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700158 bool echo_canceller_enabled,
159 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700160 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700161 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700162 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700163 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200164 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200165 bool echo_controller_enabled,
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200166 bool voice_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700167 bool transient_suppressor_enabled) {
168 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200169 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700170 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
171 changed |=
172 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700173 changed |=
174 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700175 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
176 changed |=
peah2ace3f92016-09-10 04:42:27 -0700177 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200178 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200179 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200180 changed |= (echo_controller_enabled != echo_controller_enabled_);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200181 changed |= (voice_detector_enabled != voice_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700182 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
183 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200184 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700185 echo_canceller_enabled_ = echo_canceller_enabled;
186 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700187 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700188 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700189 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700190 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200191 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200192 echo_controller_enabled_ = echo_controller_enabled;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200193 voice_detector_enabled_ = voice_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700194 transient_suppressor_enabled_ = transient_suppressor_enabled;
195 }
196
197 changed |= first_update_;
198 first_update_ = false;
199 return changed;
200}
201
202bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
203 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200204 return CaptureMultiBandProcessingPresent() || voice_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700205}
206
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200207bool AudioProcessingImpl::ApmSubmoduleStates::
208 CaptureMultiBandProcessingPresent() const {
209 // If echo controller is present, assume it performs active processing.
210 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
211}
212
213bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive(
214 bool ec_processing_active) const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200215 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700216 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200217 adaptive_gain_controller_enabled_ ||
218 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700219}
220
peah23ac8b42017-05-23 05:33:56 -0700221bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
222 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200223 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
224 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700225}
226
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200227bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
228 return capture_analyzer_enabled_;
229}
230
peah2ace3f92016-09-10 04:42:27 -0700231bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
232 const {
233 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800234 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200235 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700236}
237
Alex Loiko5825aa62017-12-18 16:02:40 +0100238bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
239 const {
240 return render_pre_processor_enabled_;
241}
242
peah2ace3f92016-09-10 04:42:27 -0700243bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
244 const {
peah2ace3f92016-09-10 04:42:27 -0700245 return false;
peah2ace3f92016-09-10 04:42:27 -0700246}
247
Per Åhgren0aefbf02019-08-23 21:29:17 +0200248bool AudioProcessingImpl::ApmSubmoduleStates::HighPassFilteringRequired()
249 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200250 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
251 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
252}
253
solenberg5e465c32015-12-08 13:22:33 -0800254struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800255 ApmPublicSubmodules() {}
saza0bad15f2019-10-16 11:46:11 +0200256 // Historically accessed externally of APM without any lock acquired.
257 // TODO(bugs.webrtc.org/9947): Move these submodules into private_submodules_.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100258 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800259 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800260 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800261
262 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800263 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800264};
265
266struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200267 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100268 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200269 rtc::scoped_refptr<EchoDetector> echo_detector,
270 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200271 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100272 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200273 render_pre_processor(std::move(render_pre_processor)),
274 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800275 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800276 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700277 std::unique_ptr<GainController2> gain_controller2;
Per Åhgren0aefbf02019-08-23 21:29:17 +0200278 std::unique_ptr<HighPassFilter> high_pass_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200279 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100280 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100281 std::unique_ptr<EchoControl> echo_controller;
282 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
saza0bad15f2019-10-16 11:46:11 +0200283 std::unique_ptr<NoiseSuppression> noise_suppressor;
Alex Loiko5825aa62017-12-18 16:02:40 +0100284 std::unique_ptr<CustomProcessing> capture_post_processor;
285 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200286 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200287 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
saza6787f232019-10-11 19:31:07 +0200288 std::unique_ptr<LevelEstimator> output_level_estimator;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200289 std::unique_ptr<VoiceDetection> voice_detector;
solenberg5e465c32015-12-08 13:22:33 -0800290};
291
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100292AudioProcessingBuilder::AudioProcessingBuilder() = default;
293AudioProcessingBuilder::~AudioProcessingBuilder() = default;
294
295AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
296 std::unique_ptr<CustomProcessing> capture_post_processing) {
297 capture_post_processing_ = std::move(capture_post_processing);
298 return *this;
299}
300
301AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
302 std::unique_ptr<CustomProcessing> render_pre_processing) {
303 render_pre_processing_ = std::move(render_pre_processing);
304 return *this;
305}
306
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200307AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
308 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
309 capture_analyzer_ = std::move(capture_analyzer);
310 return *this;
311}
312
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100313AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
314 std::unique_ptr<EchoControlFactory> echo_control_factory) {
315 echo_control_factory_ = std::move(echo_control_factory);
316 return *this;
317}
318
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100319AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200320 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100321 echo_detector_ = std::move(echo_detector);
322 return *this;
323}
324
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100325AudioProcessing* AudioProcessingBuilder::Create() {
326 webrtc::Config config;
327 return Create(config);
328}
329
330AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100331 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
332 config, std::move(capture_post_processing_),
333 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200334 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100335 if (apm->Initialize() != AudioProcessing::kNoError) {
336 delete apm;
337 apm = nullptr;
338 }
339 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100340}
341
peah88ac8532016-09-12 16:47:25 -0700342AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200343 : AudioProcessingImpl(config,
344 /*capture_post_processor=*/nullptr,
345 /*render_pre_processor=*/nullptr,
346 /*echo_control_factory=*/nullptr,
347 /*echo_detector=*/nullptr,
348 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000349
Per Åhgren13735822018-02-12 21:42:56 +0100350int AudioProcessingImpl::instance_count_ = 0;
351
Sam Zackrisson0beac582017-09-25 12:04:02 +0200352AudioProcessingImpl::AudioProcessingImpl(
353 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100354 std::unique_ptr<CustomProcessing> capture_post_processor,
355 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200356 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200357 rtc::scoped_refptr<EchoDetector> echo_detector,
358 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100359 : data_dumper_(
360 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200361 capture_runtime_settings_(kRuntimeSettingQueueSize),
362 render_runtime_settings_(kRuntimeSettingQueueSize),
363 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
364 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200365 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200366 submodule_states_(!!capture_post_processor,
367 !!render_pre_processor,
368 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800369 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200370 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200371 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100372 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200373 std::move(echo_detector),
374 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800375 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800376 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000377#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200378 /* enabled= */ false,
379 /* enabled_agc2_level_estimator= */ false,
380 /* digital_adaptive_disabled= */ false,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200381 /* analyze_before_aec= */ false,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000382#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200383 config.Get<ExperimentalAgc>().enabled,
384 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200385 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200386 config.Get<ExperimentalAgc>().analyze_before_aec,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000387#endif
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200388 !field_trial::IsEnabled(
389 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
390 !field_trial::IsEnabled(
391 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch")),
andrew1c7075f2015-06-24 18:14:14 -0700392#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200393 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700394#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200395 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700396#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200397 capture_nonlocked_() {
Sam Zackrisson421c8592019-02-11 13:39:46 +0100398 // Mark Echo Controller enabled if a factory is injected.
399 capture_nonlocked_.echo_controller_enabled =
400 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000401
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100402 public_submodules_->gain_control.reset(new GainControlImpl());
Sam Zackrisson421c8592019-02-11 13:39:46 +0100403 public_submodules_->gain_control_for_experimental_agc.reset(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100404 new GainControlForExperimentalAgc(
405 public_submodules_->gain_control.get()));
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200406
Sam Zackrisson421c8592019-02-11 13:39:46 +0100407 // If no echo detector is injected, use the ResidualEchoDetector.
408 if (!private_submodules_->echo_detector) {
409 private_submodules_->echo_detector =
410 new rtc::RefCountedObject<ResidualEchoDetector>();
peahdf3efa82015-11-28 12:35:15 -0800411 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000412
Sam Zackrisson421c8592019-02-11 13:39:46 +0100413 // TODO(alessiob): Move the injected gain controller once injection is
414 // implemented.
415 private_submodules_->gain_controller2.reset(new GainController2());
416
417 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
418 << !!private_submodules_->capture_analyzer
419 << "\nCapture post processor activated: "
420 << !!private_submodules_->capture_post_processor
421 << "\nRender pre processor activated: "
422 << !!private_submodules_->render_pre_processor;
423
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000424 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000425}
426
427AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800428 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800429 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800430 private_submodules_->agc_manager.reset();
431 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800432 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000433}
434
niklase@google.com470e71d2011-07-07 08:21:25 +0000435int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800436 // Run in a single-threaded manner during initialization.
437 rtc::CritScope cs_render(&crit_render_);
438 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000439 return InitializeLocked();
440}
441
peahde65ddc2016-09-16 15:02:15 -0700442int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
443 int capture_output_sample_rate_hz,
444 int render_input_sample_rate_hz,
445 ChannelLayout capture_input_layout,
446 ChannelLayout capture_output_layout,
447 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700448 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700449 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
450 LayoutHasKeyboard(capture_input_layout)},
451 {capture_output_sample_rate_hz,
452 ChannelsFromLayout(capture_output_layout),
453 LayoutHasKeyboard(capture_output_layout)},
454 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
455 LayoutHasKeyboard(render_input_layout)},
456 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
457 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700458
459 return Initialize(processing_config);
460}
461
462int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800463 // Run in a single-threaded manner during initialization.
464 rtc::CritScope cs_render(&crit_render_);
465 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700466 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000467}
468
peahdf3efa82015-11-28 12:35:15 -0800469int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800470 const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800471 // Called from both threads. Thread check is therefore not possible.
Oskar Sundbom4b276482019-05-23 14:28:00 +0200472 if (processing_config == formats_.api_format) {
peah192164e2015-11-17 02:16:45 -0800473 return kNoError;
474 }
peahdf3efa82015-11-28 12:35:15 -0800475
476 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800477 return InitializeLocked(processing_config);
478}
479
niklase@google.com470e71d2011-07-07 08:21:25 +0000480int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200481 UpdateActiveSubmoduleStates();
482
Per Åhgrend47941e2019-08-22 11:51:13 +0200483 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800484 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200485 ? formats_.render_processing_format.sample_rate_hz()
486 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800487 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
488 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200489 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800490 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200491 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700492 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200493 render_audiobuffer_sample_rate_hz,
494 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700495 if (formats_.api_format.reverse_input_stream() !=
496 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800497 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800498 formats_.api_format.reverse_input_stream().num_channels(),
499 formats_.api_format.reverse_input_stream().num_frames(),
500 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800501 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700502 } else {
peahdf3efa82015-11-28 12:35:15 -0800503 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700504 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700505 } else {
peahdf3efa82015-11-28 12:35:15 -0800506 render_.render_audio.reset(nullptr);
507 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700508 }
peahce4d9152017-05-19 01:28:05 -0700509
Per Åhgrend47941e2019-08-22 11:51:13 +0200510 capture_.capture_audio.reset(new AudioBuffer(
511 formats_.api_format.input_stream().sample_rate_hz(),
512 formats_.api_format.input_stream().num_channels(),
513 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
514 formats_.api_format.output_stream().num_channels(),
515 formats_.api_format.output_stream().sample_rate_hz(),
516 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000517
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200518 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
519 formats_.api_format.output_stream().sample_rate_hz() &&
520 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
521 capture_.capture_fullband_audio.reset(
522 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
523 formats_.api_format.input_stream().num_channels(),
524 formats_.api_format.output_stream().sample_rate_hz(),
525 formats_.api_format.output_stream().num_channels(),
526 formats_.api_format.output_stream().sample_rate_hz(),
527 formats_.api_format.output_stream().num_channels()));
528 } else {
529 capture_.capture_fullband_audio.reset();
530 }
531
peah764e3642016-10-22 05:04:30 -0700532 AllocateRenderQueue();
533
peah135259a2016-10-28 03:12:11 -0700534 public_submodules_->gain_control->Initialize(num_proc_channels(),
535 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700536 if (constants_.use_experimental_agc) {
537 if (!private_submodules_->agc_manager.get()) {
538 private_submodules_->agc_manager.reset(new AgcManagerDirect(
539 public_submodules_->gain_control.get(),
540 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200541 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
542 constants_.use_experimental_agc_agc2_level_estimation,
543 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700544 }
545 private_submodules_->agc_manager->Initialize();
546 private_submodules_->agc_manager->SetCaptureMuted(
547 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700548 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700549 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200550 InitializeTransient();
Per Åhgren0aefbf02019-08-23 21:29:17 +0200551 InitializeHighPassFilter();
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200552 InitializeVoiceDetector();
ivoc9f4a4a02016-10-28 05:39:16 -0700553 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200554 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700555 InitializeGainController2();
saza0bad15f2019-10-16 11:46:11 +0200556 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200557 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200558 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100559 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800560
aleloi868f32f2017-05-23 07:20:05 -0700561 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200562 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700563 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000564 return kNoError;
565}
566
Michael Graczyk86c6d332015-07-23 11:41:39 -0700567int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200568 UpdateActiveSubmoduleStates();
569
Michael Graczyk86c6d332015-07-23 11:41:39 -0700570 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700571 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
572 return kBadSampleRateError;
573 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000574 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700575
Peter Kasting69558702016-01-12 16:26:35 -0800576 const size_t num_in_channels = config.input_stream().num_channels();
577 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700578
579 // Need at least one input channel.
580 // Need either one output channel or as many outputs as there are inputs.
581 if (num_in_channels == 0 ||
582 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700583 return kBadNumberChannelsError;
584 }
585
peahdf3efa82015-11-28 12:35:15 -0800586 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000587
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200588 // Choose maximum rate to use for the split filtering.
589 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
590 config_.pipeline.maximum_internal_processing_rate == 32000);
591 int max_splitting_rate = 48000;
592 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
593 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
594 }
595
Per Åhgrenc8626b62019-08-23 15:49:51 +0200596 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700597 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700598 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200599 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700600 submodule_states_.CaptureMultiBandSubModulesActive() ||
601 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200602 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000603
peahde65ddc2016-09-16 15:02:15 -0700604 capture_nonlocked_.capture_processing_format =
605 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700606
peah2ce640f2017-04-07 03:57:48 -0700607 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200608 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200609 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700610 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
611 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200612 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700613 submodule_states_.CaptureMultiBandSubModulesActive() ||
614 submodule_states_.RenderMultiBandSubModulesActive());
615 } else {
616 render_processing_rate = capture_processing_rate;
617 }
618
peahde65ddc2016-09-16 15:02:15 -0700619 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700620 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700621 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
622 kSampleRate8kHz) {
623 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000624 } else {
peahde65ddc2016-09-16 15:02:15 -0700625 render_processing_rate =
626 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000627 }
628
Per Åhgrenc8626b62019-08-23 15:49:51 +0200629 RTC_DCHECK_NE(8000, render_processing_rate);
630
peahce4d9152017-05-19 01:28:05 -0700631 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200632 // By default, downmix the render stream to mono for analysis. This has been
633 // demonstrated to work well for AEC in most practical scenarios.
634 const bool experimental_multi_channel_render =
635 config_.pipeline.experimental_multi_channel &&
636 constants_.experimental_multi_channel_render_support;
637 int render_processing_num_channels =
638 experimental_multi_channel_render
639 ? formats_.api_format.reverse_input_stream().num_channels()
640 : 1;
641 formats_.render_processing_format =
642 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700643 } else {
644 formats_.render_processing_format = StreamConfig(
645 formats_.api_format.reverse_input_stream().sample_rate_hz(),
646 formats_.api_format.reverse_input_stream().num_channels());
647 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000648
peahde65ddc2016-09-16 15:02:15 -0700649 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
650 kSampleRate32kHz ||
651 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
652 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800653 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000654 } else {
peahdf3efa82015-11-28 12:35:15 -0800655 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700656 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000657 }
658
659 return InitializeLocked();
660}
661
peah88ac8532016-09-12 16:47:25 -0700662void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700663 // Run in a single-threaded manner when applying the settings.
664 rtc::CritScope cs_render(&crit_render_);
665 rtc::CritScope cs_capture(&crit_capture_);
666
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200667 const bool pipeline_config_changed =
668 config_.pipeline.experimental_multi_channel !=
669 config.pipeline.experimental_multi_channel;
670
Per Åhgren200feba2019-03-06 04:16:46 +0100671 const bool aec_config_changed =
672 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
673 config_.echo_canceller.use_legacy_aec !=
674 config.echo_canceller.use_legacy_aec ||
675 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode ||
676 (config_.echo_canceller.enabled && config.echo_canceller.use_legacy_aec &&
677 config_.echo_canceller.legacy_moderate_suppression_level !=
678 config.echo_canceller.legacy_moderate_suppression_level);
679
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100680 const bool agc1_config_changed =
681 config_.gain_controller1.enabled != config.gain_controller1.enabled ||
682 config_.gain_controller1.mode != config.gain_controller1.mode ||
683 config_.gain_controller1.target_level_dbfs !=
684 config.gain_controller1.target_level_dbfs ||
685 config_.gain_controller1.compression_gain_db !=
686 config.gain_controller1.compression_gain_db ||
687 config_.gain_controller1.enable_limiter !=
688 config.gain_controller1.enable_limiter ||
689 config_.gain_controller1.analog_level_minimum !=
690 config.gain_controller1.analog_level_minimum ||
691 config_.gain_controller1.analog_level_maximum !=
692 config.gain_controller1.analog_level_maximum;
693
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200694 const bool voice_detection_config_changed =
695 config_.voice_detection.enabled != config.voice_detection.enabled;
696
saza0bad15f2019-10-16 11:46:11 +0200697 const bool ns_config_changed =
698 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
699 config_.noise_suppression.level != config.noise_suppression.level;
700
Yves Gerey499bc6c2018-10-10 18:29:07 +0200701 config_ = config;
702
Per Åhgren200feba2019-03-06 04:16:46 +0100703 if (aec_config_changed) {
704 InitializeEchoController();
705 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200706
saza0bad15f2019-10-16 11:46:11 +0200707 if (ns_config_changed) {
708 InitializeNoiseSuppressor();
709 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100710
Per Åhgren0aefbf02019-08-23 21:29:17 +0200711 InitializeHighPassFilter();
peah8271d042016-11-22 07:24:52 -0800712
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) {
saza6787f232019-10-11 19:31:07 +0200738 private_submodules_->output_level_estimator =
739 std::make_unique<LevelEstimator>();
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100740 }
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100741
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200742 if (voice_detection_config_changed) {
743 InitializeVoiceDetector();
Sam Zackrisson4db667b2018-12-21 16:29:27 +0100744 }
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200745
746 // Reinitialization must happen after all submodule configuration to avoid
747 // additional reinitializations on the next capture / render processing call.
748 if (pipeline_config_changed) {
749 InitializeLocked(formats_.api_format);
750 }
peah88ac8532016-09-12 16:47:25 -0700751}
752
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100753void AudioProcessingImpl::ApplyAgc1Config(
754 const Config::GainController1& config) {
755 GainControl* agc = agc1();
756 int error = agc->Enable(config.enabled);
757 RTC_DCHECK_EQ(kNoError, error);
758 error = agc->set_mode(Agc1ConfigModeToInterfaceMode(config.mode));
759 RTC_DCHECK_EQ(kNoError, error);
760 error = agc->set_target_level_dbfs(config.target_level_dbfs);
761 RTC_DCHECK_EQ(kNoError, error);
762 error = agc->set_compression_gain_db(config.compression_gain_db);
763 RTC_DCHECK_EQ(kNoError, error);
764 error = agc->enable_limiter(config.enable_limiter);
765 RTC_DCHECK_EQ(kNoError, error);
766 error = agc->set_analog_level_limits(config.analog_level_minimum,
767 config.analog_level_maximum);
768 RTC_DCHECK_EQ(kNoError, error);
769}
770
771GainControl* AudioProcessingImpl::agc1() {
772 if (constants_.use_experimental_agc) {
773 return public_submodules_->gain_control_for_experimental_agc.get();
774 }
775 return public_submodules_->gain_control.get();
776}
777
778const GainControl* AudioProcessingImpl::agc1() const {
779 if (constants_.use_experimental_agc) {
780 return public_submodules_->gain_control_for_experimental_agc.get();
781 }
782 return public_submodules_->gain_control.get();
783}
784
peah88ac8532016-09-12 16:47:25 -0700785void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800786 // Run in a single-threaded manner when setting the extra options.
787 rtc::CritScope cs_render(&crit_render_);
788 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000789
Per Åhgrenf204faf2019-04-25 15:18:06 +0200790 capture_nonlocked_.use_aec2_extended_filter =
791 config.Get<ExtendedFilter>().enabled;
792 capture_nonlocked_.use_aec2_delay_agnostic =
793 config.Get<DelayAgnostic>().enabled;
794 capture_nonlocked_.use_aec2_refined_adaptive_filter =
795 config.Get<RefinedAdaptiveFilter>().enabled;
peahb624d8c2016-03-05 03:01:14 -0800796
peahdf3efa82015-11-28 12:35:15 -0800797 if (capture_.transient_suppressor_enabled !=
798 config.Get<ExperimentalNs>().enabled) {
799 capture_.transient_suppressor_enabled =
800 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000801 InitializeTransient();
802 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000803}
804
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000805int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800806 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700807 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000808}
809
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200810int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
811 return capture_.capture_fullband_audio
812 ? capture_.capture_fullband_audio->num_frames() * 100
813 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
814}
815
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000816int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800817 // Used as callback from submodules, hence locking is not allowed.
818 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000819}
820
Peter Kasting69558702016-01-12 16:26:35 -0800821size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800822 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700823 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000824}
825
Peter Kasting69558702016-01-12 16:26:35 -0800826size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800827 // Used as callback from submodules, hence locking is not allowed.
828 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000829}
830
Peter Kasting69558702016-01-12 16:26:35 -0800831size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800832 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200833 const bool experimental_multi_channel_capture =
834 config_.pipeline.experimental_multi_channel &&
835 constants_.experimental_multi_channel_capture_support;
836 if (capture_nonlocked_.echo_controller_enabled &&
837 !experimental_multi_channel_capture) {
838 return 1;
839 }
840 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800841}
842
Peter Kasting69558702016-01-12 16:26:35 -0800843size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800844 // Used as callback from submodules, hence locking is not allowed.
845 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000846}
847
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000848void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800849 rtc::CritScope cs(&crit_capture_);
850 capture_.output_will_be_muted = muted;
851 if (private_submodules_->agc_manager.get()) {
852 private_submodules_->agc_manager->SetCaptureMuted(
853 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000854 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000855}
856
Alessio Bazzicac054e782018-04-16 12:10:09 +0200857void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200858 switch (setting.type()) {
859 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
860 render_runtime_settings_enqueuer_.Enqueue(setting);
861 return;
862 case RuntimeSetting::Type::kNotSpecified:
863 RTC_NOTREACHED();
864 return;
865 case RuntimeSetting::Type::kCapturePreGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100866 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200867 case RuntimeSetting::Type::kCaptureFixedPostGain:
Fredrik Hernqvistca362852019-05-10 15:50:02 +0200868 case RuntimeSetting::Type::kPlayoutVolumeChange:
Alex Loiko73ec0192018-05-15 10:52:28 +0200869 capture_runtime_settings_enqueuer_.Enqueue(setting);
870 return;
871 }
872 // The language allows the enum to have a non-enumerator
873 // value. Check that this doesn't happen.
874 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200875}
876
877AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
878 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200879 : runtime_settings_(*runtime_settings) {
880 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200881}
882
883AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
884 default;
885
886void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
887 RuntimeSetting setting) {
888 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200889 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200890 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200891 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200892 RTC_LOG(LS_ERROR)
893 << "The runtime settings queue is full. Oldest setting discarded.";
894 }
895 if (remaining_attempts == 0)
896 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
897}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000898
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000899int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700900 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000901 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000902 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000903 int output_sample_rate_hz,
904 ChannelLayout output_layout,
905 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800906 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800907 StreamConfig input_stream;
908 StreamConfig output_stream;
909 {
910 // Access the formats_.api_format.input_stream beneath the capture lock.
911 // The lock must be released as it is later required in the call
912 // to ProcessStream(,,,);
913 rtc::CritScope cs(&crit_capture_);
914 input_stream = formats_.api_format.input_stream();
915 output_stream = formats_.api_format.output_stream();
916 }
917
Michael Graczyk86c6d332015-07-23 11:41:39 -0700918 input_stream.set_sample_rate_hz(input_sample_rate_hz);
919 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
920 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700921 output_stream.set_sample_rate_hz(output_sample_rate_hz);
922 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
923 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
924
925 if (samples_per_channel != input_stream.num_frames()) {
926 return kBadDataLengthError;
927 }
928 return ProcessStream(src, input_stream, output_stream, dest);
929}
930
931int AudioProcessingImpl::ProcessStream(const float* const* src,
932 const StreamConfig& input_config,
933 const StreamConfig& output_config,
934 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800935 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800936 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700937 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800938 {
939 // Acquire the capture lock in order to safely call the function
940 // that retrieves the render side data. This function accesses apm
941 // getters that need the capture lock held when being called.
942 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700943 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800944
945 if (!src || !dest) {
946 return kNullPointerError;
947 }
948
949 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700950 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000951 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000952
Oskar Sundbom4b276482019-05-23 14:28:00 +0200953 if (processing_config.input_stream() != input_config) {
954 processing_config.input_stream() = input_config;
955 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800956 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200957
958 if (processing_config.output_stream() != output_config) {
959 processing_config.output_stream() = output_config;
960 reinitialization_required = true;
961 }
962
963 if (reinitialization_required) {
964 // Reinitialize.
965 rtc::CritScope cs_render(&crit_render_);
966 rtc::CritScope cs_capture(&crit_capture_);
967 RETURN_ON_ERR(InitializeLocked(processing_config));
968 }
969
peahdf3efa82015-11-28 12:35:15 -0800970 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700971 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
972 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000973
aleloi868f32f2017-05-23 07:20:05 -0700974 if (aec_dump_) {
975 RecordUnprocessedCaptureStream(src);
976 }
977
Per Åhgrena1351272019-08-15 12:15:46 +0200978 capture_.keyboard_info.Extract(src, formats_.api_format.input_stream());
peahdf3efa82015-11-28 12:35:15 -0800979 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200980 if (capture_.capture_fullband_audio) {
981 capture_.capture_fullband_audio->CopyFrom(
982 src, formats_.api_format.input_stream());
983 }
peahde65ddc2016-09-16 15:02:15 -0700984 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200985 if (capture_.capture_fullband_audio) {
986 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
987 dest);
988 } else {
989 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
990 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000991
aleloi868f32f2017-05-23 07:20:05 -0700992 if (aec_dump_) {
993 RecordProcessedCaptureStream(dest);
994 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000995 return kNoError;
996}
997
Alex Loiko73ec0192018-05-15 10:52:28 +0200998void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200999 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +02001000 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001001 if (aec_dump_) {
1002 aec_dump_->WriteRuntimeSetting(setting);
1003 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001004 switch (setting.type()) {
1005 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +02001006 if (config_.pre_amplifier.enabled) {
1007 float value;
1008 setting.GetFloat(&value);
1009 private_submodules_->pre_amplifier->SetGainFactor(value);
1010 }
1011 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001012 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001013 case RuntimeSetting::Type::kCaptureCompressionGain: {
1014 float value;
1015 setting.GetFloat(&value);
1016 int int_value = static_cast<int>(value + .5f);
1017 config_.gain_controller1.compression_gain_db = int_value;
1018 int error = agc1()->set_compression_gain_db(int_value);
1019 RTC_DCHECK_EQ(kNoError, error);
1020 break;
1021 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001022 case RuntimeSetting::Type::kCaptureFixedPostGain: {
1023 if (config_.gain_controller2.enabled) {
1024 float value;
1025 setting.GetFloat(&value);
1026 config_.gain_controller2.fixed_digital.gain_db = value;
1027 private_submodules_->gain_controller2->ApplyConfig(
1028 config_.gain_controller2);
1029 }
1030 break;
1031 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001032 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1033 int value;
1034 setting.GetInt(&value);
1035 capture_.playout_volume = value;
1036 break;
1037 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001038 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1039 RTC_NOTREACHED();
1040 break;
1041 case RuntimeSetting::Type::kNotSpecified:
1042 RTC_NOTREACHED();
1043 break;
1044 }
1045 }
1046}
1047
1048void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1049 RuntimeSetting setting;
1050 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001051 if (aec_dump_) {
1052 aec_dump_->WriteRuntimeSetting(setting);
1053 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001054 switch (setting.type()) {
1055 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
1056 if (private_submodules_->render_pre_processor) {
1057 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
1058 }
1059 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001060 case RuntimeSetting::Type::kCapturePreGain: // fall-through
1061 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001062 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001063 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001064 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +02001065 RTC_NOTREACHED();
1066 break;
1067 }
1068 }
1069}
1070
peah9e6a2902017-05-15 07:19:21 -07001071void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001072 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001073
1074 // Insert the samples into the queue.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001075 if (private_submodules_->echo_cancellation) {
1076 RTC_DCHECK(aec_render_signal_queue_);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001077 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1078 num_reverse_channels(),
1079 &aec_render_queue_buffer_);
1080
Per Åhgrenf204faf2019-04-25 15:18:06 +02001081 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
1082 // The data queue is full and needs to be emptied.
1083 EmptyQueuedRenderAudio();
peah764e3642016-10-22 05:04:30 -07001084
Per Åhgrenf204faf2019-04-25 15:18:06 +02001085 // Retry the insert (should always work).
1086 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
1087 RTC_DCHECK(result);
1088 }
peaha0624602016-10-25 04:45:24 -07001089 }
1090
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001091 if (private_submodules_->echo_control_mobile) {
1092 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1093 num_reverse_channels(),
1094 &aecm_render_queue_buffer_);
1095 RTC_DCHECK(aecm_render_signal_queue_);
1096 // Insert the samples into the queue.
1097 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1098 // The data queue is full and needs to be emptied.
1099 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001100
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001101 // Retry the insert (should always work).
1102 bool result =
1103 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1104 RTC_DCHECK(result);
1105 }
peah764e3642016-10-22 05:04:30 -07001106 }
peah701d6282016-10-25 05:42:20 -07001107
1108 if (!constants_.use_experimental_agc) {
1109 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
1110 // Insert the samples into the queue.
1111 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1112 // The data queue is full and needs to be emptied.
1113 EmptyQueuedRenderAudio();
1114
1115 // Retry the insert (should always work).
1116 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1117 RTC_DCHECK(result);
1118 }
1119 }
peah9e6a2902017-05-15 07:19:21 -07001120}
ivoc9f4a4a02016-10-28 05:39:16 -07001121
peah9e6a2902017-05-15 07:19:21 -07001122void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -07001123 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
1124
1125 // Insert the samples into the queue.
1126 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1127 // The data queue is full and needs to be emptied.
1128 EmptyQueuedRenderAudio();
1129
1130 // Retry the insert (should always work).
1131 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1132 RTC_DCHECK(result);
1133 }
peah764e3642016-10-22 05:04:30 -07001134}
1135
1136void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001137 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001138 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001139
ivoc9f4a4a02016-10-28 05:39:16 -07001140 const size_t new_red_render_queue_element_max_size =
1141 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1142
peaha0624602016-10-25 04:45:24 -07001143 // Reallocate the queues if the queue item sizes are too small to fit the
1144 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001145
1146 if (agc_render_queue_element_max_size_ <
1147 new_agc_render_queue_element_max_size) {
1148 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1149
1150 std::vector<int16_t> template_queue_element(
1151 agc_render_queue_element_max_size_);
1152
1153 agc_render_signal_queue_.reset(
1154 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1155 kMaxNumFramesToBuffer, template_queue_element,
1156 RenderQueueItemVerifier<int16_t>(
1157 agc_render_queue_element_max_size_)));
1158
1159 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1160 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1161 } else {
1162 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001163 }
ivoc9f4a4a02016-10-28 05:39:16 -07001164
1165 if (red_render_queue_element_max_size_ <
1166 new_red_render_queue_element_max_size) {
1167 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1168
1169 std::vector<float> template_queue_element(
1170 red_render_queue_element_max_size_);
1171
1172 red_render_signal_queue_.reset(
1173 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1174 kMaxNumFramesToBuffer, template_queue_element,
1175 RenderQueueItemVerifier<float>(
1176 red_render_queue_element_max_size_)));
1177
1178 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1179 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1180 } else {
1181 red_render_signal_queue_->Clear();
1182 }
peah764e3642016-10-22 05:04:30 -07001183}
1184
1185void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1186 rtc::CritScope cs_capture(&crit_capture_);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001187 if (private_submodules_->echo_cancellation) {
1188 RTC_DCHECK(aec_render_signal_queue_);
1189 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
1190 private_submodules_->echo_cancellation->ProcessRenderAudio(
1191 aec_capture_queue_buffer_);
1192 }
peaha0624602016-10-25 04:45:24 -07001193 }
1194
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001195 if (private_submodules_->echo_control_mobile) {
1196 RTC_DCHECK(aecm_render_signal_queue_);
1197 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
1198 private_submodules_->echo_control_mobile->ProcessRenderAudio(
1199 aecm_capture_queue_buffer_);
1200 }
peah701d6282016-10-25 05:42:20 -07001201 }
1202
1203 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1204 public_submodules_->gain_control->ProcessRenderAudio(
1205 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001206 }
ivoc9f4a4a02016-10-28 05:39:16 -07001207
1208 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001209 RTC_DCHECK(private_submodules_->echo_detector);
1210 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001211 red_capture_queue_buffer_);
1212 }
peah764e3642016-10-22 05:04:30 -07001213}
1214
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001215int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001216 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001217 {
1218 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001219 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001220 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001221 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001222 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001223 }
peahfa6228e2015-11-16 16:27:42 -08001224
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001225 if (!frame) {
1226 return kNullPointerError;
1227 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001228 // Must be a native rate.
1229 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1230 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001231 frame->sample_rate_hz_ != kSampleRate32kHz &&
1232 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001233 return kBadSampleRateError;
1234 }
peah192164e2015-11-17 02:16:45 -08001235
peahdf3efa82015-11-28 12:35:15 -08001236 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001237 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001238 {
1239 // Aquire lock for the access of api_format.
1240 // The lock is released immediately due to the conditional
1241 // reinitialization.
1242 rtc::CritScope cs_capture(&crit_capture_);
1243 // TODO(ajm): The input and output rates and channels are currently
1244 // constrained to be identical in the int16 interface.
1245 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001246
1247 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001248 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001249
Oskar Sundbom4b276482019-05-23 14:28:00 +02001250 reinitialization_required =
1251 reinitialization_required ||
1252 processing_config.input_stream().sample_rate_hz() !=
1253 frame->sample_rate_hz_ ||
1254 processing_config.input_stream().num_channels() != frame->num_channels_ ||
1255 processing_config.output_stream().sample_rate_hz() !=
1256 frame->sample_rate_hz_ ||
1257 processing_config.output_stream().num_channels() != frame->num_channels_;
1258
1259 if (reinitialization_required) {
1260 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1261 processing_config.input_stream().set_num_channels(frame->num_channels_);
1262 processing_config.output_stream().set_sample_rate_hz(
1263 frame->sample_rate_hz_);
1264 processing_config.output_stream().set_num_channels(frame->num_channels_);
1265
1266 // Reinitialize.
peahdf3efa82015-11-28 12:35:15 -08001267 rtc::CritScope cs_render(&crit_render_);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001268 rtc::CritScope cs_capture(&crit_capture_);
1269 RETURN_ON_ERR(InitializeLocked(processing_config));
peahdf3efa82015-11-28 12:35:15 -08001270 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001271
peahdf3efa82015-11-28 12:35:15 -08001272 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001273 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001274 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001275 return kBadDataLengthError;
1276 }
1277
aleloi868f32f2017-05-23 07:20:05 -07001278 if (aec_dump_) {
1279 RecordUnprocessedCaptureStream(*frame);
1280 }
1281
Per Åhgrend47941e2019-08-22 11:51:13 +02001282 capture_.capture_audio->CopyFrom(frame);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001283 if (capture_.capture_fullband_audio) {
1284 capture_.capture_fullband_audio->CopyFrom(frame);
1285 }
peahde65ddc2016-09-16 15:02:15 -07001286 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001287 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001288 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001289 if (capture_.capture_fullband_audio) {
1290 capture_.capture_fullband_audio->CopyTo(frame);
1291 } else {
1292 capture_.capture_audio->CopyTo(frame);
1293 }
Per Åhgrena1351272019-08-15 12:15:46 +02001294 }
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001295 if (capture_.stats.voice_detected) {
1296 frame->vad_activity_ = *capture_.stats.voice_detected
1297 ? AudioFrame::kVadActive
1298 : AudioFrame::kVadPassive;
1299 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001300
aleloi868f32f2017-05-23 07:20:05 -07001301 if (aec_dump_) {
1302 RecordProcessedCaptureStream(*frame);
1303 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001304
1305 return kNoError;
1306}
1307
peahde65ddc2016-09-16 15:02:15 -07001308int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001309 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001310
peahb58a1582016-03-15 09:34:24 -07001311 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001312 // TODO(peah): Simplify once the public API Enable functions for these
1313 // are moved to APM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001314 RTC_DCHECK_LE(!!private_submodules_->echo_controller +
1315 !!private_submodules_->echo_cancellation +
1316 !!private_submodules_->echo_control_mobile,
1317 1);
peahb58a1582016-03-15 09:34:24 -07001318
peahde65ddc2016-09-16 15:02:15 -07001319 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001320
Alex Loikob5c9a792018-04-16 16:31:22 +02001321 if (private_submodules_->pre_amplifier) {
1322 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001323 capture_buffer->channels(), capture_buffer->num_channels(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001324 capture_buffer->num_frames()));
1325 }
1326
Per Åhgren928146f2019-08-20 09:19:21 +02001327 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001328 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001329 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001330 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1331 if (log_rms) {
1332 capture_rms_interval_counter_ = 0;
1333 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001334 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1335 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1336 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1337 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001338 }
1339
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001340 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001341 // Detect and flag any change in the analog gain.
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001342 int analog_mic_level = agc1()->stream_analog_level();
Per Åhgren88cf0502018-07-16 17:08:41 +02001343 capture_.echo_path_gain_change =
1344 capture_.prev_analog_mic_level != analog_mic_level &&
1345 capture_.prev_analog_mic_level != -1;
1346 capture_.prev_analog_mic_level = analog_mic_level;
1347
Per Åhgrend2650d12018-10-02 17:00:59 +02001348 // Detect and flag any change in the pre-amplifier gain.
1349 if (private_submodules_->pre_amplifier) {
1350 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1351 capture_.echo_path_gain_change =
1352 capture_.echo_path_gain_change ||
1353 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001354 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001355 capture_.prev_pre_amp_gain = pre_amp_gain;
1356 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001357
1358 // Detect volume change.
1359 capture_.echo_path_gain_change =
1360 capture_.echo_path_gain_change ||
1361 (capture_.prev_playout_volume != capture_.playout_volume &&
1362 capture_.prev_playout_volume >= 0);
1363 capture_.prev_playout_volume = capture_.playout_volume;
1364
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001365 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001366 }
1367
peahbe615622016-02-13 16:40:47 -08001368 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001369 public_submodules_->gain_control->is_enabled()) {
1370 private_submodules_->agc_manager->AnalyzePreProcess(
Per Åhgren928146f2019-08-20 09:19:21 +02001371 capture_buffer->channels_f()[0], capture_buffer->num_channels(),
peahde65ddc2016-09-16 15:02:15 -07001372 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001373
1374 if (constants_.use_experimental_agc_process_before_aec) {
1375 private_submodules_->agc_manager->Process(
Per Åhgrend47941e2019-08-22 11:51:13 +02001376 capture_buffer->channels_const()[0],
Alex Loikod9342442018-09-10 13:59:41 +02001377 capture_nonlocked_.capture_processing_format.num_frames(),
1378 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1379 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001380 }
1381
peah2ace3f92016-09-10 04:42:27 -07001382 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1383 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001384 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1385 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001386 }
1387
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001388 const bool experimental_multi_channel_capture =
1389 config_.pipeline.experimental_multi_channel &&
1390 constants_.experimental_multi_channel_capture_support;
1391 if (private_submodules_->echo_controller &&
1392 !experimental_multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001393 // Force down-mixing of the number of channels after the detection of
1394 // capture signal saturation.
1395 // TODO(peah): Look into ensuring that this kind of tampering with the
1396 // AudioBuffer functionality should not be needed.
1397 capture_buffer->set_num_channels(1);
1398 }
1399
Per Åhgren0aefbf02019-08-23 21:29:17 +02001400 if (private_submodules_->high_pass_filter) {
1401 private_submodules_->high_pass_filter->Process(capture_buffer);
peah8271d042016-11-22 07:24:52 -08001402 }
peahde65ddc2016-09-16 15:02:15 -07001403 RETURN_ON_ERR(
1404 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
saza0bad15f2019-10-16 11:46:11 +02001405 if (private_submodules_->noise_suppressor) {
1406 private_submodules_->noise_suppressor->AnalyzeCaptureAudio(capture_buffer);
1407 }
peahb58a1582016-03-15 09:34:24 -07001408
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001409 if (private_submodules_->echo_control_mobile) {
1410 // Ensure that the stream delay was set before the call to the
1411 // AECM ProcessCaptureAudio function.
1412 if (!was_stream_delay_set()) {
1413 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001414 }
1415
saza0bad15f2019-10-16 11:46:11 +02001416 if (private_submodules_->noise_suppressor) {
Per Åhgrena1351272019-08-15 12:15:46 +02001417 private_submodules_->echo_control_mobile->CopyLowPassReference(
1418 capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001419 private_submodules_->noise_suppressor->ProcessCaptureAudio(
1420 capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001421 }
peahe0eae3c2016-12-14 01:16:23 -08001422
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001423 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001424 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001425 } else {
1426 if (private_submodules_->echo_controller) {
1427 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1428
1429 if (was_stream_delay_set()) {
1430 private_submodules_->echo_controller->SetAudioBufferDelay(
1431 stream_delay_ms());
1432 }
1433
1434 private_submodules_->echo_controller->ProcessCapture(
1435 capture_buffer, capture_.echo_path_gain_change);
1436 } else if (private_submodules_->echo_cancellation) {
1437 // Ensure that the stream delay was set before the call to the
1438 // AEC ProcessCaptureAudio function.
1439 if (!was_stream_delay_set()) {
1440 return AudioProcessing::kStreamParameterNotSetError;
1441 }
1442
1443 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
1444 capture_buffer, stream_delay_ms()));
1445 }
1446
saza0bad15f2019-10-16 11:46:11 +02001447 if (private_submodules_->noise_suppressor) {
1448 private_submodules_->noise_suppressor->ProcessCaptureAudio(
1449 capture_buffer);
1450 }
Per Åhgren46537a32017-06-07 10:08:10 +02001451 }
ivoc9f4a4a02016-10-28 05:39:16 -07001452
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001453 if (config_.voice_detection.enabled) {
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001454 capture_.stats.voice_detected =
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001455 private_submodules_->voice_detector->ProcessCaptureAudio(
1456 capture_buffer);
Sam Zackrisson4db667b2018-12-21 16:29:27 +01001457 } else {
1458 capture_.stats.voice_detected = absl::nullopt;
1459 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001460
peahbe615622016-02-13 16:40:47 -08001461 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001462 public_submodules_->gain_control->is_enabled() &&
1463 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001464 private_submodules_->agc_manager->Process(
Per Åhgren928146f2019-08-20 09:19:21 +02001465 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
peahde65ddc2016-09-16 15:02:15 -07001466 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001467 }
Per Åhgren200feba2019-03-06 04:16:46 +01001468 // TODO(peah): Add reporting from AEC3 whether there is echo.
peahb8fbb542016-03-15 02:28:08 -07001469 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001470 capture_buffer,
Per Åhgrenf204faf2019-04-25 15:18:06 +02001471 private_submodules_->echo_cancellation &&
1472 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001473
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001474 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
peah2ace3f92016-09-10 04:42:27 -07001475 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001476 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1477 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001478 }
1479
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001480 if (capture_.capture_fullband_audio) {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001481 const auto& ec = private_submodules_->echo_controller;
1482 bool ec_active = ec ? ec->ActiveProcessing() : false;
1483 // Only update the fullband buffer if the multiband processing has changed
1484 // the signal. Keep the original signal otherwise.
1485 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1486 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1487 }
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001488 capture_buffer = capture_.capture_fullband_audio.get();
1489 }
1490
peah9e6a2902017-05-15 07:19:21 -07001491 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001492 RTC_DCHECK(private_submodules_->echo_detector);
1493 private_submodules_->echo_detector->AnalyzeCaptureAudio(
Per Åhgrend47941e2019-08-22 11:51:13 +02001494 rtc::ArrayView<const float>(capture_buffer->channels()[0],
peah9e6a2902017-05-15 07:19:21 -07001495 capture_buffer->num_frames()));
1496 }
1497
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001498 // TODO(aluebs): Investigate if the transient suppression placement should be
1499 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001500 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001501 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001502 private_submodules_->agc_manager.get()
1503 ? private_submodules_->agc_manager->voice_probability()
1504 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001505
peahdf3efa82015-11-28 12:35:15 -08001506 public_submodules_->transient_suppressor->Suppress(
Per Åhgrend47941e2019-08-22 11:51:13 +02001507 capture_buffer->channels()[0], capture_buffer->num_frames(),
peahde65ddc2016-09-16 15:02:15 -07001508 capture_buffer->num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +02001509 capture_buffer->split_bands_const(0)[kBand0To8kHz],
Per Åhgrena1351272019-08-15 12:15:46 +02001510 capture_buffer->num_frames_per_band(),
1511 capture_.keyboard_info.keyboard_data,
1512 capture_.keyboard_info.num_keyboard_frames, voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001513 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001514 }
1515
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001516 // Experimental APM sub-module that analyzes |capture_buffer|.
1517 if (private_submodules_->capture_analyzer) {
1518 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1519 }
1520
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001521 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001522 private_submodules_->gain_controller2->NotifyAnalogLevel(
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001523 agc1()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001524 private_submodules_->gain_controller2->Process(capture_buffer);
1525 }
1526
Sam Zackrisson0beac582017-09-25 12:04:02 +02001527 if (private_submodules_->capture_post_processor) {
1528 private_submodules_->capture_post_processor->Process(capture_buffer);
1529 }
1530
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001531 // The level estimator operates on the recombined data.
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001532 if (config_.level_estimation.enabled) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001533 private_submodules_->output_level_estimator->ProcessStream(*capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001534 capture_.stats.output_rms_dbfs =
1535 private_submodules_->output_level_estimator->RMS();
1536 } else {
1537 capture_.stats.output_rms_dbfs = absl::nullopt;
1538 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001539
Per Åhgren928146f2019-08-20 09:19:21 +02001540 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001541 capture_buffer->channels_const()[0],
peah1b08dc32016-12-20 13:45:58 -08001542 capture_nonlocked_.capture_processing_format.num_frames()));
1543 if (log_rms) {
1544 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1545 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1546 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1547 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1548 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1549 }
1550
peahdf3efa82015-11-28 12:35:15 -08001551 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001552 return kNoError;
1553}
1554
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001555int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001556 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001557 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001558 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001559 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001560 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001561 const StreamConfig reverse_config = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001562 sample_rate_hz,
1563 ChannelsFromLayout(layout),
1564 LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001565 };
1566 if (samples_per_channel != reverse_config.num_frames()) {
1567 return kBadDataLengthError;
1568 }
peahdf3efa82015-11-28 12:35:15 -08001569 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001570}
1571
peahde65ddc2016-09-16 15:02:15 -07001572int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1573 const StreamConfig& input_config,
1574 const StreamConfig& output_config,
1575 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001576 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001577 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001578 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001579 if (submodule_states_.RenderMultiBandProcessingActive() ||
1580 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001581 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1582 dest);
peah2ace3f92016-09-10 04:42:27 -07001583 } else if (formats_.api_format.reverse_input_stream() !=
1584 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001585 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1586 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001587 } else {
peahde65ddc2016-09-16 15:02:15 -07001588 CopyAudioIfNeeded(src, input_config.num_frames(),
1589 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001590 }
1591
1592 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001593}
1594
peahdf3efa82015-11-28 12:35:15 -08001595int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001596 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001597 const StreamConfig& input_config,
1598 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001599 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001600 return kNullPointerError;
1601 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001602
peahde65ddc2016-09-16 15:02:15 -07001603 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001604 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001605 }
1606
peahdf3efa82015-11-28 12:35:15 -08001607 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001608 processing_config.reverse_input_stream() = input_config;
1609 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001610
peahdf3efa82015-11-28 12:35:15 -08001611 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001612 RTC_DCHECK_EQ(input_config.num_frames(),
1613 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001614
aleloi868f32f2017-05-23 07:20:05 -07001615 if (aec_dump_) {
1616 const size_t channel_size =
1617 formats_.api_format.reverse_input_stream().num_frames();
1618 const size_t num_channels =
1619 formats_.api_format.reverse_input_stream().num_channels();
1620 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001621 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001622 }
peahdf3efa82015-11-28 12:35:15 -08001623 render_.render_audio->CopyFrom(src,
1624 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001625 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001626}
1627
1628int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001629 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001630 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001631 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001632 return kNullPointerError;
1633 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001634 // Must be a native rate.
1635 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1636 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001637 frame->sample_rate_hz_ != kSampleRate32kHz &&
1638 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001639 return kBadSampleRateError;
1640 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001641
Michael Graczyk86c6d332015-07-23 11:41:39 -07001642 if (frame->num_channels_ <= 0) {
1643 return kBadNumberChannelsError;
1644 }
1645
peahdf3efa82015-11-28 12:35:15 -08001646 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001647 processing_config.reverse_input_stream().set_sample_rate_hz(
1648 frame->sample_rate_hz_);
1649 processing_config.reverse_input_stream().set_num_channels(
1650 frame->num_channels_);
1651 processing_config.reverse_output_stream().set_sample_rate_hz(
1652 frame->sample_rate_hz_);
1653 processing_config.reverse_output_stream().set_num_channels(
1654 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001655
peahdf3efa82015-11-28 12:35:15 -08001656 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001657 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001658 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001659 return kBadDataLengthError;
1660 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001661
aleloi868f32f2017-05-23 07:20:05 -07001662 if (aec_dump_) {
1663 aec_dump_->WriteRenderStreamMessage(*frame);
1664 }
1665
Per Åhgrend47941e2019-08-22 11:51:13 +02001666 render_.render_audio->CopyFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001667 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001668 if (submodule_states_.RenderMultiBandProcessingActive() ||
1669 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgrend47941e2019-08-22 11:51:13 +02001670 render_.render_audio->CopyTo(frame);
Per Åhgrena1351272019-08-15 12:15:46 +02001671 }
aluebsb0319552016-03-17 20:39:53 -07001672 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001673}
niklase@google.com470e71d2011-07-07 08:21:25 +00001674
peahde65ddc2016-09-16 15:02:15 -07001675int AudioProcessingImpl::ProcessRenderStreamLocked() {
1676 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001677
Alex Loiko73ec0192018-05-15 10:52:28 +02001678 HandleRenderRuntimeSettings();
1679
Alex Loiko5825aa62017-12-18 16:02:40 +01001680 if (private_submodules_->render_pre_processor) {
1681 private_submodules_->render_pre_processor->Process(render_buffer);
1682 }
1683
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001684 QueueNonbandedRenderAudio(render_buffer);
1685
peah2ace3f92016-09-10 04:42:27 -07001686 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001687 SampleRateSupportsMultiBand(
1688 formats_.render_processing_format.sample_rate_hz())) {
1689 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001690 }
1691
peahce4d9152017-05-19 01:28:05 -07001692 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1693 QueueBandedRenderAudio(render_buffer);
1694 }
1695
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001696 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001697 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001698 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001699 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001700
peah2ace3f92016-09-10 04:42:27 -07001701 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001702 SampleRateSupportsMultiBand(
1703 formats_.render_processing_format.sample_rate_hz())) {
1704 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001705 }
1706
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001707 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001708}
1709
1710int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001711 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001712 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001713 capture_.was_stream_delay_set = true;
1714 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001715
niklase@google.com470e71d2011-07-07 08:21:25 +00001716 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001717 delay = 0;
1718 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001719 }
1720
1721 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1722 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001723 delay = 500;
1724 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001725 }
1726
peahdf3efa82015-11-28 12:35:15 -08001727 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001728 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001729}
1730
1731int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001732 // Used as callback from submodules, hence locking is not allowed.
1733 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001734}
1735
1736bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001737 // Used as callback from submodules, hence locking is not allowed.
1738 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001739}
1740
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001741void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001742 rtc::CritScope cs(&crit_capture_);
1743 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001744}
1745
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001746void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001747 rtc::CritScope cs(&crit_capture_);
1748 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001749}
1750
1751int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001752 rtc::CritScope cs(&crit_capture_);
1753 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001754}
1755
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001756void AudioProcessingImpl::set_stream_analog_level(int level) {
1757 rtc::CritScope cs_capture(&crit_capture_);
1758 int error = agc1()->set_stream_analog_level(level);
1759 RTC_DCHECK_EQ(kNoError, error);
1760}
1761
1762int AudioProcessingImpl::recommended_stream_analog_level() const {
1763 rtc::CritScope cs_capture(&crit_capture_);
1764 return agc1()->stream_analog_level();
1765}
1766
aleloi868f32f2017-05-23 07:20:05 -07001767void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1768 RTC_DCHECK(aec_dump);
1769 rtc::CritScope cs_render(&crit_render_);
1770 rtc::CritScope cs_capture(&crit_capture_);
1771
1772 // The previously attached AecDump will be destroyed with the
1773 // 'aec_dump' parameter, which is after locks are released.
1774 aec_dump_.swap(aec_dump);
1775 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001776 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001777}
1778
1779void AudioProcessingImpl::DetachAecDump() {
1780 // The d-tor of a task-queue based AecDump blocks until all pending
1781 // tasks are done. This construction avoids blocking while holding
1782 // the render and capture locks.
1783 std::unique_ptr<AecDump> aec_dump = nullptr;
1784 {
1785 rtc::CritScope cs_render(&crit_render_);
1786 rtc::CritScope cs_capture(&crit_capture_);
1787 aec_dump = std::move(aec_dump_);
1788 }
1789}
1790
Sam Zackrisson4d364492018-03-02 16:03:21 +01001791void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1792 std::unique_ptr<AudioGenerator> audio_generator) {
1793 // TODO(bugs.webrtc.org/8882) Stub.
1794 // Reset internal audio generator with audio_generator.
1795}
1796
1797void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1798 // TODO(bugs.webrtc.org/8882) Stub.
1799 // Delete audio generator, if one is attached.
1800}
1801
Ivo Creusen56d46092017-11-24 17:29:59 +01001802AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001803 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001804 rtc::CritScope cs_capture(&crit_capture_);
1805 if (!has_remote_tracks) {
1806 return capture_.stats;
1807 }
1808 AudioProcessingStats stats = capture_.stats;
1809 EchoCancellationImpl::Metrics metrics;
1810 if (private_submodules_->echo_controller) {
1811 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1812 stats.echo_return_loss = ec_metrics.echo_return_loss;
1813 stats.echo_return_loss_enhancement =
1814 ec_metrics.echo_return_loss_enhancement;
1815 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001816 }
1817 if (config_.residual_echo_detector.enabled) {
1818 RTC_DCHECK(private_submodules_->echo_detector);
1819 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1820 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1821 stats.residual_echo_likelihood_recent_max =
1822 ed_metrics.echo_likelihood_recent_max;
1823 }
Ivo Creusenae026092017-11-20 13:07:16 +01001824 return stats;
1825}
1826
peah8271d042016-11-22 07:24:52 -08001827void AudioProcessingImpl::MutateConfig(
1828 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1829 rtc::CritScope cs_render(&crit_render_);
1830 rtc::CritScope cs_capture(&crit_capture_);
1831 mutator(&config_);
1832 ApplyConfig(config_);
1833}
1834
1835AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1836 rtc::CritScope cs_render(&crit_render_);
1837 rtc::CritScope cs_capture(&crit_capture_);
1838 return config_;
1839}
1840
peah2ace3f92016-09-10 04:42:27 -07001841bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1842 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001843 config_.high_pass_filter.enabled,
Per Åhgrend547d862019-05-03 15:48:47 +02001844 !!private_submodules_->echo_cancellation,
1845 !!private_submodules_->echo_control_mobile,
ivoc9f4a4a02016-10-28 05:39:16 -07001846 config_.residual_echo_detector.enabled,
saza0bad15f2019-10-16 11:46:11 +02001847 !!private_submodules_->noise_suppressor,
peah2ace3f92016-09-10 04:42:27 -07001848 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001849 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001850 capture_nonlocked_.echo_controller_enabled,
saza0bad15f2019-10-16 11:46:11 +02001851 config_.voice_detection.enabled, capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001852}
1853
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001854void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001855 if (capture_.transient_suppressor_enabled) {
1856 if (!public_submodules_->transient_suppressor.get()) {
1857 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001858 }
peahdf3efa82015-11-28 12:35:15 -08001859 public_submodules_->transient_suppressor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001860 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1861 num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001862 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001863}
1864
Per Åhgren0aefbf02019-08-23 21:29:17 +02001865void AudioProcessingImpl::InitializeHighPassFilter() {
1866 if (submodule_states_.HighPassFilteringRequired()) {
1867 private_submodules_->high_pass_filter.reset(
1868 new HighPassFilter(num_proc_channels()));
peah8271d042016-11-22 07:24:52 -08001869 } else {
Per Åhgren0aefbf02019-08-23 21:29:17 +02001870 private_submodules_->high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001871 }
1872}
alessiob3ec96df2017-05-22 06:57:06 -07001873
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001874void AudioProcessingImpl::InitializeVoiceDetector() {
1875 if (config_.voice_detection.enabled) {
1876 private_submodules_->voice_detector = std::make_unique<VoiceDetection>(
1877 proc_split_sample_rate_hz(), VoiceDetection::kVeryLowLikelihood);
1878 } else {
1879 private_submodules_->voice_detector.reset();
1880 }
1881}
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001882void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001883 bool use_echo_controller =
1884 echo_control_factory_ ||
Per Åhgren200feba2019-03-06 04:16:46 +01001885 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode &&
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001886 !config_.echo_canceller.use_legacy_aec);
1887
1888 if (use_echo_controller) {
1889 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001890 if (echo_control_factory_) {
1891 private_submodules_->echo_controller =
1892 echo_control_factory_->Create(proc_sample_rate_hz());
1893 } else {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001894 private_submodules_->echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001895 EchoCanceller3Config(), proc_sample_rate_hz(), num_reverse_channels(),
1896 num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001897 }
1898
1899 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001900
Per Åhgrenf204faf2019-04-25 15:18:06 +02001901 private_submodules_->echo_cancellation.reset();
1902 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001903 private_submodules_->echo_control_mobile.reset();
1904 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001905 return;
peahe0eae3c2016-12-14 01:16:23 -08001906 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001907
1908 private_submodules_->echo_controller.reset();
1909 capture_nonlocked_.echo_controller_enabled = false;
1910
1911 if (!config_.echo_canceller.enabled) {
1912 private_submodules_->echo_cancellation.reset();
1913 aec_render_signal_queue_.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001914 private_submodules_->echo_control_mobile.reset();
1915 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001916 return;
1917 }
1918
1919 if (config_.echo_canceller.mobile_mode) {
1920 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001921 size_t max_element_size =
1922 std::max(static_cast<size_t>(1),
1923 kMaxAllowedValuesOfSamplesPerBand *
1924 EchoControlMobileImpl::NumCancellersRequired(
1925 num_output_channels(), num_reverse_channels()));
1926
1927 std::vector<int16_t> template_queue_element(max_element_size);
1928
1929 aecm_render_signal_queue_.reset(
1930 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1931 kMaxNumFramesToBuffer, template_queue_element,
1932 RenderQueueItemVerifier<int16_t>(max_element_size)));
1933
1934 aecm_render_queue_buffer_.resize(max_element_size);
1935 aecm_capture_queue_buffer_.resize(max_element_size);
1936
1937 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
1938
1939 private_submodules_->echo_control_mobile->Initialize(
1940 proc_split_sample_rate_hz(), num_reverse_channels(),
1941 num_output_channels());
1942
Per Åhgrenf204faf2019-04-25 15:18:06 +02001943 private_submodules_->echo_cancellation.reset();
1944 aec_render_signal_queue_.reset();
1945 return;
1946 }
1947
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001948 private_submodules_->echo_control_mobile.reset();
1949 aecm_render_signal_queue_.reset();
1950
Per Åhgrenf204faf2019-04-25 15:18:06 +02001951 // Create and activate AEC2.
Per Åhgrenf204faf2019-04-25 15:18:06 +02001952 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
1953 private_submodules_->echo_cancellation->SetExtraOptions(
1954 capture_nonlocked_.use_aec2_extended_filter,
1955 capture_nonlocked_.use_aec2_delay_agnostic,
1956 capture_nonlocked_.use_aec2_refined_adaptive_filter);
1957
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001958 size_t element_max_size =
Per Åhgrenf204faf2019-04-25 15:18:06 +02001959 std::max(static_cast<size_t>(1),
1960 kMaxAllowedValuesOfSamplesPerBand *
1961 EchoCancellationImpl::NumCancellersRequired(
1962 num_output_channels(), num_reverse_channels()));
1963
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001964 std::vector<float> template_queue_element(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001965
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001966 aec_render_signal_queue_.reset(
1967 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1968 kMaxNumFramesToBuffer, template_queue_element,
1969 RenderQueueItemVerifier<float>(element_max_size)));
Per Åhgrenf204faf2019-04-25 15:18:06 +02001970
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001971 aec_render_queue_buffer_.resize(element_max_size);
1972 aec_capture_queue_buffer_.resize(element_max_size);
Per Åhgrenf204faf2019-04-25 15:18:06 +02001973
1974 private_submodules_->echo_cancellation->Initialize(
1975 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
1976 num_proc_channels());
1977
Per Åhgrenf204faf2019-04-25 15:18:06 +02001978 private_submodules_->echo_cancellation->set_suppression_level(
1979 config_.echo_canceller.legacy_moderate_suppression_level
1980 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
1981 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
peahe0eae3c2016-12-14 01:16:23 -08001982}
peah8271d042016-11-22 07:24:52 -08001983
alessiob3ec96df2017-05-22 06:57:06 -07001984void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001985 if (config_.gain_controller2.enabled) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001986 private_submodules_->gain_controller2->Initialize(
1987 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001988 }
1989}
1990
saza0bad15f2019-10-16 11:46:11 +02001991void AudioProcessingImpl::InitializeNoiseSuppressor() {
1992 if (config_.noise_suppression.enabled) {
1993 auto ns_level =
1994 NsConfigLevelToInterfaceLevel(config_.noise_suppression.level);
1995 private_submodules_->noise_suppressor = std::make_unique<NoiseSuppression>(
1996 num_proc_channels(), proc_sample_rate_hz(), ns_level);
1997 } else {
1998 private_submodules_->noise_suppressor.reset();
1999 }
2000}
2001
Alex Loikob5c9a792018-04-16 16:31:22 +02002002void AudioProcessingImpl::InitializePreAmplifier() {
2003 if (config_.pre_amplifier.enabled) {
2004 private_submodules_->pre_amplifier.reset(
2005 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
2006 } else {
2007 private_submodules_->pre_amplifier.reset();
2008 }
2009}
2010
ivoc9f4a4a02016-10-28 05:39:16 -07002011void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01002012 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01002013 private_submodules_->echo_detector->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002014 proc_fullband_sample_rate_hz(), 1,
Ivo Creusenb1facc12018-04-12 16:15:58 +02002015 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07002016}
2017
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002018void AudioProcessingImpl::InitializeAnalyzer() {
2019 if (private_submodules_->capture_analyzer) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002020 private_submodules_->capture_analyzer->Initialize(
2021 proc_fullband_sample_rate_hz(), num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002022 }
2023}
2024
Sam Zackrisson0beac582017-09-25 12:04:02 +02002025void AudioProcessingImpl::InitializePostProcessor() {
2026 if (private_submodules_->capture_post_processor) {
2027 private_submodules_->capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002028 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002029 }
2030}
2031
Alex Loiko5825aa62017-12-18 16:02:40 +01002032void AudioProcessingImpl::InitializePreProcessor() {
2033 if (private_submodules_->render_pre_processor) {
2034 private_submodules_->render_pre_processor->Initialize(
2035 formats_.render_processing_format.sample_rate_hz(),
2036 formats_.render_processing_format.num_channels());
2037 }
2038}
2039
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002040void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {}
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02002041
aleloi868f32f2017-05-23 07:20:05 -07002042void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2043 if (!aec_dump_) {
2044 return;
2045 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002046
2047 std::string experiments_description = "";
2048 if (private_submodules_->echo_cancellation) {
2049 experiments_description +=
2050 private_submodules_->echo_cancellation->GetExperimentsDescription();
2051 }
aleloi868f32f2017-05-23 07:20:05 -07002052 // TODO(peah): Add semicolon-separated concatenations of experiment
2053 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07002054 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2055 experiments_description += "AgcClippingLevelExperiment;";
2056 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002057 if (capture_nonlocked_.echo_controller_enabled) {
2058 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002059 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002060 if (config_.gain_controller2.enabled) {
2061 experiments_description += "GainController2;";
2062 }
aleloi868f32f2017-05-23 07:20:05 -07002063
2064 InternalAPMConfig apm_config;
2065
Per Åhgren200feba2019-03-06 04:16:46 +01002066 apm_config.aec_enabled = config_.echo_canceller.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002067 apm_config.aec_delay_agnostic_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002068 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002069 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002070 apm_config.aec_drift_compensation_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002071 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002072 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07002073 apm_config.aec_extended_filter_enabled =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002074 private_submodules_->echo_cancellation &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01002075 private_submodules_->echo_cancellation->is_extended_filter_enabled();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002076 apm_config.aec_suppression_level =
2077 private_submodules_->echo_cancellation
2078 ? static_cast<int>(
2079 private_submodules_->echo_cancellation->suppression_level())
2080 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002081
Per Åhgrend547d862019-05-03 15:48:47 +02002082 apm_config.aecm_enabled = !!private_submodules_->echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002083 apm_config.aecm_comfort_noise_enabled =
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002084 private_submodules_->echo_control_mobile &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01002085 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002086 apm_config.aecm_routing_mode =
2087 private_submodules_->echo_control_mobile
2088 ? static_cast<int>(
2089 private_submodules_->echo_control_mobile->routing_mode())
2090 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002091
2092 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2093 apm_config.agc_mode =
2094 static_cast<int>(public_submodules_->gain_control->mode());
2095 apm_config.agc_limiter_enabled =
2096 public_submodules_->gain_control->is_limiter_enabled();
2097 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2098
2099 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2100
saza0bad15f2019-10-16 11:46:11 +02002101 apm_config.ns_enabled = config_.noise_suppression.enabled;
2102 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002103
2104 apm_config.transient_suppression_enabled =
2105 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07002106 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002107 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2108 apm_config.pre_amplifier_fixed_gain_factor =
2109 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002110
2111 if (!forced && apm_config == apm_config_for_aec_dump_) {
2112 return;
2113 }
2114 aec_dump_->WriteConfig(apm_config);
2115 apm_config_for_aec_dump_ = apm_config;
2116}
2117
2118void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2119 const float* const* src) {
2120 RTC_DCHECK(aec_dump_);
2121 WriteAecDumpConfigMessage(false);
2122
2123 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2124 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2125 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002126 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002127 RecordAudioProcessingState();
2128}
2129
2130void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2131 const AudioFrame& capture_frame) {
2132 RTC_DCHECK(aec_dump_);
2133 WriteAecDumpConfigMessage(false);
2134
2135 aec_dump_->AddCaptureStreamInput(capture_frame);
2136 RecordAudioProcessingState();
2137}
2138
2139void AudioProcessingImpl::RecordProcessedCaptureStream(
2140 const float* const* processed_capture_stream) {
2141 RTC_DCHECK(aec_dump_);
2142
2143 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2144 const size_t num_channels =
2145 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002146 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2147 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002148 aec_dump_->WriteCaptureStreamMessage();
2149}
2150
2151void AudioProcessingImpl::RecordProcessedCaptureStream(
2152 const AudioFrame& processed_capture_frame) {
2153 RTC_DCHECK(aec_dump_);
2154
2155 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2156 aec_dump_->WriteCaptureStreamMessage();
2157}
2158
2159void AudioProcessingImpl::RecordAudioProcessingState() {
2160 RTC_DCHECK(aec_dump_);
2161 AecDump::AudioProcessingState audio_proc_state;
2162 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2163 audio_proc_state.drift =
Per Åhgrenf204faf2019-04-25 15:18:06 +02002164 private_submodules_->echo_cancellation
2165 ? private_submodules_->echo_cancellation->stream_drift_samples()
2166 : 0;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002167 audio_proc_state.level = agc1()->stream_analog_level();
aleloi868f32f2017-05-23 07:20:05 -07002168 audio_proc_state.keypress = capture_.key_pressed;
2169 aec_dump_->AddAudioProcessingState(audio_proc_state);
2170}
2171
kwiberg83ffe452016-08-29 14:46:07 -07002172AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002173 bool transient_suppressor_enabled)
Per Åhgrenea4c5df2019-05-03 09:00:08 +02002174 : delay_offset_ms(0),
kwiberg83ffe452016-08-29 14:46:07 -07002175 was_stream_delay_set(false),
kwiberg83ffe452016-08-29 14:46:07 -07002176 output_will_be_muted(false),
2177 key_pressed(false),
2178 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002179 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002180 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002181 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002182 prev_analog_mic_level(-1),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002183 prev_pre_amp_gain(-1.f),
2184 playout_volume(-1),
2185 prev_playout_volume(-1) {}
kwiberg83ffe452016-08-29 14:46:07 -07002186
2187AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2188
Per Åhgrena1351272019-08-15 12:15:46 +02002189void AudioProcessingImpl::ApmCaptureState::KeyboardInfo::Extract(
2190 const float* const* data,
2191 const StreamConfig& stream_config) {
2192 if (stream_config.has_keyboard()) {
2193 keyboard_data = data[stream_config.num_channels()];
2194 } else {
2195 keyboard_data = NULL;
2196 }
2197 num_keyboard_frames = stream_config.num_frames();
2198}
2199
kwiberg83ffe452016-08-29 14:46:07 -07002200AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2201
2202AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2203
niklase@google.com470e71d2011-07-07 08:21:25 +00002204} // namespace webrtc