blob: 2cb48588d8e66110aa5a5373b31b43e348c8b3f3 [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"
Hanna Silena6574902022-11-30 16:59:05 +010034#include "rtc_base/experiments/field_trial_parser.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/trace_event.h"
Alessio Bazzica0441bb62021-08-10 15:23:23 +020038#include "system_wrappers/include/denormal_disabler.h"
Sam Zackrissonfeee1e42019-09-20 07:50:35 +020039#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000041
Michael Graczyk86c6d332015-07-23 11:41:39 -070042#define RETURN_ON_ERR(expr) \
43 do { \
44 int err = (expr); \
45 if (err != kNoError) { \
46 return err; \
47 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000048 } while (0)
49
niklase@google.com470e71d2011-07-07 08:21:25 +000050namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070051
Michael Graczyk86c6d332015-07-23 11:41:39 -070052namespace {
53
peah2ace3f92016-09-10 04:42:27 -070054bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070055 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
56 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
57}
58
Per Åhgrenc0424252019-12-10 13:04:15 +010059// Checks whether the high-pass filter should be done in the full-band.
60bool EnforceSplitBandHpf() {
61 return field_trial::IsEnabled("WebRTC-FullBandHpfKillSwitch");
62}
63
Per Åhgrenb2b58d82019-12-02 14:59:40 +010064// Checks whether AEC3 should be allowed to decide what the default
65// configuration should be based on the render and capture channel configuration
66// at hand.
67bool UseSetupSpecificDefaultAec3Congfig() {
68 return !field_trial::IsEnabled(
69 "WebRTC-Aec3SetupSpecificDefaultConfigDefaultsKillSwitch");
70}
71
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +010072// If the "WebRTC-Audio-TransientSuppressorVadMode" field trial is unspecified,
73// returns `TransientSuppressor::VadMode::kDefault`, otherwise parses the field
74// trial and returns the specified mode:
75// - WebRTC-Audio-TransientSuppressorVadMode/Enabled-Default returns `kDefault`;
76// - WebRTC-Audio-TransientSuppressorVadMode/Enabled-RnnVad returns `kRnnVad`;
77// - WebRTC-Audio-TransientSuppressorVadMode/Enabled-NoVad returns `kNoVad`.
78TransientSuppressor::VadMode GetTransientSuppressorVadMode() {
79 constexpr char kFieldTrial[] = "WebRTC-Audio-TransientSuppressorVadMode";
80 std::string full_name = webrtc::field_trial::FindFullName(kFieldTrial);
81 if (full_name.empty() || absl::EndsWith(full_name, "-Default")) {
82 return TransientSuppressor::VadMode::kDefault;
83 }
84 if (absl::EndsWith(full_name, "-RnnVad")) {
85 return TransientSuppressor::VadMode::kRnnVad;
86 }
87 if (absl::EndsWith(full_name, "-NoVad")) {
88 return TransientSuppressor::VadMode::kNoVad;
89 }
90 // Fallback to default.
91 RTC_LOG(LS_WARNING) << "Invalid parameter for " << kFieldTrial;
92 return TransientSuppressor::VadMode::kDefault;
93}
94
Per Åhgrenc8626b62019-08-23 15:49:51 +020095// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020096int SuitableProcessRate(int minimum_rate,
97 int max_splitting_rate,
98 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020099 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200100 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +0200101 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -0700102 if (rate >= uppermost_native_rate) {
103 return uppermost_native_rate;
104 }
105 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700106 return rate;
107 }
108 }
Artem Titovd3251962021-11-15 16:57:07 +0100109 RTC_DCHECK_NOTREACHED();
peah2ace3f92016-09-10 04:42:27 -0700110 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700111}
112
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100113GainControl::Mode Agc1ConfigModeToInterfaceMode(
114 AudioProcessing::Config::GainController1::Mode mode) {
115 using Agc1Config = AudioProcessing::Config::GainController1;
116 switch (mode) {
117 case Agc1Config::kAdaptiveAnalog:
118 return GainControl::kAdaptiveAnalog;
119 case Agc1Config::kAdaptiveDigital:
120 return GainControl::kAdaptiveDigital;
121 case Agc1Config::kFixedDigital:
122 return GainControl::kFixedDigital;
123 }
Karl Wibergc95b9392020-11-08 00:49:37 +0100124 RTC_CHECK_NOTREACHED();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100125}
126
Per Åhgren19775cb2021-03-12 23:08:09 +0000127bool MinimizeProcessingForUnusedOutput() {
128 return !field_trial::IsEnabled("WebRTC-MutedStateKillSwitch");
129}
130
peah9e6a2902017-05-15 07:19:21 -0700131// Maximum lengths that frame of samples being passed from the render side to
132// the capture side can have (does not apply to AEC3).
133static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
134static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
135
peah764e3642016-10-22 05:04:30 -0700136// Maximum number of frames to buffer in the render queue.
137// TODO(peah): Decrease this once we properly handle hugely unbalanced
138// reverse and forward call numbers.
139static const size_t kMaxNumFramesToBuffer = 100;
Alessio Bazzica3438a932020-10-14 12:47:50 +0200140
Sam Zackrisson03cb7e52021-12-06 15:40:04 +0100141void PackRenderAudioBufferForEchoDetector(const AudioBuffer& audio,
142 std::vector<float>& packed_buffer) {
143 packed_buffer.clear();
144 packed_buffer.insert(packed_buffer.end(), audio.channels_const()[0],
145 audio.channels_const()[0] + audio.num_frames());
146}
147
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100148// Options for gracefully handling processing errors.
149enum class FormatErrorOutputOption {
150 kOutputExactCopyOfInput,
151 kOutputBroadcastCopyOfFirstInputChannel,
152 kOutputSilence,
153 kDoNothing
154};
155
156enum class AudioFormatValidity {
157 // Format is supported by APM.
158 kValidAndSupported,
159 // Format has a reasonable interpretation but is not supported.
160 kValidButUnsupportedSampleRate,
161 // The remaining enums values signal that the audio does not have a reasonable
162 // interpretation and cannot be used.
163 kInvalidSampleRate,
164 kInvalidChannelCount
165};
166
167AudioFormatValidity ValidateAudioFormat(const StreamConfig& config) {
168 if (config.sample_rate_hz() < 0)
169 return AudioFormatValidity::kInvalidSampleRate;
170 if (config.num_channels() == 0)
171 return AudioFormatValidity::kInvalidChannelCount;
172
173 // Format has a reasonable interpretation, but may still be unsupported.
174 if (config.sample_rate_hz() < 8000 ||
175 config.sample_rate_hz() > AudioBuffer::kMaxSampleRate)
176 return AudioFormatValidity::kValidButUnsupportedSampleRate;
177
178 // Format is fully supported.
179 return AudioFormatValidity::kValidAndSupported;
180}
181
182int AudioFormatValidityToErrorCode(AudioFormatValidity validity) {
183 switch (validity) {
184 case AudioFormatValidity::kValidAndSupported:
185 return AudioProcessing::kNoError;
186 case AudioFormatValidity::kValidButUnsupportedSampleRate: // fall-through
187 case AudioFormatValidity::kInvalidSampleRate:
188 return AudioProcessing::kBadSampleRateError;
189 case AudioFormatValidity::kInvalidChannelCount:
190 return AudioProcessing::kBadNumberChannelsError;
191 }
192 RTC_DCHECK(false);
193}
194
195// Returns an AudioProcessing::Error together with the best possible option for
196// output audio content.
197std::pair<int, FormatErrorOutputOption> ChooseErrorOutputOption(
198 const StreamConfig& input_config,
199 const StreamConfig& output_config) {
200 AudioFormatValidity input_validity = ValidateAudioFormat(input_config);
201 AudioFormatValidity output_validity = ValidateAudioFormat(output_config);
202
Sam Zackrisson06cba442022-11-21 16:32:42 +0100203 if (input_validity == AudioFormatValidity::kValidAndSupported &&
204 output_validity == AudioFormatValidity::kValidAndSupported &&
205 (output_config.num_channels() == 1 ||
206 output_config.num_channels() == input_config.num_channels())) {
207 return {AudioProcessing::kNoError, FormatErrorOutputOption::kDoNothing};
208 }
209
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100210 int error_code = AudioFormatValidityToErrorCode(input_validity);
211 if (error_code == AudioProcessing::kNoError) {
212 error_code = AudioFormatValidityToErrorCode(output_validity);
213 }
Sam Zackrisson06cba442022-11-21 16:32:42 +0100214 if (error_code == AudioProcessing::kNoError) {
215 // The individual formats are valid but there is some error - must be
216 // channel mismatch.
217 error_code = AudioProcessing::kBadNumberChannelsError;
218 }
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100219
220 FormatErrorOutputOption output_option;
221 if (output_validity != AudioFormatValidity::kValidAndSupported &&
222 output_validity != AudioFormatValidity::kValidButUnsupportedSampleRate) {
223 // The output format is uninterpretable: cannot do anything.
224 output_option = FormatErrorOutputOption::kDoNothing;
225 } else if (input_validity != AudioFormatValidity::kValidAndSupported &&
226 input_validity !=
227 AudioFormatValidity::kValidButUnsupportedSampleRate) {
228 // The input format is uninterpretable: cannot use it, must output silence.
229 output_option = FormatErrorOutputOption::kOutputSilence;
230 } else if (input_config.sample_rate_hz() != output_config.sample_rate_hz()) {
231 // Sample rates do not match: Cannot copy input into output, output silence.
232 // Note: If the sample rates are in a supported range, we could resample.
233 // However, that would significantly increase complexity of this error
234 // handling code.
235 output_option = FormatErrorOutputOption::kOutputSilence;
236 } else if (input_config.num_channels() != output_config.num_channels()) {
237 // Channel counts do not match: We cannot easily map input channels to
238 // output channels.
239 output_option =
240 FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel;
241 } else {
242 // The formats match exactly.
243 RTC_DCHECK(input_config == output_config);
244 output_option = FormatErrorOutputOption::kOutputExactCopyOfInput;
245 }
246 return std::make_pair(error_code, output_option);
247}
248
249// Checks if the audio format is supported. If not, the output is populated in a
250// best-effort manner and an APM error code is returned.
251int HandleUnsupportedAudioFormats(const int16_t* const src,
252 const StreamConfig& input_config,
253 const StreamConfig& output_config,
254 int16_t* const dest) {
255 RTC_DCHECK(src);
256 RTC_DCHECK(dest);
257
258 auto [error_code, output_option] =
259 ChooseErrorOutputOption(input_config, output_config);
260 if (error_code == AudioProcessing::kNoError)
261 return AudioProcessing::kNoError;
262
263 const size_t num_output_channels = output_config.num_channels();
264 switch (output_option) {
265 case FormatErrorOutputOption::kOutputSilence:
266 memset(dest, 0, output_config.num_samples() * sizeof(int16_t));
267 break;
268 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
269 for (size_t i = 0; i < output_config.num_frames(); ++i) {
270 int16_t sample = src[input_config.num_channels() * i];
271 for (size_t ch = 0; ch < num_output_channels; ++ch) {
272 dest[ch + num_output_channels * i] = sample;
273 }
274 }
275 break;
276 case FormatErrorOutputOption::kOutputExactCopyOfInput:
277 memcpy(dest, src, output_config.num_samples() * sizeof(int16_t));
278 break;
279 case FormatErrorOutputOption::kDoNothing:
280 break;
281 }
282 return error_code;
283}
284
285// Checks if the audio format is supported. If not, the output is populated in a
286// best-effort manner and an APM error code is returned.
287int HandleUnsupportedAudioFormats(const float* const* src,
288 const StreamConfig& input_config,
289 const StreamConfig& output_config,
290 float* const* dest) {
291 RTC_DCHECK(src);
292 RTC_DCHECK(dest);
293 for (size_t i = 0; i < input_config.num_channels(); ++i) {
294 RTC_DCHECK(src[i]);
295 }
296 for (size_t i = 0; i < output_config.num_channels(); ++i) {
297 RTC_DCHECK(dest[i]);
298 }
299
300 auto [error_code, output_option] =
301 ChooseErrorOutputOption(input_config, output_config);
302 if (error_code == AudioProcessing::kNoError)
303 return AudioProcessing::kNoError;
304
305 const size_t num_output_channels = output_config.num_channels();
306 switch (output_option) {
307 case FormatErrorOutputOption::kOutputSilence:
308 for (size_t ch = 0; ch < num_output_channels; ++ch) {
309 memset(dest[ch], 0, output_config.num_frames() * sizeof(float));
310 }
311 break;
312 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
313 for (size_t ch = 0; ch < num_output_channels; ++ch) {
314 memcpy(dest[ch], src[0], output_config.num_frames() * sizeof(float));
315 }
316 break;
317 case FormatErrorOutputOption::kOutputExactCopyOfInput:
318 for (size_t ch = 0; ch < num_output_channels; ++ch) {
319 memcpy(dest[ch], src[ch], output_config.num_frames() * sizeof(float));
320 }
321 break;
322 case FormatErrorOutputOption::kDoNothing:
323 break;
324 }
325 return error_code;
326}
327
Hanna Silena6574902022-11-30 16:59:05 +0100328const absl::optional<InputVolumeController::Config>
329GetInputVolumeControllerConfigOverride() {
330 constexpr char kInputVolumeControllerFieldTrial[] =
331 "WebRTC-Audio-InputVolumeControllerExperiment";
332
333 if (!field_trial::IsEnabled(kInputVolumeControllerFieldTrial)) {
334 return absl::nullopt;
335 }
336
337 constexpr InputVolumeController::Config kDefaultConfig;
338
339 FieldTrialFlag enabled("Enabled", false);
340 FieldTrialConstrained<int> clipped_level_min(
341 "clipped_level_min", kDefaultConfig.clipped_level_min, 0, 255);
342 FieldTrialConstrained<int> clipped_level_step(
343 "clipped_level_step", kDefaultConfig.clipped_level_step, 0, 255);
344 FieldTrialConstrained<double> clipped_ratio_threshold(
345 "clipped_ratio_threshold", kDefaultConfig.clipped_ratio_threshold, 0, 1);
346 FieldTrialConstrained<int> clipped_wait_frames(
347 "clipped_wait_frames", kDefaultConfig.clipped_wait_frames, 0,
348 absl::nullopt);
349 FieldTrialParameter<bool> enable_clipping_predictor(
350 "enable_clipping_predictor", kDefaultConfig.enable_clipping_predictor);
351 FieldTrialConstrained<int> target_range_max_dbfs(
352 "target_range_max_dbfs", kDefaultConfig.target_range_max_dbfs, -90, 30);
353 FieldTrialConstrained<int> target_range_min_dbfs(
354 "target_range_min_dbfs", kDefaultConfig.target_range_min_dbfs, -90, 30);
355 FieldTrialConstrained<int> update_input_volume_wait_frames(
356 "update_input_volume_wait_frames",
357 kDefaultConfig.update_input_volume_wait_frames, 0, absl::nullopt);
358 FieldTrialConstrained<double> speech_probability_threshold(
359 "speech_probability_threshold",
360 kDefaultConfig.speech_probability_threshold, 0, 1);
361 FieldTrialConstrained<double> speech_ratio_threshold(
362 "speech_ratio_threshold", kDefaultConfig.speech_ratio_threshold, 0, 1);
363
364 // Field-trial based override for the input volume controller config.
365 const std::string field_trial_name =
366 field_trial::FindFullName(kInputVolumeControllerFieldTrial);
367
368 ParseFieldTrial({&enabled, &clipped_level_min, &clipped_level_step,
369 &clipped_ratio_threshold, &clipped_wait_frames,
370 &enable_clipping_predictor, &target_range_max_dbfs,
371 &target_range_min_dbfs, &update_input_volume_wait_frames,
372 &speech_probability_threshold, &speech_ratio_threshold},
373 field_trial_name);
374
375 // Checked already by `IsEnabled()` before parsing, therefore always true.
376 RTC_DCHECK(enabled);
377
378 return InputVolumeController::Config{
379 .clipped_level_min = static_cast<int>(clipped_level_min.Get()),
380 .clipped_level_step = static_cast<int>(clipped_level_step.Get()),
381 .clipped_ratio_threshold =
382 static_cast<float>(clipped_ratio_threshold.Get()),
383 .clipped_wait_frames = static_cast<int>(clipped_wait_frames.Get()),
384 .enable_clipping_predictor =
385 static_cast<bool>(enable_clipping_predictor.Get()),
386 .target_range_max_dbfs = static_cast<int>(target_range_max_dbfs.Get()),
387 .target_range_min_dbfs = static_cast<int>(target_range_min_dbfs.Get()),
388 .update_input_volume_wait_frames =
389 static_cast<int>(update_input_volume_wait_frames.Get()),
390 .speech_probability_threshold =
391 static_cast<float>(speech_probability_threshold.Get()),
392 .speech_ratio_threshold =
393 static_cast<float>(speech_ratio_threshold.Get()),
394 };
395}
396
397// Switches all gain control to AGC2 if experimenting with input volume
398// controller.
399const AudioProcessing::Config AdjustConfig(
400 const AudioProcessing::Config& config,
401 const absl::optional<InputVolumeController::Config>&
402 input_volume_controller_config_override) {
403 const bool analog_agc_enabled =
404 config.gain_controller1.enabled &&
405 (config.gain_controller1.mode ==
406 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
407 config.gain_controller1.analog_gain_controller.enabled);
408
409 // Do not update the config if none of the analog AGCs is active
410 // regardless of the input volume controller override.
411 if (!analog_agc_enabled ||
412 !input_volume_controller_config_override.has_value()) {
413 return config;
414 }
415
416 const bool hybrid_agc_config_detected =
417 config.gain_controller1.enabled &&
418 config.gain_controller1.analog_gain_controller.enabled &&
419 !config.gain_controller1.analog_gain_controller.enable_digital_adaptive &&
420 config.gain_controller2.enabled &&
421 config.gain_controller2.adaptive_digital.enabled;
422
423 const bool full_agc1_config_detected =
424 config.gain_controller1.enabled &&
425 config.gain_controller1.analog_gain_controller.enabled &&
426 config.gain_controller1.analog_gain_controller.enable_digital_adaptive &&
427 !config.gain_controller2.enabled;
428
429 if (hybrid_agc_config_detected == full_agc1_config_detected ||
430 config.gain_controller2.input_volume_controller.enabled) {
431 RTC_LOG(LS_ERROR) << "Unexpected AGC config: Config not adjusted.";
432 return config;
433 }
434
435 AudioProcessing::Config adjusted_config = config;
436 adjusted_config.gain_controller1.enabled = false;
437 adjusted_config.gain_controller1.analog_gain_controller.enabled = false;
438 adjusted_config.gain_controller2.enabled = true;
439 adjusted_config.gain_controller2.adaptive_digital.enabled = true;
440 adjusted_config.gain_controller2.input_volume_controller.enabled = true;
441
442 return adjusted_config;
443}
444
Alessio Bazzica504bd592022-12-01 13:26:26 +0100445using DownmixMethod = AudioProcessing::Config::Pipeline::DownmixMethod;
446
447void SetDownmixMethod(AudioBuffer& buffer, DownmixMethod method) {
448 switch (method) {
449 case DownmixMethod::kAverageChannels:
450 buffer.set_downmixing_by_averaging();
451 break;
452 case DownmixMethod::kUseFirstChannel:
453 buffer.set_downmixing_to_specific_channel(/*channel=*/0);
454 break;
455 }
456}
457
Hanna Silena6574902022-11-30 16:59:05 +0100458constexpr int kUnspecifiedDataDumpInputVolume = -100;
459
Michael Graczyk86c6d332015-07-23 11:41:39 -0700460} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000461
462// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000463static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000464
saza1d600522019-10-18 13:29:43 +0200465AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100466 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200467 bool render_pre_processor_enabled,
468 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100469 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200470 render_pre_processor_enabled_(render_pre_processor_enabled),
471 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700472
saza1d600522019-10-18 13:29:43 +0200473bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200474 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700475 bool mobile_echo_controller_enabled,
476 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700477 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700478 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200479 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000480 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200481 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700482 bool transient_suppressor_enabled) {
483 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200484 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700485 changed |=
486 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
487 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
488 changed |=
peah2ace3f92016-09-10 04:42:27 -0700489 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200490 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200491 changed |=
492 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000493 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200494 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700495 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
496 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200497 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700498 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
499 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700500 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700501 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200502 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000503 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200504 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700505 transient_suppressor_enabled_ = transient_suppressor_enabled;
506 }
507
508 changed |= first_update_;
509 first_update_ = false;
510 return changed;
511}
512
saza1d600522019-10-18 13:29:43 +0200513bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700514 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000515 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700516}
517
saza1d600522019-10-18 13:29:43 +0200518bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
519 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200520 // If echo controller is present, assume it performs active processing.
521 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
522}
523
saza1d600522019-10-18 13:29:43 +0200524bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200525 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100526 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
527 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200528 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700529}
530
saza1d600522019-10-18 13:29:43 +0200531bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700532 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200533 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000534 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700535}
536
saza1d600522019-10-18 13:29:43 +0200537bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200538 return capture_analyzer_enabled_;
539}
540
saza1d600522019-10-18 13:29:43 +0200541bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700542 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100543 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
544 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700545}
546
saza1d600522019-10-18 13:29:43 +0200547bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100548 const {
549 return render_pre_processor_enabled_;
550}
551
saza1d600522019-10-18 13:29:43 +0200552bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700553 const {
peah2ace3f92016-09-10 04:42:27 -0700554 return false;
peah2ace3f92016-09-10 04:42:27 -0700555}
556
saza1d600522019-10-18 13:29:43 +0200557bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100558 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
559 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200560}
561
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200562AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200563 : AudioProcessingImpl(/*config=*/{},
564 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200565 /*render_pre_processor=*/nullptr,
566 /*echo_control_factory=*/nullptr,
567 /*echo_detector=*/nullptr,
568 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000569
Niels Möller7a669002022-06-27 09:47:02 +0200570std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100571
Sam Zackrisson0beac582017-09-25 12:04:02 +0200572AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200573 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100574 std::unique_ptr<CustomProcessing> capture_post_processor,
575 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200576 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200577 rtc::scoped_refptr<EchoDetector> echo_detector,
578 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200579 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100580 use_setup_specific_default_aec3_config_(
581 UseSetupSpecificDefaultAec3Congfig()),
Hanna Silena6574902022-11-30 16:59:05 +0100582 input_volume_controller_config_override_(
583 GetInputVolumeControllerConfigOverride()),
Alessio Bazzica0441bb62021-08-10 15:23:23 +0200584 use_denormal_disabler_(
585 !field_trial::IsEnabled("WebRTC-ApmDenormalDisablerKillSwitch")),
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +0100586 transient_suppressor_vad_mode_(GetTransientSuppressorVadMode()),
Per Åhgren652ada52021-03-03 10:52:44 +0000587 capture_runtime_settings_(RuntimeSettingQueueSize()),
588 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200589 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
590 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200591 echo_control_factory_(std::move(echo_control_factory)),
Hanna Silena6574902022-11-30 16:59:05 +0100592 config_(AdjustConfig(config, input_volume_controller_config_override_)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200593 submodule_states_(!!capture_post_processor,
594 !!render_pre_processor,
595 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200596 submodules_(std::move(capture_post_processor),
597 std::move(render_pre_processor),
598 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100599 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100600 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200601 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
602 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100603 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000604 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200605 MinimizeProcessingForUnusedOutput(),
606 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000607 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200608 capture_nonlocked_(),
609 applied_input_volume_stats_reporter_(
610 InputVolumeStatsReporter::InputVolumeType::kApplied),
611 recommended_input_volume_stats_reporter_(
612 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200613 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100614 "\nEcho control factory: "
615 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200616 << "\nEcho detector: " << !!submodules_.echo_detector
617 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
618 << "\nCapture post processor: "
619 << !!submodules_.capture_post_processor
620 << "\nRender pre processor: "
621 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100622 if (!DenormalDisabler::IsSupported()) {
623 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
624 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200625
Hanna Silena6574902022-11-30 16:59:05 +0100626 RTC_LOG(LS_INFO) << "AudioProcessing: " << config_.ToString();
627
Sam Zackrisson421c8592019-02-11 13:39:46 +0100628 // Mark Echo Controller enabled if a factory is injected.
629 capture_nonlocked_.echo_controller_enabled =
630 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000631
Per Åhgren0ade9832020-09-01 23:57:20 +0200632 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000633}
634
Per Åhgren0e3198e2019-11-18 08:52:22 +0100635AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000636
niklase@google.com470e71d2011-07-07 08:21:25 +0000637int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800638 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200639 MutexLock lock_render(&mutex_render_);
640 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200641 InitializeLocked();
642 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000643}
644
Michael Graczyk86c6d332015-07-23 11:41:39 -0700645int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800646 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200647 MutexLock lock_render(&mutex_render_);
648 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100649 InitializeLocked(processing_config);
650 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000651}
652
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100653void AudioProcessingImpl::MaybeInitializeRender(
654 const StreamConfig& input_config,
655 const StreamConfig& output_config) {
656 ProcessingConfig processing_config = formats_.api_format;
657 processing_config.reverse_input_stream() = input_config;
658 processing_config.reverse_output_stream() = output_config;
659
Oskar Sundbom4b276482019-05-23 14:28:00 +0200660 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100661 return;
peah192164e2015-11-17 02:16:45 -0800662 }
peahdf3efa82015-11-28 12:35:15 -0800663
Markus Handell0df0fae2020-07-07 15:53:34 +0200664 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100665 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800666}
667
Per Åhgren0ade9832020-09-01 23:57:20 +0200668void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200669 UpdateActiveSubmoduleStates();
670
Per Åhgrend47941e2019-08-22 11:51:13 +0200671 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800672 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200673 ? formats_.render_processing_format.sample_rate_hz()
674 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800675 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
676 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200677 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800678 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200679 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700680 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200681 render_audiobuffer_sample_rate_hz,
682 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700683 if (formats_.api_format.reverse_input_stream() !=
684 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800685 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800686 formats_.api_format.reverse_input_stream().num_channels(),
687 formats_.api_format.reverse_input_stream().num_frames(),
688 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800689 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700690 } else {
peahdf3efa82015-11-28 12:35:15 -0800691 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700692 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700693 } else {
peahdf3efa82015-11-28 12:35:15 -0800694 render_.render_audio.reset(nullptr);
695 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700696 }
peahce4d9152017-05-19 01:28:05 -0700697
Per Åhgrend47941e2019-08-22 11:51:13 +0200698 capture_.capture_audio.reset(new AudioBuffer(
699 formats_.api_format.input_stream().sample_rate_hz(),
700 formats_.api_format.input_stream().num_channels(),
701 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
702 formats_.api_format.output_stream().num_channels(),
703 formats_.api_format.output_stream().sample_rate_hz(),
704 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100705 SetDownmixMethod(*capture_.capture_audio,
706 config_.pipeline.capture_downmix_method);
niklase@google.com470e71d2011-07-07 08:21:25 +0000707
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200708 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
709 formats_.api_format.output_stream().sample_rate_hz() &&
710 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
711 capture_.capture_fullband_audio.reset(
712 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
713 formats_.api_format.input_stream().num_channels(),
714 formats_.api_format.output_stream().sample_rate_hz(),
715 formats_.api_format.output_stream().num_channels(),
716 formats_.api_format.output_stream().sample_rate_hz(),
717 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100718 SetDownmixMethod(*capture_.capture_fullband_audio,
719 config_.pipeline.capture_downmix_method);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200720 } else {
721 capture_.capture_fullband_audio.reset();
722 }
723
peah764e3642016-10-22 05:04:30 -0700724 AllocateRenderQueue();
725
Per Åhgren0695df12020-01-13 14:43:13 +0100726 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100727 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100728 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700729 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200730 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200731 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200732 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200733 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200734 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200735 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100736 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000737 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800738
aleloi868f32f2017-05-23 07:20:05 -0700739 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200740 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700741 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000742}
743
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100744void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200745 UpdateActiveSubmoduleStates();
746
peahdf3efa82015-11-28 12:35:15 -0800747 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000748
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200749 // Choose maximum rate to use for the split filtering.
750 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
751 config_.pipeline.maximum_internal_processing_rate == 32000);
752 int max_splitting_rate = 48000;
753 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
754 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
755 }
756
Per Åhgrenc8626b62019-08-23 15:49:51 +0200757 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700758 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700759 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200760 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700761 submodule_states_.CaptureMultiBandSubModulesActive() ||
762 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200763 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000764
peahde65ddc2016-09-16 15:02:15 -0700765 capture_nonlocked_.capture_processing_format =
766 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700767
peah2ce640f2017-04-07 03:57:48 -0700768 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200769 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200770 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700771 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
772 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200773 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700774 submodule_states_.CaptureMultiBandSubModulesActive() ||
775 submodule_states_.RenderMultiBandSubModulesActive());
776 } else {
777 render_processing_rate = capture_processing_rate;
778 }
779
peahde65ddc2016-09-16 15:02:15 -0700780 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700781 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700782 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
783 kSampleRate8kHz) {
784 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000785 } else {
peahde65ddc2016-09-16 15:02:15 -0700786 render_processing_rate =
787 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000788 }
789
Per Åhgrenc8626b62019-08-23 15:49:51 +0200790 RTC_DCHECK_NE(8000, render_processing_rate);
791
peahce4d9152017-05-19 01:28:05 -0700792 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200793 // By default, downmix the render stream to mono for analysis. This has been
794 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100795 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
796 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200797 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100798 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200799 ? formats_.api_format.reverse_input_stream().num_channels()
800 : 1;
801 formats_.render_processing_format =
802 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700803 } else {
804 formats_.render_processing_format = StreamConfig(
805 formats_.api_format.reverse_input_stream().sample_rate_hz(),
806 formats_.api_format.reverse_input_stream().num_channels());
807 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000808
peahde65ddc2016-09-16 15:02:15 -0700809 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
810 kSampleRate32kHz ||
811 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
812 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800813 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000814 } else {
peahdf3efa82015-11-28 12:35:15 -0800815 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700816 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000817 }
818
Per Åhgren0ade9832020-09-01 23:57:20 +0200819 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000820}
821
peah88ac8532016-09-12 16:47:25 -0700822void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700823 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200824 MutexLock lock_render(&mutex_render_);
825 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700826
Hanna Silena6574902022-11-30 16:59:05 +0100827 // TODO(bugs.webrtc.org/7494): Replace `adjusted_config` with `config` after
828 // "WebRTC-Audio-InputVolumeControllerExperiment" field trial is removed.
829 const auto adjusted_config =
830 AdjustConfig(config, input_volume_controller_config_override_);
831
832 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: "
833 << adjusted_config.ToString();
834
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200835 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100836 config_.pipeline.multi_channel_render !=
Hanna Silena6574902022-11-30 16:59:05 +0100837 adjusted_config.pipeline.multi_channel_render ||
Per Åhgrene14cb992019-11-27 09:34:22 +0100838 config_.pipeline.multi_channel_capture !=
Hanna Silena6574902022-11-30 16:59:05 +0100839 adjusted_config.pipeline.multi_channel_capture ||
Per Åhgrenc0424252019-12-10 13:04:15 +0100840 config_.pipeline.maximum_internal_processing_rate !=
Alessio Bazzica504bd592022-12-01 13:26:26 +0100841 adjusted_config.pipeline.maximum_internal_processing_rate ||
842 config_.pipeline.capture_downmix_method !=
843 adjusted_config.pipeline.capture_downmix_method;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200844
Per Åhgren200feba2019-03-06 04:16:46 +0100845 const bool aec_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100846 config_.echo_canceller.enabled !=
847 adjusted_config.echo_canceller.enabled ||
848 config_.echo_canceller.mobile_mode !=
849 adjusted_config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100850
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100851 const bool agc1_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100852 config_.gain_controller1 != adjusted_config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100853
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100854 const bool agc2_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100855 config_.gain_controller2 != adjusted_config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100856
saza0bad15f2019-10-16 11:46:11 +0200857 const bool ns_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100858 config_.noise_suppression.enabled !=
859 adjusted_config.noise_suppression.enabled ||
860 config_.noise_suppression.level !=
861 adjusted_config.noise_suppression.level;
saza0bad15f2019-10-16 11:46:11 +0200862
Per Åhgrenc0734712020-01-02 15:15:36 +0100863 const bool ts_config_changed = config_.transient_suppression.enabled !=
Hanna Silena6574902022-11-30 16:59:05 +0100864 adjusted_config.transient_suppression.enabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100865
Per Åhgren0f14db22020-01-03 14:27:14 +0100866 const bool pre_amplifier_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100867 config_.pre_amplifier.enabled != adjusted_config.pre_amplifier.enabled ||
Per Åhgren0f14db22020-01-03 14:27:14 +0100868 config_.pre_amplifier.fixed_gain_factor !=
Hanna Silena6574902022-11-30 16:59:05 +0100869 adjusted_config.pre_amplifier.fixed_gain_factor;
Per Åhgren0f14db22020-01-03 14:27:14 +0100870
Per Åhgrendb5d7282021-03-15 16:31:04 +0000871 const bool gain_adjustment_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100872 config_.capture_level_adjustment !=
873 adjusted_config.capture_level_adjustment;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000874
Hanna Silena6574902022-11-30 16:59:05 +0100875 config_ = adjusted_config;
Yves Gerey499bc6c2018-10-10 18:29:07 +0200876
Per Åhgren200feba2019-03-06 04:16:46 +0100877 if (aec_config_changed) {
878 InitializeEchoController();
879 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200880
saza0bad15f2019-10-16 11:46:11 +0200881 if (ns_config_changed) {
882 InitializeNoiseSuppressor();
883 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100884
Per Åhgrenc0734712020-01-02 15:15:36 +0100885 if (ts_config_changed) {
886 InitializeTransientSuppressor();
887 }
888
Per Åhgren0f14db22020-01-03 14:27:14 +0100889 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800890
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100891 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100892 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100893 }
894
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100895 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700896 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200897 RTC_LOG(LS_ERROR)
898 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700899 config_.gain_controller2 = AudioProcessing::Config::GainController2();
900 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100901
Alessio Bazzica38901042021-10-14 12:14:21 +0200902 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200903 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100904
Per Åhgrendb5d7282021-03-15 16:31:04 +0000905 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
906 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100907 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100908
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200909 // Reinitialization must happen after all submodule configuration to avoid
910 // additional reinitializations on the next capture / render processing call.
911 if (pipeline_config_changed) {
912 InitializeLocked(formats_.api_format);
913 }
peah88ac8532016-09-12 16:47:25 -0700914}
915
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200916void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
917 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200918 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200919 submodule_creation_overrides_ = overrides;
920}
921
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000922int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800923 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700924 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000925}
926
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200927int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
928 return capture_.capture_fullband_audio
929 ? capture_.capture_fullband_audio->num_frames() * 100
930 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
931}
932
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000933int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800934 // Used as callback from submodules, hence locking is not allowed.
935 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000936}
937
Peter Kasting69558702016-01-12 16:26:35 -0800938size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800939 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700940 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000941}
942
Peter Kasting69558702016-01-12 16:26:35 -0800943size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800944 // Used as callback from submodules, hence locking is not allowed.
945 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000946}
947
Peter Kasting69558702016-01-12 16:26:35 -0800948size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800949 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100950 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
951 constants_.multi_channel_capture_support;
952 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200953 return 1;
954 }
955 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800956}
957
Peter Kasting69558702016-01-12 16:26:35 -0800958size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800959 // Used as callback from submodules, hence locking is not allowed.
960 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000961}
962
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000963void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200964 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +0100965 HandleCaptureOutputUsedSetting(!muted);
966}
967
968void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
969 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +0000970 capture_.capture_output_used =
971 capture_output_used || !constants_.minimize_processing_for_unused_output;
972
saza1d600522019-10-18 13:29:43 +0200973 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100974 submodules_.agc_manager->HandleCaptureOutputUsedChange(
975 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000976 }
Per Åhgren652ada52021-03-03 10:52:44 +0000977 if (submodules_.echo_controller) {
978 submodules_.echo_controller->SetCaptureOutputUsage(
979 capture_.capture_output_used);
980 }
Per Åhgren15179a92021-03-12 14:12:44 +0000981 if (submodules_.noise_suppressor) {
982 submodules_.noise_suppressor->SetCaptureOutputUsage(
983 capture_.capture_output_used);
984 }
Hanna Silend4dbe452022-11-30 15:16:21 +0100985 if (submodules_.gain_controller2) {
986 submodules_.gain_controller2->SetCaptureOutputUsed(
987 capture_.capture_output_used);
988 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000989}
990
Alessio Bazzicac054e782018-04-16 12:10:09 +0200991void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100992 PostRuntimeSetting(setting);
993}
994
995bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200996 switch (setting.type()) {
997 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100998 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +0100999 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001000 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001001 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001002 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001003 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +02001004 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001005 return capture_runtime_settings_enqueuer_.Enqueue(setting);
1006 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1007 bool enqueueing_successful;
1008 enqueueing_successful =
1009 capture_runtime_settings_enqueuer_.Enqueue(setting);
1010 enqueueing_successful =
1011 render_runtime_settings_enqueuer_.Enqueue(setting) &&
1012 enqueueing_successful;
1013 return enqueueing_successful;
1014 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001015 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001016 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001017 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +02001018 }
1019 // The language allows the enum to have a non-enumerator
1020 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +01001021 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001022 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001023}
1024
1025AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
1026 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001027 : runtime_settings_(*runtime_settings) {
1028 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001029}
1030
1031AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
1032 default;
1033
Per Åhgren0a144a72021-02-09 08:47:51 +01001034bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +02001035 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +00001036 const bool successful_insert = runtime_settings_.Insert(&setting);
1037
1038 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001039 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +02001040 }
Per Åhgren652ada52021-03-03 10:52:44 +00001041 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001042}
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001043
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001044void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001045 const StreamConfig& input_config,
1046 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001047 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001048 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001049 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001050 // Acquire the capture lock in order to access api_format. The lock is
1051 // released immediately, as we may need to acquire the render lock as part
1052 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +02001053 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001054 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001055 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +00001056 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001057
Oskar Sundbom4b276482019-05-23 14:28:00 +02001058 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001059 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -08001060 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001061
1062 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001063 reinitialization_required = true;
1064 }
1065
1066 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001067 MutexLock lock_render(&mutex_render_);
1068 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +02001069 // Reread the API format since the render format may have changed.
1070 processing_config = formats_.api_format;
1071 processing_config.input_stream() = input_config;
1072 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001073 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001074 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001075}
1076
1077int AudioProcessingImpl::ProcessStream(const float* const* src,
1078 const StreamConfig& input_config,
1079 const StreamConfig& output_config,
1080 float* const* dest) {
1081 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001082 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1083 RETURN_ON_ERR(
1084 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1085 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001086
Markus Handell0df0fae2020-07-07 15:53:34 +02001087 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001088
aleloi868f32f2017-05-23 07:20:05 -07001089 if (aec_dump_) {
1090 RecordUnprocessedCaptureStream(src);
1091 }
1092
peahdf3efa82015-11-28 12:35:15 -08001093 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001094 if (capture_.capture_fullband_audio) {
1095 capture_.capture_fullband_audio->CopyFrom(
1096 src, formats_.api_format.input_stream());
1097 }
peahde65ddc2016-09-16 15:02:15 -07001098 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001099 if (capture_.capture_fullband_audio) {
1100 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1101 dest);
1102 } else {
1103 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1104 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001105
aleloi868f32f2017-05-23 07:20:05 -07001106 if (aec_dump_) {
1107 RecordProcessedCaptureStream(dest);
1108 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001109 return kNoError;
1110}
1111
Alex Loiko73ec0192018-05-15 10:52:28 +02001112void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001113 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +00001114 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +02001115 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001116 if (aec_dump_) {
1117 aec_dump_->WriteRuntimeSetting(setting);
1118 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001119 switch (setting.type()) {
1120 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001121 if (config_.pre_amplifier.enabled ||
1122 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +02001123 float value;
1124 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001125 // If the pre-amplifier is used, apply the new gain to the
1126 // pre-amplifier regardless if the capture level adjustment is
1127 // activated. This approach allows both functionalities to coexist
1128 // until they have been properly merged.
1129 if (config_.pre_amplifier.enabled) {
1130 config_.pre_amplifier.fixed_gain_factor = value;
1131 } else {
1132 config_.capture_level_adjustment.pre_gain_factor = value;
1133 }
1134
1135 // Use both the pre-amplifier and the capture level adjustment gains
1136 // as pre-gains.
1137 float gain = 1.f;
1138 if (config_.pre_amplifier.enabled) {
1139 gain *= config_.pre_amplifier.fixed_gain_factor;
1140 }
1141 if (config_.capture_level_adjustment.enabled) {
1142 gain *= config_.capture_level_adjustment.pre_gain_factor;
1143 }
1144
1145 submodules_.capture_levels_adjuster->SetPreGain(gain);
1146 }
1147 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
1148 break;
1149 case RuntimeSetting::Type::kCapturePostGain:
1150 if (config_.capture_level_adjustment.enabled) {
1151 float value;
1152 setting.GetFloat(&value);
1153 config_.capture_level_adjustment.post_gain_factor = value;
1154 submodules_.capture_levels_adjuster->SetPostGain(
1155 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001156 }
1157 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001158 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001159 case RuntimeSetting::Type::kCaptureCompressionGain: {
Hanna Silend4dbe452022-11-30 15:16:21 +01001160 if (!submodules_.agc_manager &&
1161 !(submodules_.gain_controller2 &&
1162 config_.gain_controller2.input_volume_controller.enabled)) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001163 float value;
1164 setting.GetFloat(&value);
1165 int int_value = static_cast<int>(value + .5f);
1166 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001167 if (submodules_.gain_control) {
1168 int error =
1169 submodules_.gain_control->set_compression_gain_db(int_value);
1170 RTC_DCHECK_EQ(kNoError, error);
1171 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001172 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001173 break;
1174 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001175 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001176 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001177 float value;
1178 setting.GetFloat(&value);
1179 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001180 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001181 }
1182 break;
1183 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001184 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1185 int value;
1186 setting.GetInt(&value);
1187 capture_.playout_volume = value;
1188 break;
1189 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001190 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001191 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001192 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001193 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001194 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001195 break;
1196 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001197 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001198 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001199 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001200 bool value;
1201 setting.GetBool(&value);
1202 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001203 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001204 }
Per Åhgren652ada52021-03-03 10:52:44 +00001205 ++num_settings_processed;
1206 }
1207
1208 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1209 // Handle overrun of the runtime settings queue, which likely will has
1210 // caused settings to be discarded.
1211 HandleOverrunInCaptureRuntimeSettingsQueue();
1212 }
1213}
1214
1215void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1216 // Fall back to a safe state for the case when a setting for capture output
1217 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001218 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001219}
1220
1221void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1222 RuntimeSetting setting;
1223 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001224 if (aec_dump_) {
1225 aec_dump_->WriteRuntimeSetting(setting);
1226 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001227 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001228 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001229 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001230 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001231 if (submodules_.render_pre_processor) {
1232 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001233 }
1234 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001235 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001236 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001237 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001238 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001239 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001240 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001241 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001242 break;
1243 }
1244 }
1245}
1246
peah9e6a2902017-05-15 07:19:21 -07001247void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001248 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001249
saza1d600522019-10-18 13:29:43 +02001250 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001251 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1252 num_reverse_channels(),
1253 &aecm_render_queue_buffer_);
1254 RTC_DCHECK(aecm_render_signal_queue_);
1255 // Insert the samples into the queue.
1256 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1257 // The data queue is full and needs to be emptied.
1258 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001259
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001260 // Retry the insert (should always work).
1261 bool result =
1262 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1263 RTC_DCHECK(result);
1264 }
peah764e3642016-10-22 05:04:30 -07001265 }
peah701d6282016-10-25 05:42:20 -07001266
Per Åhgren0695df12020-01-13 14:43:13 +01001267 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001268 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001269 // Insert the samples into the queue.
1270 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1271 // The data queue is full and needs to be emptied.
1272 EmptyQueuedRenderAudio();
1273
1274 // Retry the insert (should always work).
1275 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1276 RTC_DCHECK(result);
1277 }
1278 }
peah9e6a2902017-05-15 07:19:21 -07001279}
ivoc9f4a4a02016-10-28 05:39:16 -07001280
peah9e6a2902017-05-15 07:19:21 -07001281void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001282 if (submodules_.echo_detector) {
1283 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1284 RTC_DCHECK(red_render_signal_queue_);
1285 // Insert the samples into the queue.
1286 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1287 // The data queue is full and needs to be emptied.
1288 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001289
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001290 // Retry the insert (should always work).
1291 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1292 RTC_DCHECK(result);
1293 }
ivoc9f4a4a02016-10-28 05:39:16 -07001294 }
peah764e3642016-10-22 05:04:30 -07001295}
1296
1297void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001298 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001299 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001300
ivoc9f4a4a02016-10-28 05:39:16 -07001301 const size_t new_red_render_queue_element_max_size =
1302 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1303
peaha0624602016-10-25 04:45:24 -07001304 // Reallocate the queues if the queue item sizes are too small to fit the
1305 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001306
1307 if (agc_render_queue_element_max_size_ <
1308 new_agc_render_queue_element_max_size) {
1309 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1310
1311 std::vector<int16_t> template_queue_element(
1312 agc_render_queue_element_max_size_);
1313
1314 agc_render_signal_queue_.reset(
1315 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1316 kMaxNumFramesToBuffer, template_queue_element,
1317 RenderQueueItemVerifier<int16_t>(
1318 agc_render_queue_element_max_size_)));
1319
1320 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1321 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1322 } else {
1323 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001324 }
ivoc9f4a4a02016-10-28 05:39:16 -07001325
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001326 if (submodules_.echo_detector) {
1327 if (red_render_queue_element_max_size_ <
1328 new_red_render_queue_element_max_size) {
1329 red_render_queue_element_max_size_ =
1330 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001331
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001332 std::vector<float> template_queue_element(
1333 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001334
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001335 red_render_signal_queue_.reset(
1336 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1337 kMaxNumFramesToBuffer, template_queue_element,
1338 RenderQueueItemVerifier<float>(
1339 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001340
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001341 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1342 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1343 } else {
1344 red_render_signal_queue_->Clear();
1345 }
ivoc9f4a4a02016-10-28 05:39:16 -07001346 }
peah764e3642016-10-22 05:04:30 -07001347}
1348
1349void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001350 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001351 EmptyQueuedRenderAudioLocked();
1352}
1353
1354void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001355 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001356 RTC_DCHECK(aecm_render_signal_queue_);
1357 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001358 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001359 aecm_capture_queue_buffer_);
1360 }
peah701d6282016-10-25 05:42:20 -07001361 }
1362
Per Åhgren0695df12020-01-13 14:43:13 +01001363 if (submodules_.gain_control) {
1364 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1365 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1366 }
peah764e3642016-10-22 05:04:30 -07001367 }
ivoc9f4a4a02016-10-28 05:39:16 -07001368
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001369 if (submodules_.echo_detector) {
1370 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1371 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1372 }
ivoc9f4a4a02016-10-28 05:39:16 -07001373 }
peah764e3642016-10-22 05:04:30 -07001374}
1375
Per Åhgren645f24c2020-03-16 12:06:02 +01001376int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1377 const StreamConfig& input_config,
1378 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001379 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001380 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001381
1382 RETURN_ON_ERR(
1383 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1384 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001385
Markus Handell0df0fae2020-07-07 15:53:34 +02001386 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001387 DenormalDisabler denormal_disabler(use_denormal_disabler_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001388
aleloi868f32f2017-05-23 07:20:05 -07001389 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001390 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001391 }
1392
Per Åhgren645f24c2020-03-16 12:06:02 +01001393 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001394 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001395 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001396 }
peahde65ddc2016-09-16 15:02:15 -07001397 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001398 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001399 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001400 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001401 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001402 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001403 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001404 }
Per Åhgrena1351272019-08-15 12:15:46 +02001405 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001406
aleloi868f32f2017-05-23 07:20:05 -07001407 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001408 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001409 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001410 return kNoError;
1411}
1412
peahde65ddc2016-09-16 15:02:15 -07001413int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001414 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001415 HandleCaptureRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001416 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001417
peahb58a1582016-03-15 09:34:24 -07001418 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001419 // TODO(peah): Simplify once the public API Enable functions for these
1420 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001421 RTC_DCHECK_LE(
1422 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001423
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001424 data_dumper_->DumpRaw(
1425 "applied_input_volume",
1426 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1427
peahde65ddc2016-09-16 15:02:15 -07001428 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001429 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001430
Per Åhgrenc0424252019-12-10 13:04:15 +01001431 if (submodules_.high_pass_filter &&
1432 config_.high_pass_filter.apply_in_full_band &&
1433 !constants_.enforce_split_band_hpf) {
1434 submodules_.high_pass_filter->Process(capture_buffer,
1435 /*use_split_band_data=*/false);
1436 }
1437
Per Åhgrendb5d7282021-03-15 16:31:04 +00001438 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001439 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001440 // When the input volume is emulated, retrieve the volume applied to the
1441 // input audio and notify that to APM so that the volume is passed to the
1442 // active AGC.
1443 set_stream_analog_level_locked(
1444 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001445 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001446 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1447 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001448 }
1449
Per Åhgren928146f2019-08-20 09:19:21 +02001450 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001451 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001452 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001453 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1454 if (log_rms) {
1455 capture_rms_interval_counter_ = 0;
1456 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001457 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1458 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1459 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1460 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001461 }
1462
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001463 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001464 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001465 *capture_.applied_input_volume);
1466 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001467
saza1d600522019-10-18 13:29:43 +02001468 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001469 // Determine if the echo path gain has changed by checking all the gains
1470 // applied before AEC.
1471 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001472
Per Åhgrendb5d7282021-03-15 16:31:04 +00001473 // Detect and flag any change in the capture level adjustment pre-gain.
1474 if (submodules_.capture_levels_adjuster) {
1475 float pre_adjustment_gain =
1476 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001477 capture_.echo_path_gain_change =
1478 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001479 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001480 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001481 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001482 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001483
1484 // Detect volume change.
1485 capture_.echo_path_gain_change =
1486 capture_.echo_path_gain_change ||
1487 (capture_.prev_playout_volume != capture_.playout_volume &&
1488 capture_.prev_playout_volume >= 0);
1489 capture_.prev_playout_volume = capture_.playout_volume;
1490
saza1d600522019-10-18 13:29:43 +02001491 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001492 }
1493
Per Åhgren0695df12020-01-13 14:43:13 +01001494 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001495 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001496 }
1497
Hanna Silend4dbe452022-11-30 15:16:21 +01001498 if (submodules_.gain_controller2 &&
1499 config_.gain_controller2.input_volume_controller.enabled) {
1500 // Expect the volume to be available if the input controller is enabled.
1501 RTC_DCHECK(capture_.applied_input_volume.has_value());
1502 if (capture_.applied_input_volume.has_value()) {
1503 submodules_.gain_controller2->Analyze(*capture_.applied_input_volume,
1504 *capture_buffer);
1505 }
1506 }
1507
peah2ace3f92016-09-10 04:42:27 -07001508 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1509 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001510 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1511 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001512 }
1513
Per Åhgrene14cb992019-11-27 09:34:22 +01001514 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1515 constants_.multi_channel_capture_support;
1516 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001517 // Force down-mixing of the number of channels after the detection of
1518 // capture signal saturation.
1519 // TODO(peah): Look into ensuring that this kind of tampering with the
1520 // AudioBuffer functionality should not be needed.
1521 capture_buffer->set_num_channels(1);
1522 }
1523
Per Åhgrenc0424252019-12-10 13:04:15 +01001524 if (submodules_.high_pass_filter &&
1525 (!config_.high_pass_filter.apply_in_full_band ||
1526 constants_.enforce_split_band_hpf)) {
1527 submodules_.high_pass_filter->Process(capture_buffer,
1528 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001529 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001530
Per Åhgren0695df12020-01-13 14:43:13 +01001531 if (submodules_.gain_control) {
1532 RETURN_ON_ERR(
1533 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1534 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001535
Per Åhgren8ad9e742020-01-30 07:40:58 +01001536 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1537 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1538 submodules_.noise_suppressor) {
1539 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001540 }
peahb58a1582016-03-15 09:34:24 -07001541
saza1d600522019-10-18 13:29:43 +02001542 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001543 // Ensure that the stream delay was set before the call to the
1544 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001545 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001546 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001547 }
1548
saza1d600522019-10-18 13:29:43 +02001549 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001550 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001551 }
peahe0eae3c2016-12-14 01:16:23 -08001552
saza1d600522019-10-18 13:29:43 +02001553 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001554 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001555 } else {
saza1d600522019-10-18 13:29:43 +02001556 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001557 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1558
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001559 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001560 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001561 }
1562
saza1d600522019-10-18 13:29:43 +02001563 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001564 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001565 }
1566
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001567 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001568 linear_aec_buffer && submodules_.noise_suppressor) {
1569 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001570 }
1571
saza1d600522019-10-18 13:29:43 +02001572 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001573 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001574 }
Per Åhgren46537a32017-06-07 10:08:10 +02001575 }
ivoc9f4a4a02016-10-28 05:39:16 -07001576
Per Åhgren0695df12020-01-13 14:43:13 +01001577 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001578 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001579
1580 absl::optional<int> new_digital_gain =
1581 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001582 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001583 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1584 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001585 }
Per Åhgren0695df12020-01-13 14:43:13 +01001586
1587 if (submodules_.gain_control) {
1588 // TODO(peah): Add reporting from AEC3 whether there is echo.
1589 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1590 capture_buffer, /*stream_has_echo*/ false));
1591 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001592
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001593 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1594 SampleRateSupportsMultiBand(
1595 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1596 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001597 }
1598
Per Åhgren19775cb2021-03-12 23:08:09 +00001599 if (capture_.capture_output_used) {
1600 if (capture_.capture_fullband_audio) {
1601 const auto& ec = submodules_.echo_controller;
1602 bool ec_active = ec ? ec->ActiveProcessing() : false;
1603 // Only update the fullband buffer if the multiband processing has changed
1604 // the signal. Keep the original signal otherwise.
1605 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1606 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1607 }
1608 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001609 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001610
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001611 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001612 submodules_.echo_detector->AnalyzeCaptureAudio(
1613 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1614 capture_buffer->num_frames()));
1615 }
1616
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001617 absl::optional<float> voice_probability;
1618 if (!!submodules_.voice_activity_detector) {
1619 voice_probability = submodules_.voice_activity_detector->Analyze(
1620 AudioFrameView<const float>(capture_buffer->channels(),
1621 capture_buffer->num_channels(),
1622 capture_buffer->num_frames()));
1623 }
1624
Per Åhgren19775cb2021-03-12 23:08:09 +00001625 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001626 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001627 switch (transient_suppressor_vad_mode_) {
1628 case TransientSuppressor::VadMode::kDefault:
1629 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001630 transient_suppressor_voice_probability =
1631 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001632 }
1633 break;
1634 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001635 RTC_DCHECK(voice_probability.has_value());
1636 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001637 break;
1638 case TransientSuppressor::VadMode::kNoVad:
1639 // The transient suppressor will ignore `voice_probability`.
1640 break;
1641 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001642 float delayed_voice_probability =
1643 submodules_.transient_suppressor->Suppress(
1644 capture_buffer->channels()[0], capture_buffer->num_frames(),
1645 capture_buffer->num_channels(),
1646 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1647 capture_buffer->num_frames_per_band(),
1648 /*reference_data=*/nullptr, /*reference_length=*/0,
1649 transient_suppressor_voice_probability, capture_.key_pressed);
1650 if (voice_probability.has_value()) {
1651 *voice_probability = delayed_voice_probability;
1652 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001653 }
1654
Artem Titov0b489302021-07-28 20:50:03 +02001655 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001656 if (submodules_.capture_analyzer) {
1657 submodules_.capture_analyzer->Analyze(capture_buffer);
1658 }
1659
1660 if (submodules_.gain_controller2) {
Hanna Silend4dbe452022-11-30 15:16:21 +01001661 // TODO(bugs.webrtc.org/7494): Let AGC2 detect applied input volume
1662 // changes.
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001663 submodules_.gain_controller2->Process(
1664 voice_probability, capture_.applied_input_volume_changed,
1665 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001666 }
1667
1668 if (submodules_.capture_post_processor) {
1669 submodules_.capture_post_processor->Process(capture_buffer);
1670 }
1671
Per Åhgren19775cb2021-03-12 23:08:09 +00001672 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1673 capture_buffer->channels_const()[0],
1674 capture_nonlocked_.capture_processing_format.num_frames()));
1675 if (log_rms) {
1676 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1677 RTC_HISTOGRAM_COUNTS_LINEAR(
1678 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1679 RmsLevel::kMinLevelDb, 64);
1680 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1681 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1682 }
1683
Per Åhgren19775cb2021-03-12 23:08:09 +00001684 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001685 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001686 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1687 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1688 capture_.stats.residual_echo_likelihood_recent_max =
1689 ed_metrics.echo_likelihood_recent_max;
1690 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001691 }
1692
Per Åhgren19775cb2021-03-12 23:08:09 +00001693 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001694 if (submodules_.echo_controller) {
1695 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1696 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1697 capture_.stats.echo_return_loss_enhancement =
1698 ec_metrics.echo_return_loss_enhancement;
1699 capture_.stats.delay_ms = ec_metrics.delay_ms;
1700 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001701
1702 // Pass stats for reporting.
1703 stats_reporter_.UpdateStatistics(capture_.stats);
1704
Alessio Bazzica533e4612022-09-07 16:58:33 +02001705 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001706 if (capture_.recommended_input_volume.has_value()) {
1707 recommended_input_volume_stats_reporter_.UpdateStatistics(
1708 *capture_.recommended_input_volume);
1709 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001710
Per Åhgrendb5d7282021-03-15 16:31:04 +00001711 if (submodules_.capture_levels_adjuster) {
1712 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1713 *capture_buffer);
1714
Per Åhgrendb5d7282021-03-15 16:31:04 +00001715 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001716 // If the input volume emulation is used, retrieve the recommended input
1717 // volume and set that to emulate the input volume on the next processed
1718 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001719 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001720 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001721 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001722 }
1723 }
1724
Per Åhgren55bc0772021-03-12 14:18:36 +00001725 // Temporarily set the output to zero after the stream has been unmuted
1726 // (capture output is again used). The purpose of this is to avoid clicks and
1727 // artefacts in the audio that results when the processing again is
1728 // reactivated after unmuting.
1729 if (!capture_.capture_output_used_last_frame &&
1730 capture_.capture_output_used) {
1731 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1732 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1733 capture_buffer->num_frames());
1734 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1735 }
1736 }
1737 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1738
peahdf3efa82015-11-28 12:35:15 -08001739 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001740
Alessio Bazzica533e4612022-09-07 16:58:33 +02001741 data_dumper_->DumpRaw("recommended_input_volume",
1742 capture_.recommended_input_volume.value_or(
1743 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001744
niklase@google.com470e71d2011-07-07 08:21:25 +00001745 return kNoError;
1746}
1747
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001748int AudioProcessingImpl::AnalyzeReverseStream(
1749 const float* const* data,
1750 const StreamConfig& reverse_config) {
1751 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001752 MutexLock lock(&mutex_render_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001753 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1754 RTC_DCHECK(data);
1755 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1756 RTC_DCHECK(data[i]);
1757 }
1758 RETURN_ON_ERR(
1759 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1760
1761 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001762 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1763}
1764
peahde65ddc2016-09-16 15:02:15 -07001765int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1766 const StreamConfig& input_config,
1767 const StreamConfig& output_config,
1768 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001769 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001770 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001771 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001772 RETURN_ON_ERR(
1773 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1774
1775 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001776
peahde65ddc2016-09-16 15:02:15 -07001777 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001778
Alex Loiko5825aa62017-12-18 16:02:40 +01001779 if (submodule_states_.RenderMultiBandProcessingActive() ||
1780 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001781 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1782 dest);
peah2ace3f92016-09-10 04:42:27 -07001783 } else if (formats_.api_format.reverse_input_stream() !=
1784 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001785 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1786 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001787 } else {
peahde65ddc2016-09-16 15:02:15 -07001788 CopyAudioIfNeeded(src, input_config.num_frames(),
1789 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001790 }
1791
1792 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001793}
1794
peahdf3efa82015-11-28 12:35:15 -08001795int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001796 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001797 const StreamConfig& input_config,
1798 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001799 if (aec_dump_) {
1800 const size_t channel_size =
1801 formats_.api_format.reverse_input_stream().num_frames();
1802 const size_t num_channels =
1803 formats_.api_format.reverse_input_stream().num_channels();
1804 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001805 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001806 }
peahdf3efa82015-11-28 12:35:15 -08001807 render_.render_audio->CopyFrom(src,
1808 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001809 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001810}
1811
Per Åhgren645f24c2020-03-16 12:06:02 +01001812int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1813 const StreamConfig& input_config,
1814 const StreamConfig& output_config,
1815 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001816 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001817
Markus Handell0df0fae2020-07-07 15:53:34 +02001818 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001819 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1820
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001821 RETURN_ON_ERR(
1822 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1823 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001824
aleloi868f32f2017-05-23 07:20:05 -07001825 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001826 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1827 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001828 }
1829
Per Åhgren645f24c2020-03-16 12:06:02 +01001830 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001831 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001832 if (submodule_states_.RenderMultiBandProcessingActive() ||
1833 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001834 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001835 }
aluebsb0319552016-03-17 20:39:53 -07001836 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001837}
niklase@google.com470e71d2011-07-07 08:21:25 +00001838
peahde65ddc2016-09-16 15:02:15 -07001839int AudioProcessingImpl::ProcessRenderStreamLocked() {
1840 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001841
Alex Loiko73ec0192018-05-15 10:52:28 +02001842 HandleRenderRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001843 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alex Loiko73ec0192018-05-15 10:52:28 +02001844
saza1d600522019-10-18 13:29:43 +02001845 if (submodules_.render_pre_processor) {
1846 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001847 }
1848
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001849 QueueNonbandedRenderAudio(render_buffer);
1850
peah2ace3f92016-09-10 04:42:27 -07001851 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001852 SampleRateSupportsMultiBand(
1853 formats_.render_processing_format.sample_rate_hz())) {
1854 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001855 }
1856
peahce4d9152017-05-19 01:28:05 -07001857 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1858 QueueBandedRenderAudio(render_buffer);
1859 }
1860
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001861 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001862 if (submodules_.echo_controller) {
1863 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001864 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001865
peah2ace3f92016-09-10 04:42:27 -07001866 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001867 SampleRateSupportsMultiBand(
1868 formats_.render_processing_format.sample_rate_hz())) {
1869 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001870 }
1871
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001872 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001873}
1874
1875int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001876 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001877 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001878 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001879
niklase@google.com470e71d2011-07-07 08:21:25 +00001880 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001881 delay = 0;
1882 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001883 }
1884
1885 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1886 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001887 delay = 500;
1888 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001889 }
1890
peahdf3efa82015-11-28 12:35:15 -08001891 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001892 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001893}
1894
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001895bool AudioProcessingImpl::GetLinearAecOutput(
1896 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001897 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001898 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1899
1900 RTC_DCHECK(linear_aec_buffer);
1901 if (linear_aec_buffer) {
1902 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1903 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1904
1905 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1906 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1907 rtc::ArrayView<const float> channel_view =
1908 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1909 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001910 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1911 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001912 }
1913 return true;
1914 }
1915 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001916 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001917 return false;
1918}
1919
niklase@google.com470e71d2011-07-07 08:21:25 +00001920int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001921 // Used as callback from submodules, hence locking is not allowed.
1922 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001923}
1924
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001925void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001926 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001927 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001928}
1929
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001930void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001931 MutexLock lock_capture(&mutex_capture_);
1932 set_stream_analog_level_locked(level);
1933}
1934
1935void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001936 capture_.applied_input_volume_changed =
1937 capture_.applied_input_volume.has_value() &&
1938 *capture_.applied_input_volume != level;
1939 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001940
Alessio Bazzica533e4612022-09-07 16:58:33 +02001941 // Invalidate any previously recommended input volume which will be updated by
1942 // `ProcessStream()`.
1943 capture_.recommended_input_volume = absl::nullopt;
1944
Per Åhgren0e3198e2019-11-18 08:52:22 +01001945 if (submodules_.agc_manager) {
1946 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001947 return;
1948 }
1949
1950 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001951 int error = submodules_.gain_control->set_stream_analog_level(level);
1952 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001953 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001954 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001955}
1956
1957int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001958 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001959 if (!capture_.applied_input_volume.has_value()) {
1960 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
1961 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001962 // Input volume to recommend when `set_stream_analog_level()` is not called.
1963 constexpr int kFallBackInputVolume = 255;
1964 // When APM has no input volume to recommend, return the latest applied input
1965 // volume that has been observed in order to possibly produce no input volume
1966 // change. If no applied input volume has been observed, return a fall-back
1967 // value.
1968 return capture_.recommended_input_volume.value_or(
1969 capture_.applied_input_volume.value_or(kFallBackInputVolume));
1970}
1971
1972void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
1973 if (!capture_.applied_input_volume.has_value()) {
1974 // When `set_stream_analog_level()` is not called, no input level can be
1975 // recommended.
1976 capture_.recommended_input_volume = absl::nullopt;
1977 return;
1978 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001979
Per Åhgrendb5d7282021-03-15 16:31:04 +00001980 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001981 capture_.recommended_input_volume =
1982 submodules_.agc_manager->recommended_analog_level();
1983 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001984 }
1985
1986 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001987 capture_.recommended_input_volume =
1988 submodules_.gain_control->stream_analog_level();
1989 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001990 }
1991
Hanna Silend4dbe452022-11-30 15:16:21 +01001992 if (submodules_.gain_controller2 &&
1993 config_.gain_controller2.input_volume_controller.enabled) {
1994 capture_.recommended_input_volume =
1995 submodules_.gain_controller2->GetRecommendedInputVolume();
1996 return;
1997 }
1998
Alessio Bazzica533e4612022-09-07 16:58:33 +02001999 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002000}
2001
Ali Tofigh1fa87c42022-07-25 22:07:08 +02002002bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
2003 int64_t max_log_size_bytes,
2004 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02002005 std::unique_ptr<AecDump> aec_dump =
2006 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02002007 if (!aec_dump) {
2008 return false;
2009 }
2010
2011 AttachAecDump(std::move(aec_dump));
2012 return true;
2013}
2014
2015bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
2016 int64_t max_log_size_bytes,
2017 rtc::TaskQueue* worker_queue) {
2018 std::unique_ptr<AecDump> aec_dump =
2019 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
2020 if (!aec_dump) {
2021 return false;
2022 }
2023
2024 AttachAecDump(std::move(aec_dump));
2025 return true;
2026}
2027
aleloi868f32f2017-05-23 07:20:05 -07002028void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
2029 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02002030 MutexLock lock_render(&mutex_render_);
2031 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002032
2033 // The previously attached AecDump will be destroyed with the
2034 // 'aec_dump' parameter, which is after locks are released.
2035 aec_dump_.swap(aec_dump);
2036 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02002037 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07002038}
2039
2040void AudioProcessingImpl::DetachAecDump() {
2041 // The d-tor of a task-queue based AecDump blocks until all pending
2042 // tasks are done. This construction avoids blocking while holding
2043 // the render and capture locks.
2044 std::unique_ptr<AecDump> aec_dump = nullptr;
2045 {
Markus Handell0df0fae2020-07-07 15:53:34 +02002046 MutexLock lock_render(&mutex_render_);
2047 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002048 aec_dump = std::move(aec_dump_);
2049 }
2050}
2051
peah8271d042016-11-22 07:24:52 -08002052AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002053 MutexLock lock_render(&mutex_render_);
2054 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08002055 return config_;
2056}
2057
peah2ace3f92016-09-10 04:42:27 -07002058bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
2059 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002060 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002061 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02002062 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00002063 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
2064 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00002065 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07002066}
2067
Per Åhgrenc0734712020-01-02 15:15:36 +01002068void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02002069 if (config_.transient_suppression.enabled &&
2070 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02002071 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01002072 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01002073 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02002074 submodule_creation_overrides_, transient_suppressor_vad_mode_,
2075 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2076 num_proc_channels());
2077 if (!submodules_.transient_suppressor) {
2078 RTC_LOG(LS_WARNING)
2079 << "No transient suppressor created (probably disabled)";
2080 }
2081 } else {
sazaaa42ecd2020-04-01 15:24:40 +02002082 submodules_.transient_suppressor->Initialize(
2083 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2084 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02002085 }
Per Åhgrenc0734712020-01-02 15:15:36 +01002086 } else {
2087 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002088 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002089}
2090
Per Åhgren0f14db22020-01-03 14:27:14 +01002091void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01002092 bool high_pass_filter_needed_by_aec =
2093 config_.echo_canceller.enabled &&
2094 config_.echo_canceller.enforce_high_pass_filtering &&
2095 !config_.echo_canceller.mobile_mode;
2096 if (submodule_states_.HighPassFilteringRequired() ||
2097 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01002098 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
2099 !constants_.enforce_split_band_hpf;
2100 int rate = use_full_band ? proc_fullband_sample_rate_hz()
2101 : proc_split_sample_rate_hz();
2102 size_t num_channels =
2103 use_full_band ? num_output_channels() : num_proc_channels();
2104
Per Åhgren0f14db22020-01-03 14:27:14 +01002105 if (!submodules_.high_pass_filter ||
2106 rate != submodules_.high_pass_filter->sample_rate_hz() ||
2107 forced_reset ||
2108 num_channels != submodules_.high_pass_filter->num_channels()) {
2109 submodules_.high_pass_filter.reset(
2110 new HighPassFilter(rate, num_channels));
2111 }
peah8271d042016-11-22 07:24:52 -08002112 } else {
saza1d600522019-10-18 13:29:43 +02002113 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08002114 }
2115}
alessiob3ec96df2017-05-22 06:57:06 -07002116
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02002117void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002118 bool use_echo_controller =
2119 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002120 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002121
2122 if (use_echo_controller) {
2123 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01002124 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01002125 submodules_.echo_controller = echo_control_factory_->Create(
2126 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01002127 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01002128 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002129 EchoCanceller3Config config;
2130 absl::optional<EchoCanceller3Config> multichannel_config;
2131 if (use_setup_specific_default_aec3_config_) {
2132 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
2133 }
saza1d600522019-10-18 13:29:43 +02002134 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002135 config, multichannel_config, proc_sample_rate_hz(),
2136 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01002137 }
2138
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002139 // Setup the storage for returning the linear AEC output.
2140 if (config_.echo_canceller.export_linear_aec_output) {
2141 constexpr int kLinearOutputRateHz = 16000;
2142 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
2143 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
2144 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
2145 } else {
2146 capture_.linear_aec_output.reset();
2147 }
2148
Per Åhgren200feba2019-03-06 04:16:46 +01002149 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002150
saza1d600522019-10-18 13:29:43 +02002151 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002152 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002153 return;
peahe0eae3c2016-12-14 01:16:23 -08002154 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002155
saza1d600522019-10-18 13:29:43 +02002156 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002157 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002158 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002159
2160 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02002161 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002162 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002163 return;
2164 }
2165
2166 if (config_.echo_canceller.mobile_mode) {
2167 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002168 size_t max_element_size =
2169 std::max(static_cast<size_t>(1),
2170 kMaxAllowedValuesOfSamplesPerBand *
2171 EchoControlMobileImpl::NumCancellersRequired(
2172 num_output_channels(), num_reverse_channels()));
2173
2174 std::vector<int16_t> template_queue_element(max_element_size);
2175
2176 aecm_render_signal_queue_.reset(
2177 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2178 kMaxNumFramesToBuffer, template_queue_element,
2179 RenderQueueItemVerifier<int16_t>(max_element_size)));
2180
2181 aecm_render_queue_buffer_.resize(max_element_size);
2182 aecm_capture_queue_buffer_.resize(max_element_size);
2183
saza1d600522019-10-18 13:29:43 +02002184 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002185
saza1d600522019-10-18 13:29:43 +02002186 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2187 num_reverse_channels(),
2188 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002189 return;
2190 }
2191
saza1d600522019-10-18 13:29:43 +02002192 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002193 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002194}
peah8271d042016-11-22 07:24:52 -08002195
Per Åhgren0695df12020-01-13 14:43:13 +01002196void AudioProcessingImpl::InitializeGainController1() {
Hanna Silend4dbe452022-11-30 15:16:21 +01002197 if (config_.gain_controller2.enabled &&
2198 config_.gain_controller2.input_volume_controller.enabled &&
2199 config_.gain_controller1.enabled &&
2200 (config_.gain_controller1.mode ==
2201 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
2202 config_.gain_controller1.analog_gain_controller.enabled)) {
2203 RTC_LOG(LS_ERROR) << "APM configuration not valid: "
2204 << "Multiple input volume controllers enabled.";
2205 }
2206
Per Åhgren0695df12020-01-13 14:43:13 +01002207 if (!config_.gain_controller1.enabled) {
2208 submodules_.agc_manager.reset();
2209 submodules_.gain_control.reset();
2210 return;
2211 }
2212
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002213 RTC_HISTOGRAM_BOOLEAN(
2214 "WebRTC.Audio.GainController.Analog.Enabled",
2215 config_.gain_controller1.analog_gain_controller.enabled);
2216
Per Åhgren0695df12020-01-13 14:43:13 +01002217 if (!submodules_.gain_control) {
2218 submodules_.gain_control.reset(new GainControlImpl());
2219 }
2220
2221 submodules_.gain_control->Initialize(num_proc_channels(),
2222 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002223 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2224 int error = submodules_.gain_control->set_mode(
2225 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2226 RTC_DCHECK_EQ(kNoError, error);
2227 error = submodules_.gain_control->set_target_level_dbfs(
2228 config_.gain_controller1.target_level_dbfs);
2229 RTC_DCHECK_EQ(kNoError, error);
2230 error = submodules_.gain_control->set_compression_gain_db(
2231 config_.gain_controller1.compression_gain_db);
2232 RTC_DCHECK_EQ(kNoError, error);
2233 error = submodules_.gain_control->enable_limiter(
2234 config_.gain_controller1.enable_limiter);
2235 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002236 constexpr int kAnalogLevelMinimum = 0;
2237 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002238 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002239 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002240 RTC_DCHECK_EQ(kNoError, error);
2241
2242 submodules_.agc_manager.reset();
2243 return;
2244 }
2245
2246 if (!submodules_.agc_manager.get() ||
2247 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002248 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002249 int stream_analog_level = -1;
2250 const bool re_creation = !!submodules_.agc_manager;
2251 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002252 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002253 }
2254 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002255 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002256 if (re_creation) {
2257 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2258 }
2259 }
2260 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002261 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002262 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2263 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002264}
2265
Alessio Bazzica38901042021-10-14 12:14:21 +02002266void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2267 if (!config_has_changed) {
2268 return;
2269 }
2270 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002271 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002272 return;
2273 }
2274 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002275 const bool use_internal_vad =
2276 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica38901042021-10-14 12:14:21 +02002277 submodules_.gain_controller2 = std::make_unique<GainController2>(
Hanna Silena6574902022-11-30 16:59:05 +01002278 config_.gain_controller2,
2279 input_volume_controller_config_override_.value_or(
2280 InputVolumeController::Config{}),
2281 proc_fullband_sample_rate_hz(), num_input_channels(), use_internal_vad);
Hanna Silend4dbe452022-11-30 15:16:21 +01002282 submodules_.gain_controller2->SetCaptureOutputUsed(
2283 capture_.capture_output_used);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002284 }
2285}
2286
2287void AudioProcessingImpl::InitializeVoiceActivityDetector(
2288 bool config_has_changed) {
2289 if (!config_has_changed) {
2290 return;
2291 }
2292 const bool use_vad =
2293 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2294 config_.gain_controller2.enabled &&
2295 config_.gain_controller2.adaptive_digital.enabled;
2296 if (!use_vad) {
2297 submodules_.voice_activity_detector.reset();
2298 return;
2299 }
2300 if (!submodules_.voice_activity_detector || config_has_changed) {
2301 RTC_DCHECK(!!submodules_.gain_controller2);
2302 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2303 submodules_.voice_activity_detector =
2304 std::make_unique<VoiceActivityDetectorWrapper>(
2305 config_.gain_controller2.adaptive_digital.vad_reset_period_ms,
2306 submodules_.gain_controller2->GetCpuFeatures(),
2307 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002308 }
2309}
2310
saza0bad15f2019-10-16 11:46:11 +02002311void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002312 submodules_.noise_suppressor.reset();
2313
saza0bad15f2019-10-16 11:46:11 +02002314 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002315 auto map_level =
2316 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2317 using NoiseSuppresionConfig =
2318 AudioProcessing::Config::NoiseSuppression;
2319 switch (level) {
2320 case NoiseSuppresionConfig::kLow:
2321 return NsConfig::SuppressionLevel::k6dB;
2322 case NoiseSuppresionConfig::kModerate:
2323 return NsConfig::SuppressionLevel::k12dB;
2324 case NoiseSuppresionConfig::kHigh:
2325 return NsConfig::SuppressionLevel::k18dB;
2326 case NoiseSuppresionConfig::kVeryHigh:
2327 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002328 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002329 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002330 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002331
sazaaa42ecd2020-04-01 15:24:40 +02002332 NsConfig cfg;
2333 cfg.target_level = map_level(config_.noise_suppression.level);
2334 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2335 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002336 }
2337}
2338
Per Åhgrendb5d7282021-03-15 16:31:04 +00002339void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2340 if (config_.pre_amplifier.enabled ||
2341 config_.capture_level_adjustment.enabled) {
2342 // Use both the pre-amplifier and the capture level adjustment gains as
2343 // pre-gains.
2344 float pre_gain = 1.f;
2345 if (config_.pre_amplifier.enabled) {
2346 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2347 }
2348 if (config_.capture_level_adjustment.enabled) {
2349 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2350 }
2351
2352 submodules_.capture_levels_adjuster =
2353 std::make_unique<CaptureLevelsAdjuster>(
2354 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2355 config_.capture_level_adjustment.analog_mic_gain_emulation
2356 .initial_level,
2357 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002358 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002359 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002360 }
2361}
2362
ivoc9f4a4a02016-10-28 05:39:16 -07002363void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002364 if (submodules_.echo_detector) {
2365 submodules_.echo_detector->Initialize(
2366 proc_fullband_sample_rate_hz(), 1,
2367 formats_.render_processing_format.sample_rate_hz(), 1);
2368 }
ivoc9f4a4a02016-10-28 05:39:16 -07002369}
2370
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002371void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002372 if (submodules_.capture_analyzer) {
2373 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2374 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002375 }
2376}
2377
Sam Zackrisson0beac582017-09-25 12:04:02 +02002378void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002379 if (submodules_.capture_post_processor) {
2380 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002381 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002382 }
2383}
2384
Alex Loiko5825aa62017-12-18 16:02:40 +01002385void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002386 if (submodules_.render_pre_processor) {
2387 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002388 formats_.render_processing_format.sample_rate_hz(),
2389 formats_.render_processing_format.num_channels());
2390 }
2391}
2392
aleloi868f32f2017-05-23 07:20:05 -07002393void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2394 if (!aec_dump_) {
2395 return;
2396 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002397
2398 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002399 // TODO(peah): Add semicolon-separated concatenations of experiment
2400 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002401 if (!!submodules_.capture_post_processor) {
2402 experiments_description += "CapturePostProcessor;";
2403 }
2404 if (!!submodules_.render_pre_processor) {
2405 experiments_description += "RenderPreProcessor;";
2406 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002407 if (capture_nonlocked_.echo_controller_enabled) {
2408 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002409 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002410 if (config_.gain_controller2.enabled) {
2411 experiments_description += "GainController2;";
2412 }
aleloi868f32f2017-05-23 07:20:05 -07002413
2414 InternalAPMConfig apm_config;
2415
Per Åhgren200feba2019-03-06 04:16:46 +01002416 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002417 apm_config.aec_delay_agnostic_enabled = false;
2418 apm_config.aec_extended_filter_enabled = false;
2419 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002420
saza1d600522019-10-18 13:29:43 +02002421 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002422 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002423 submodules_.echo_control_mobile &&
2424 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002425 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002426 submodules_.echo_control_mobile
2427 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002428 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002429
Per Åhgren0695df12020-01-13 14:43:13 +01002430 apm_config.agc_enabled = !!submodules_.gain_control;
2431
2432 apm_config.agc_mode = submodules_.gain_control
2433 ? static_cast<int>(submodules_.gain_control->mode())
2434 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002435 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002436 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2437 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002438 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002439
2440 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2441
saza0bad15f2019-10-16 11:46:11 +02002442 apm_config.ns_enabled = config_.noise_suppression.enabled;
2443 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002444
2445 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002446 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002447 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002448 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2449 apm_config.pre_amplifier_fixed_gain_factor =
2450 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002451
2452 if (!forced && apm_config == apm_config_for_aec_dump_) {
2453 return;
2454 }
2455 aec_dump_->WriteConfig(apm_config);
2456 apm_config_for_aec_dump_ = apm_config;
2457}
2458
2459void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2460 const float* const* src) {
2461 RTC_DCHECK(aec_dump_);
2462 WriteAecDumpConfigMessage(false);
2463
2464 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2465 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2466 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002467 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002468 RecordAudioProcessingState();
2469}
2470
2471void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002472 const int16_t* const data,
2473 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002474 RTC_DCHECK(aec_dump_);
2475 WriteAecDumpConfigMessage(false);
2476
Per Åhgren645f24c2020-03-16 12:06:02 +01002477 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2478 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002479 RecordAudioProcessingState();
2480}
2481
2482void AudioProcessingImpl::RecordProcessedCaptureStream(
2483 const float* const* processed_capture_stream) {
2484 RTC_DCHECK(aec_dump_);
2485
2486 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2487 const size_t num_channels =
2488 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002489 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2490 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002491 aec_dump_->WriteCaptureStreamMessage();
2492}
2493
2494void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002495 const int16_t* const data,
2496 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002497 RTC_DCHECK(aec_dump_);
2498
Per Åhgren645f24c2020-03-16 12:06:02 +01002499 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002500 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002501 aec_dump_->WriteCaptureStreamMessage();
2502}
2503
2504void AudioProcessingImpl::RecordAudioProcessingState() {
2505 RTC_DCHECK(aec_dump_);
2506 AecDump::AudioProcessingState audio_proc_state;
2507 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002508 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002509 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002510 audio_proc_state.keypress = capture_.key_pressed;
2511 aec_dump_->AddAudioProcessingState(audio_proc_state);
2512}
2513
Per Åhgrenc0734712020-01-02 15:15:36 +01002514AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002515 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002516 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002517 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002518 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002519 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002520 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002521 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002522 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002523 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002524 prev_playout_volume(-1),
2525 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002526
2527AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2528
2529AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2530
2531AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2532
Per Åhgrencf4c8722019-12-30 14:32:14 +01002533AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2534 : stats_message_queue_(1) {}
2535
2536AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2537
2538AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002539 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002540 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2541 // If the message queue is full, return the cached stats.
2542 static_cast<void>(new_stats_available);
2543
2544 return cached_stats_;
2545}
2546
2547void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2548 const AudioProcessingStats& new_stats) {
2549 AudioProcessingStats stats_to_queue = new_stats;
2550 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2551 // If the message queue is full, discard the new stats.
2552 static_cast<void>(stats_message_passed);
2553}
2554
niklase@google.com470e71d2011-07-07 08:21:25 +00002555} // namespace webrtc