blob: 6dba8d7e635bd2d6c12c4115e08e358cd1e491dd [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
Sam Zackrisson06cba442022-11-21 16:32:42 +0100204 if (input_validity == AudioFormatValidity::kValidAndSupported &&
205 output_validity == AudioFormatValidity::kValidAndSupported &&
206 (output_config.num_channels() == 1 ||
207 output_config.num_channels() == input_config.num_channels())) {
208 return {AudioProcessing::kNoError, FormatErrorOutputOption::kDoNothing};
209 }
210
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100211 int error_code = AudioFormatValidityToErrorCode(input_validity);
212 if (error_code == AudioProcessing::kNoError) {
213 error_code = AudioFormatValidityToErrorCode(output_validity);
214 }
Sam Zackrisson06cba442022-11-21 16:32:42 +0100215 if (error_code == AudioProcessing::kNoError) {
216 // The individual formats are valid but there is some error - must be
217 // channel mismatch.
218 error_code = AudioProcessing::kBadNumberChannelsError;
219 }
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100220
221 FormatErrorOutputOption output_option;
222 if (output_validity != AudioFormatValidity::kValidAndSupported &&
223 output_validity != AudioFormatValidity::kValidButUnsupportedSampleRate) {
224 // The output format is uninterpretable: cannot do anything.
225 output_option = FormatErrorOutputOption::kDoNothing;
226 } else if (input_validity != AudioFormatValidity::kValidAndSupported &&
227 input_validity !=
228 AudioFormatValidity::kValidButUnsupportedSampleRate) {
229 // The input format is uninterpretable: cannot use it, must output silence.
230 output_option = FormatErrorOutputOption::kOutputSilence;
231 } else if (input_config.sample_rate_hz() != output_config.sample_rate_hz()) {
232 // Sample rates do not match: Cannot copy input into output, output silence.
233 // Note: If the sample rates are in a supported range, we could resample.
234 // However, that would significantly increase complexity of this error
235 // handling code.
236 output_option = FormatErrorOutputOption::kOutputSilence;
237 } else if (input_config.num_channels() != output_config.num_channels()) {
238 // Channel counts do not match: We cannot easily map input channels to
239 // output channels.
240 output_option =
241 FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel;
242 } else {
243 // The formats match exactly.
244 RTC_DCHECK(input_config == output_config);
245 output_option = FormatErrorOutputOption::kOutputExactCopyOfInput;
246 }
247 return std::make_pair(error_code, output_option);
248}
249
250// Checks if the audio format is supported. If not, the output is populated in a
251// best-effort manner and an APM error code is returned.
252int HandleUnsupportedAudioFormats(const int16_t* const src,
253 const StreamConfig& input_config,
254 const StreamConfig& output_config,
255 int16_t* const dest) {
256 RTC_DCHECK(src);
257 RTC_DCHECK(dest);
258
259 auto [error_code, output_option] =
260 ChooseErrorOutputOption(input_config, output_config);
261 if (error_code == AudioProcessing::kNoError)
262 return AudioProcessing::kNoError;
263
264 const size_t num_output_channels = output_config.num_channels();
265 switch (output_option) {
266 case FormatErrorOutputOption::kOutputSilence:
267 memset(dest, 0, output_config.num_samples() * sizeof(int16_t));
268 break;
269 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
270 for (size_t i = 0; i < output_config.num_frames(); ++i) {
271 int16_t sample = src[input_config.num_channels() * i];
272 for (size_t ch = 0; ch < num_output_channels; ++ch) {
273 dest[ch + num_output_channels * i] = sample;
274 }
275 }
276 break;
277 case FormatErrorOutputOption::kOutputExactCopyOfInput:
278 memcpy(dest, src, output_config.num_samples() * sizeof(int16_t));
279 break;
280 case FormatErrorOutputOption::kDoNothing:
281 break;
282 }
283 return error_code;
284}
285
286// Checks if the audio format is supported. If not, the output is populated in a
287// best-effort manner and an APM error code is returned.
288int HandleUnsupportedAudioFormats(const float* const* src,
289 const StreamConfig& input_config,
290 const StreamConfig& output_config,
291 float* const* dest) {
292 RTC_DCHECK(src);
293 RTC_DCHECK(dest);
294 for (size_t i = 0; i < input_config.num_channels(); ++i) {
295 RTC_DCHECK(src[i]);
296 }
297 for (size_t i = 0; i < output_config.num_channels(); ++i) {
298 RTC_DCHECK(dest[i]);
299 }
300
301 auto [error_code, output_option] =
302 ChooseErrorOutputOption(input_config, output_config);
303 if (error_code == AudioProcessing::kNoError)
304 return AudioProcessing::kNoError;
305
306 const size_t num_output_channels = output_config.num_channels();
307 switch (output_option) {
308 case FormatErrorOutputOption::kOutputSilence:
309 for (size_t ch = 0; ch < num_output_channels; ++ch) {
310 memset(dest[ch], 0, output_config.num_frames() * sizeof(float));
311 }
312 break;
313 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
314 for (size_t ch = 0; ch < num_output_channels; ++ch) {
315 memcpy(dest[ch], src[0], output_config.num_frames() * sizeof(float));
316 }
317 break;
318 case FormatErrorOutputOption::kOutputExactCopyOfInput:
319 for (size_t ch = 0; ch < num_output_channels; ++ch) {
320 memcpy(dest[ch], src[ch], output_config.num_frames() * sizeof(float));
321 }
322 break;
323 case FormatErrorOutputOption::kDoNothing:
324 break;
325 }
326 return error_code;
327}
328
Michael Graczyk86c6d332015-07-23 11:41:39 -0700329} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000330
331// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000332static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000333
saza1d600522019-10-18 13:29:43 +0200334AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100335 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200336 bool render_pre_processor_enabled,
337 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100338 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200339 render_pre_processor_enabled_(render_pre_processor_enabled),
340 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700341
saza1d600522019-10-18 13:29:43 +0200342bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200343 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700344 bool mobile_echo_controller_enabled,
345 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700346 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700347 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200348 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000349 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200350 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700351 bool transient_suppressor_enabled) {
352 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200353 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700354 changed |=
355 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
356 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
357 changed |=
peah2ace3f92016-09-10 04:42:27 -0700358 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200359 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200360 changed |=
361 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000362 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200363 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700364 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
365 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200366 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700367 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
368 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700369 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700370 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200371 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000372 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200373 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700374 transient_suppressor_enabled_ = transient_suppressor_enabled;
375 }
376
377 changed |= first_update_;
378 first_update_ = false;
379 return changed;
380}
381
saza1d600522019-10-18 13:29:43 +0200382bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700383 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000384 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700385}
386
saza1d600522019-10-18 13:29:43 +0200387bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
388 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200389 // If echo controller is present, assume it performs active processing.
390 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
391}
392
saza1d600522019-10-18 13:29:43 +0200393bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200394 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100395 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
396 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200397 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700398}
399
saza1d600522019-10-18 13:29:43 +0200400bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700401 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200402 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000403 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700404}
405
saza1d600522019-10-18 13:29:43 +0200406bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200407 return capture_analyzer_enabled_;
408}
409
saza1d600522019-10-18 13:29:43 +0200410bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700411 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100412 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
413 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700414}
415
saza1d600522019-10-18 13:29:43 +0200416bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100417 const {
418 return render_pre_processor_enabled_;
419}
420
saza1d600522019-10-18 13:29:43 +0200421bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700422 const {
peah2ace3f92016-09-10 04:42:27 -0700423 return false;
peah2ace3f92016-09-10 04:42:27 -0700424}
425
saza1d600522019-10-18 13:29:43 +0200426bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100427 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
428 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200429}
430
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200431AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200432 : AudioProcessingImpl(/*config=*/{},
433 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200434 /*render_pre_processor=*/nullptr,
435 /*echo_control_factory=*/nullptr,
436 /*echo_detector=*/nullptr,
437 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000438
Niels Möller7a669002022-06-27 09:47:02 +0200439std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100440
Sam Zackrisson0beac582017-09-25 12:04:02 +0200441AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200442 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100443 std::unique_ptr<CustomProcessing> capture_post_processor,
444 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200445 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200446 rtc::scoped_refptr<EchoDetector> echo_detector,
447 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200448 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100449 use_setup_specific_default_aec3_config_(
450 UseSetupSpecificDefaultAec3Congfig()),
Alessio Bazzica0441bb62021-08-10 15:23:23 +0200451 use_denormal_disabler_(
452 !field_trial::IsEnabled("WebRTC-ApmDenormalDisablerKillSwitch")),
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +0100453 transient_suppressor_vad_mode_(GetTransientSuppressorVadMode()),
Per Åhgren652ada52021-03-03 10:52:44 +0000454 capture_runtime_settings_(RuntimeSettingQueueSize()),
455 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200456 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
457 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200458 echo_control_factory_(std::move(echo_control_factory)),
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200459 config_(config),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200460 submodule_states_(!!capture_post_processor,
461 !!render_pre_processor,
462 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200463 submodules_(std::move(capture_post_processor),
464 std::move(render_pre_processor),
465 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100466 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100467 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200468 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
469 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100470 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000471 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200472 MinimizeProcessingForUnusedOutput(),
473 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000474 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200475 capture_nonlocked_(),
476 applied_input_volume_stats_reporter_(
477 InputVolumeStatsReporter::InputVolumeType::kApplied),
478 recommended_input_volume_stats_reporter_(
479 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200480 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100481 "\nEcho control factory: "
482 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200483 << "\nEcho detector: " << !!submodules_.echo_detector
484 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
485 << "\nCapture post processor: "
486 << !!submodules_.capture_post_processor
487 << "\nRender pre processor: "
488 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100489 if (!DenormalDisabler::IsSupported()) {
490 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
491 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200492
Sam Zackrisson421c8592019-02-11 13:39:46 +0100493 // Mark Echo Controller enabled if a factory is injected.
494 capture_nonlocked_.echo_controller_enabled =
495 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000496
Per Åhgren0ade9832020-09-01 23:57:20 +0200497 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000498}
499
Per Åhgren0e3198e2019-11-18 08:52:22 +0100500AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000501
niklase@google.com470e71d2011-07-07 08:21:25 +0000502int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800503 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200504 MutexLock lock_render(&mutex_render_);
505 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200506 InitializeLocked();
507 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000508}
509
Michael Graczyk86c6d332015-07-23 11:41:39 -0700510int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800511 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200512 MutexLock lock_render(&mutex_render_);
513 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100514 InitializeLocked(processing_config);
515 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000516}
517
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100518void AudioProcessingImpl::MaybeInitializeRender(
519 const StreamConfig& input_config,
520 const StreamConfig& output_config) {
521 ProcessingConfig processing_config = formats_.api_format;
522 processing_config.reverse_input_stream() = input_config;
523 processing_config.reverse_output_stream() = output_config;
524
Oskar Sundbom4b276482019-05-23 14:28:00 +0200525 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100526 return;
peah192164e2015-11-17 02:16:45 -0800527 }
peahdf3efa82015-11-28 12:35:15 -0800528
Markus Handell0df0fae2020-07-07 15:53:34 +0200529 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100530 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800531}
532
Per Åhgren0ade9832020-09-01 23:57:20 +0200533void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200534 UpdateActiveSubmoduleStates();
535
Per Åhgrend47941e2019-08-22 11:51:13 +0200536 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800537 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200538 ? formats_.render_processing_format.sample_rate_hz()
539 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800540 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
541 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200542 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800543 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200544 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700545 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200546 render_audiobuffer_sample_rate_hz,
547 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700548 if (formats_.api_format.reverse_input_stream() !=
549 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800550 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800551 formats_.api_format.reverse_input_stream().num_channels(),
552 formats_.api_format.reverse_input_stream().num_frames(),
553 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800554 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700555 } else {
peahdf3efa82015-11-28 12:35:15 -0800556 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700557 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700558 } else {
peahdf3efa82015-11-28 12:35:15 -0800559 render_.render_audio.reset(nullptr);
560 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700561 }
peahce4d9152017-05-19 01:28:05 -0700562
Per Åhgrend47941e2019-08-22 11:51:13 +0200563 capture_.capture_audio.reset(new AudioBuffer(
564 formats_.api_format.input_stream().sample_rate_hz(),
565 formats_.api_format.input_stream().num_channels(),
566 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
567 formats_.api_format.output_stream().num_channels(),
568 formats_.api_format.output_stream().sample_rate_hz(),
569 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000570
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200571 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
572 formats_.api_format.output_stream().sample_rate_hz() &&
573 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
574 capture_.capture_fullband_audio.reset(
575 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
576 formats_.api_format.input_stream().num_channels(),
577 formats_.api_format.output_stream().sample_rate_hz(),
578 formats_.api_format.output_stream().num_channels(),
579 formats_.api_format.output_stream().sample_rate_hz(),
580 formats_.api_format.output_stream().num_channels()));
581 } else {
582 capture_.capture_fullband_audio.reset();
583 }
584
peah764e3642016-10-22 05:04:30 -0700585 AllocateRenderQueue();
586
Per Åhgren0695df12020-01-13 14:43:13 +0100587 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100588 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100589 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700590 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200591 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200592 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200593 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200594 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200595 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200596 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100597 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000598 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800599
aleloi868f32f2017-05-23 07:20:05 -0700600 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200601 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700602 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000603}
604
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100605void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200606 UpdateActiveSubmoduleStates();
607
peahdf3efa82015-11-28 12:35:15 -0800608 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000609
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200610 // Choose maximum rate to use for the split filtering.
611 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
612 config_.pipeline.maximum_internal_processing_rate == 32000);
613 int max_splitting_rate = 48000;
614 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
615 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
616 }
617
Per Åhgrenc8626b62019-08-23 15:49:51 +0200618 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700619 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700620 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200621 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700622 submodule_states_.CaptureMultiBandSubModulesActive() ||
623 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200624 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000625
peahde65ddc2016-09-16 15:02:15 -0700626 capture_nonlocked_.capture_processing_format =
627 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700628
peah2ce640f2017-04-07 03:57:48 -0700629 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200630 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200631 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700632 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
633 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200634 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700635 submodule_states_.CaptureMultiBandSubModulesActive() ||
636 submodule_states_.RenderMultiBandSubModulesActive());
637 } else {
638 render_processing_rate = capture_processing_rate;
639 }
640
peahde65ddc2016-09-16 15:02:15 -0700641 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700642 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700643 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
644 kSampleRate8kHz) {
645 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000646 } else {
peahde65ddc2016-09-16 15:02:15 -0700647 render_processing_rate =
648 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000649 }
650
Per Åhgrenc8626b62019-08-23 15:49:51 +0200651 RTC_DCHECK_NE(8000, render_processing_rate);
652
peahce4d9152017-05-19 01:28:05 -0700653 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200654 // By default, downmix the render stream to mono for analysis. This has been
655 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100656 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
657 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200658 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100659 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200660 ? formats_.api_format.reverse_input_stream().num_channels()
661 : 1;
662 formats_.render_processing_format =
663 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700664 } else {
665 formats_.render_processing_format = StreamConfig(
666 formats_.api_format.reverse_input_stream().sample_rate_hz(),
667 formats_.api_format.reverse_input_stream().num_channels());
668 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000669
peahde65ddc2016-09-16 15:02:15 -0700670 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
671 kSampleRate32kHz ||
672 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
673 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800674 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000675 } else {
peahdf3efa82015-11-28 12:35:15 -0800676 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700677 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000678 }
679
Per Åhgren0ade9832020-09-01 23:57:20 +0200680 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000681}
682
peah88ac8532016-09-12 16:47:25 -0700683void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200684 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: " << config.ToString();
685
peah88ac8532016-09-12 16:47:25 -0700686 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200687 MutexLock lock_render(&mutex_render_);
688 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700689
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200690 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100691 config_.pipeline.multi_channel_render !=
692 config.pipeline.multi_channel_render ||
693 config_.pipeline.multi_channel_capture !=
Per Åhgrenc0424252019-12-10 13:04:15 +0100694 config.pipeline.multi_channel_capture ||
695 config_.pipeline.maximum_internal_processing_rate !=
696 config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200697
Per Åhgren200feba2019-03-06 04:16:46 +0100698 const bool aec_config_changed =
699 config_.echo_canceller.enabled != config.echo_canceller.enabled ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100700 config_.echo_canceller.mobile_mode != config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100701
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100702 const bool agc1_config_changed =
Alessio Bazzica3438a932020-10-14 12:47:50 +0200703 config_.gain_controller1 != config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100704
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100705 const bool agc2_config_changed =
Alessio Bazzica3438a932020-10-14 12:47:50 +0200706 config_.gain_controller2 != config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100707
saza0bad15f2019-10-16 11:46:11 +0200708 const bool ns_config_changed =
709 config_.noise_suppression.enabled != config.noise_suppression.enabled ||
710 config_.noise_suppression.level != config.noise_suppression.level;
711
Per Åhgrenc0734712020-01-02 15:15:36 +0100712 const bool ts_config_changed = config_.transient_suppression.enabled !=
713 config.transient_suppression.enabled;
714
Per Åhgren0f14db22020-01-03 14:27:14 +0100715 const bool pre_amplifier_config_changed =
716 config_.pre_amplifier.enabled != config.pre_amplifier.enabled ||
717 config_.pre_amplifier.fixed_gain_factor !=
718 config.pre_amplifier.fixed_gain_factor;
719
Per Åhgrendb5d7282021-03-15 16:31:04 +0000720 const bool gain_adjustment_config_changed =
721 config_.capture_level_adjustment != config.capture_level_adjustment;
722
Yves Gerey499bc6c2018-10-10 18:29:07 +0200723 config_ = config;
724
Per Åhgren200feba2019-03-06 04:16:46 +0100725 if (aec_config_changed) {
726 InitializeEchoController();
727 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200728
saza0bad15f2019-10-16 11:46:11 +0200729 if (ns_config_changed) {
730 InitializeNoiseSuppressor();
731 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100732
Per Åhgrenc0734712020-01-02 15:15:36 +0100733 if (ts_config_changed) {
734 InitializeTransientSuppressor();
735 }
736
Per Åhgren0f14db22020-01-03 14:27:14 +0100737 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800738
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100739 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100740 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100741 }
742
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100743 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700744 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200745 RTC_LOG(LS_ERROR)
746 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700747 config_.gain_controller2 = AudioProcessing::Config::GainController2();
748 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100749
Alessio Bazzica38901042021-10-14 12:14:21 +0200750 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200751 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100752
Per Åhgrendb5d7282021-03-15 16:31:04 +0000753 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
754 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100755 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100756
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200757 // Reinitialization must happen after all submodule configuration to avoid
758 // additional reinitializations on the next capture / render processing call.
759 if (pipeline_config_changed) {
760 InitializeLocked(formats_.api_format);
761 }
peah88ac8532016-09-12 16:47:25 -0700762}
763
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200764void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
765 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200766 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200767 submodule_creation_overrides_ = overrides;
768}
769
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000770int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800771 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700772 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000773}
774
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200775int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
776 return capture_.capture_fullband_audio
777 ? capture_.capture_fullband_audio->num_frames() * 100
778 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
779}
780
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000781int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800782 // Used as callback from submodules, hence locking is not allowed.
783 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000784}
785
Peter Kasting69558702016-01-12 16:26:35 -0800786size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800787 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700788 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000789}
790
Peter Kasting69558702016-01-12 16:26:35 -0800791size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800792 // Used as callback from submodules, hence locking is not allowed.
793 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000794}
795
Peter Kasting69558702016-01-12 16:26:35 -0800796size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800797 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100798 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
799 constants_.multi_channel_capture_support;
800 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200801 return 1;
802 }
803 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800804}
805
Peter Kasting69558702016-01-12 16:26:35 -0800806size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800807 // Used as callback from submodules, hence locking is not allowed.
808 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000809}
810
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000811void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200812 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +0100813 HandleCaptureOutputUsedSetting(!muted);
814}
815
816void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
817 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +0000818 capture_.capture_output_used =
819 capture_output_used || !constants_.minimize_processing_for_unused_output;
820
saza1d600522019-10-18 13:29:43 +0200821 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100822 submodules_.agc_manager->HandleCaptureOutputUsedChange(
823 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000824 }
Per Åhgren652ada52021-03-03 10:52:44 +0000825 if (submodules_.echo_controller) {
826 submodules_.echo_controller->SetCaptureOutputUsage(
827 capture_.capture_output_used);
828 }
Per Åhgren15179a92021-03-12 14:12:44 +0000829 if (submodules_.noise_suppressor) {
830 submodules_.noise_suppressor->SetCaptureOutputUsage(
831 capture_.capture_output_used);
832 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000833}
834
Alessio Bazzicac054e782018-04-16 12:10:09 +0200835void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100836 PostRuntimeSetting(setting);
837}
838
839bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200840 switch (setting.type()) {
841 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100842 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +0100843 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200844 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +0000845 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100846 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200847 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +0200848 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +0100849 return capture_runtime_settings_enqueuer_.Enqueue(setting);
850 case RuntimeSetting::Type::kPlayoutVolumeChange: {
851 bool enqueueing_successful;
852 enqueueing_successful =
853 capture_runtime_settings_enqueuer_.Enqueue(setting);
854 enqueueing_successful =
855 render_runtime_settings_enqueuer_.Enqueue(setting) &&
856 enqueueing_successful;
857 return enqueueing_successful;
858 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100859 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +0100860 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +0100861 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +0200862 }
863 // The language allows the enum to have a non-enumerator
864 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +0100865 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +0100866 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +0200867}
868
869AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
870 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200871 : runtime_settings_(*runtime_settings) {
872 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200873}
874
875AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
876 default;
877
Per Åhgren0a144a72021-02-09 08:47:51 +0100878bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +0200879 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +0000880 const bool successful_insert = runtime_settings_.Insert(&setting);
881
882 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200883 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +0200884 }
Per Åhgren652ada52021-03-03 10:52:44 +0000885 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +0200886}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000887
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100888void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100889 const StreamConfig& input_config,
890 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -0800891 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700892 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800893 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100894 // Acquire the capture lock in order to access api_format. The lock is
895 // released immediately, as we may need to acquire the render lock as part
896 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200897 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -0800898 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700899 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000900 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000901
Oskar Sundbom4b276482019-05-23 14:28:00 +0200902 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200903 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -0800904 }
Oskar Sundbom4b276482019-05-23 14:28:00 +0200905
906 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +0200907 reinitialization_required = true;
908 }
909
910 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200911 MutexLock lock_render(&mutex_render_);
912 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +0200913 // Reread the API format since the render format may have changed.
914 processing_config = formats_.api_format;
915 processing_config.input_stream() = input_config;
916 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100917 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +0200918 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +0100919}
920
921int AudioProcessingImpl::ProcessStream(const float* const* src,
922 const StreamConfig& input_config,
923 const StreamConfig& output_config,
924 float* const* dest) {
925 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100926 DenormalDisabler denormal_disabler(use_denormal_disabler_);
927 RETURN_ON_ERR(
928 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
929 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +0200930
Markus Handell0df0fae2020-07-07 15:53:34 +0200931 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000932
aleloi868f32f2017-05-23 07:20:05 -0700933 if (aec_dump_) {
934 RecordUnprocessedCaptureStream(src);
935 }
936
peahdf3efa82015-11-28 12:35:15 -0800937 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200938 if (capture_.capture_fullband_audio) {
939 capture_.capture_fullband_audio->CopyFrom(
940 src, formats_.api_format.input_stream());
941 }
peahde65ddc2016-09-16 15:02:15 -0700942 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200943 if (capture_.capture_fullband_audio) {
944 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
945 dest);
946 } else {
947 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
948 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000949
aleloi868f32f2017-05-23 07:20:05 -0700950 if (aec_dump_) {
951 RecordProcessedCaptureStream(dest);
952 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000953 return kNoError;
954}
955
Alex Loiko73ec0192018-05-15 10:52:28 +0200956void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200957 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +0000958 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +0200959 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200960 if (aec_dump_) {
961 aec_dump_->WriteRuntimeSetting(setting);
962 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200963 switch (setting.type()) {
964 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +0000965 if (config_.pre_amplifier.enabled ||
966 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +0200967 float value;
968 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000969 // If the pre-amplifier is used, apply the new gain to the
970 // pre-amplifier regardless if the capture level adjustment is
971 // activated. This approach allows both functionalities to coexist
972 // until they have been properly merged.
973 if (config_.pre_amplifier.enabled) {
974 config_.pre_amplifier.fixed_gain_factor = value;
975 } else {
976 config_.capture_level_adjustment.pre_gain_factor = value;
977 }
978
979 // Use both the pre-amplifier and the capture level adjustment gains
980 // as pre-gains.
981 float gain = 1.f;
982 if (config_.pre_amplifier.enabled) {
983 gain *= config_.pre_amplifier.fixed_gain_factor;
984 }
985 if (config_.capture_level_adjustment.enabled) {
986 gain *= config_.capture_level_adjustment.pre_gain_factor;
987 }
988
989 submodules_.capture_levels_adjuster->SetPreGain(gain);
990 }
991 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
992 break;
993 case RuntimeSetting::Type::kCapturePostGain:
994 if (config_.capture_level_adjustment.enabled) {
995 float value;
996 setting.GetFloat(&value);
997 config_.capture_level_adjustment.post_gain_factor = value;
998 submodules_.capture_levels_adjuster->SetPostGain(
999 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001000 }
1001 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001002 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001003 case RuntimeSetting::Type::kCaptureCompressionGain: {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001004 if (!submodules_.agc_manager) {
1005 float value;
1006 setting.GetFloat(&value);
1007 int int_value = static_cast<int>(value + .5f);
1008 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001009 if (submodules_.gain_control) {
1010 int error =
1011 submodules_.gain_control->set_compression_gain_db(int_value);
1012 RTC_DCHECK_EQ(kNoError, error);
1013 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001014 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001015 break;
1016 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001017 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001018 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001019 float value;
1020 setting.GetFloat(&value);
1021 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001022 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001023 }
1024 break;
1025 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001026 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1027 int value;
1028 setting.GetInt(&value);
1029 capture_.playout_volume = value;
1030 break;
1031 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001032 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001033 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001034 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001035 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001036 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001037 break;
1038 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001039 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001040 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001041 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001042 bool value;
1043 setting.GetBool(&value);
1044 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001045 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001046 }
Per Åhgren652ada52021-03-03 10:52:44 +00001047 ++num_settings_processed;
1048 }
1049
1050 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1051 // Handle overrun of the runtime settings queue, which likely will has
1052 // caused settings to be discarded.
1053 HandleOverrunInCaptureRuntimeSettingsQueue();
1054 }
1055}
1056
1057void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1058 // Fall back to a safe state for the case when a setting for capture output
1059 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001060 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001061}
1062
1063void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1064 RuntimeSetting setting;
1065 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001066 if (aec_dump_) {
1067 aec_dump_->WriteRuntimeSetting(setting);
1068 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001069 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001070 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001071 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001072 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001073 if (submodules_.render_pre_processor) {
1074 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001075 }
1076 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001077 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001078 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001079 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001080 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001081 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001082 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001083 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001084 break;
1085 }
1086 }
1087}
1088
peah9e6a2902017-05-15 07:19:21 -07001089void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001090 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001091
saza1d600522019-10-18 13:29:43 +02001092 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001093 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1094 num_reverse_channels(),
1095 &aecm_render_queue_buffer_);
1096 RTC_DCHECK(aecm_render_signal_queue_);
1097 // Insert the samples into the queue.
1098 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1099 // The data queue is full and needs to be emptied.
1100 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001101
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001102 // Retry the insert (should always work).
1103 bool result =
1104 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1105 RTC_DCHECK(result);
1106 }
peah764e3642016-10-22 05:04:30 -07001107 }
peah701d6282016-10-25 05:42:20 -07001108
Per Åhgren0695df12020-01-13 14:43:13 +01001109 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001110 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001111 // Insert the samples into the queue.
1112 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1113 // The data queue is full and needs to be emptied.
1114 EmptyQueuedRenderAudio();
1115
1116 // Retry the insert (should always work).
1117 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1118 RTC_DCHECK(result);
1119 }
1120 }
peah9e6a2902017-05-15 07:19:21 -07001121}
ivoc9f4a4a02016-10-28 05:39:16 -07001122
peah9e6a2902017-05-15 07:19:21 -07001123void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001124 if (submodules_.echo_detector) {
1125 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1126 RTC_DCHECK(red_render_signal_queue_);
1127 // Insert the samples into the queue.
1128 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1129 // The data queue is full and needs to be emptied.
1130 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001131
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001132 // Retry the insert (should always work).
1133 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1134 RTC_DCHECK(result);
1135 }
ivoc9f4a4a02016-10-28 05:39:16 -07001136 }
peah764e3642016-10-22 05:04:30 -07001137}
1138
1139void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001140 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001141 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001142
ivoc9f4a4a02016-10-28 05:39:16 -07001143 const size_t new_red_render_queue_element_max_size =
1144 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1145
peaha0624602016-10-25 04:45:24 -07001146 // Reallocate the queues if the queue item sizes are too small to fit the
1147 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001148
1149 if (agc_render_queue_element_max_size_ <
1150 new_agc_render_queue_element_max_size) {
1151 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1152
1153 std::vector<int16_t> template_queue_element(
1154 agc_render_queue_element_max_size_);
1155
1156 agc_render_signal_queue_.reset(
1157 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1158 kMaxNumFramesToBuffer, template_queue_element,
1159 RenderQueueItemVerifier<int16_t>(
1160 agc_render_queue_element_max_size_)));
1161
1162 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1163 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1164 } else {
1165 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001166 }
ivoc9f4a4a02016-10-28 05:39:16 -07001167
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001168 if (submodules_.echo_detector) {
1169 if (red_render_queue_element_max_size_ <
1170 new_red_render_queue_element_max_size) {
1171 red_render_queue_element_max_size_ =
1172 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001173
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001174 std::vector<float> template_queue_element(
1175 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001176
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001177 red_render_signal_queue_.reset(
1178 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1179 kMaxNumFramesToBuffer, template_queue_element,
1180 RenderQueueItemVerifier<float>(
1181 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001182
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001183 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1184 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1185 } else {
1186 red_render_signal_queue_->Clear();
1187 }
ivoc9f4a4a02016-10-28 05:39:16 -07001188 }
peah764e3642016-10-22 05:04:30 -07001189}
1190
1191void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001192 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001193 EmptyQueuedRenderAudioLocked();
1194}
1195
1196void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001197 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001198 RTC_DCHECK(aecm_render_signal_queue_);
1199 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001200 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001201 aecm_capture_queue_buffer_);
1202 }
peah701d6282016-10-25 05:42:20 -07001203 }
1204
Per Åhgren0695df12020-01-13 14:43:13 +01001205 if (submodules_.gain_control) {
1206 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1207 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1208 }
peah764e3642016-10-22 05:04:30 -07001209 }
ivoc9f4a4a02016-10-28 05:39:16 -07001210
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001211 if (submodules_.echo_detector) {
1212 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1213 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1214 }
ivoc9f4a4a02016-10-28 05:39:16 -07001215 }
peah764e3642016-10-22 05:04:30 -07001216}
1217
Per Åhgren645f24c2020-03-16 12:06:02 +01001218int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1219 const StreamConfig& input_config,
1220 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001221 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001222 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001223
1224 RETURN_ON_ERR(
1225 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1226 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001227
Markus Handell0df0fae2020-07-07 15:53:34 +02001228 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001229 DenormalDisabler denormal_disabler(use_denormal_disabler_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001230
aleloi868f32f2017-05-23 07:20:05 -07001231 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001232 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001233 }
1234
Per Åhgren645f24c2020-03-16 12:06:02 +01001235 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001236 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001237 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001238 }
peahde65ddc2016-09-16 15:02:15 -07001239 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001240 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001241 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001242 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001243 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001244 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001245 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001246 }
Per Åhgrena1351272019-08-15 12:15:46 +02001247 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001248
aleloi868f32f2017-05-23 07:20:05 -07001249 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001250 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001251 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001252 return kNoError;
1253}
1254
peahde65ddc2016-09-16 15:02:15 -07001255int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001256 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001257 HandleCaptureRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001258 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001259
peahb58a1582016-03-15 09:34:24 -07001260 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001261 // TODO(peah): Simplify once the public API Enable functions for these
1262 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001263 RTC_DCHECK_LE(
1264 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001265
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001266 data_dumper_->DumpRaw(
1267 "applied_input_volume",
1268 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1269
peahde65ddc2016-09-16 15:02:15 -07001270 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001271 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001272
Per Åhgrenc0424252019-12-10 13:04:15 +01001273 if (submodules_.high_pass_filter &&
1274 config_.high_pass_filter.apply_in_full_band &&
1275 !constants_.enforce_split_band_hpf) {
1276 submodules_.high_pass_filter->Process(capture_buffer,
1277 /*use_split_band_data=*/false);
1278 }
1279
Per Åhgrendb5d7282021-03-15 16:31:04 +00001280 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001281 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001282 // When the input volume is emulated, retrieve the volume applied to the
1283 // input audio and notify that to APM so that the volume is passed to the
1284 // active AGC.
1285 set_stream_analog_level_locked(
1286 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001287 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001288 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1289 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001290 }
1291
Per Åhgren928146f2019-08-20 09:19:21 +02001292 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001293 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001294 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001295 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1296 if (log_rms) {
1297 capture_rms_interval_counter_ = 0;
1298 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001299 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1300 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1301 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1302 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001303 }
1304
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001305 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001306 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001307 *capture_.applied_input_volume);
1308 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001309
saza1d600522019-10-18 13:29:43 +02001310 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001311 // Determine if the echo path gain has changed by checking all the gains
1312 // applied before AEC.
1313 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001314
Per Åhgrendb5d7282021-03-15 16:31:04 +00001315 // Detect and flag any change in the capture level adjustment pre-gain.
1316 if (submodules_.capture_levels_adjuster) {
1317 float pre_adjustment_gain =
1318 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001319 capture_.echo_path_gain_change =
1320 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001321 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001322 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001323 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001324 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001325
1326 // Detect volume change.
1327 capture_.echo_path_gain_change =
1328 capture_.echo_path_gain_change ||
1329 (capture_.prev_playout_volume != capture_.playout_volume &&
1330 capture_.prev_playout_volume >= 0);
1331 capture_.prev_playout_volume = capture_.playout_volume;
1332
saza1d600522019-10-18 13:29:43 +02001333 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001334 }
1335
Per Åhgren0695df12020-01-13 14:43:13 +01001336 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001337 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001338 }
1339
peah2ace3f92016-09-10 04:42:27 -07001340 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1341 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001342 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1343 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001344 }
1345
Per Åhgrene14cb992019-11-27 09:34:22 +01001346 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1347 constants_.multi_channel_capture_support;
1348 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001349 // Force down-mixing of the number of channels after the detection of
1350 // capture signal saturation.
1351 // TODO(peah): Look into ensuring that this kind of tampering with the
1352 // AudioBuffer functionality should not be needed.
1353 capture_buffer->set_num_channels(1);
1354 }
1355
Per Åhgrenc0424252019-12-10 13:04:15 +01001356 if (submodules_.high_pass_filter &&
1357 (!config_.high_pass_filter.apply_in_full_band ||
1358 constants_.enforce_split_band_hpf)) {
1359 submodules_.high_pass_filter->Process(capture_buffer,
1360 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001361 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001362
Per Åhgren0695df12020-01-13 14:43:13 +01001363 if (submodules_.gain_control) {
1364 RETURN_ON_ERR(
1365 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1366 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001367
Per Åhgren8ad9e742020-01-30 07:40:58 +01001368 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1369 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1370 submodules_.noise_suppressor) {
1371 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001372 }
peahb58a1582016-03-15 09:34:24 -07001373
saza1d600522019-10-18 13:29:43 +02001374 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001375 // Ensure that the stream delay was set before the call to the
1376 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001377 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001378 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001379 }
1380
saza1d600522019-10-18 13:29:43 +02001381 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001382 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001383 }
peahe0eae3c2016-12-14 01:16:23 -08001384
saza1d600522019-10-18 13:29:43 +02001385 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001386 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001387 } else {
saza1d600522019-10-18 13:29:43 +02001388 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001389 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1390
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001391 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001392 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001393 }
1394
saza1d600522019-10-18 13:29:43 +02001395 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001396 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001397 }
1398
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001399 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001400 linear_aec_buffer && submodules_.noise_suppressor) {
1401 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001402 }
1403
saza1d600522019-10-18 13:29:43 +02001404 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001405 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001406 }
Per Åhgren46537a32017-06-07 10:08:10 +02001407 }
ivoc9f4a4a02016-10-28 05:39:16 -07001408
Per Åhgren0695df12020-01-13 14:43:13 +01001409 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001410 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001411
1412 absl::optional<int> new_digital_gain =
1413 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001414 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001415 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1416 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001417 }
Per Åhgren0695df12020-01-13 14:43:13 +01001418
1419 if (submodules_.gain_control) {
1420 // TODO(peah): Add reporting from AEC3 whether there is echo.
1421 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1422 capture_buffer, /*stream_has_echo*/ false));
1423 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001424
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001425 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1426 SampleRateSupportsMultiBand(
1427 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1428 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001429 }
1430
Per Åhgren19775cb2021-03-12 23:08:09 +00001431 if (capture_.capture_output_used) {
1432 if (capture_.capture_fullband_audio) {
1433 const auto& ec = submodules_.echo_controller;
1434 bool ec_active = ec ? ec->ActiveProcessing() : false;
1435 // Only update the fullband buffer if the multiband processing has changed
1436 // the signal. Keep the original signal otherwise.
1437 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1438 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1439 }
1440 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001441 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001442
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001443 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001444 submodules_.echo_detector->AnalyzeCaptureAudio(
1445 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1446 capture_buffer->num_frames()));
1447 }
1448
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001449 absl::optional<float> voice_probability;
1450 if (!!submodules_.voice_activity_detector) {
1451 voice_probability = submodules_.voice_activity_detector->Analyze(
1452 AudioFrameView<const float>(capture_buffer->channels(),
1453 capture_buffer->num_channels(),
1454 capture_buffer->num_frames()));
1455 }
1456
Per Åhgren19775cb2021-03-12 23:08:09 +00001457 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001458 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001459 switch (transient_suppressor_vad_mode_) {
1460 case TransientSuppressor::VadMode::kDefault:
1461 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001462 transient_suppressor_voice_probability =
1463 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001464 }
1465 break;
1466 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001467 RTC_DCHECK(voice_probability.has_value());
1468 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001469 break;
1470 case TransientSuppressor::VadMode::kNoVad:
1471 // The transient suppressor will ignore `voice_probability`.
1472 break;
1473 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001474 float delayed_voice_probability =
1475 submodules_.transient_suppressor->Suppress(
1476 capture_buffer->channels()[0], capture_buffer->num_frames(),
1477 capture_buffer->num_channels(),
1478 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1479 capture_buffer->num_frames_per_band(),
1480 /*reference_data=*/nullptr, /*reference_length=*/0,
1481 transient_suppressor_voice_probability, capture_.key_pressed);
1482 if (voice_probability.has_value()) {
1483 *voice_probability = delayed_voice_probability;
1484 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001485 }
1486
Artem Titov0b489302021-07-28 20:50:03 +02001487 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001488 if (submodules_.capture_analyzer) {
1489 submodules_.capture_analyzer->Analyze(capture_buffer);
1490 }
1491
1492 if (submodules_.gain_controller2) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001493 submodules_.gain_controller2->Process(
1494 voice_probability, capture_.applied_input_volume_changed,
1495 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001496 }
1497
1498 if (submodules_.capture_post_processor) {
1499 submodules_.capture_post_processor->Process(capture_buffer);
1500 }
1501
Per Åhgren19775cb2021-03-12 23:08:09 +00001502 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1503 capture_buffer->channels_const()[0],
1504 capture_nonlocked_.capture_processing_format.num_frames()));
1505 if (log_rms) {
1506 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1507 RTC_HISTOGRAM_COUNTS_LINEAR(
1508 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1509 RmsLevel::kMinLevelDb, 64);
1510 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1511 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1512 }
1513
Per Åhgren19775cb2021-03-12 23:08:09 +00001514 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001515 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001516 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1517 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1518 capture_.stats.residual_echo_likelihood_recent_max =
1519 ed_metrics.echo_likelihood_recent_max;
1520 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001521 }
1522
Per Åhgren19775cb2021-03-12 23:08:09 +00001523 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001524 if (submodules_.echo_controller) {
1525 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1526 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1527 capture_.stats.echo_return_loss_enhancement =
1528 ec_metrics.echo_return_loss_enhancement;
1529 capture_.stats.delay_ms = ec_metrics.delay_ms;
1530 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001531
1532 // Pass stats for reporting.
1533 stats_reporter_.UpdateStatistics(capture_.stats);
1534
Alessio Bazzica533e4612022-09-07 16:58:33 +02001535 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001536 if (capture_.recommended_input_volume.has_value()) {
1537 recommended_input_volume_stats_reporter_.UpdateStatistics(
1538 *capture_.recommended_input_volume);
1539 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001540
Per Åhgrendb5d7282021-03-15 16:31:04 +00001541 if (submodules_.capture_levels_adjuster) {
1542 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1543 *capture_buffer);
1544
Per Åhgrendb5d7282021-03-15 16:31:04 +00001545 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001546 // If the input volume emulation is used, retrieve the recommended input
1547 // volume and set that to emulate the input volume on the next processed
1548 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001549 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001550 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001551 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001552 }
1553 }
1554
Per Åhgren55bc0772021-03-12 14:18:36 +00001555 // Temporarily set the output to zero after the stream has been unmuted
1556 // (capture output is again used). The purpose of this is to avoid clicks and
1557 // artefacts in the audio that results when the processing again is
1558 // reactivated after unmuting.
1559 if (!capture_.capture_output_used_last_frame &&
1560 capture_.capture_output_used) {
1561 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1562 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1563 capture_buffer->num_frames());
1564 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1565 }
1566 }
1567 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1568
peahdf3efa82015-11-28 12:35:15 -08001569 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001570
Alessio Bazzica533e4612022-09-07 16:58:33 +02001571 data_dumper_->DumpRaw("recommended_input_volume",
1572 capture_.recommended_input_volume.value_or(
1573 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001574
niklase@google.com470e71d2011-07-07 08:21:25 +00001575 return kNoError;
1576}
1577
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001578int AudioProcessingImpl::AnalyzeReverseStream(
1579 const float* const* data,
1580 const StreamConfig& reverse_config) {
1581 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001582 MutexLock lock(&mutex_render_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001583 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1584 RTC_DCHECK(data);
1585 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1586 RTC_DCHECK(data[i]);
1587 }
1588 RETURN_ON_ERR(
1589 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1590
1591 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001592 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1593}
1594
peahde65ddc2016-09-16 15:02:15 -07001595int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1596 const StreamConfig& input_config,
1597 const StreamConfig& output_config,
1598 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001599 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001600 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001601 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001602 RETURN_ON_ERR(
1603 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1604
1605 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001606
peahde65ddc2016-09-16 15:02:15 -07001607 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001608
Alex Loiko5825aa62017-12-18 16:02:40 +01001609 if (submodule_states_.RenderMultiBandProcessingActive() ||
1610 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001611 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1612 dest);
peah2ace3f92016-09-10 04:42:27 -07001613 } else if (formats_.api_format.reverse_input_stream() !=
1614 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001615 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1616 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001617 } else {
peahde65ddc2016-09-16 15:02:15 -07001618 CopyAudioIfNeeded(src, input_config.num_frames(),
1619 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001620 }
1621
1622 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001623}
1624
peahdf3efa82015-11-28 12:35:15 -08001625int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001626 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001627 const StreamConfig& input_config,
1628 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001629 if (aec_dump_) {
1630 const size_t channel_size =
1631 formats_.api_format.reverse_input_stream().num_frames();
1632 const size_t num_channels =
1633 formats_.api_format.reverse_input_stream().num_channels();
1634 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001635 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001636 }
peahdf3efa82015-11-28 12:35:15 -08001637 render_.render_audio->CopyFrom(src,
1638 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001639 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001640}
1641
Per Åhgren645f24c2020-03-16 12:06:02 +01001642int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1643 const StreamConfig& input_config,
1644 const StreamConfig& output_config,
1645 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001646 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001647
Markus Handell0df0fae2020-07-07 15:53:34 +02001648 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001649 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1650
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001651 RETURN_ON_ERR(
1652 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1653 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001654
aleloi868f32f2017-05-23 07:20:05 -07001655 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001656 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1657 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001658 }
1659
Per Åhgren645f24c2020-03-16 12:06:02 +01001660 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001661 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001662 if (submodule_states_.RenderMultiBandProcessingActive() ||
1663 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001664 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001665 }
aluebsb0319552016-03-17 20:39:53 -07001666 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001667}
niklase@google.com470e71d2011-07-07 08:21:25 +00001668
peahde65ddc2016-09-16 15:02:15 -07001669int AudioProcessingImpl::ProcessRenderStreamLocked() {
1670 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001671
Alex Loiko73ec0192018-05-15 10:52:28 +02001672 HandleRenderRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001673 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alex Loiko73ec0192018-05-15 10:52:28 +02001674
saza1d600522019-10-18 13:29:43 +02001675 if (submodules_.render_pre_processor) {
1676 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001677 }
1678
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001679 QueueNonbandedRenderAudio(render_buffer);
1680
peah2ace3f92016-09-10 04:42:27 -07001681 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001682 SampleRateSupportsMultiBand(
1683 formats_.render_processing_format.sample_rate_hz())) {
1684 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001685 }
1686
peahce4d9152017-05-19 01:28:05 -07001687 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1688 QueueBandedRenderAudio(render_buffer);
1689 }
1690
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001691 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001692 if (submodules_.echo_controller) {
1693 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001694 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001695
peah2ace3f92016-09-10 04:42:27 -07001696 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001697 SampleRateSupportsMultiBand(
1698 formats_.render_processing_format.sample_rate_hz())) {
1699 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001700 }
1701
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001702 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001703}
1704
1705int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001706 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001707 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001708 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001709
niklase@google.com470e71d2011-07-07 08:21:25 +00001710 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001711 delay = 0;
1712 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001713 }
1714
1715 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1716 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001717 delay = 500;
1718 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001719 }
1720
peahdf3efa82015-11-28 12:35:15 -08001721 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001722 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001723}
1724
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001725bool AudioProcessingImpl::GetLinearAecOutput(
1726 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001727 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001728 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1729
1730 RTC_DCHECK(linear_aec_buffer);
1731 if (linear_aec_buffer) {
1732 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1733 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1734
1735 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1736 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1737 rtc::ArrayView<const float> channel_view =
1738 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1739 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001740 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1741 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001742 }
1743 return true;
1744 }
1745 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001746 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001747 return false;
1748}
1749
niklase@google.com470e71d2011-07-07 08:21:25 +00001750int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001751 // Used as callback from submodules, hence locking is not allowed.
1752 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001753}
1754
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001755void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001756 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001757 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001758}
1759
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001760void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001761 MutexLock lock_capture(&mutex_capture_);
1762 set_stream_analog_level_locked(level);
1763}
1764
1765void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001766 capture_.applied_input_volume_changed =
1767 capture_.applied_input_volume.has_value() &&
1768 *capture_.applied_input_volume != level;
1769 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001770
Alessio Bazzica533e4612022-09-07 16:58:33 +02001771 // Invalidate any previously recommended input volume which will be updated by
1772 // `ProcessStream()`.
1773 capture_.recommended_input_volume = absl::nullopt;
1774
Per Åhgren0e3198e2019-11-18 08:52:22 +01001775 if (submodules_.agc_manager) {
1776 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001777 return;
1778 }
1779
1780 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001781 int error = submodules_.gain_control->set_stream_analog_level(level);
1782 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001783 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001784 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001785}
1786
1787int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001788 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001789 if (!capture_.applied_input_volume.has_value()) {
1790 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
1791 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001792 // Input volume to recommend when `set_stream_analog_level()` is not called.
1793 constexpr int kFallBackInputVolume = 255;
1794 // When APM has no input volume to recommend, return the latest applied input
1795 // volume that has been observed in order to possibly produce no input volume
1796 // change. If no applied input volume has been observed, return a fall-back
1797 // value.
1798 return capture_.recommended_input_volume.value_or(
1799 capture_.applied_input_volume.value_or(kFallBackInputVolume));
1800}
1801
1802void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
1803 if (!capture_.applied_input_volume.has_value()) {
1804 // When `set_stream_analog_level()` is not called, no input level can be
1805 // recommended.
1806 capture_.recommended_input_volume = absl::nullopt;
1807 return;
1808 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001809
Per Åhgrendb5d7282021-03-15 16:31:04 +00001810 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001811 capture_.recommended_input_volume =
1812 submodules_.agc_manager->recommended_analog_level();
1813 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001814 }
1815
1816 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001817 capture_.recommended_input_volume =
1818 submodules_.gain_control->stream_analog_level();
1819 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001820 }
1821
Alessio Bazzica533e4612022-09-07 16:58:33 +02001822 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001823}
1824
Ali Tofigh1fa87c42022-07-25 22:07:08 +02001825bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
1826 int64_t max_log_size_bytes,
1827 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02001828 std::unique_ptr<AecDump> aec_dump =
1829 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02001830 if (!aec_dump) {
1831 return false;
1832 }
1833
1834 AttachAecDump(std::move(aec_dump));
1835 return true;
1836}
1837
1838bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
1839 int64_t max_log_size_bytes,
1840 rtc::TaskQueue* worker_queue) {
1841 std::unique_ptr<AecDump> aec_dump =
1842 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
1843 if (!aec_dump) {
1844 return false;
1845 }
1846
1847 AttachAecDump(std::move(aec_dump));
1848 return true;
1849}
1850
aleloi868f32f2017-05-23 07:20:05 -07001851void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1852 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02001853 MutexLock lock_render(&mutex_render_);
1854 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07001855
1856 // The previously attached AecDump will be destroyed with the
1857 // 'aec_dump' parameter, which is after locks are released.
1858 aec_dump_.swap(aec_dump);
1859 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001860 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001861}
1862
1863void AudioProcessingImpl::DetachAecDump() {
1864 // The d-tor of a task-queue based AecDump blocks until all pending
1865 // tasks are done. This construction avoids blocking while holding
1866 // the render and capture locks.
1867 std::unique_ptr<AecDump> aec_dump = nullptr;
1868 {
Markus Handell0df0fae2020-07-07 15:53:34 +02001869 MutexLock lock_render(&mutex_render_);
1870 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07001871 aec_dump = std::move(aec_dump_);
1872 }
1873}
1874
peah8271d042016-11-22 07:24:52 -08001875AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001876 MutexLock lock_render(&mutex_render_);
1877 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08001878 return config_;
1879}
1880
peah2ace3f92016-09-10 04:42:27 -07001881bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1882 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001883 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001884 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02001885 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00001886 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
1887 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00001888 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07001889}
1890
Per Åhgrenc0734712020-01-02 15:15:36 +01001891void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02001892 if (config_.transient_suppression.enabled &&
1893 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02001894 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01001895 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001896 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02001897 submodule_creation_overrides_, transient_suppressor_vad_mode_,
1898 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1899 num_proc_channels());
1900 if (!submodules_.transient_suppressor) {
1901 RTC_LOG(LS_WARNING)
1902 << "No transient suppressor created (probably disabled)";
1903 }
1904 } else {
sazaaa42ecd2020-04-01 15:24:40 +02001905 submodules_.transient_suppressor->Initialize(
1906 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
1907 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02001908 }
Per Åhgrenc0734712020-01-02 15:15:36 +01001909 } else {
1910 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001911 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001912}
1913
Per Åhgren0f14db22020-01-03 14:27:14 +01001914void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01001915 bool high_pass_filter_needed_by_aec =
1916 config_.echo_canceller.enabled &&
1917 config_.echo_canceller.enforce_high_pass_filtering &&
1918 !config_.echo_canceller.mobile_mode;
1919 if (submodule_states_.HighPassFilteringRequired() ||
1920 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01001921 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
1922 !constants_.enforce_split_band_hpf;
1923 int rate = use_full_band ? proc_fullband_sample_rate_hz()
1924 : proc_split_sample_rate_hz();
1925 size_t num_channels =
1926 use_full_band ? num_output_channels() : num_proc_channels();
1927
Per Åhgren0f14db22020-01-03 14:27:14 +01001928 if (!submodules_.high_pass_filter ||
1929 rate != submodules_.high_pass_filter->sample_rate_hz() ||
1930 forced_reset ||
1931 num_channels != submodules_.high_pass_filter->num_channels()) {
1932 submodules_.high_pass_filter.reset(
1933 new HighPassFilter(rate, num_channels));
1934 }
peah8271d042016-11-22 07:24:52 -08001935 } else {
saza1d600522019-10-18 13:29:43 +02001936 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08001937 }
1938}
alessiob3ec96df2017-05-22 06:57:06 -07001939
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001940void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001941 bool use_echo_controller =
1942 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01001943 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001944
1945 if (use_echo_controller) {
1946 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01001947 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01001948 submodules_.echo_controller = echo_control_factory_->Create(
1949 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01001950 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01001951 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02001952 EchoCanceller3Config config;
1953 absl::optional<EchoCanceller3Config> multichannel_config;
1954 if (use_setup_specific_default_aec3_config_) {
1955 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
1956 }
saza1d600522019-10-18 13:29:43 +02001957 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02001958 config, multichannel_config, proc_sample_rate_hz(),
1959 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01001960 }
1961
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001962 // Setup the storage for returning the linear AEC output.
1963 if (config_.echo_canceller.export_linear_aec_output) {
1964 constexpr int kLinearOutputRateHz = 16000;
1965 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
1966 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
1967 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
1968 } else {
1969 capture_.linear_aec_output.reset();
1970 }
1971
Per Åhgren200feba2019-03-06 04:16:46 +01001972 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01001973
saza1d600522019-10-18 13:29:43 +02001974 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001975 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001976 return;
peahe0eae3c2016-12-14 01:16:23 -08001977 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02001978
saza1d600522019-10-18 13:29:43 +02001979 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001980 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001981 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001982
1983 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02001984 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001985 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02001986 return;
1987 }
1988
1989 if (config_.echo_canceller.mobile_mode) {
1990 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001991 size_t max_element_size =
1992 std::max(static_cast<size_t>(1),
1993 kMaxAllowedValuesOfSamplesPerBand *
1994 EchoControlMobileImpl::NumCancellersRequired(
1995 num_output_channels(), num_reverse_channels()));
1996
1997 std::vector<int16_t> template_queue_element(max_element_size);
1998
1999 aecm_render_signal_queue_.reset(
2000 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2001 kMaxNumFramesToBuffer, template_queue_element,
2002 RenderQueueItemVerifier<int16_t>(max_element_size)));
2003
2004 aecm_render_queue_buffer_.resize(max_element_size);
2005 aecm_capture_queue_buffer_.resize(max_element_size);
2006
saza1d600522019-10-18 13:29:43 +02002007 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002008
saza1d600522019-10-18 13:29:43 +02002009 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2010 num_reverse_channels(),
2011 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002012 return;
2013 }
2014
saza1d600522019-10-18 13:29:43 +02002015 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002016 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002017}
peah8271d042016-11-22 07:24:52 -08002018
Per Åhgren0695df12020-01-13 14:43:13 +01002019void AudioProcessingImpl::InitializeGainController1() {
2020 if (!config_.gain_controller1.enabled) {
2021 submodules_.agc_manager.reset();
2022 submodules_.gain_control.reset();
2023 return;
2024 }
2025
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002026 RTC_HISTOGRAM_BOOLEAN(
2027 "WebRTC.Audio.GainController.Analog.Enabled",
2028 config_.gain_controller1.analog_gain_controller.enabled);
2029
Per Åhgren0695df12020-01-13 14:43:13 +01002030 if (!submodules_.gain_control) {
2031 submodules_.gain_control.reset(new GainControlImpl());
2032 }
2033
2034 submodules_.gain_control->Initialize(num_proc_channels(),
2035 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002036 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2037 int error = submodules_.gain_control->set_mode(
2038 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2039 RTC_DCHECK_EQ(kNoError, error);
2040 error = submodules_.gain_control->set_target_level_dbfs(
2041 config_.gain_controller1.target_level_dbfs);
2042 RTC_DCHECK_EQ(kNoError, error);
2043 error = submodules_.gain_control->set_compression_gain_db(
2044 config_.gain_controller1.compression_gain_db);
2045 RTC_DCHECK_EQ(kNoError, error);
2046 error = submodules_.gain_control->enable_limiter(
2047 config_.gain_controller1.enable_limiter);
2048 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002049 constexpr int kAnalogLevelMinimum = 0;
2050 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002051 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002052 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002053 RTC_DCHECK_EQ(kNoError, error);
2054
2055 submodules_.agc_manager.reset();
2056 return;
2057 }
2058
2059 if (!submodules_.agc_manager.get() ||
2060 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002061 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002062 int stream_analog_level = -1;
2063 const bool re_creation = !!submodules_.agc_manager;
2064 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002065 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002066 }
2067 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002068 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002069 if (re_creation) {
2070 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2071 }
2072 }
2073 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002074 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002075 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2076 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002077}
2078
Alessio Bazzica38901042021-10-14 12:14:21 +02002079void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2080 if (!config_has_changed) {
2081 return;
2082 }
2083 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002084 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002085 return;
2086 }
2087 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002088 const bool use_internal_vad =
2089 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica38901042021-10-14 12:14:21 +02002090 submodules_.gain_controller2 = std::make_unique<GainController2>(
2091 config_.gain_controller2, proc_fullband_sample_rate_hz(),
Hanna Silen0c1ad292022-06-16 16:35:45 +02002092 num_input_channels(), use_internal_vad);
2093 }
2094}
2095
2096void AudioProcessingImpl::InitializeVoiceActivityDetector(
2097 bool config_has_changed) {
2098 if (!config_has_changed) {
2099 return;
2100 }
2101 const bool use_vad =
2102 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2103 config_.gain_controller2.enabled &&
2104 config_.gain_controller2.adaptive_digital.enabled;
2105 if (!use_vad) {
2106 submodules_.voice_activity_detector.reset();
2107 return;
2108 }
2109 if (!submodules_.voice_activity_detector || config_has_changed) {
2110 RTC_DCHECK(!!submodules_.gain_controller2);
2111 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2112 submodules_.voice_activity_detector =
2113 std::make_unique<VoiceActivityDetectorWrapper>(
2114 config_.gain_controller2.adaptive_digital.vad_reset_period_ms,
2115 submodules_.gain_controller2->GetCpuFeatures(),
2116 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002117 }
2118}
2119
saza0bad15f2019-10-16 11:46:11 +02002120void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002121 submodules_.noise_suppressor.reset();
2122
saza0bad15f2019-10-16 11:46:11 +02002123 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002124 auto map_level =
2125 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2126 using NoiseSuppresionConfig =
2127 AudioProcessing::Config::NoiseSuppression;
2128 switch (level) {
2129 case NoiseSuppresionConfig::kLow:
2130 return NsConfig::SuppressionLevel::k6dB;
2131 case NoiseSuppresionConfig::kModerate:
2132 return NsConfig::SuppressionLevel::k12dB;
2133 case NoiseSuppresionConfig::kHigh:
2134 return NsConfig::SuppressionLevel::k18dB;
2135 case NoiseSuppresionConfig::kVeryHigh:
2136 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002137 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002138 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002139 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002140
sazaaa42ecd2020-04-01 15:24:40 +02002141 NsConfig cfg;
2142 cfg.target_level = map_level(config_.noise_suppression.level);
2143 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2144 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002145 }
2146}
2147
Per Åhgrendb5d7282021-03-15 16:31:04 +00002148void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2149 if (config_.pre_amplifier.enabled ||
2150 config_.capture_level_adjustment.enabled) {
2151 // Use both the pre-amplifier and the capture level adjustment gains as
2152 // pre-gains.
2153 float pre_gain = 1.f;
2154 if (config_.pre_amplifier.enabled) {
2155 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2156 }
2157 if (config_.capture_level_adjustment.enabled) {
2158 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2159 }
2160
2161 submodules_.capture_levels_adjuster =
2162 std::make_unique<CaptureLevelsAdjuster>(
2163 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2164 config_.capture_level_adjustment.analog_mic_gain_emulation
2165 .initial_level,
2166 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002167 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002168 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002169 }
2170}
2171
ivoc9f4a4a02016-10-28 05:39:16 -07002172void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002173 if (submodules_.echo_detector) {
2174 submodules_.echo_detector->Initialize(
2175 proc_fullband_sample_rate_hz(), 1,
2176 formats_.render_processing_format.sample_rate_hz(), 1);
2177 }
ivoc9f4a4a02016-10-28 05:39:16 -07002178}
2179
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002180void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002181 if (submodules_.capture_analyzer) {
2182 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2183 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002184 }
2185}
2186
Sam Zackrisson0beac582017-09-25 12:04:02 +02002187void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002188 if (submodules_.capture_post_processor) {
2189 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002190 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002191 }
2192}
2193
Alex Loiko5825aa62017-12-18 16:02:40 +01002194void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002195 if (submodules_.render_pre_processor) {
2196 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002197 formats_.render_processing_format.sample_rate_hz(),
2198 formats_.render_processing_format.num_channels());
2199 }
2200}
2201
aleloi868f32f2017-05-23 07:20:05 -07002202void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2203 if (!aec_dump_) {
2204 return;
2205 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002206
2207 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002208 // TODO(peah): Add semicolon-separated concatenations of experiment
2209 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002210 if (!!submodules_.capture_post_processor) {
2211 experiments_description += "CapturePostProcessor;";
2212 }
2213 if (!!submodules_.render_pre_processor) {
2214 experiments_description += "RenderPreProcessor;";
2215 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002216 if (capture_nonlocked_.echo_controller_enabled) {
2217 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002218 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002219 if (config_.gain_controller2.enabled) {
2220 experiments_description += "GainController2;";
2221 }
aleloi868f32f2017-05-23 07:20:05 -07002222
2223 InternalAPMConfig apm_config;
2224
Per Åhgren200feba2019-03-06 04:16:46 +01002225 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002226 apm_config.aec_delay_agnostic_enabled = false;
2227 apm_config.aec_extended_filter_enabled = false;
2228 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002229
saza1d600522019-10-18 13:29:43 +02002230 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002231 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002232 submodules_.echo_control_mobile &&
2233 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002234 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002235 submodules_.echo_control_mobile
2236 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002237 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002238
Per Åhgren0695df12020-01-13 14:43:13 +01002239 apm_config.agc_enabled = !!submodules_.gain_control;
2240
2241 apm_config.agc_mode = submodules_.gain_control
2242 ? static_cast<int>(submodules_.gain_control->mode())
2243 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002244 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002245 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2246 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002247 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002248
2249 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2250
saza0bad15f2019-10-16 11:46:11 +02002251 apm_config.ns_enabled = config_.noise_suppression.enabled;
2252 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002253
2254 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002255 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002256 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002257 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2258 apm_config.pre_amplifier_fixed_gain_factor =
2259 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002260
2261 if (!forced && apm_config == apm_config_for_aec_dump_) {
2262 return;
2263 }
2264 aec_dump_->WriteConfig(apm_config);
2265 apm_config_for_aec_dump_ = apm_config;
2266}
2267
2268void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2269 const float* const* src) {
2270 RTC_DCHECK(aec_dump_);
2271 WriteAecDumpConfigMessage(false);
2272
2273 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2274 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2275 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002276 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002277 RecordAudioProcessingState();
2278}
2279
2280void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002281 const int16_t* const data,
2282 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002283 RTC_DCHECK(aec_dump_);
2284 WriteAecDumpConfigMessage(false);
2285
Per Åhgren645f24c2020-03-16 12:06:02 +01002286 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2287 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002288 RecordAudioProcessingState();
2289}
2290
2291void AudioProcessingImpl::RecordProcessedCaptureStream(
2292 const float* const* processed_capture_stream) {
2293 RTC_DCHECK(aec_dump_);
2294
2295 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2296 const size_t num_channels =
2297 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002298 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2299 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002300 aec_dump_->WriteCaptureStreamMessage();
2301}
2302
2303void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002304 const int16_t* const data,
2305 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002306 RTC_DCHECK(aec_dump_);
2307
Per Åhgren645f24c2020-03-16 12:06:02 +01002308 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002309 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002310 aec_dump_->WriteCaptureStreamMessage();
2311}
2312
2313void AudioProcessingImpl::RecordAudioProcessingState() {
2314 RTC_DCHECK(aec_dump_);
2315 AecDump::AudioProcessingState audio_proc_state;
2316 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002317 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002318 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002319 audio_proc_state.keypress = capture_.key_pressed;
2320 aec_dump_->AddAudioProcessingState(audio_proc_state);
2321}
2322
Per Åhgrenc0734712020-01-02 15:15:36 +01002323AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002324 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002325 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002326 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002327 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002328 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002329 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002330 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002331 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002332 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002333 prev_playout_volume(-1),
2334 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002335
2336AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2337
2338AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2339
2340AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2341
Per Åhgrencf4c8722019-12-30 14:32:14 +01002342AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2343 : stats_message_queue_(1) {}
2344
2345AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2346
2347AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002348 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002349 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2350 // If the message queue is full, return the cached stats.
2351 static_cast<void>(new_stats_available);
2352
2353 return cached_stats_;
2354}
2355
2356void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2357 const AudioProcessingStats& new_stats) {
2358 AudioProcessingStats stats_to_queue = new_stats;
2359 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2360 // If the message queue is full, discard the new stats.
2361 static_cast<void>(stats_message_passed);
2362}
2363
niklase@google.com470e71d2011-07-07 08:21:25 +00002364} // namespace webrtc