blob: 2579f6c2189506a9e6091b69e1b0280d37e9884b [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>
Sam Zackrisson5dd54822022-11-17 11:26:58 +010015#include <cstring>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020016#include <memory>
alessiob3ec96df2017-05-22 06:57:06 -070017#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020018#include <type_traits>
19#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000020
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +010021#include "absl/strings/match.h"
Ali Tofigh1fa87c42022-07-25 22:07:08 +020022#include "absl/strings/string_view.h"
Yves Gerey988cc082018-10-23 12:03:01 +020023#include "absl/types/optional.h"
24#include "api/array_view.h"
Per Åhgren645f24c2020-03-16 12:06:02 +010025#include "api/audio/audio_frame.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "common_audio/include/audio_util.h"
Per Åhgren09e9a832020-05-11 11:03:47 +020028#include "modules/audio_processing/aec_dump/aec_dump_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "modules/audio_processing/audio_buffer.h"
Yves Gerey988cc082018-10-23 12:03:01 +020030#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgren13735822018-02-12 21:42:56 +010031#include "modules/audio_processing/logging/apm_data_dumper.h"
Sam Zackrissonb37e59d2020-04-27 08:39:33 +020032#include "modules/audio_processing/optionally_built_submodule_creators.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/checks.h"
34#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
Alessio Bazzica0441bb62021-08-10 15:23:23 +020037#include "system_wrappers/include/denormal_disabler.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020038#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000040
Michael Graczyk86c6d332015-07-23 11:41:39 -070041#define RETURN_ON_ERR(expr) \
42 do { \
43 int err = (expr); \
44 if (err != kNoError) { \
45 return err; \
46 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000047 } while (0)
48
niklase@google.com470e71d2011-07-07 08:21:25 +000049namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070050
Michael Graczyk86c6d332015-07-23 11:41:39 -070051namespace {
52
peah2ace3f92016-09-10 04:42:27 -070053bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070054 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
55 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
56}
57
Per Åhgrenc0424252019-12-10 13:04:15 +010058// Checks whether the high-pass filter should be done in the full-band.
59bool EnforceSplitBandHpf() {
60 return field_trial::IsEnabled("WebRTC-FullBandHpfKillSwitch");
61}
62
Per Åhgrenb2b58d82019-12-02 14:59:40 +010063// Checks whether AEC3 should be allowed to decide what the default
64// configuration should be based on the render and capture channel configuration
65// at hand.
66bool UseSetupSpecificDefaultAec3Congfig() {
67 return !field_trial::IsEnabled(
68 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
69}
70
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +010071// If the "WebRTC-Audio-TransientSuppressorVadMode" field trial is unspecified,
72// returns `TransientSuppressor::VadMode::kDefault`, otherwise parses the field
73// trial and returns the specified mode:
74// - WebRTC-Audio-TransientSuppressorVadMode/Enabled-Default returns `kDefault`;
75// - WebRTC-Audio-TransientSuppressorVadMode/Enabled-RnnVad returns `kRnnVad`;
76// - WebRTC-Audio-TransientSuppressorVadMode/Enabled-NoVad returns `kNoVad`.
77TransientSuppressor::VadMode GetTransientSuppressorVadMode() {
78 constexpr char kFieldTrial[] = "WebRTC-Audio-TransientSuppressorVadMode";
79 std::string full_name = webrtc::field_trial::FindFullName(kFieldTrial);
80 if (full_name.empty() || absl::EndsWith(full_name, "-Default")) {
81 return TransientSuppressor::VadMode::kDefault;
82 }
83 if (absl::EndsWith(full_name, "-RnnVad")) {
84 return TransientSuppressor::VadMode::kRnnVad;
85 }
86 if (absl::EndsWith(full_name, "-NoVad")) {
87 return TransientSuppressor::VadMode::kNoVad;
88 }
89 // Fallback to default.
90 RTC_LOG(LS_WARNING) << "Invalid parameter for " << kFieldTrial;
91 return TransientSuppressor::VadMode::kDefault;
92}
93
Per Åhgrenc8626b62019-08-23 15:49:51 +020094// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020095int SuitableProcessRate(int minimum_rate,
96 int max_splitting_rate,
97 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020098 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020099 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +0200100 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -0700101 if (rate >= uppermost_native_rate) {
102 return uppermost_native_rate;
103 }
104 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700105 return rate;
106 }
107 }
Artem Titovd3251962021-11-15 16:57:07 +0100108 RTC_DCHECK_NOTREACHED();
peah2ace3f92016-09-10 04:42:27 -0700109 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700110}
111
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100112GainControl::Mode Agc1ConfigModeToInterfaceMode(
113 AudioProcessing::Config::GainController1::Mode mode) {
114 using Agc1Config = AudioProcessing::Config::GainController1;
115 switch (mode) {
116 case Agc1Config::kAdaptiveAnalog:
117 return GainControl::kAdaptiveAnalog;
118 case Agc1Config::kAdaptiveDigital:
119 return GainControl::kAdaptiveDigital;
120 case Agc1Config::kFixedDigital:
121 return GainControl::kFixedDigital;
122 }
Karl Wibergc95b9392020-11-08 00:49:37 +0100123 RTC_CHECK_NOTREACHED();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100124}
125
Per Åhgren19775cb2021-03-12 23:08:09 +0000126bool MinimizeProcessingForUnusedOutput() {
127 return !field_trial::IsEnabled("WebRTC-MutedStateKillSwitch");
128}
129
peah9e6a2902017-05-15 07:19:21 -0700130// Maximum lengths that frame of samples being passed from the render side to
131// the capture side can have (does not apply to AEC3).
132static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
133static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
134
peah764e3642016-10-22 05:04:30 -0700135// Maximum number of frames to buffer in the render queue.
136// TODO(peah): Decrease this once we properly handle hugely unbalanced
137// reverse and forward call numbers.
138static const size_t kMaxNumFramesToBuffer = 100;
Alessio Bazzica3438a932020-10-14 12:47:50 +0200139
Sam Zackrisson03cb7e52021-12-06 15:40:04 +0100140void PackRenderAudioBufferForEchoDetector(const AudioBuffer& audio,
141 std::vector<float>& packed_buffer) {
142 packed_buffer.clear();
143 packed_buffer.insert(packed_buffer.end(), audio.channels_const()[0],
144 audio.channels_const()[0] + audio.num_frames());
145}
146
Alessio Bazzicafcf1af32022-09-07 17:14:26 +0200147constexpr int kUnspecifiedDataDumpInputVolume = -100;
148
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100149// Options for gracefully handling processing errors.
150enum class FormatErrorOutputOption {
151 kOutputExactCopyOfInput,
152 kOutputBroadcastCopyOfFirstInputChannel,
153 kOutputSilence,
154 kDoNothing
155};
156
157enum class AudioFormatValidity {
158 // Format is supported by APM.
159 kValidAndSupported,
160 // Format has a reasonable interpretation but is not supported.
161 kValidButUnsupportedSampleRate,
162 // The remaining enums values signal that the audio does not have a reasonable
163 // interpretation and cannot be used.
164 kInvalidSampleRate,
165 kInvalidChannelCount
166};
167
168AudioFormatValidity ValidateAudioFormat(const StreamConfig& config) {
169 if (config.sample_rate_hz() < 0)
170 return AudioFormatValidity::kInvalidSampleRate;
171 if (config.num_channels() == 0)
172 return AudioFormatValidity::kInvalidChannelCount;
173
174 // Format has a reasonable interpretation, but may still be unsupported.
175 if (config.sample_rate_hz() < 8000 ||
176 config.sample_rate_hz() > AudioBuffer::kMaxSampleRate)
177 return AudioFormatValidity::kValidButUnsupportedSampleRate;
178
179 // Format is fully supported.
180 return AudioFormatValidity::kValidAndSupported;
181}
182
183int AudioFormatValidityToErrorCode(AudioFormatValidity validity) {
184 switch (validity) {
185 case AudioFormatValidity::kValidAndSupported:
186 return AudioProcessing::kNoError;
187 case AudioFormatValidity::kValidButUnsupportedSampleRate: // fall-through
188 case AudioFormatValidity::kInvalidSampleRate:
189 return AudioProcessing::kBadSampleRateError;
190 case AudioFormatValidity::kInvalidChannelCount:
191 return AudioProcessing::kBadNumberChannelsError;
192 }
193 RTC_DCHECK(false);
194}
195
196// Returns an AudioProcessing::Error together with the best possible option for
197// output audio content.
198std::pair<int, FormatErrorOutputOption> ChooseErrorOutputOption(
199 const StreamConfig& input_config,
200 const StreamConfig& output_config) {
201 AudioFormatValidity input_validity = ValidateAudioFormat(input_config);
202 AudioFormatValidity output_validity = ValidateAudioFormat(output_config);
203
204 int error_code = AudioFormatValidityToErrorCode(input_validity);
205 if (error_code == AudioProcessing::kNoError) {
206 error_code = AudioFormatValidityToErrorCode(output_validity);
207 }
208
209 FormatErrorOutputOption output_option;
210 if (output_validity != AudioFormatValidity::kValidAndSupported &&
211 output_validity != AudioFormatValidity::kValidButUnsupportedSampleRate) {
212 // The output format is uninterpretable: cannot do anything.
213 output_option = FormatErrorOutputOption::kDoNothing;
214 } else if (input_validity != AudioFormatValidity::kValidAndSupported &&
215 input_validity !=
216 AudioFormatValidity::kValidButUnsupportedSampleRate) {
217 // The input format is uninterpretable: cannot use it, must output silence.
218 output_option = FormatErrorOutputOption::kOutputSilence;
219 } else if (input_config.sample_rate_hz() != output_config.sample_rate_hz()) {
220 // Sample rates do not match: Cannot copy input into output, output silence.
221 // Note: If the sample rates are in a supported range, we could resample.
222 // However, that would significantly increase complexity of this error
223 // handling code.
224 output_option = FormatErrorOutputOption::kOutputSilence;
225 } else if (input_config.num_channels() != output_config.num_channels()) {
226 // Channel counts do not match: We cannot easily map input channels to
227 // output channels.
228 output_option =
229 FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel;
230 } else {
231 // The formats match exactly.
232 RTC_DCHECK(input_config == output_config);
233 output_option = FormatErrorOutputOption::kOutputExactCopyOfInput;
234 }
235 return std::make_pair(error_code, output_option);
236}
237
238// Checks if the audio format is supported. If not, the output is populated in a
239// best-effort manner and an APM error code is returned.
240int HandleUnsupportedAudioFormats(const int16_t* const src,
241 const StreamConfig& input_config,
242 const StreamConfig& output_config,
243 int16_t* const dest) {
244 RTC_DCHECK(src);
245 RTC_DCHECK(dest);
246
247 auto [error_code, output_option] =
248 ChooseErrorOutputOption(input_config, output_config);
249 if (error_code == AudioProcessing::kNoError)
250 return AudioProcessing::kNoError;
251
252 const size_t num_output_channels = output_config.num_channels();
253 switch (output_option) {
254 case FormatErrorOutputOption::kOutputSilence:
255 memset(dest, 0, output_config.num_samples() * sizeof(int16_t));
256 break;
257 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
258 for (size_t i = 0; i < output_config.num_frames(); ++i) {
259 int16_t sample = src[input_config.num_channels() * i];
260 for (size_t ch = 0; ch < num_output_channels; ++ch) {
261 dest[ch + num_output_channels * i] = sample;
262 }
263 }
264 break;
265 case FormatErrorOutputOption::kOutputExactCopyOfInput:
266 memcpy(dest, src, output_config.num_samples() * sizeof(int16_t));
267 break;
268 case FormatErrorOutputOption::kDoNothing:
269 break;
270 }
271 return error_code;
272}
273
274// Checks if the audio format is supported. If not, the output is populated in a
275// best-effort manner and an APM error code is returned.
276int HandleUnsupportedAudioFormats(const float* const* src,
277 const StreamConfig& input_config,
278 const StreamConfig& output_config,
279 float* const* dest) {
280 RTC_DCHECK(src);
281 RTC_DCHECK(dest);
282 for (size_t i = 0; i < input_config.num_channels(); ++i) {
283 RTC_DCHECK(src[i]);
284 }
285 for (size_t i = 0; i < output_config.num_channels(); ++i) {
286 RTC_DCHECK(dest[i]);
287 }
288
289 auto [error_code, output_option] =
290 ChooseErrorOutputOption(input_config, output_config);
291 if (error_code == AudioProcessing::kNoError)
292 return AudioProcessing::kNoError;
293
294 const size_t num_output_channels = output_config.num_channels();
295 switch (output_option) {
296 case FormatErrorOutputOption::kOutputSilence:
297 for (size_t ch = 0; ch < num_output_channels; ++ch) {
298 memset(dest[ch], 0, output_config.num_frames() * sizeof(float));
299 }
300 break;
301 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
302 for (size_t ch = 0; ch < num_output_channels; ++ch) {
303 memcpy(dest[ch], src[0], output_config.num_frames() * sizeof(float));
304 }
305 break;
306 case FormatErrorOutputOption::kOutputExactCopyOfInput:
307 for (size_t ch = 0; ch < num_output_channels; ++ch) {
308 memcpy(dest[ch], src[ch], output_config.num_frames() * sizeof(float));
309 }
310 break;
311 case FormatErrorOutputOption::kDoNothing:
312 break;
313 }
314 return error_code;
315}
316
Michael Graczyk86c6d332015-07-23 11:41:39 -0700317} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000318
319// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000320static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000321
saza1d600522019-10-18 13:29:43 +0200322AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100323 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200324 bool render_pre_processor_enabled,
325 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100326 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200327 render_pre_processor_enabled_(render_pre_processor_enabled),
328 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700329
saza1d600522019-10-18 13:29:43 +0200330bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200331 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700332 bool mobile_echo_controller_enabled,
333 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700334 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700335 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200336 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000337 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200338 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700339 bool transient_suppressor_enabled) {
340 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200341 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700342 changed |=
343 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
344 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
345 changed |=
peah2ace3f92016-09-10 04:42:27 -0700346 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200347 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200348 changed |=
349 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000350 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200351 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700352 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
353 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200354 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700355 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
356 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700357 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700358 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200359 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000360 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200361 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700362 transient_suppressor_enabled_ = transient_suppressor_enabled;
363 }
364
365 changed |= first_update_;
366 first_update_ = false;
367 return changed;
368}
369
saza1d600522019-10-18 13:29:43 +0200370bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700371 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000372 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700373}
374
saza1d600522019-10-18 13:29:43 +0200375bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
376 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200377 // If echo controller is present, assume it performs active processing.
378 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
379}
380
saza1d600522019-10-18 13:29:43 +0200381bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200382 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100383 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
384 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200385 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700386}
387
saza1d600522019-10-18 13:29:43 +0200388bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700389 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200390 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000391 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700392}
393
saza1d600522019-10-18 13:29:43 +0200394bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200395 return capture_analyzer_enabled_;
396}
397
saza1d600522019-10-18 13:29:43 +0200398bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700399 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100400 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
401 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700402}
403
saza1d600522019-10-18 13:29:43 +0200404bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100405 const {
406 return render_pre_processor_enabled_;
407}
408
saza1d600522019-10-18 13:29:43 +0200409bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700410 const {
peah2ace3f92016-09-10 04:42:27 -0700411 return false;
peah2ace3f92016-09-10 04:42:27 -0700412}
413
saza1d600522019-10-18 13:29:43 +0200414bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100415 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
416 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200417}
418
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200419AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200420 : AudioProcessingImpl(/*config=*/{},
421 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200422 /*render_pre_processor=*/nullptr,
423 /*echo_control_factory=*/nullptr,
424 /*echo_detector=*/nullptr,
425 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000426
Niels Möller7a669002022-06-27 09:47:02 +0200427std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100428
Sam Zackrisson0beac582017-09-25 12:04:02 +0200429AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200430 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100431 std::unique_ptr<CustomProcessing> capture_post_processor,
432 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200433 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200434 rtc::scoped_refptr<EchoDetector> echo_detector,
435 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200436 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100437 use_setup_specific_default_aec3_config_(
438 UseSetupSpecificDefaultAec3Congfig()),
Alessio Bazzica0441bb62021-08-10 15:23:23 +0200439 use_denormal_disabler_(
440 !field_trial::IsEnabled("WebRTC-ApmDenormalDisablerKillSwitch")),
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +0100441 transient_suppressor_vad_mode_(GetTransientSuppressorVadMode()),
Per Åhgren652ada52021-03-03 10:52:44 +0000442 capture_runtime_settings_(RuntimeSettingQueueSize()),
443 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200444 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
445 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200446 echo_control_factory_(std::move(echo_control_factory)),
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200447 config_(config),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200448 submodule_states_(!!capture_post_processor,
449 !!render_pre_processor,
450 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200451 submodules_(std::move(capture_post_processor),
452 std::move(render_pre_processor),
453 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100454 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100455 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200456 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
457 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100458 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000459 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200460 MinimizeProcessingForUnusedOutput(),
461 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000462 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200463 capture_nonlocked_(),
464 applied_input_volume_stats_reporter_(
465 InputVolumeStatsReporter::InputVolumeType::kApplied),
466 recommended_input_volume_stats_reporter_(
467 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200468 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100469 "\nEcho control factory: "
470 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200471 << "\nEcho detector: " << !!submodules_.echo_detector
472 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
473 << "\nCapture post processor: "
474 << !!submodules_.capture_post_processor
475 << "\nRender pre processor: "
476 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100477 if (!DenormalDisabler::IsSupported()) {
478 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
479 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200480
Sam Zackrisson421c8592019-02-11 13:39:46 +0100481 // Mark Echo Controller enabled if a factory is injected.
482 capture_nonlocked_.echo_controller_enabled =
483 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000484
Per Åhgren0ade9832020-09-01 23:57:20 +0200485 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000486}
487
Per Åhgren0e3198e2019-11-18 08:52:22 +0100488AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000489
niklase@google.com470e71d2011-07-07 08:21:25 +0000490int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800491 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200492 MutexLock lock_render(&mutex_render_);
493 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200494 InitializeLocked();
495 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000496}
497
Michael Graczyk86c6d332015-07-23 11:41:39 -0700498int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800499 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200500 MutexLock lock_render(&mutex_render_);
501 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100502 InitializeLocked(processing_config);
503 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000504}
505
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100506void AudioProcessingImpl::MaybeInitializeRender(
507 const StreamConfig& input_config,
508 const StreamConfig& output_config) {
509 ProcessingConfig processing_config = formats_.api_format;
510 processing_config.reverse_input_stream() = input_config;
511 processing_config.reverse_output_stream() = output_config;
512
Oskar Sundbom4b276482019-05-23 14:28:00 +0200513 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100514 return;
peah192164e2015-11-17 02:16:45 -0800515 }
peahdf3efa82015-11-28 12:35:15 -0800516
Markus Handell0df0fae2020-07-07 15:53:34 +0200517 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100518 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800519}
520
Per Åhgren0ade9832020-09-01 23:57:20 +0200521void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200522 UpdateActiveSubmoduleStates();
523
Per Åhgrend47941e2019-08-22 11:51:13 +0200524 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800525 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200526 ? formats_.render_processing_format.sample_rate_hz()
527 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800528 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
529 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200530 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800531 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200532 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700533 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200534 render_audiobuffer_sample_rate_hz,
535 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700536 if (formats_.api_format.reverse_input_stream() !=
537 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800538 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800539 formats_.api_format.reverse_input_stream().num_channels(),
540 formats_.api_format.reverse_input_stream().num_frames(),
541 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800542 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700543 } else {
peahdf3efa82015-11-28 12:35:15 -0800544 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700545 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700546 } else {
peahdf3efa82015-11-28 12:35:15 -0800547 render_.render_audio.reset(nullptr);
548 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700549 }
peahce4d9152017-05-19 01:28:05 -0700550
Per Åhgrend47941e2019-08-22 11:51:13 +0200551 capture_.capture_audio.reset(new AudioBuffer(
552 formats_.api_format.input_stream().sample_rate_hz(),
553 formats_.api_format.input_stream().num_channels(),
554 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
555 formats_.api_format.output_stream().num_channels(),
556 formats_.api_format.output_stream().sample_rate_hz(),
557 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000558
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200559 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
560 formats_.api_format.output_stream().sample_rate_hz() &&
561 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
562 capture_.capture_fullband_audio.reset(
563 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
564 formats_.api_format.input_stream().num_channels(),
565 formats_.api_format.output_stream().sample_rate_hz(),
566 formats_.api_format.output_stream().num_channels(),
567 formats_.api_format.output_stream().sample_rate_hz(),
568 formats_.api_format.output_stream().num_channels()));
569 } else {
570 capture_.capture_fullband_audio.reset();
571 }
572
peah764e3642016-10-22 05:04:30 -0700573 AllocateRenderQueue();
574
Per Åhgren0695df12020-01-13 14:43:13 +0100575 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100576 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100577 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700578 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200579 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200580 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200581 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200582 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200583 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200584 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100585 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000586 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800587
aleloi868f32f2017-05-23 07:20:05 -0700588 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200589 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700590 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000591}
592
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100593void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200594 UpdateActiveSubmoduleStates();
595
peahdf3efa82015-11-28 12:35:15 -0800596 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000597
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200598 // Choose maximum rate to use for the split filtering.
599 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
600 config_.pipeline.maximum_internal_processing_rate == 32000);
601 int max_splitting_rate = 48000;
602 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
603 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
604 }
605
Per Åhgrenc8626b62019-08-23 15:49:51 +0200606 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700607 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700608 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200609 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700610 submodule_states_.CaptureMultiBandSubModulesActive() ||
611 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200612 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000613
peahde65ddc2016-09-16 15:02:15 -0700614 capture_nonlocked_.capture_processing_format =
615 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700616
peah2ce640f2017-04-07 03:57:48 -0700617 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200618 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200619 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700620 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
621 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200622 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700623 submodule_states_.CaptureMultiBandSubModulesActive() ||
624 submodule_states_.RenderMultiBandSubModulesActive());
625 } else {
626 render_processing_rate = capture_processing_rate;
627 }
628
peahde65ddc2016-09-16 15:02:15 -0700629 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700630 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700631 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
632 kSampleRate8kHz) {
633 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000634 } else {
peahde65ddc2016-09-16 15:02:15 -0700635 render_processing_rate =
636 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000637 }
638
Per Åhgrenc8626b62019-08-23 15:49:51 +0200639 RTC_DCHECK_NE(8000, render_processing_rate);
640
peahce4d9152017-05-19 01:28:05 -0700641 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200642 // By default, downmix the render stream to mono for analysis. This has been
643 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100644 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
645 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200646 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100647 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200648 ? formats_.api_format.reverse_input_stream().num_channels()
649 : 1;
650 formats_.render_processing_format =
651 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700652 } else {
653 formats_.render_processing_format = StreamConfig(
654 formats_.api_format.reverse_input_stream().sample_rate_hz(),
655 formats_.api_format.reverse_input_stream().num_channels());
656 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000657
peahde65ddc2016-09-16 15:02:15 -0700658 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
659 kSampleRate32kHz ||
660 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
661 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800662 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000663 } else {
peahdf3efa82015-11-28 12:35:15 -0800664 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700665 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000666 }
667
Per Åhgren0ade9832020-09-01 23:57:20 +0200668 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000669}
670
peah88ac8532016-09-12 16:47:25 -0700671void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200672 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
673
peah88ac8532016-09-12 16:47:25 -0700674 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200675 MutexLock lock_render(&mutex_render_);
676 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700677
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200678 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100679 config_.pipeline.multi_channel_render !=
680 config.pipeline.multi_channel_render ||
681 config_.pipeline.multi_channel_capture !=
Per Åhgrenc0424252019-12-10 13:04:15 +0100682 config.pipeline.multi_channel_capture ||
683 config_.pipeline.maximum_internal_processing_rate !=
684 config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200685
Per Åhgren200feba2019-03-06 04:16:46 +0100686 const bool aec_config_changed =
687 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100688 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100689
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100690 const bool agc1_config_changed =
Alessio Bazzica3438a932020-10-14 12:47:50 +0200691 config_.gain_controller1 != config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100692
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100693 const bool agc2_config_changed =
Alessio Bazzica3438a932020-10-14 12:47:50 +0200694 config_.gain_controller2 != config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100695
saza0bad15f2019-10-16 11:46:11 +0200696 const bool ns_config_changed =
697 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
698 config_.noise_suppression.level != config.noise_suppression.level;
699
Per Åhgrenc0734712020-01-02 15:15:36 +0100700 const bool ts_config_changed = config_.transient_suppression.enabled !=
701 config.transient_suppression.enabled;
702
Per Åhgren0f14db22020-01-03 14:27:14 +0100703 const bool pre_amplifier_config_changed =
704 config_.pre_amplifier.enabled != config.pre_amplifier.enabled ||
705 config_.pre_amplifier.fixed_gain_factor !=
706 config.pre_amplifier.fixed_gain_factor;
707
Per Åhgrendb5d7282021-03-15 16:31:04 +0000708 const bool gain_adjustment_config_changed =
709 config_.capture_level_adjustment != config.capture_level_adjustment;
710
Yves Gerey499bc6c2018-10-10 18:29:07 +0200711 config_ = config;
712
Per Åhgren200feba2019-03-06 04:16:46 +0100713 if (aec_config_changed) {
714 InitializeEchoController();
715 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200716
saza0bad15f2019-10-16 11:46:11 +0200717 if (ns_config_changed) {
718 InitializeNoiseSuppressor();
719 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100720
Per Åhgrenc0734712020-01-02 15:15:36 +0100721 if (ts_config_changed) {
722 InitializeTransientSuppressor();
723 }
724
Per Åhgren0f14db22020-01-03 14:27:14 +0100725 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800726
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100727 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100728 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100729 }
730
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100731 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700732 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200733 RTC_LOG(LS_ERROR)
734 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700735 config_.gain_controller2 = AudioProcessing::Config::GainController2();
736 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100737
Alessio Bazzica38901042021-10-14 12:14:21 +0200738 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200739 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100740
Per Åhgrendb5d7282021-03-15 16:31:04 +0000741 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
742 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100743 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100744
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200745 // Reinitialization must happen after all submodule configuration to avoid
746 // additional reinitializations on the next capture / render processing call.
747 if (pipeline_config_changed) {
748 InitializeLocked(formats_.api_format);
749 }
peah88ac8532016-09-12 16:47:25 -0700750}
751
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200752void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
753 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200754 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200755 submodule_creation_overrides_ = overrides;
756}
757
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000758int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800759 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700760 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000761}
762
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200763int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
764 return capture_.capture_fullband_audio
765 ? capture_.capture_fullband_audio->num_frames() * 100
766 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
767}
768
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000769int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800770 // Used as callback from submodules, hence locking is not allowed.
771 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000772}
773
Peter Kasting69558702016-01-12 16:26:35 -0800774size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800775 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700776 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000777}
778
Peter Kasting69558702016-01-12 16:26:35 -0800779size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800780 // Used as callback from submodules, hence locking is not allowed.
781 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000782}
783
Peter Kasting69558702016-01-12 16:26:35 -0800784size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800785 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100786 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
787 constants_.multi_channel_capture_support;
788 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200789 return 1;
790 }
791 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800792}
793
Peter Kasting69558702016-01-12 16:26:35 -0800794size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800795 // Used as callback from submodules, hence locking is not allowed.
796 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000797}
798
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000799void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200800 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +0100801 HandleCaptureOutputUsedSetting(!muted);
802}
803
804void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
805 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +0000806 capture_.capture_output_used =
807 capture_output_used || !constants_.minimize_processing_for_unused_output;
808
saza1d600522019-10-18 13:29:43 +0200809 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100810 submodules_.agc_manager->HandleCaptureOutputUsedChange(
811 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000812 }
Per Åhgren652ada52021-03-03 10:52:44 +0000813 if (submodules_.echo_controller) {
814 submodules_.echo_controller->SetCaptureOutputUsage(
815 capture_.capture_output_used);
816 }
Per Åhgren15179a92021-03-12 14:12:44 +0000817 if (submodules_.noise_suppressor) {
818 submodules_.noise_suppressor->SetCaptureOutputUsage(
819 capture_.capture_output_used);
820 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000821}
822
Alessio Bazzicac054e782018-04-16 12:10:09 +0200823void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100824 PostRuntimeSetting(setting);
825}
826
827bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200828 switch (setting.type()) {
829 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100830 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +0100831 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200832 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +0000833 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100834 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200835 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +0200836 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +0100837 return capture_runtime_settings_enqueuer_.Enqueue(setting);
838 case RuntimeSetting::Type::kPlayoutVolumeChange: {
839 bool enqueueing_successful;
840 enqueueing_successful =
841 capture_runtime_settings_enqueuer_.Enqueue(setting);
842 enqueueing_successful =
843 render_runtime_settings_enqueuer_.Enqueue(setting) &&
844 enqueueing_successful;
845 return enqueueing_successful;
846 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100847 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +0100848 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +0100849 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +0200850 }
851 // The language allows the enum to have a non-enumerator
852 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +0100853 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +0100854 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +0200855}
856
857AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
858 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200859 : runtime_settings_(*runtime_settings) {
860 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200861}
862
863AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
864 default;
865
Per Åhgren0a144a72021-02-09 08:47:51 +0100866bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +0200867 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +0000868 const bool successful_insert = runtime_settings_.Insert(&setting);
869
870 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200871 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +0200872 }
Per Åhgren652ada52021-03-03 10:52:44 +0000873 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +0200874}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000875
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100876void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100877 const StreamConfig& input_config,
878 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -0800879 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700880 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800881 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100882 // Acquire the capture lock in order to access api_format. The lock is
883 // released immediately, as we may need to acquire the render lock as part
884 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200885 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -0800886 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700887 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000888 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000889
Oskar Sundbom4b276482019-05-23 14:28:00 +0200890 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200891 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800892 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200893
894 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200895 reinitialization_required = true;
896 }
897
898 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200899 MutexLock lock_render(&mutex_render_);
900 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +0200901 // Reread the API format since the render format may have changed.
902 processing_config = formats_.api_format;
903 processing_config.input_stream() = input_config;
904 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100905 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +0200906 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100907}
908
909int AudioProcessingImpl::ProcessStream(const float* const* src,
910 const StreamConfig& input_config,
911 const StreamConfig& output_config,
912 float* const* dest) {
913 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100914 DenormalDisabler denormal_disabler(use_denormal_disabler_);
915 RETURN_ON_ERR(
916 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
917 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +0200918
Markus Handell0df0fae2020-07-07 15:53:34 +0200919 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000920
aleloi868f32f2017-05-23 07:20:05 -0700921 if (aec_dump_) {
922 RecordUnprocessedCaptureStream(src);
923 }
924
peahdf3efa82015-11-28 12:35:15 -0800925 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200926 if (capture_.capture_fullband_audio) {
927 capture_.capture_fullband_audio->CopyFrom(
928 src, formats_.api_format.input_stream());
929 }
peahde65ddc2016-09-16 15:02:15 -0700930 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200931 if (capture_.capture_fullband_audio) {
932 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
933 dest);
934 } else {
935 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
936 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000937
aleloi868f32f2017-05-23 07:20:05 -0700938 if (aec_dump_) {
939 RecordProcessedCaptureStream(dest);
940 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000941 return kNoError;
942}
943
Alex Loiko73ec0192018-05-15 10:52:28 +0200944void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200945 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +0000946 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +0200947 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200948 if (aec_dump_) {
949 aec_dump_->WriteRuntimeSetting(setting);
950 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200951 switch (setting.type()) {
952 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +0000953 if (config_.pre_amplifier.enabled ||
954 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +0200955 float value;
956 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000957 // If the pre-amplifier is used, apply the new gain to the
958 // pre-amplifier regardless if the capture level adjustment is
959 // activated. This approach allows both functionalities to coexist
960 // until they have been properly merged.
961 if (config_.pre_amplifier.enabled) {
962 config_.pre_amplifier.fixed_gain_factor = value;
963 } else {
964 config_.capture_level_adjustment.pre_gain_factor = value;
965 }
966
967 // Use both the pre-amplifier and the capture level adjustment gains
968 // as pre-gains.
969 float gain = 1.f;
970 if (config_.pre_amplifier.enabled) {
971 gain *= config_.pre_amplifier.fixed_gain_factor;
972 }
973 if (config_.capture_level_adjustment.enabled) {
974 gain *= config_.capture_level_adjustment.pre_gain_factor;
975 }
976
977 submodules_.capture_levels_adjuster->SetPreGain(gain);
978 }
979 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
980 break;
981 case RuntimeSetting::Type::kCapturePostGain:
982 if (config_.capture_level_adjustment.enabled) {
983 float value;
984 setting.GetFloat(&value);
985 config_.capture_level_adjustment.post_gain_factor = value;
986 submodules_.capture_levels_adjuster->SetPostGain(
987 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +0200988 }
989 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200990 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100991 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +0100992 if (!submodules_.agc_manager) {
993 float value;
994 setting.GetFloat(&value);
995 int int_value = static_cast<int>(value + .5f);
996 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +0100997 if (submodules_.gain_control) {
998 int error =
999 submodules_.gain_control->set_compression_gain_db(int_value);
1000 RTC_DCHECK_EQ(kNoError, error);
1001 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001002 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001003 break;
1004 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001005 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001006 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001007 float value;
1008 setting.GetFloat(&value);
1009 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001010 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001011 }
1012 break;
1013 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001014 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1015 int value;
1016 setting.GetInt(&value);
1017 capture_.playout_volume = value;
1018 break;
1019 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001020 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001021 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001022 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001023 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001024 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001025 break;
1026 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001027 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001028 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001029 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001030 bool value;
1031 setting.GetBool(&value);
1032 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001033 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001034 }
Per Åhgren652ada52021-03-03 10:52:44 +00001035 ++num_settings_processed;
1036 }
1037
1038 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1039 // Handle overrun of the runtime settings queue, which likely will has
1040 // caused settings to be discarded.
1041 HandleOverrunInCaptureRuntimeSettingsQueue();
1042 }
1043}
1044
1045void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1046 // Fall back to a safe state for the case when a setting for capture output
1047 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001048 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001049}
1050
1051void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1052 RuntimeSetting setting;
1053 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001054 if (aec_dump_) {
1055 aec_dump_->WriteRuntimeSetting(setting);
1056 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001057 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001058 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001059 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001060 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001061 if (submodules_.render_pre_processor) {
1062 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001063 }
1064 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001065 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001066 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001067 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001068 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001069 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001070 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001071 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001072 break;
1073 }
1074 }
1075}
1076
peah9e6a2902017-05-15 07:19:21 -07001077void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001078 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001079
saza1d600522019-10-18 13:29:43 +02001080 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001081 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1082 num_reverse_channels(),
1083 &aecm_render_queue_buffer_);
1084 RTC_DCHECK(aecm_render_signal_queue_);
1085 // Insert the samples into the queue.
1086 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1087 // The data queue is full and needs to be emptied.
1088 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001089
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001090 // Retry the insert (should always work).
1091 bool result =
1092 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1093 RTC_DCHECK(result);
1094 }
peah764e3642016-10-22 05:04:30 -07001095 }
peah701d6282016-10-25 05:42:20 -07001096
Per Åhgren0695df12020-01-13 14:43:13 +01001097 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001098 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001099 // Insert the samples into the queue.
1100 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1101 // The data queue is full and needs to be emptied.
1102 EmptyQueuedRenderAudio();
1103
1104 // Retry the insert (should always work).
1105 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1106 RTC_DCHECK(result);
1107 }
1108 }
peah9e6a2902017-05-15 07:19:21 -07001109}
ivoc9f4a4a02016-10-28 05:39:16 -07001110
peah9e6a2902017-05-15 07:19:21 -07001111void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001112 if (submodules_.echo_detector) {
1113 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1114 RTC_DCHECK(red_render_signal_queue_);
1115 // Insert the samples into the queue.
1116 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1117 // The data queue is full and needs to be emptied.
1118 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001119
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001120 // Retry the insert (should always work).
1121 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1122 RTC_DCHECK(result);
1123 }
ivoc9f4a4a02016-10-28 05:39:16 -07001124 }
peah764e3642016-10-22 05:04:30 -07001125}
1126
1127void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001128 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001129 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001130
ivoc9f4a4a02016-10-28 05:39:16 -07001131 const size_t new_red_render_queue_element_max_size =
1132 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1133
peaha0624602016-10-25 04:45:24 -07001134 // Reallocate the queues if the queue item sizes are too small to fit the
1135 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001136
1137 if (agc_render_queue_element_max_size_ <
1138 new_agc_render_queue_element_max_size) {
1139 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1140
1141 std::vector<int16_t> template_queue_element(
1142 agc_render_queue_element_max_size_);
1143
1144 agc_render_signal_queue_.reset(
1145 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1146 kMaxNumFramesToBuffer, template_queue_element,
1147 RenderQueueItemVerifier<int16_t>(
1148 agc_render_queue_element_max_size_)));
1149
1150 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1151 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1152 } else {
1153 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001154 }
ivoc9f4a4a02016-10-28 05:39:16 -07001155
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001156 if (submodules_.echo_detector) {
1157 if (red_render_queue_element_max_size_ <
1158 new_red_render_queue_element_max_size) {
1159 red_render_queue_element_max_size_ =
1160 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001161
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001162 std::vector<float> template_queue_element(
1163 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001164
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001165 red_render_signal_queue_.reset(
1166 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1167 kMaxNumFramesToBuffer, template_queue_element,
1168 RenderQueueItemVerifier<float>(
1169 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001170
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001171 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1172 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1173 } else {
1174 red_render_signal_queue_->Clear();
1175 }
ivoc9f4a4a02016-10-28 05:39:16 -07001176 }
peah764e3642016-10-22 05:04:30 -07001177}
1178
1179void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001180 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001181 EmptyQueuedRenderAudioLocked();
1182}
1183
1184void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001185 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001186 RTC_DCHECK(aecm_render_signal_queue_);
1187 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001188 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001189 aecm_capture_queue_buffer_);
1190 }
peah701d6282016-10-25 05:42:20 -07001191 }
1192
Per Åhgren0695df12020-01-13 14:43:13 +01001193 if (submodules_.gain_control) {
1194 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1195 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1196 }
peah764e3642016-10-22 05:04:30 -07001197 }
ivoc9f4a4a02016-10-28 05:39:16 -07001198
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001199 if (submodules_.echo_detector) {
1200 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1201 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1202 }
ivoc9f4a4a02016-10-28 05:39:16 -07001203 }
peah764e3642016-10-22 05:04:30 -07001204}
1205
Per Åhgren645f24c2020-03-16 12:06:02 +01001206int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1207 const StreamConfig& input_config,
1208 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001209 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001210 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001211
1212 RETURN_ON_ERR(
1213 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1214 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001215
Markus Handell0df0fae2020-07-07 15:53:34 +02001216 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001217 DenormalDisabler denormal_disabler(use_denormal_disabler_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001218
aleloi868f32f2017-05-23 07:20:05 -07001219 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001220 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001221 }
1222
Per Åhgren645f24c2020-03-16 12:06:02 +01001223 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001224 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001225 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001226 }
peahde65ddc2016-09-16 15:02:15 -07001227 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001228 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001229 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001230 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001231 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001232 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001233 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001234 }
Per Åhgrena1351272019-08-15 12:15:46 +02001235 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001236
aleloi868f32f2017-05-23 07:20:05 -07001237 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001238 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001239 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001240 return kNoError;
1241}
1242
peahde65ddc2016-09-16 15:02:15 -07001243int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001244 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001245 HandleCaptureRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001246 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001247
peahb58a1582016-03-15 09:34:24 -07001248 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001249 // TODO(peah): Simplify once the public API Enable functions for these
1250 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001251 RTC_DCHECK_LE(
1252 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001253
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001254 data_dumper_->DumpRaw(
1255 "applied_input_volume",
1256 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1257
peahde65ddc2016-09-16 15:02:15 -07001258 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001259 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001260
Per Åhgrenc0424252019-12-10 13:04:15 +01001261 if (submodules_.high_pass_filter &&
1262 config_.high_pass_filter.apply_in_full_band &&
1263 !constants_.enforce_split_band_hpf) {
1264 submodules_.high_pass_filter->Process(capture_buffer,
1265 /*use_split_band_data=*/false);
1266 }
1267
Per Åhgrendb5d7282021-03-15 16:31:04 +00001268 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001269 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001270 // When the input volume is emulated, retrieve the volume applied to the
1271 // input audio and notify that to APM so that the volume is passed to the
1272 // active AGC.
1273 set_stream_analog_level_locked(
1274 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001275 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001276 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1277 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001278 }
1279
Per Åhgren928146f2019-08-20 09:19:21 +02001280 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001281 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001282 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001283 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1284 if (log_rms) {
1285 capture_rms_interval_counter_ = 0;
1286 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001287 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1288 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1289 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1290 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001291 }
1292
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001293 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001294 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001295 *capture_.applied_input_volume);
1296 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001297
saza1d600522019-10-18 13:29:43 +02001298 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001299 // Determine if the echo path gain has changed by checking all the gains
1300 // applied before AEC.
1301 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001302
Per Åhgrendb5d7282021-03-15 16:31:04 +00001303 // Detect and flag any change in the capture level adjustment pre-gain.
1304 if (submodules_.capture_levels_adjuster) {
1305 float pre_adjustment_gain =
1306 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001307 capture_.echo_path_gain_change =
1308 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001309 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001310 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001311 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001312 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001313
1314 // Detect volume change.
1315 capture_.echo_path_gain_change =
1316 capture_.echo_path_gain_change ||
1317 (capture_.prev_playout_volume != capture_.playout_volume &&
1318 capture_.prev_playout_volume >= 0);
1319 capture_.prev_playout_volume = capture_.playout_volume;
1320
saza1d600522019-10-18 13:29:43 +02001321 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001322 }
1323
Per Åhgren0695df12020-01-13 14:43:13 +01001324 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001325 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001326 }
1327
peah2ace3f92016-09-10 04:42:27 -07001328 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1329 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001330 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1331 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001332 }
1333
Per Åhgrene14cb992019-11-27 09:34:22 +01001334 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1335 constants_.multi_channel_capture_support;
1336 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001337 // Force down-mixing of the number of channels after the detection of
1338 // capture signal saturation.
1339 // TODO(peah): Look into ensuring that this kind of tampering with the
1340 // AudioBuffer functionality should not be needed.
1341 capture_buffer->set_num_channels(1);
1342 }
1343
Per Åhgrenc0424252019-12-10 13:04:15 +01001344 if (submodules_.high_pass_filter &&
1345 (!config_.high_pass_filter.apply_in_full_band ||
1346 constants_.enforce_split_band_hpf)) {
1347 submodules_.high_pass_filter->Process(capture_buffer,
1348 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001349 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001350
Per Åhgren0695df12020-01-13 14:43:13 +01001351 if (submodules_.gain_control) {
1352 RETURN_ON_ERR(
1353 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1354 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001355
Per Åhgren8ad9e742020-01-30 07:40:58 +01001356 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1357 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1358 submodules_.noise_suppressor) {
1359 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001360 }
peahb58a1582016-03-15 09:34:24 -07001361
saza1d600522019-10-18 13:29:43 +02001362 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001363 // Ensure that the stream delay was set before the call to the
1364 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001365 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001366 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001367 }
1368
saza1d600522019-10-18 13:29:43 +02001369 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001370 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001371 }
peahe0eae3c2016-12-14 01:16:23 -08001372
saza1d600522019-10-18 13:29:43 +02001373 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001374 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001375 } else {
saza1d600522019-10-18 13:29:43 +02001376 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001377 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1378
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001379 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001380 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001381 }
1382
saza1d600522019-10-18 13:29:43 +02001383 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001384 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001385 }
1386
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001387 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001388 linear_aec_buffer && submodules_.noise_suppressor) {
1389 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001390 }
1391
saza1d600522019-10-18 13:29:43 +02001392 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001393 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001394 }
Per Åhgren46537a32017-06-07 10:08:10 +02001395 }
ivoc9f4a4a02016-10-28 05:39:16 -07001396
Per Åhgren0695df12020-01-13 14:43:13 +01001397 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001398 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001399
1400 absl::optional<int> new_digital_gain =
1401 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001402 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001403 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1404 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001405 }
Per Åhgren0695df12020-01-13 14:43:13 +01001406
1407 if (submodules_.gain_control) {
1408 // TODO(peah): Add reporting from AEC3 whether there is echo.
1409 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1410 capture_buffer, /*stream_has_echo*/ false));
1411 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001412
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001413 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1414 SampleRateSupportsMultiBand(
1415 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1416 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001417 }
1418
Per Åhgren19775cb2021-03-12 23:08:09 +00001419 if (capture_.capture_output_used) {
1420 if (capture_.capture_fullband_audio) {
1421 const auto& ec = submodules_.echo_controller;
1422 bool ec_active = ec ? ec->ActiveProcessing() : false;
1423 // Only update the fullband buffer if the multiband processing has changed
1424 // the signal. Keep the original signal otherwise.
1425 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1426 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1427 }
1428 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001429 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001430
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001431 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001432 submodules_.echo_detector->AnalyzeCaptureAudio(
1433 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1434 capture_buffer->num_frames()));
1435 }
1436
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001437 absl::optional<float> voice_probability;
1438 if (!!submodules_.voice_activity_detector) {
1439 voice_probability = submodules_.voice_activity_detector->Analyze(
1440 AudioFrameView<const float>(capture_buffer->channels(),
1441 capture_buffer->num_channels(),
1442 capture_buffer->num_frames()));
1443 }
1444
Per Åhgren19775cb2021-03-12 23:08:09 +00001445 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001446 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001447 switch (transient_suppressor_vad_mode_) {
1448 case TransientSuppressor::VadMode::kDefault:
1449 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001450 transient_suppressor_voice_probability =
1451 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001452 }
1453 break;
1454 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001455 RTC_DCHECK(voice_probability.has_value());
1456 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001457 break;
1458 case TransientSuppressor::VadMode::kNoVad:
1459 // The transient suppressor will ignore `voice_probability`.
1460 break;
1461 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001462 float delayed_voice_probability =
1463 submodules_.transient_suppressor->Suppress(
1464 capture_buffer->channels()[0], capture_buffer->num_frames(),
1465 capture_buffer->num_channels(),
1466 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1467 capture_buffer->num_frames_per_band(),
1468 /*reference_data=*/nullptr, /*reference_length=*/0,
1469 transient_suppressor_voice_probability, capture_.key_pressed);
1470 if (voice_probability.has_value()) {
1471 *voice_probability = delayed_voice_probability;
1472 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001473 }
1474
Artem Titov0b489302021-07-28 20:50:03 +02001475 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001476 if (submodules_.capture_analyzer) {
1477 submodules_.capture_analyzer->Analyze(capture_buffer);
1478 }
1479
1480 if (submodules_.gain_controller2) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001481 submodules_.gain_controller2->Process(
1482 voice_probability, capture_.applied_input_volume_changed,
1483 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001484 }
1485
1486 if (submodules_.capture_post_processor) {
1487 submodules_.capture_post_processor->Process(capture_buffer);
1488 }
1489
Per Åhgren19775cb2021-03-12 23:08:09 +00001490 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1491 capture_buffer->channels_const()[0],
1492 capture_nonlocked_.capture_processing_format.num_frames()));
1493 if (log_rms) {
1494 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1495 RTC_HISTOGRAM_COUNTS_LINEAR(
1496 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1497 RmsLevel::kMinLevelDb, 64);
1498 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1499 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1500 }
1501
Per Åhgren19775cb2021-03-12 23:08:09 +00001502 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001503 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001504 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1505 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1506 capture_.stats.residual_echo_likelihood_recent_max =
1507 ed_metrics.echo_likelihood_recent_max;
1508 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001509 }
1510
Per Åhgren19775cb2021-03-12 23:08:09 +00001511 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001512 if (submodules_.echo_controller) {
1513 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1514 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1515 capture_.stats.echo_return_loss_enhancement =
1516 ec_metrics.echo_return_loss_enhancement;
1517 capture_.stats.delay_ms = ec_metrics.delay_ms;
1518 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001519
1520 // Pass stats for reporting.
1521 stats_reporter_.UpdateStatistics(capture_.stats);
1522
Alessio Bazzica533e4612022-09-07 16:58:33 +02001523 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001524 if (capture_.recommended_input_volume.has_value()) {
1525 recommended_input_volume_stats_reporter_.UpdateStatistics(
1526 *capture_.recommended_input_volume);
1527 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001528
Per Åhgrendb5d7282021-03-15 16:31:04 +00001529 if (submodules_.capture_levels_adjuster) {
1530 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1531 *capture_buffer);
1532
Per Åhgrendb5d7282021-03-15 16:31:04 +00001533 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001534 // If the input volume emulation is used, retrieve the recommended input
1535 // volume and set that to emulate the input volume on the next processed
1536 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001537 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001538 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001539 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001540 }
1541 }
1542
Per Åhgren55bc0772021-03-12 14:18:36 +00001543 // Temporarily set the output to zero after the stream has been unmuted
1544 // (capture output is again used). The purpose of this is to avoid clicks and
1545 // artefacts in the audio that results when the processing again is
1546 // reactivated after unmuting.
1547 if (!capture_.capture_output_used_last_frame &&
1548 capture_.capture_output_used) {
1549 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1550 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1551 capture_buffer->num_frames());
1552 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1553 }
1554 }
1555 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1556
peahdf3efa82015-11-28 12:35:15 -08001557 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001558
Alessio Bazzica533e4612022-09-07 16:58:33 +02001559 data_dumper_->DumpRaw("recommended_input_volume",
1560 capture_.recommended_input_volume.value_or(
1561 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001562
niklase@google.com470e71d2011-07-07 08:21:25 +00001563 return kNoError;
1564}
1565
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001566int AudioProcessingImpl::AnalyzeReverseStream(
1567 const float* const* data,
1568 const StreamConfig& reverse_config) {
1569 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001570 MutexLock lock(&mutex_render_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001571 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1572 RTC_DCHECK(data);
1573 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1574 RTC_DCHECK(data[i]);
1575 }
1576 RETURN_ON_ERR(
1577 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1578
1579 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001580 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1581}
1582
peahde65ddc2016-09-16 15:02:15 -07001583int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1584 const StreamConfig& input_config,
1585 const StreamConfig& output_config,
1586 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001587 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001588 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001589 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001590 RETURN_ON_ERR(
1591 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1592
1593 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001594
peahde65ddc2016-09-16 15:02:15 -07001595 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001596
Alex Loiko5825aa62017-12-18 16:02:40 +01001597 if (submodule_states_.RenderMultiBandProcessingActive() ||
1598 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001599 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1600 dest);
peah2ace3f92016-09-10 04:42:27 -07001601 } else if (formats_.api_format.reverse_input_stream() !=
1602 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001603 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1604 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001605 } else {
peahde65ddc2016-09-16 15:02:15 -07001606 CopyAudioIfNeeded(src, input_config.num_frames(),
1607 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001608 }
1609
1610 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001611}
1612
peahdf3efa82015-11-28 12:35:15 -08001613int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001614 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001615 const StreamConfig& input_config,
1616 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001617 if (aec_dump_) {
1618 const size_t channel_size =
1619 formats_.api_format.reverse_input_stream().num_frames();
1620 const size_t num_channels =
1621 formats_.api_format.reverse_input_stream().num_channels();
1622 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001623 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001624 }
peahdf3efa82015-11-28 12:35:15 -08001625 render_.render_audio->CopyFrom(src,
1626 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001627 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001628}
1629
Per Åhgren645f24c2020-03-16 12:06:02 +01001630int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1631 const StreamConfig& input_config,
1632 const StreamConfig& output_config,
1633 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001634 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001635
Markus Handell0df0fae2020-07-07 15:53:34 +02001636 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001637 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1638
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001639 RETURN_ON_ERR(
1640 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1641 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001642
aleloi868f32f2017-05-23 07:20:05 -07001643 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001644 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1645 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001646 }
1647
Per Åhgren645f24c2020-03-16 12:06:02 +01001648 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001649 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001650 if (submodule_states_.RenderMultiBandProcessingActive() ||
1651 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001652 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001653 }
aluebsb0319552016-03-17 20:39:53 -07001654 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001655}
niklase@google.com470e71d2011-07-07 08:21:25 +00001656
peahde65ddc2016-09-16 15:02:15 -07001657int AudioProcessingImpl::ProcessRenderStreamLocked() {
1658 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001659
Alex Loiko73ec0192018-05-15 10:52:28 +02001660 HandleRenderRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001661 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alex Loiko73ec0192018-05-15 10:52:28 +02001662
saza1d600522019-10-18 13:29:43 +02001663 if (submodules_.render_pre_processor) {
1664 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001665 }
1666
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001667 QueueNonbandedRenderAudio(render_buffer);
1668
peah2ace3f92016-09-10 04:42:27 -07001669 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001670 SampleRateSupportsMultiBand(
1671 formats_.render_processing_format.sample_rate_hz())) {
1672 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001673 }
1674
peahce4d9152017-05-19 01:28:05 -07001675 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1676 QueueBandedRenderAudio(render_buffer);
1677 }
1678
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001679 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001680 if (submodules_.echo_controller) {
1681 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001682 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001683
peah2ace3f92016-09-10 04:42:27 -07001684 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001685 SampleRateSupportsMultiBand(
1686 formats_.render_processing_format.sample_rate_hz())) {
1687 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001688 }
1689
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001690 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001691}
1692
1693int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001694 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001695 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001696 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001697
niklase@google.com470e71d2011-07-07 08:21:25 +00001698 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001699 delay = 0;
1700 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001701 }
1702
1703 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1704 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001705 delay = 500;
1706 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001707 }
1708
peahdf3efa82015-11-28 12:35:15 -08001709 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001710 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001711}
1712
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001713bool AudioProcessingImpl::GetLinearAecOutput(
1714 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001715 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001716 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1717
1718 RTC_DCHECK(linear_aec_buffer);
1719 if (linear_aec_buffer) {
1720 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1721 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1722
1723 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1724 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1725 rtc::ArrayView<const float> channel_view =
1726 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1727 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001728 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1729 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001730 }
1731 return true;
1732 }
1733 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001734 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001735 return false;
1736}
1737
niklase@google.com470e71d2011-07-07 08:21:25 +00001738int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001739 // Used as callback from submodules, hence locking is not allowed.
1740 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001741}
1742
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001743void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001744 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001745 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001746}
1747
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001748void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001749 MutexLock lock_capture(&mutex_capture_);
1750 set_stream_analog_level_locked(level);
1751}
1752
1753void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001754 capture_.applied_input_volume_changed =
1755 capture_.applied_input_volume.has_value() &&
1756 *capture_.applied_input_volume != level;
1757 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001758
Alessio Bazzica533e4612022-09-07 16:58:33 +02001759 // Invalidate any previously recommended input volume which will be updated by
1760 // `ProcessStream()`.
1761 capture_.recommended_input_volume = absl::nullopt;
1762
Per Åhgren0e3198e2019-11-18 08:52:22 +01001763 if (submodules_.agc_manager) {
1764 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001765 return;
1766 }
1767
1768 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001769 int error = submodules_.gain_control->set_stream_analog_level(level);
1770 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001771 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001772 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001773}
1774
1775int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001776 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001777 if (!capture_.applied_input_volume.has_value()) {
1778 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
1779 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001780 // Input volume to recommend when `set_stream_analog_level()` is not called.
1781 constexpr int kFallBackInputVolume = 255;
1782 // When APM has no input volume to recommend, return the latest applied input
1783 // volume that has been observed in order to possibly produce no input volume
1784 // change. If no applied input volume has been observed, return a fall-back
1785 // value.
1786 return capture_.recommended_input_volume.value_or(
1787 capture_.applied_input_volume.value_or(kFallBackInputVolume));
1788}
1789
1790void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
1791 if (!capture_.applied_input_volume.has_value()) {
1792 // When `set_stream_analog_level()` is not called, no input level can be
1793 // recommended.
1794 capture_.recommended_input_volume = absl::nullopt;
1795 return;
1796 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001797
Per Åhgrendb5d7282021-03-15 16:31:04 +00001798 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001799 capture_.recommended_input_volume =
1800 submodules_.agc_manager->recommended_analog_level();
1801 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001802 }
1803
1804 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001805 capture_.recommended_input_volume =
1806 submodules_.gain_control->stream_analog_level();
1807 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001808 }
1809
Alessio Bazzica533e4612022-09-07 16:58:33 +02001810 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001811}
1812
Ali Tofigh1fa87c42022-07-25 22:07:08 +02001813bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
1814 int64_t max_log_size_bytes,
1815 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02001816 std::unique_ptr<AecDump> aec_dump =
1817 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02001818 if (!aec_dump) {
1819 return false;
1820 }
1821
1822 AttachAecDump(std::move(aec_dump));
1823 return true;
1824}
1825
1826bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
1827 int64_t max_log_size_bytes,
1828 rtc::TaskQueue* worker_queue) {
1829 std::unique_ptr<AecDump> aec_dump =
1830 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
1831 if (!aec_dump) {
1832 return false;
1833 }
1834
1835 AttachAecDump(std::move(aec_dump));
1836 return true;
1837}
1838
aleloi868f32f2017-05-23 07:20:05 -07001839void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1840 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02001841 MutexLock lock_render(&mutex_render_);
1842 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07001843
1844 // The previously attached AecDump will be destroyed with the
1845 // 'aec_dump' parameter, which is after locks are released.
1846 aec_dump_.swap(aec_dump);
1847 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001848 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001849}
1850
1851void AudioProcessingImpl::DetachAecDump() {
1852 // The d-tor of a task-queue based AecDump blocks until all pending
1853 // tasks are done. This construction avoids blocking while holding
1854 // the render and capture locks.
1855 std::unique_ptr<AecDump> aec_dump = nullptr;
1856 {
Markus Handell0df0fae2020-07-07 15:53:34 +02001857 MutexLock lock_render(&mutex_render_);
1858 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07001859 aec_dump = std::move(aec_dump_);
1860 }
1861}
1862
peah8271d042016-11-22 07:24:52 -08001863AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001864 MutexLock lock_render(&mutex_render_);
1865 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08001866 return config_;
1867}
1868
peah2ace3f92016-09-10 04:42:27 -07001869bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1870 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001871 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001872 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02001873 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00001874 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
1875 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00001876 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001877}
1878
Per Åhgrenc0734712020-01-02 15:15:36 +01001879void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02001880 if (config_.transient_suppression.enabled &&
1881 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02001882 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01001883 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001884 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02001885 submodule_creation_overrides_, transient_suppressor_vad_mode_,
1886 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1887 num_proc_channels());
1888 if (!submodules_.transient_suppressor) {
1889 RTC_LOG(LS_WARNING)
1890 << "No transient suppressor created (probably disabled)";
1891 }
1892 } else {
sazaaa42ecd2020-04-01 15:24:40 +02001893 submodules_.transient_suppressor->Initialize(
1894 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1895 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02001896 }
Per Åhgrenc0734712020-01-02 15:15:36 +01001897 } else {
1898 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001899 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001900}
1901
Per Åhgren0f14db22020-01-03 14:27:14 +01001902void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01001903 bool high_pass_filter_needed_by_aec =
1904 config_.echo_canceller.enabled &&
1905 config_.echo_canceller.enforce_high_pass_filtering &&
1906 !config_.echo_canceller.mobile_mode;
1907 if (submodule_states_.HighPassFilteringRequired() ||
1908 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001909 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1910 !constants_.enforce_split_band_hpf;
1911 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1912 : proc_split_sample_rate_hz();
1913 size_t num_channels =
1914 use_full_band ? num_output_channels() : num_proc_channels();
1915
Per Åhgren0f14db22020-01-03 14:27:14 +01001916 if (!submodules_.high_pass_filter ||
1917 rate != submodules_.high_pass_filter->sample_rate_hz() ||
1918 forced_reset ||
1919 num_channels != submodules_.high_pass_filter->num_channels()) {
1920 submodules_.high_pass_filter.reset(
1921 new HighPassFilter(rate, num_channels));
1922 }
peah8271d042016-11-22 07:24:52 -08001923 } else {
saza1d600522019-10-18 13:29:43 +02001924 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001925 }
1926}
alessiob3ec96df2017-05-22 06:57:06 -07001927
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001928void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001929 bool use_echo_controller =
1930 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001931 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001932
1933 if (use_echo_controller) {
1934 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001935 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001936 submodules_.echo_controller = echo_control_factory_->Create(
1937 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001938 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001939 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02001940 EchoCanceller3Config config;
1941 absl::optional<EchoCanceller3Config> multichannel_config;
1942 if (use_setup_specific_default_aec3_config_) {
1943 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
1944 }
saza1d600522019-10-18 13:29:43 +02001945 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02001946 config, multichannel_config, proc_sample_rate_hz(),
1947 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001948 }
1949
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001950 // Setup the storage for returning the linear AEC output.
1951 if (config_.echo_canceller.export_linear_aec_output) {
1952 constexpr int kLinearOutputRateHz = 16000;
1953 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1954 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1955 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1956 } else {
1957 capture_.linear_aec_output.reset();
1958 }
1959
Per Åhgren200feba2019-03-06 04:16:46 +01001960 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001961
saza1d600522019-10-18 13:29:43 +02001962 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001963 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001964 return;
peahe0eae3c2016-12-14 01:16:23 -08001965 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001966
saza1d600522019-10-18 13:29:43 +02001967 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001968 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001969 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001970
1971 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001972 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001973 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001974 return;
1975 }
1976
1977 if (config_.echo_canceller.mobile_mode) {
1978 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001979 size_t max_element_size =
1980 std::max(static_cast<size_t>(1),
1981 kMaxAllowedValuesOfSamplesPerBand *
1982 EchoControlMobileImpl::NumCancellersRequired(
1983 num_output_channels(), num_reverse_channels()));
1984
1985 std::vector<int16_t> template_queue_element(max_element_size);
1986
1987 aecm_render_signal_queue_.reset(
1988 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1989 kMaxNumFramesToBuffer, template_queue_element,
1990 RenderQueueItemVerifier<int16_t>(max_element_size)));
1991
1992 aecm_render_queue_buffer_.resize(max_element_size);
1993 aecm_capture_queue_buffer_.resize(max_element_size);
1994
saza1d600522019-10-18 13:29:43 +02001995 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001996
saza1d600522019-10-18 13:29:43 +02001997 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
1998 num_reverse_channels(),
1999 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002000 return;
2001 }
2002
saza1d600522019-10-18 13:29:43 +02002003 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002004 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002005}
peah8271d042016-11-22 07:24:52 -08002006
Per Åhgren0695df12020-01-13 14:43:13 +01002007void AudioProcessingImpl::InitializeGainController1() {
2008 if (!config_.gain_controller1.enabled) {
2009 submodules_.agc_manager.reset();
2010 submodules_.gain_control.reset();
2011 return;
2012 }
2013
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002014 RTC_HISTOGRAM_BOOLEAN(
2015 "WebRTC.Audio.GainController.Analog.Enabled",
2016 config_.gain_controller1.analog_gain_controller.enabled);
2017
Per Åhgren0695df12020-01-13 14:43:13 +01002018 if (!submodules_.gain_control) {
2019 submodules_.gain_control.reset(new GainControlImpl());
2020 }
2021
2022 submodules_.gain_control->Initialize(num_proc_channels(),
2023 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002024 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2025 int error = submodules_.gain_control->set_mode(
2026 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2027 RTC_DCHECK_EQ(kNoError, error);
2028 error = submodules_.gain_control->set_target_level_dbfs(
2029 config_.gain_controller1.target_level_dbfs);
2030 RTC_DCHECK_EQ(kNoError, error);
2031 error = submodules_.gain_control->set_compression_gain_db(
2032 config_.gain_controller1.compression_gain_db);
2033 RTC_DCHECK_EQ(kNoError, error);
2034 error = submodules_.gain_control->enable_limiter(
2035 config_.gain_controller1.enable_limiter);
2036 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002037 constexpr int kAnalogLevelMinimum = 0;
2038 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002039 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002040 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002041 RTC_DCHECK_EQ(kNoError, error);
2042
2043 submodules_.agc_manager.reset();
2044 return;
2045 }
2046
2047 if (!submodules_.agc_manager.get() ||
2048 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002049 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002050 int stream_analog_level = -1;
2051 const bool re_creation = !!submodules_.agc_manager;
2052 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002053 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002054 }
2055 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002056 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002057 if (re_creation) {
2058 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2059 }
2060 }
2061 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002062 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002063 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2064 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002065}
2066
Alessio Bazzica38901042021-10-14 12:14:21 +02002067void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2068 if (!config_has_changed) {
2069 return;
2070 }
2071 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002072 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002073 return;
2074 }
2075 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002076 const bool use_internal_vad =
2077 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica38901042021-10-14 12:14:21 +02002078 submodules_.gain_controller2 = std::make_unique<GainController2>(
2079 config_.gain_controller2, proc_fullband_sample_rate_hz(),
Hanna Silen0c1ad292022-06-16 16:35:45 +02002080 num_input_channels(), use_internal_vad);
2081 }
2082}
2083
2084void AudioProcessingImpl::InitializeVoiceActivityDetector(
2085 bool config_has_changed) {
2086 if (!config_has_changed) {
2087 return;
2088 }
2089 const bool use_vad =
2090 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2091 config_.gain_controller2.enabled &&
2092 config_.gain_controller2.adaptive_digital.enabled;
2093 if (!use_vad) {
2094 submodules_.voice_activity_detector.reset();
2095 return;
2096 }
2097 if (!submodules_.voice_activity_detector || config_has_changed) {
2098 RTC_DCHECK(!!submodules_.gain_controller2);
2099 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2100 submodules_.voice_activity_detector =
2101 std::make_unique<VoiceActivityDetectorWrapper>(
2102 config_.gain_controller2.adaptive_digital.vad_reset_period_ms,
2103 submodules_.gain_controller2->GetCpuFeatures(),
2104 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002105 }
2106}
2107
saza0bad15f2019-10-16 11:46:11 +02002108void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002109 submodules_.noise_suppressor.reset();
2110
saza0bad15f2019-10-16 11:46:11 +02002111 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002112 auto map_level =
2113 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2114 using NoiseSuppresionConfig =
2115 AudioProcessing::Config::NoiseSuppression;
2116 switch (level) {
2117 case NoiseSuppresionConfig::kLow:
2118 return NsConfig::SuppressionLevel::k6dB;
2119 case NoiseSuppresionConfig::kModerate:
2120 return NsConfig::SuppressionLevel::k12dB;
2121 case NoiseSuppresionConfig::kHigh:
2122 return NsConfig::SuppressionLevel::k18dB;
2123 case NoiseSuppresionConfig::kVeryHigh:
2124 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002125 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002126 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002127 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002128
sazaaa42ecd2020-04-01 15:24:40 +02002129 NsConfig cfg;
2130 cfg.target_level = map_level(config_.noise_suppression.level);
2131 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2132 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002133 }
2134}
2135
Per Åhgrendb5d7282021-03-15 16:31:04 +00002136void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2137 if (config_.pre_amplifier.enabled ||
2138 config_.capture_level_adjustment.enabled) {
2139 // Use both the pre-amplifier and the capture level adjustment gains as
2140 // pre-gains.
2141 float pre_gain = 1.f;
2142 if (config_.pre_amplifier.enabled) {
2143 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2144 }
2145 if (config_.capture_level_adjustment.enabled) {
2146 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2147 }
2148
2149 submodules_.capture_levels_adjuster =
2150 std::make_unique<CaptureLevelsAdjuster>(
2151 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2152 config_.capture_level_adjustment.analog_mic_gain_emulation
2153 .initial_level,
2154 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002155 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002156 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002157 }
2158}
2159
ivoc9f4a4a02016-10-28 05:39:16 -07002160void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002161 if (submodules_.echo_detector) {
2162 submodules_.echo_detector->Initialize(
2163 proc_fullband_sample_rate_hz(), 1,
2164 formats_.render_processing_format.sample_rate_hz(), 1);
2165 }
ivoc9f4a4a02016-10-28 05:39:16 -07002166}
2167
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002168void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002169 if (submodules_.capture_analyzer) {
2170 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2171 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002172 }
2173}
2174
Sam Zackrisson0beac582017-09-25 12:04:02 +02002175void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002176 if (submodules_.capture_post_processor) {
2177 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002178 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002179 }
2180}
2181
Alex Loiko5825aa62017-12-18 16:02:40 +01002182void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002183 if (submodules_.render_pre_processor) {
2184 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002185 formats_.render_processing_format.sample_rate_hz(),
2186 formats_.render_processing_format.num_channels());
2187 }
2188}
2189
aleloi868f32f2017-05-23 07:20:05 -07002190void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2191 if (!aec_dump_) {
2192 return;
2193 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002194
2195 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002196 // TODO(peah): Add semicolon-separated concatenations of experiment
2197 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002198 if (!!submodules_.capture_post_processor) {
2199 experiments_description += "CapturePostProcessor;";
2200 }
2201 if (!!submodules_.render_pre_processor) {
2202 experiments_description += "RenderPreProcessor;";
2203 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002204 if (capture_nonlocked_.echo_controller_enabled) {
2205 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002206 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002207 if (config_.gain_controller2.enabled) {
2208 experiments_description += "GainController2;";
2209 }
aleloi868f32f2017-05-23 07:20:05 -07002210
2211 InternalAPMConfig apm_config;
2212
Per Åhgren200feba2019-03-06 04:16:46 +01002213 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002214 apm_config.aec_delay_agnostic_enabled = false;
2215 apm_config.aec_extended_filter_enabled = false;
2216 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002217
saza1d600522019-10-18 13:29:43 +02002218 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002219 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002220 submodules_.echo_control_mobile &&
2221 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002222 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002223 submodules_.echo_control_mobile
2224 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002225 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002226
Per Åhgren0695df12020-01-13 14:43:13 +01002227 apm_config.agc_enabled = !!submodules_.gain_control;
2228
2229 apm_config.agc_mode = submodules_.gain_control
2230 ? static_cast<int>(submodules_.gain_control->mode())
2231 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002232 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002233 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2234 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002235 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002236
2237 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2238
saza0bad15f2019-10-16 11:46:11 +02002239 apm_config.ns_enabled = config_.noise_suppression.enabled;
2240 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002241
2242 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002243 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002244 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002245 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2246 apm_config.pre_amplifier_fixed_gain_factor =
2247 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002248
2249 if (!forced && apm_config == apm_config_for_aec_dump_) {
2250 return;
2251 }
2252 aec_dump_->WriteConfig(apm_config);
2253 apm_config_for_aec_dump_ = apm_config;
2254}
2255
2256void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2257 const float* const* src) {
2258 RTC_DCHECK(aec_dump_);
2259 WriteAecDumpConfigMessage(false);
2260
2261 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2262 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2263 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002264 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002265 RecordAudioProcessingState();
2266}
2267
2268void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002269 const int16_t* const data,
2270 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002271 RTC_DCHECK(aec_dump_);
2272 WriteAecDumpConfigMessage(false);
2273
Per Åhgren645f24c2020-03-16 12:06:02 +01002274 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2275 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002276 RecordAudioProcessingState();
2277}
2278
2279void AudioProcessingImpl::RecordProcessedCaptureStream(
2280 const float* const* processed_capture_stream) {
2281 RTC_DCHECK(aec_dump_);
2282
2283 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2284 const size_t num_channels =
2285 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002286 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2287 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002288 aec_dump_->WriteCaptureStreamMessage();
2289}
2290
2291void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002292 const int16_t* const data,
2293 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002294 RTC_DCHECK(aec_dump_);
2295
Per Åhgren645f24c2020-03-16 12:06:02 +01002296 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002297 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002298 aec_dump_->WriteCaptureStreamMessage();
2299}
2300
2301void AudioProcessingImpl::RecordAudioProcessingState() {
2302 RTC_DCHECK(aec_dump_);
2303 AecDump::AudioProcessingState audio_proc_state;
2304 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002305 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002306 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002307 audio_proc_state.keypress = capture_.key_pressed;
2308 aec_dump_->AddAudioProcessingState(audio_proc_state);
2309}
2310
Per Åhgrenc0734712020-01-02 15:15:36 +01002311AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002312 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002313 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002314 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002315 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002316 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002317 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002318 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002319 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002320 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002321 prev_playout_volume(-1),
2322 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002323
2324AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2325
2326AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2327
2328AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2329
Per Åhgrencf4c8722019-12-30 14:32:14 +01002330AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2331 : stats_message_queue_(1) {}
2332
2333AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2334
2335AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002336 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002337 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2338 // If the message queue is full, return the cached stats.
2339 static_cast<void>(new_stats_available);
2340
2341 return cached_stats_;
2342}
2343
2344void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2345 const AudioProcessingStats& new_stats) {
2346 AudioProcessingStats stats_to_queue = new_stats;
2347 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2348 // If the message queue is full, discard the new stats.
2349 static_cast<void>(stats_message_passed);
2350}
2351
niklase@google.com470e71d2011-07-07 08:21:25 +00002352} // namespace webrtc