blob: 52f2fcb14c2c7d86ee075c829a927b3bca0468d1 [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
445constexpr int kUnspecifiedDataDumpInputVolume = -100;
446
Michael Graczyk86c6d332015-07-23 11:41:39 -0700447} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000448
449// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000450static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000451
saza1d600522019-10-18 13:29:43 +0200452AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100453 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200454 bool render_pre_processor_enabled,
455 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100456 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200457 render_pre_processor_enabled_(render_pre_processor_enabled),
458 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700459
saza1d600522019-10-18 13:29:43 +0200460bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200461 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700462 bool mobile_echo_controller_enabled,
463 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700464 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700465 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200466 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000467 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200468 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700469 bool transient_suppressor_enabled) {
470 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200471 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700472 changed |=
473 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
474 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
475 changed |=
peah2ace3f92016-09-10 04:42:27 -0700476 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200477 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200478 changed |=
479 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000480 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200481 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700482 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
483 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200484 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700485 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
486 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700487 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700488 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200489 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000490 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200491 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700492 transient_suppressor_enabled_ = transient_suppressor_enabled;
493 }
494
495 changed |= first_update_;
496 first_update_ = false;
497 return changed;
498}
499
saza1d600522019-10-18 13:29:43 +0200500bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700501 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000502 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700503}
504
saza1d600522019-10-18 13:29:43 +0200505bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
506 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200507 // If echo controller is present, assume it performs active processing.
508 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
509}
510
saza1d600522019-10-18 13:29:43 +0200511bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200512 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100513 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
514 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200515 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700516}
517
saza1d600522019-10-18 13:29:43 +0200518bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700519 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200520 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000521 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700522}
523
saza1d600522019-10-18 13:29:43 +0200524bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200525 return capture_analyzer_enabled_;
526}
527
saza1d600522019-10-18 13:29:43 +0200528bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700529 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100530 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
531 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700532}
533
saza1d600522019-10-18 13:29:43 +0200534bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100535 const {
536 return render_pre_processor_enabled_;
537}
538
saza1d600522019-10-18 13:29:43 +0200539bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700540 const {
peah2ace3f92016-09-10 04:42:27 -0700541 return false;
peah2ace3f92016-09-10 04:42:27 -0700542}
543
saza1d600522019-10-18 13:29:43 +0200544bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100545 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
546 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200547}
548
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200549AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200550 : AudioProcessingImpl(/*config=*/{},
551 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200552 /*render_pre_processor=*/nullptr,
553 /*echo_control_factory=*/nullptr,
554 /*echo_detector=*/nullptr,
555 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000556
Niels Möller7a669002022-06-27 09:47:02 +0200557std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100558
Sam Zackrisson0beac582017-09-25 12:04:02 +0200559AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200560 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100561 std::unique_ptr<CustomProcessing> capture_post_processor,
562 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200563 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200564 rtc::scoped_refptr<EchoDetector> echo_detector,
565 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200566 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100567 use_setup_specific_default_aec3_config_(
568 UseSetupSpecificDefaultAec3Congfig()),
Hanna Silena6574902022-11-30 16:59:05 +0100569 input_volume_controller_config_override_(
570 GetInputVolumeControllerConfigOverride()),
Alessio Bazzica0441bb62021-08-10 15:23:23 +0200571 use_denormal_disabler_(
572 !field_trial::IsEnabled("WebRTC-ApmDenormalDisablerKillSwitch")),
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +0100573 transient_suppressor_vad_mode_(GetTransientSuppressorVadMode()),
Per Åhgren652ada52021-03-03 10:52:44 +0000574 capture_runtime_settings_(RuntimeSettingQueueSize()),
575 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200576 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
577 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200578 echo_control_factory_(std::move(echo_control_factory)),
Hanna Silena6574902022-11-30 16:59:05 +0100579 config_(AdjustConfig(config, input_volume_controller_config_override_)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200580 submodule_states_(!!capture_post_processor,
581 !!render_pre_processor,
582 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200583 submodules_(std::move(capture_post_processor),
584 std::move(render_pre_processor),
585 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100586 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100587 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200588 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
589 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100590 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000591 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200592 MinimizeProcessingForUnusedOutput(),
593 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000594 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200595 capture_nonlocked_(),
596 applied_input_volume_stats_reporter_(
597 InputVolumeStatsReporter::InputVolumeType::kApplied),
598 recommended_input_volume_stats_reporter_(
599 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200600 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100601 "\nEcho control factory: "
602 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200603 << "\nEcho detector: " << !!submodules_.echo_detector
604 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
605 << "\nCapture post processor: "
606 << !!submodules_.capture_post_processor
607 << "\nRender pre processor: "
608 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100609 if (!DenormalDisabler::IsSupported()) {
610 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
611 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200612
Hanna Silena6574902022-11-30 16:59:05 +0100613 RTC_LOG(LS_INFO) << "AudioProcessing: " << config_.ToString();
614
Sam Zackrisson421c8592019-02-11 13:39:46 +0100615 // Mark Echo Controller enabled if a factory is injected.
616 capture_nonlocked_.echo_controller_enabled =
617 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000618
Per Åhgren0ade9832020-09-01 23:57:20 +0200619 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000620}
621
Per Åhgren0e3198e2019-11-18 08:52:22 +0100622AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000623
niklase@google.com470e71d2011-07-07 08:21:25 +0000624int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800625 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200626 MutexLock lock_render(&mutex_render_);
627 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200628 InitializeLocked();
629 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000630}
631
Michael Graczyk86c6d332015-07-23 11:41:39 -0700632int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800633 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200634 MutexLock lock_render(&mutex_render_);
635 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100636 InitializeLocked(processing_config);
637 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000638}
639
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100640void AudioProcessingImpl::MaybeInitializeRender(
641 const StreamConfig& input_config,
642 const StreamConfig& output_config) {
643 ProcessingConfig processing_config = formats_.api_format;
644 processing_config.reverse_input_stream() = input_config;
645 processing_config.reverse_output_stream() = output_config;
646
Oskar Sundbom4b276482019-05-23 14:28:00 +0200647 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100648 return;
peah192164e2015-11-17 02:16:45 -0800649 }
peahdf3efa82015-11-28 12:35:15 -0800650
Markus Handell0df0fae2020-07-07 15:53:34 +0200651 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100652 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800653}
654
Per Åhgren0ade9832020-09-01 23:57:20 +0200655void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200656 UpdateActiveSubmoduleStates();
657
Per Åhgrend47941e2019-08-22 11:51:13 +0200658 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800659 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200660 ? formats_.render_processing_format.sample_rate_hz()
661 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800662 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
663 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200664 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800665 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200666 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700667 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200668 render_audiobuffer_sample_rate_hz,
669 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700670 if (formats_.api_format.reverse_input_stream() !=
671 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800672 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800673 formats_.api_format.reverse_input_stream().num_channels(),
674 formats_.api_format.reverse_input_stream().num_frames(),
675 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800676 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700677 } else {
peahdf3efa82015-11-28 12:35:15 -0800678 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700679 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700680 } else {
peahdf3efa82015-11-28 12:35:15 -0800681 render_.render_audio.reset(nullptr);
682 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700683 }
peahce4d9152017-05-19 01:28:05 -0700684
Per Åhgrend47941e2019-08-22 11:51:13 +0200685 capture_.capture_audio.reset(new AudioBuffer(
686 formats_.api_format.input_stream().sample_rate_hz(),
687 formats_.api_format.input_stream().num_channels(),
688 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
689 formats_.api_format.output_stream().num_channels(),
690 formats_.api_format.output_stream().sample_rate_hz(),
691 formats_.api_format.output_stream().num_channels()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000692
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200693 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
694 formats_.api_format.output_stream().sample_rate_hz() &&
695 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
696 capture_.capture_fullband_audio.reset(
697 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
698 formats_.api_format.input_stream().num_channels(),
699 formats_.api_format.output_stream().sample_rate_hz(),
700 formats_.api_format.output_stream().num_channels(),
701 formats_.api_format.output_stream().sample_rate_hz(),
702 formats_.api_format.output_stream().num_channels()));
703 } else {
704 capture_.capture_fullband_audio.reset();
705 }
706
peah764e3642016-10-22 05:04:30 -0700707 AllocateRenderQueue();
708
Per Åhgren0695df12020-01-13 14:43:13 +0100709 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100710 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100711 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700712 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200713 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200714 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200715 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200716 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200717 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200718 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100719 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000720 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800721
aleloi868f32f2017-05-23 07:20:05 -0700722 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200723 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700724 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100727void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200728 UpdateActiveSubmoduleStates();
729
peahdf3efa82015-11-28 12:35:15 -0800730 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000731
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200732 // Choose maximum rate to use for the split filtering.
733 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
734 config_.pipeline.maximum_internal_processing_rate == 32000);
735 int max_splitting_rate = 48000;
736 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
737 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
738 }
739
Per Åhgrenc8626b62019-08-23 15:49:51 +0200740 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700741 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700742 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200743 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700744 submodule_states_.CaptureMultiBandSubModulesActive() ||
745 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200746 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000747
peahde65ddc2016-09-16 15:02:15 -0700748 capture_nonlocked_.capture_processing_format =
749 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700750
peah2ce640f2017-04-07 03:57:48 -0700751 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200752 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200753 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700754 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
755 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200756 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700757 submodule_states_.CaptureMultiBandSubModulesActive() ||
758 submodule_states_.RenderMultiBandSubModulesActive());
759 } else {
760 render_processing_rate = capture_processing_rate;
761 }
762
peahde65ddc2016-09-16 15:02:15 -0700763 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700764 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700765 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
766 kSampleRate8kHz) {
767 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000768 } else {
peahde65ddc2016-09-16 15:02:15 -0700769 render_processing_rate =
770 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000771 }
772
Per Åhgrenc8626b62019-08-23 15:49:51 +0200773 RTC_DCHECK_NE(8000, render_processing_rate);
774
peahce4d9152017-05-19 01:28:05 -0700775 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200776 // By default, downmix the render stream to mono for analysis. This has been
777 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100778 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
779 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200780 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100781 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200782 ? formats_.api_format.reverse_input_stream().num_channels()
783 : 1;
784 formats_.render_processing_format =
785 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700786 } else {
787 formats_.render_processing_format = StreamConfig(
788 formats_.api_format.reverse_input_stream().sample_rate_hz(),
789 formats_.api_format.reverse_input_stream().num_channels());
790 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000791
peahde65ddc2016-09-16 15:02:15 -0700792 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
793 kSampleRate32kHz ||
794 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
795 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800796 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000797 } else {
peahdf3efa82015-11-28 12:35:15 -0800798 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700799 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000800 }
801
Per Åhgren0ade9832020-09-01 23:57:20 +0200802 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000803}
804
peah88ac8532016-09-12 16:47:25 -0700805void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700806 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200807 MutexLock lock_render(&mutex_render_);
808 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700809
Hanna Silena6574902022-11-30 16:59:05 +0100810 // TODO(bugs.webrtc.org/7494): Replace `adjusted_config` with `config` after
811 // "WebRTC-Audio-InputVolumeControllerExperiment" field trial is removed.
812 const auto adjusted_config =
813 AdjustConfig(config, input_volume_controller_config_override_);
814
815 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: "
816 << adjusted_config.ToString();
817
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200818 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100819 config_.pipeline.multi_channel_render !=
Hanna Silena6574902022-11-30 16:59:05 +0100820 adjusted_config.pipeline.multi_channel_render ||
Per Åhgrene14cb992019-11-27 09:34:22 +0100821 config_.pipeline.multi_channel_capture !=
Hanna Silena6574902022-11-30 16:59:05 +0100822 adjusted_config.pipeline.multi_channel_capture ||
Per Åhgrenc0424252019-12-10 13:04:15 +0100823 config_.pipeline.maximum_internal_processing_rate !=
Hanna Silena6574902022-11-30 16:59:05 +0100824 adjusted_config.pipeline.maximum_internal_processing_rate;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200825
Per Åhgren200feba2019-03-06 04:16:46 +0100826 const bool aec_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100827 config_.echo_canceller.enabled !=
828 adjusted_config.echo_canceller.enabled ||
829 config_.echo_canceller.mobile_mode !=
830 adjusted_config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100831
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100832 const bool agc1_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100833 config_.gain_controller1 != adjusted_config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100834
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100835 const bool agc2_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100836 config_.gain_controller2 != adjusted_config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100837
saza0bad15f2019-10-16 11:46:11 +0200838 const bool ns_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100839 config_.noise_suppression.enabled !=
840 adjusted_config.noise_suppression.enabled ||
841 config_.noise_suppression.level !=
842 adjusted_config.noise_suppression.level;
saza0bad15f2019-10-16 11:46:11 +0200843
Per Åhgrenc0734712020-01-02 15:15:36 +0100844 const bool ts_config_changed = config_.transient_suppression.enabled !=
Hanna Silena6574902022-11-30 16:59:05 +0100845 adjusted_config.transient_suppression.enabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100846
Per Åhgren0f14db22020-01-03 14:27:14 +0100847 const bool pre_amplifier_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100848 config_.pre_amplifier.enabled != adjusted_config.pre_amplifier.enabled ||
Per Åhgren0f14db22020-01-03 14:27:14 +0100849 config_.pre_amplifier.fixed_gain_factor !=
Hanna Silena6574902022-11-30 16:59:05 +0100850 adjusted_config.pre_amplifier.fixed_gain_factor;
Per Åhgren0f14db22020-01-03 14:27:14 +0100851
Per Åhgrendb5d7282021-03-15 16:31:04 +0000852 const bool gain_adjustment_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100853 config_.capture_level_adjustment !=
854 adjusted_config.capture_level_adjustment;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000855
Hanna Silena6574902022-11-30 16:59:05 +0100856 config_ = adjusted_config;
Yves Gerey499bc6c2018-10-10 18:29:07 +0200857
Per Åhgren200feba2019-03-06 04:16:46 +0100858 if (aec_config_changed) {
859 InitializeEchoController();
860 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200861
saza0bad15f2019-10-16 11:46:11 +0200862 if (ns_config_changed) {
863 InitializeNoiseSuppressor();
864 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100865
Per Åhgrenc0734712020-01-02 15:15:36 +0100866 if (ts_config_changed) {
867 InitializeTransientSuppressor();
868 }
869
Per Åhgren0f14db22020-01-03 14:27:14 +0100870 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800871
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100872 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100873 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100874 }
875
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100876 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700877 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200878 RTC_LOG(LS_ERROR)
879 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700880 config_.gain_controller2 = AudioProcessing::Config::GainController2();
881 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100882
Alessio Bazzica38901042021-10-14 12:14:21 +0200883 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200884 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100885
Per Åhgrendb5d7282021-03-15 16:31:04 +0000886 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
887 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100888 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100889
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200890 // Reinitialization must happen after all submodule configuration to avoid
891 // additional reinitializations on the next capture / render processing call.
892 if (pipeline_config_changed) {
893 InitializeLocked(formats_.api_format);
894 }
peah88ac8532016-09-12 16:47:25 -0700895}
896
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200897void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
898 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200899 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200900 submodule_creation_overrides_ = overrides;
901}
902
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000903int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800904 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700905 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000906}
907
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200908int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
909 return capture_.capture_fullband_audio
910 ? capture_.capture_fullband_audio->num_frames() * 100
911 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
912}
913
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000914int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800915 // Used as callback from submodules, hence locking is not allowed.
916 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000917}
918
Peter Kasting69558702016-01-12 16:26:35 -0800919size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800920 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700921 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000922}
923
Peter Kasting69558702016-01-12 16:26:35 -0800924size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800925 // Used as callback from submodules, hence locking is not allowed.
926 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000927}
928
Peter Kasting69558702016-01-12 16:26:35 -0800929size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800930 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +0100931 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
932 constants_.multi_channel_capture_support;
933 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200934 return 1;
935 }
936 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800937}
938
Peter Kasting69558702016-01-12 16:26:35 -0800939size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800940 // Used as callback from submodules, hence locking is not allowed.
941 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000942}
943
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000944void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200945 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +0100946 HandleCaptureOutputUsedSetting(!muted);
947}
948
949void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
950 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +0000951 capture_.capture_output_used =
952 capture_output_used || !constants_.minimize_processing_for_unused_output;
953
saza1d600522019-10-18 13:29:43 +0200954 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100955 submodules_.agc_manager->HandleCaptureOutputUsedChange(
956 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000957 }
Per Åhgren652ada52021-03-03 10:52:44 +0000958 if (submodules_.echo_controller) {
959 submodules_.echo_controller->SetCaptureOutputUsage(
960 capture_.capture_output_used);
961 }
Per Åhgren15179a92021-03-12 14:12:44 +0000962 if (submodules_.noise_suppressor) {
963 submodules_.noise_suppressor->SetCaptureOutputUsage(
964 capture_.capture_output_used);
965 }
Hanna Silend4dbe452022-11-30 15:16:21 +0100966 if (submodules_.gain_controller2) {
967 submodules_.gain_controller2->SetCaptureOutputUsed(
968 capture_.capture_output_used);
969 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000970}
971
Alessio Bazzicac054e782018-04-16 12:10:09 +0200972void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +0100973 PostRuntimeSetting(setting);
974}
975
976bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200977 switch (setting.type()) {
978 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100979 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +0100980 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +0200981 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +0000982 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100983 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200984 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +0200985 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +0100986 return capture_runtime_settings_enqueuer_.Enqueue(setting);
987 case RuntimeSetting::Type::kPlayoutVolumeChange: {
988 bool enqueueing_successful;
989 enqueueing_successful =
990 capture_runtime_settings_enqueuer_.Enqueue(setting);
991 enqueueing_successful =
992 render_runtime_settings_enqueuer_.Enqueue(setting) &&
993 enqueueing_successful;
994 return enqueueing_successful;
995 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +0100996 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +0100997 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +0100998 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +0200999 }
1000 // The language allows the enum to have a non-enumerator
1001 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +01001002 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001003 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001004}
1005
1006AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
1007 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001008 : runtime_settings_(*runtime_settings) {
1009 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001010}
1011
1012AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
1013 default;
1014
Per Åhgren0a144a72021-02-09 08:47:51 +01001015bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +02001016 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +00001017 const bool successful_insert = runtime_settings_.Insert(&setting);
1018
1019 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001020 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +02001021 }
Per Åhgren652ada52021-03-03 10:52:44 +00001022 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001023}
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001024
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001025void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001026 const StreamConfig& input_config,
1027 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001028 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001029 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001030 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001031 // Acquire the capture lock in order to access api_format. The lock is
1032 // released immediately, as we may need to acquire the render lock as part
1033 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +02001034 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001035 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001036 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +00001037 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001038
Oskar Sundbom4b276482019-05-23 14:28:00 +02001039 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001040 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -08001041 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001042
1043 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001044 reinitialization_required = true;
1045 }
1046
1047 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001048 MutexLock lock_render(&mutex_render_);
1049 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +02001050 // Reread the API format since the render format may have changed.
1051 processing_config = formats_.api_format;
1052 processing_config.input_stream() = input_config;
1053 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001054 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001055 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001056}
1057
1058int AudioProcessingImpl::ProcessStream(const float* const* src,
1059 const StreamConfig& input_config,
1060 const StreamConfig& output_config,
1061 float* const* dest) {
1062 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001063 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1064 RETURN_ON_ERR(
1065 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1066 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001067
Markus Handell0df0fae2020-07-07 15:53:34 +02001068 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001069
aleloi868f32f2017-05-23 07:20:05 -07001070 if (aec_dump_) {
1071 RecordUnprocessedCaptureStream(src);
1072 }
1073
peahdf3efa82015-11-28 12:35:15 -08001074 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001075 if (capture_.capture_fullband_audio) {
1076 capture_.capture_fullband_audio->CopyFrom(
1077 src, formats_.api_format.input_stream());
1078 }
peahde65ddc2016-09-16 15:02:15 -07001079 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001080 if (capture_.capture_fullband_audio) {
1081 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1082 dest);
1083 } else {
1084 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1085 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001086
aleloi868f32f2017-05-23 07:20:05 -07001087 if (aec_dump_) {
1088 RecordProcessedCaptureStream(dest);
1089 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001090 return kNoError;
1091}
1092
Alex Loiko73ec0192018-05-15 10:52:28 +02001093void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001094 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +00001095 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +02001096 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001097 if (aec_dump_) {
1098 aec_dump_->WriteRuntimeSetting(setting);
1099 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001100 switch (setting.type()) {
1101 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001102 if (config_.pre_amplifier.enabled ||
1103 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +02001104 float value;
1105 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001106 // If the pre-amplifier is used, apply the new gain to the
1107 // pre-amplifier regardless if the capture level adjustment is
1108 // activated. This approach allows both functionalities to coexist
1109 // until they have been properly merged.
1110 if (config_.pre_amplifier.enabled) {
1111 config_.pre_amplifier.fixed_gain_factor = value;
1112 } else {
1113 config_.capture_level_adjustment.pre_gain_factor = value;
1114 }
1115
1116 // Use both the pre-amplifier and the capture level adjustment gains
1117 // as pre-gains.
1118 float gain = 1.f;
1119 if (config_.pre_amplifier.enabled) {
1120 gain *= config_.pre_amplifier.fixed_gain_factor;
1121 }
1122 if (config_.capture_level_adjustment.enabled) {
1123 gain *= config_.capture_level_adjustment.pre_gain_factor;
1124 }
1125
1126 submodules_.capture_levels_adjuster->SetPreGain(gain);
1127 }
1128 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
1129 break;
1130 case RuntimeSetting::Type::kCapturePostGain:
1131 if (config_.capture_level_adjustment.enabled) {
1132 float value;
1133 setting.GetFloat(&value);
1134 config_.capture_level_adjustment.post_gain_factor = value;
1135 submodules_.capture_levels_adjuster->SetPostGain(
1136 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001137 }
1138 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001139 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001140 case RuntimeSetting::Type::kCaptureCompressionGain: {
Hanna Silend4dbe452022-11-30 15:16:21 +01001141 if (!submodules_.agc_manager &&
1142 !(submodules_.gain_controller2 &&
1143 config_.gain_controller2.input_volume_controller.enabled)) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001144 float value;
1145 setting.GetFloat(&value);
1146 int int_value = static_cast<int>(value + .5f);
1147 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001148 if (submodules_.gain_control) {
1149 int error =
1150 submodules_.gain_control->set_compression_gain_db(int_value);
1151 RTC_DCHECK_EQ(kNoError, error);
1152 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001153 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001154 break;
1155 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001156 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001157 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001158 float value;
1159 setting.GetFloat(&value);
1160 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001161 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001162 }
1163 break;
1164 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001165 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1166 int value;
1167 setting.GetInt(&value);
1168 capture_.playout_volume = value;
1169 break;
1170 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001171 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001172 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001173 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001174 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001175 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001176 break;
1177 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001178 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001179 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001180 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001181 bool value;
1182 setting.GetBool(&value);
1183 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001184 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001185 }
Per Åhgren652ada52021-03-03 10:52:44 +00001186 ++num_settings_processed;
1187 }
1188
1189 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1190 // Handle overrun of the runtime settings queue, which likely will has
1191 // caused settings to be discarded.
1192 HandleOverrunInCaptureRuntimeSettingsQueue();
1193 }
1194}
1195
1196void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1197 // Fall back to a safe state for the case when a setting for capture output
1198 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001199 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001200}
1201
1202void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1203 RuntimeSetting setting;
1204 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001205 if (aec_dump_) {
1206 aec_dump_->WriteRuntimeSetting(setting);
1207 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001208 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001209 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001210 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001211 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001212 if (submodules_.render_pre_processor) {
1213 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001214 }
1215 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001216 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001217 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001218 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001219 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001220 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001221 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001222 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001223 break;
1224 }
1225 }
1226}
1227
peah9e6a2902017-05-15 07:19:21 -07001228void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001229 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001230
saza1d600522019-10-18 13:29:43 +02001231 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001232 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1233 num_reverse_channels(),
1234 &aecm_render_queue_buffer_);
1235 RTC_DCHECK(aecm_render_signal_queue_);
1236 // Insert the samples into the queue.
1237 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1238 // The data queue is full and needs to be emptied.
1239 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001240
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001241 // Retry the insert (should always work).
1242 bool result =
1243 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1244 RTC_DCHECK(result);
1245 }
peah764e3642016-10-22 05:04:30 -07001246 }
peah701d6282016-10-25 05:42:20 -07001247
Per Åhgren0695df12020-01-13 14:43:13 +01001248 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001249 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001250 // Insert the samples into the queue.
1251 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1252 // The data queue is full and needs to be emptied.
1253 EmptyQueuedRenderAudio();
1254
1255 // Retry the insert (should always work).
1256 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1257 RTC_DCHECK(result);
1258 }
1259 }
peah9e6a2902017-05-15 07:19:21 -07001260}
ivoc9f4a4a02016-10-28 05:39:16 -07001261
peah9e6a2902017-05-15 07:19:21 -07001262void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001263 if (submodules_.echo_detector) {
1264 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1265 RTC_DCHECK(red_render_signal_queue_);
1266 // Insert the samples into the queue.
1267 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1268 // The data queue is full and needs to be emptied.
1269 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001270
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001271 // Retry the insert (should always work).
1272 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1273 RTC_DCHECK(result);
1274 }
ivoc9f4a4a02016-10-28 05:39:16 -07001275 }
peah764e3642016-10-22 05:04:30 -07001276}
1277
1278void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001279 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001280 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001281
ivoc9f4a4a02016-10-28 05:39:16 -07001282 const size_t new_red_render_queue_element_max_size =
1283 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1284
peaha0624602016-10-25 04:45:24 -07001285 // Reallocate the queues if the queue item sizes are too small to fit the
1286 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001287
1288 if (agc_render_queue_element_max_size_ <
1289 new_agc_render_queue_element_max_size) {
1290 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1291
1292 std::vector<int16_t> template_queue_element(
1293 agc_render_queue_element_max_size_);
1294
1295 agc_render_signal_queue_.reset(
1296 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1297 kMaxNumFramesToBuffer, template_queue_element,
1298 RenderQueueItemVerifier<int16_t>(
1299 agc_render_queue_element_max_size_)));
1300
1301 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1302 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1303 } else {
1304 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001305 }
ivoc9f4a4a02016-10-28 05:39:16 -07001306
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001307 if (submodules_.echo_detector) {
1308 if (red_render_queue_element_max_size_ <
1309 new_red_render_queue_element_max_size) {
1310 red_render_queue_element_max_size_ =
1311 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001312
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001313 std::vector<float> template_queue_element(
1314 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001315
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001316 red_render_signal_queue_.reset(
1317 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1318 kMaxNumFramesToBuffer, template_queue_element,
1319 RenderQueueItemVerifier<float>(
1320 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001321
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001322 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1323 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1324 } else {
1325 red_render_signal_queue_->Clear();
1326 }
ivoc9f4a4a02016-10-28 05:39:16 -07001327 }
peah764e3642016-10-22 05:04:30 -07001328}
1329
1330void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001331 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001332 EmptyQueuedRenderAudioLocked();
1333}
1334
1335void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001336 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001337 RTC_DCHECK(aecm_render_signal_queue_);
1338 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001339 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001340 aecm_capture_queue_buffer_);
1341 }
peah701d6282016-10-25 05:42:20 -07001342 }
1343
Per Åhgren0695df12020-01-13 14:43:13 +01001344 if (submodules_.gain_control) {
1345 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1346 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1347 }
peah764e3642016-10-22 05:04:30 -07001348 }
ivoc9f4a4a02016-10-28 05:39:16 -07001349
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001350 if (submodules_.echo_detector) {
1351 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1352 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1353 }
ivoc9f4a4a02016-10-28 05:39:16 -07001354 }
peah764e3642016-10-22 05:04:30 -07001355}
1356
Per Åhgren645f24c2020-03-16 12:06:02 +01001357int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1358 const StreamConfig& input_config,
1359 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001360 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001361 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001362
1363 RETURN_ON_ERR(
1364 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1365 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001366
Markus Handell0df0fae2020-07-07 15:53:34 +02001367 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001368 DenormalDisabler denormal_disabler(use_denormal_disabler_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001369
aleloi868f32f2017-05-23 07:20:05 -07001370 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001371 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001372 }
1373
Per Åhgren645f24c2020-03-16 12:06:02 +01001374 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001375 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001376 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001377 }
peahde65ddc2016-09-16 15:02:15 -07001378 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001379 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001380 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001381 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001382 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001383 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001384 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001385 }
Per Åhgrena1351272019-08-15 12:15:46 +02001386 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001387
aleloi868f32f2017-05-23 07:20:05 -07001388 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001389 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001390 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001391 return kNoError;
1392}
1393
peahde65ddc2016-09-16 15:02:15 -07001394int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001395 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001396 HandleCaptureRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001397 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001398
peahb58a1582016-03-15 09:34:24 -07001399 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001400 // TODO(peah): Simplify once the public API Enable functions for these
1401 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001402 RTC_DCHECK_LE(
1403 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001404
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001405 data_dumper_->DumpRaw(
1406 "applied_input_volume",
1407 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1408
peahde65ddc2016-09-16 15:02:15 -07001409 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001410 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001411
Per Åhgrenc0424252019-12-10 13:04:15 +01001412 if (submodules_.high_pass_filter &&
1413 config_.high_pass_filter.apply_in_full_band &&
1414 !constants_.enforce_split_band_hpf) {
1415 submodules_.high_pass_filter->Process(capture_buffer,
1416 /*use_split_band_data=*/false);
1417 }
1418
Per Åhgrendb5d7282021-03-15 16:31:04 +00001419 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001420 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001421 // When the input volume is emulated, retrieve the volume applied to the
1422 // input audio and notify that to APM so that the volume is passed to the
1423 // active AGC.
1424 set_stream_analog_level_locked(
1425 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001426 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001427 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1428 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001429 }
1430
Per Åhgren928146f2019-08-20 09:19:21 +02001431 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001432 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001433 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001434 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1435 if (log_rms) {
1436 capture_rms_interval_counter_ = 0;
1437 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001438 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1439 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1440 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1441 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001442 }
1443
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001444 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001445 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001446 *capture_.applied_input_volume);
1447 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001448
saza1d600522019-10-18 13:29:43 +02001449 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001450 // Determine if the echo path gain has changed by checking all the gains
1451 // applied before AEC.
1452 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001453
Per Åhgrendb5d7282021-03-15 16:31:04 +00001454 // Detect and flag any change in the capture level adjustment pre-gain.
1455 if (submodules_.capture_levels_adjuster) {
1456 float pre_adjustment_gain =
1457 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001458 capture_.echo_path_gain_change =
1459 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001460 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001461 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001462 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001463 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001464
1465 // Detect volume change.
1466 capture_.echo_path_gain_change =
1467 capture_.echo_path_gain_change ||
1468 (capture_.prev_playout_volume != capture_.playout_volume &&
1469 capture_.prev_playout_volume >= 0);
1470 capture_.prev_playout_volume = capture_.playout_volume;
1471
saza1d600522019-10-18 13:29:43 +02001472 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001473 }
1474
Per Åhgren0695df12020-01-13 14:43:13 +01001475 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001476 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001477 }
1478
Hanna Silend4dbe452022-11-30 15:16:21 +01001479 if (submodules_.gain_controller2 &&
1480 config_.gain_controller2.input_volume_controller.enabled) {
1481 // Expect the volume to be available if the input controller is enabled.
1482 RTC_DCHECK(capture_.applied_input_volume.has_value());
1483 if (capture_.applied_input_volume.has_value()) {
1484 submodules_.gain_controller2->Analyze(*capture_.applied_input_volume,
1485 *capture_buffer);
1486 }
1487 }
1488
peah2ace3f92016-09-10 04:42:27 -07001489 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1490 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001491 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1492 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001493 }
1494
Per Åhgrene14cb992019-11-27 09:34:22 +01001495 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1496 constants_.multi_channel_capture_support;
1497 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001498 // Force down-mixing of the number of channels after the detection of
1499 // capture signal saturation.
1500 // TODO(peah): Look into ensuring that this kind of tampering with the
1501 // AudioBuffer functionality should not be needed.
1502 capture_buffer->set_num_channels(1);
1503 }
1504
Per Åhgrenc0424252019-12-10 13:04:15 +01001505 if (submodules_.high_pass_filter &&
1506 (!config_.high_pass_filter.apply_in_full_band ||
1507 constants_.enforce_split_band_hpf)) {
1508 submodules_.high_pass_filter->Process(capture_buffer,
1509 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001510 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001511
Per Åhgren0695df12020-01-13 14:43:13 +01001512 if (submodules_.gain_control) {
1513 RETURN_ON_ERR(
1514 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1515 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001516
Per Åhgren8ad9e742020-01-30 07:40:58 +01001517 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1518 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1519 submodules_.noise_suppressor) {
1520 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001521 }
peahb58a1582016-03-15 09:34:24 -07001522
saza1d600522019-10-18 13:29:43 +02001523 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001524 // Ensure that the stream delay was set before the call to the
1525 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001526 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001527 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001528 }
1529
saza1d600522019-10-18 13:29:43 +02001530 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001531 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001532 }
peahe0eae3c2016-12-14 01:16:23 -08001533
saza1d600522019-10-18 13:29:43 +02001534 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001535 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001536 } else {
saza1d600522019-10-18 13:29:43 +02001537 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001538 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1539
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001540 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001541 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001542 }
1543
saza1d600522019-10-18 13:29:43 +02001544 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001545 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001546 }
1547
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001548 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001549 linear_aec_buffer && submodules_.noise_suppressor) {
1550 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001551 }
1552
saza1d600522019-10-18 13:29:43 +02001553 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001554 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001555 }
Per Åhgren46537a32017-06-07 10:08:10 +02001556 }
ivoc9f4a4a02016-10-28 05:39:16 -07001557
Per Åhgren0695df12020-01-13 14:43:13 +01001558 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001559 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001560
1561 absl::optional<int> new_digital_gain =
1562 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001563 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001564 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1565 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001566 }
Per Åhgren0695df12020-01-13 14:43:13 +01001567
1568 if (submodules_.gain_control) {
1569 // TODO(peah): Add reporting from AEC3 whether there is echo.
1570 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1571 capture_buffer, /*stream_has_echo*/ false));
1572 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001573
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001574 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1575 SampleRateSupportsMultiBand(
1576 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1577 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001578 }
1579
Per Åhgren19775cb2021-03-12 23:08:09 +00001580 if (capture_.capture_output_used) {
1581 if (capture_.capture_fullband_audio) {
1582 const auto& ec = submodules_.echo_controller;
1583 bool ec_active = ec ? ec->ActiveProcessing() : false;
1584 // Only update the fullband buffer if the multiband processing has changed
1585 // the signal. Keep the original signal otherwise.
1586 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1587 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1588 }
1589 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001590 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001591
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001592 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001593 submodules_.echo_detector->AnalyzeCaptureAudio(
1594 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1595 capture_buffer->num_frames()));
1596 }
1597
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001598 absl::optional<float> voice_probability;
1599 if (!!submodules_.voice_activity_detector) {
1600 voice_probability = submodules_.voice_activity_detector->Analyze(
1601 AudioFrameView<const float>(capture_buffer->channels(),
1602 capture_buffer->num_channels(),
1603 capture_buffer->num_frames()));
1604 }
1605
Per Åhgren19775cb2021-03-12 23:08:09 +00001606 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001607 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001608 switch (transient_suppressor_vad_mode_) {
1609 case TransientSuppressor::VadMode::kDefault:
1610 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001611 transient_suppressor_voice_probability =
1612 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001613 }
1614 break;
1615 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001616 RTC_DCHECK(voice_probability.has_value());
1617 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001618 break;
1619 case TransientSuppressor::VadMode::kNoVad:
1620 // The transient suppressor will ignore `voice_probability`.
1621 break;
1622 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001623 float delayed_voice_probability =
1624 submodules_.transient_suppressor->Suppress(
1625 capture_buffer->channels()[0], capture_buffer->num_frames(),
1626 capture_buffer->num_channels(),
1627 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1628 capture_buffer->num_frames_per_band(),
1629 /*reference_data=*/nullptr, /*reference_length=*/0,
1630 transient_suppressor_voice_probability, capture_.key_pressed);
1631 if (voice_probability.has_value()) {
1632 *voice_probability = delayed_voice_probability;
1633 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001634 }
1635
Artem Titov0b489302021-07-28 20:50:03 +02001636 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001637 if (submodules_.capture_analyzer) {
1638 submodules_.capture_analyzer->Analyze(capture_buffer);
1639 }
1640
1641 if (submodules_.gain_controller2) {
Hanna Silend4dbe452022-11-30 15:16:21 +01001642 // TODO(bugs.webrtc.org/7494): Let AGC2 detect applied input volume
1643 // changes.
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001644 submodules_.gain_controller2->Process(
1645 voice_probability, capture_.applied_input_volume_changed,
1646 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001647 }
1648
1649 if (submodules_.capture_post_processor) {
1650 submodules_.capture_post_processor->Process(capture_buffer);
1651 }
1652
Per Åhgren19775cb2021-03-12 23:08:09 +00001653 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1654 capture_buffer->channels_const()[0],
1655 capture_nonlocked_.capture_processing_format.num_frames()));
1656 if (log_rms) {
1657 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1658 RTC_HISTOGRAM_COUNTS_LINEAR(
1659 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1660 RmsLevel::kMinLevelDb, 64);
1661 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1662 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1663 }
1664
Per Åhgren19775cb2021-03-12 23:08:09 +00001665 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001666 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001667 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1668 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1669 capture_.stats.residual_echo_likelihood_recent_max =
1670 ed_metrics.echo_likelihood_recent_max;
1671 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001672 }
1673
Per Åhgren19775cb2021-03-12 23:08:09 +00001674 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001675 if (submodules_.echo_controller) {
1676 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1677 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1678 capture_.stats.echo_return_loss_enhancement =
1679 ec_metrics.echo_return_loss_enhancement;
1680 capture_.stats.delay_ms = ec_metrics.delay_ms;
1681 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001682
1683 // Pass stats for reporting.
1684 stats_reporter_.UpdateStatistics(capture_.stats);
1685
Alessio Bazzica533e4612022-09-07 16:58:33 +02001686 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001687 if (capture_.recommended_input_volume.has_value()) {
1688 recommended_input_volume_stats_reporter_.UpdateStatistics(
1689 *capture_.recommended_input_volume);
1690 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001691
Per Åhgrendb5d7282021-03-15 16:31:04 +00001692 if (submodules_.capture_levels_adjuster) {
1693 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1694 *capture_buffer);
1695
Per Åhgrendb5d7282021-03-15 16:31:04 +00001696 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001697 // If the input volume emulation is used, retrieve the recommended input
1698 // volume and set that to emulate the input volume on the next processed
1699 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001700 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001701 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001702 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001703 }
1704 }
1705
Per Åhgren55bc0772021-03-12 14:18:36 +00001706 // Temporarily set the output to zero after the stream has been unmuted
1707 // (capture output is again used). The purpose of this is to avoid clicks and
1708 // artefacts in the audio that results when the processing again is
1709 // reactivated after unmuting.
1710 if (!capture_.capture_output_used_last_frame &&
1711 capture_.capture_output_used) {
1712 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1713 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1714 capture_buffer->num_frames());
1715 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1716 }
1717 }
1718 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1719
peahdf3efa82015-11-28 12:35:15 -08001720 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001721
Alessio Bazzica533e4612022-09-07 16:58:33 +02001722 data_dumper_->DumpRaw("recommended_input_volume",
1723 capture_.recommended_input_volume.value_or(
1724 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001725
niklase@google.com470e71d2011-07-07 08:21:25 +00001726 return kNoError;
1727}
1728
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001729int AudioProcessingImpl::AnalyzeReverseStream(
1730 const float* const* data,
1731 const StreamConfig& reverse_config) {
1732 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001733 MutexLock lock(&mutex_render_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001734 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1735 RTC_DCHECK(data);
1736 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1737 RTC_DCHECK(data[i]);
1738 }
1739 RETURN_ON_ERR(
1740 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1741
1742 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001743 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1744}
1745
peahde65ddc2016-09-16 15:02:15 -07001746int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1747 const StreamConfig& input_config,
1748 const StreamConfig& output_config,
1749 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001750 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001751 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001752 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001753 RETURN_ON_ERR(
1754 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1755
1756 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001757
peahde65ddc2016-09-16 15:02:15 -07001758 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001759
Alex Loiko5825aa62017-12-18 16:02:40 +01001760 if (submodule_states_.RenderMultiBandProcessingActive() ||
1761 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001762 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1763 dest);
peah2ace3f92016-09-10 04:42:27 -07001764 } else if (formats_.api_format.reverse_input_stream() !=
1765 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001766 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1767 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001768 } else {
peahde65ddc2016-09-16 15:02:15 -07001769 CopyAudioIfNeeded(src, input_config.num_frames(),
1770 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001771 }
1772
1773 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001774}
1775
peahdf3efa82015-11-28 12:35:15 -08001776int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001777 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001778 const StreamConfig& input_config,
1779 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001780 if (aec_dump_) {
1781 const size_t channel_size =
1782 formats_.api_format.reverse_input_stream().num_frames();
1783 const size_t num_channels =
1784 formats_.api_format.reverse_input_stream().num_channels();
1785 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001786 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001787 }
peahdf3efa82015-11-28 12:35:15 -08001788 render_.render_audio->CopyFrom(src,
1789 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001790 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001791}
1792
Per Åhgren645f24c2020-03-16 12:06:02 +01001793int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1794 const StreamConfig& input_config,
1795 const StreamConfig& output_config,
1796 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001797 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001798
Markus Handell0df0fae2020-07-07 15:53:34 +02001799 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001800 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1801
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001802 RETURN_ON_ERR(
1803 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1804 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001805
aleloi868f32f2017-05-23 07:20:05 -07001806 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001807 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1808 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001809 }
1810
Per Åhgren645f24c2020-03-16 12:06:02 +01001811 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001812 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001813 if (submodule_states_.RenderMultiBandProcessingActive() ||
1814 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001815 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001816 }
aluebsb0319552016-03-17 20:39:53 -07001817 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001818}
niklase@google.com470e71d2011-07-07 08:21:25 +00001819
peahde65ddc2016-09-16 15:02:15 -07001820int AudioProcessingImpl::ProcessRenderStreamLocked() {
1821 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001822
Alex Loiko73ec0192018-05-15 10:52:28 +02001823 HandleRenderRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001824 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alex Loiko73ec0192018-05-15 10:52:28 +02001825
saza1d600522019-10-18 13:29:43 +02001826 if (submodules_.render_pre_processor) {
1827 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001828 }
1829
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001830 QueueNonbandedRenderAudio(render_buffer);
1831
peah2ace3f92016-09-10 04:42:27 -07001832 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001833 SampleRateSupportsMultiBand(
1834 formats_.render_processing_format.sample_rate_hz())) {
1835 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001836 }
1837
peahce4d9152017-05-19 01:28:05 -07001838 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1839 QueueBandedRenderAudio(render_buffer);
1840 }
1841
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001842 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001843 if (submodules_.echo_controller) {
1844 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001845 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001846
peah2ace3f92016-09-10 04:42:27 -07001847 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001848 SampleRateSupportsMultiBand(
1849 formats_.render_processing_format.sample_rate_hz())) {
1850 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001851 }
1852
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001853 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001854}
1855
1856int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001857 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001858 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001859 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001860
niklase@google.com470e71d2011-07-07 08:21:25 +00001861 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001862 delay = 0;
1863 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001864 }
1865
1866 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1867 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001868 delay = 500;
1869 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001870 }
1871
peahdf3efa82015-11-28 12:35:15 -08001872 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001873 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001874}
1875
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001876bool AudioProcessingImpl::GetLinearAecOutput(
1877 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001878 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001879 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1880
1881 RTC_DCHECK(linear_aec_buffer);
1882 if (linear_aec_buffer) {
1883 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1884 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1885
1886 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1887 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1888 rtc::ArrayView<const float> channel_view =
1889 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1890 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001891 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1892 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001893 }
1894 return true;
1895 }
1896 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001897 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001898 return false;
1899}
1900
niklase@google.com470e71d2011-07-07 08:21:25 +00001901int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001902 // Used as callback from submodules, hence locking is not allowed.
1903 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001904}
1905
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001906void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001907 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001908 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001909}
1910
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001911void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001912 MutexLock lock_capture(&mutex_capture_);
1913 set_stream_analog_level_locked(level);
1914}
1915
1916void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001917 capture_.applied_input_volume_changed =
1918 capture_.applied_input_volume.has_value() &&
1919 *capture_.applied_input_volume != level;
1920 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001921
Alessio Bazzica533e4612022-09-07 16:58:33 +02001922 // Invalidate any previously recommended input volume which will be updated by
1923 // `ProcessStream()`.
1924 capture_.recommended_input_volume = absl::nullopt;
1925
Per Åhgren0e3198e2019-11-18 08:52:22 +01001926 if (submodules_.agc_manager) {
1927 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001928 return;
1929 }
1930
1931 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001932 int error = submodules_.gain_control->set_stream_analog_level(level);
1933 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001934 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01001935 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001936}
1937
1938int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001939 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001940 if (!capture_.applied_input_volume.has_value()) {
1941 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
1942 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001943 // Input volume to recommend when `set_stream_analog_level()` is not called.
1944 constexpr int kFallBackInputVolume = 255;
1945 // When APM has no input volume to recommend, return the latest applied input
1946 // volume that has been observed in order to possibly produce no input volume
1947 // change. If no applied input volume has been observed, return a fall-back
1948 // value.
1949 return capture_.recommended_input_volume.value_or(
1950 capture_.applied_input_volume.value_or(kFallBackInputVolume));
1951}
1952
1953void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
1954 if (!capture_.applied_input_volume.has_value()) {
1955 // When `set_stream_analog_level()` is not called, no input level can be
1956 // recommended.
1957 capture_.recommended_input_volume = absl::nullopt;
1958 return;
1959 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001960
Per Åhgrendb5d7282021-03-15 16:31:04 +00001961 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001962 capture_.recommended_input_volume =
1963 submodules_.agc_manager->recommended_analog_level();
1964 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001965 }
1966
1967 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02001968 capture_.recommended_input_volume =
1969 submodules_.gain_control->stream_analog_level();
1970 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00001971 }
1972
Hanna Silend4dbe452022-11-30 15:16:21 +01001973 if (submodules_.gain_controller2 &&
1974 config_.gain_controller2.input_volume_controller.enabled) {
1975 capture_.recommended_input_volume =
1976 submodules_.gain_controller2->GetRecommendedInputVolume();
1977 return;
1978 }
1979
Alessio Bazzica533e4612022-09-07 16:58:33 +02001980 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001981}
1982
Ali Tofigh1fa87c42022-07-25 22:07:08 +02001983bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
1984 int64_t max_log_size_bytes,
1985 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02001986 std::unique_ptr<AecDump> aec_dump =
1987 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02001988 if (!aec_dump) {
1989 return false;
1990 }
1991
1992 AttachAecDump(std::move(aec_dump));
1993 return true;
1994}
1995
1996bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
1997 int64_t max_log_size_bytes,
1998 rtc::TaskQueue* worker_queue) {
1999 std::unique_ptr<AecDump> aec_dump =
2000 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
2001 if (!aec_dump) {
2002 return false;
2003 }
2004
2005 AttachAecDump(std::move(aec_dump));
2006 return true;
2007}
2008
aleloi868f32f2017-05-23 07:20:05 -07002009void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
2010 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02002011 MutexLock lock_render(&mutex_render_);
2012 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002013
2014 // The previously attached AecDump will be destroyed with the
2015 // 'aec_dump' parameter, which is after locks are released.
2016 aec_dump_.swap(aec_dump);
2017 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02002018 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07002019}
2020
2021void AudioProcessingImpl::DetachAecDump() {
2022 // The d-tor of a task-queue based AecDump blocks until all pending
2023 // tasks are done. This construction avoids blocking while holding
2024 // the render and capture locks.
2025 std::unique_ptr<AecDump> aec_dump = nullptr;
2026 {
Markus Handell0df0fae2020-07-07 15:53:34 +02002027 MutexLock lock_render(&mutex_render_);
2028 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002029 aec_dump = std::move(aec_dump_);
2030 }
2031}
2032
peah8271d042016-11-22 07:24:52 -08002033AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002034 MutexLock lock_render(&mutex_render_);
2035 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08002036 return config_;
2037}
2038
peah2ace3f92016-09-10 04:42:27 -07002039bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
2040 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002041 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002042 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02002043 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00002044 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
2045 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00002046 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07002047}
2048
Per Åhgrenc0734712020-01-02 15:15:36 +01002049void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02002050 if (config_.transient_suppression.enabled &&
2051 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02002052 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01002053 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01002054 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02002055 submodule_creation_overrides_, transient_suppressor_vad_mode_,
2056 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2057 num_proc_channels());
2058 if (!submodules_.transient_suppressor) {
2059 RTC_LOG(LS_WARNING)
2060 << "No transient suppressor created (probably disabled)";
2061 }
2062 } else {
sazaaa42ecd2020-04-01 15:24:40 +02002063 submodules_.transient_suppressor->Initialize(
2064 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2065 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02002066 }
Per Åhgrenc0734712020-01-02 15:15:36 +01002067 } else {
2068 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002069 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002070}
2071
Per Åhgren0f14db22020-01-03 14:27:14 +01002072void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01002073 bool high_pass_filter_needed_by_aec =
2074 config_.echo_canceller.enabled &&
2075 config_.echo_canceller.enforce_high_pass_filtering &&
2076 !config_.echo_canceller.mobile_mode;
2077 if (submodule_states_.HighPassFilteringRequired() ||
2078 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01002079 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
2080 !constants_.enforce_split_band_hpf;
2081 int rate = use_full_band ? proc_fullband_sample_rate_hz()
2082 : proc_split_sample_rate_hz();
2083 size_t num_channels =
2084 use_full_band ? num_output_channels() : num_proc_channels();
2085
Per Åhgren0f14db22020-01-03 14:27:14 +01002086 if (!submodules_.high_pass_filter ||
2087 rate != submodules_.high_pass_filter->sample_rate_hz() ||
2088 forced_reset ||
2089 num_channels != submodules_.high_pass_filter->num_channels()) {
2090 submodules_.high_pass_filter.reset(
2091 new HighPassFilter(rate, num_channels));
2092 }
peah8271d042016-11-22 07:24:52 -08002093 } else {
saza1d600522019-10-18 13:29:43 +02002094 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08002095 }
2096}
alessiob3ec96df2017-05-22 06:57:06 -07002097
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02002098void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002099 bool use_echo_controller =
2100 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002101 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002102
2103 if (use_echo_controller) {
2104 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01002105 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01002106 submodules_.echo_controller = echo_control_factory_->Create(
2107 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01002108 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01002109 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002110 EchoCanceller3Config config;
2111 absl::optional<EchoCanceller3Config> multichannel_config;
2112 if (use_setup_specific_default_aec3_config_) {
2113 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
2114 }
saza1d600522019-10-18 13:29:43 +02002115 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002116 config, multichannel_config, proc_sample_rate_hz(),
2117 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01002118 }
2119
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002120 // Setup the storage for returning the linear AEC output.
2121 if (config_.echo_canceller.export_linear_aec_output) {
2122 constexpr int kLinearOutputRateHz = 16000;
2123 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
2124 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
2125 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
2126 } else {
2127 capture_.linear_aec_output.reset();
2128 }
2129
Per Åhgren200feba2019-03-06 04:16:46 +01002130 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002131
saza1d600522019-10-18 13:29:43 +02002132 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002133 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002134 return;
peahe0eae3c2016-12-14 01:16:23 -08002135 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002136
saza1d600522019-10-18 13:29:43 +02002137 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002138 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002139 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002140
2141 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02002142 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002143 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002144 return;
2145 }
2146
2147 if (config_.echo_canceller.mobile_mode) {
2148 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002149 size_t max_element_size =
2150 std::max(static_cast<size_t>(1),
2151 kMaxAllowedValuesOfSamplesPerBand *
2152 EchoControlMobileImpl::NumCancellersRequired(
2153 num_output_channels(), num_reverse_channels()));
2154
2155 std::vector<int16_t> template_queue_element(max_element_size);
2156
2157 aecm_render_signal_queue_.reset(
2158 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2159 kMaxNumFramesToBuffer, template_queue_element,
2160 RenderQueueItemVerifier<int16_t>(max_element_size)));
2161
2162 aecm_render_queue_buffer_.resize(max_element_size);
2163 aecm_capture_queue_buffer_.resize(max_element_size);
2164
saza1d600522019-10-18 13:29:43 +02002165 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002166
saza1d600522019-10-18 13:29:43 +02002167 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2168 num_reverse_channels(),
2169 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002170 return;
2171 }
2172
saza1d600522019-10-18 13:29:43 +02002173 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002174 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002175}
peah8271d042016-11-22 07:24:52 -08002176
Per Åhgren0695df12020-01-13 14:43:13 +01002177void AudioProcessingImpl::InitializeGainController1() {
Hanna Silend4dbe452022-11-30 15:16:21 +01002178 if (config_.gain_controller2.enabled &&
2179 config_.gain_controller2.input_volume_controller.enabled &&
2180 config_.gain_controller1.enabled &&
2181 (config_.gain_controller1.mode ==
2182 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
2183 config_.gain_controller1.analog_gain_controller.enabled)) {
2184 RTC_LOG(LS_ERROR) << "APM configuration not valid: "
2185 << "Multiple input volume controllers enabled.";
2186 }
2187
Per Åhgren0695df12020-01-13 14:43:13 +01002188 if (!config_.gain_controller1.enabled) {
2189 submodules_.agc_manager.reset();
2190 submodules_.gain_control.reset();
2191 return;
2192 }
2193
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002194 RTC_HISTOGRAM_BOOLEAN(
2195 "WebRTC.Audio.GainController.Analog.Enabled",
2196 config_.gain_controller1.analog_gain_controller.enabled);
2197
Per Åhgren0695df12020-01-13 14:43:13 +01002198 if (!submodules_.gain_control) {
2199 submodules_.gain_control.reset(new GainControlImpl());
2200 }
2201
2202 submodules_.gain_control->Initialize(num_proc_channels(),
2203 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002204 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2205 int error = submodules_.gain_control->set_mode(
2206 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2207 RTC_DCHECK_EQ(kNoError, error);
2208 error = submodules_.gain_control->set_target_level_dbfs(
2209 config_.gain_controller1.target_level_dbfs);
2210 RTC_DCHECK_EQ(kNoError, error);
2211 error = submodules_.gain_control->set_compression_gain_db(
2212 config_.gain_controller1.compression_gain_db);
2213 RTC_DCHECK_EQ(kNoError, error);
2214 error = submodules_.gain_control->enable_limiter(
2215 config_.gain_controller1.enable_limiter);
2216 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002217 constexpr int kAnalogLevelMinimum = 0;
2218 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002219 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002220 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002221 RTC_DCHECK_EQ(kNoError, error);
2222
2223 submodules_.agc_manager.reset();
2224 return;
2225 }
2226
2227 if (!submodules_.agc_manager.get() ||
2228 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002229 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002230 int stream_analog_level = -1;
2231 const bool re_creation = !!submodules_.agc_manager;
2232 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002233 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002234 }
2235 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002236 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002237 if (re_creation) {
2238 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2239 }
2240 }
2241 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002242 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002243 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2244 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002245}
2246
Alessio Bazzica38901042021-10-14 12:14:21 +02002247void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2248 if (!config_has_changed) {
2249 return;
2250 }
2251 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002252 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002253 return;
2254 }
2255 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002256 const bool use_internal_vad =
2257 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica38901042021-10-14 12:14:21 +02002258 submodules_.gain_controller2 = std::make_unique<GainController2>(
Hanna Silena6574902022-11-30 16:59:05 +01002259 config_.gain_controller2,
2260 input_volume_controller_config_override_.value_or(
2261 InputVolumeController::Config{}),
2262 proc_fullband_sample_rate_hz(), num_input_channels(), use_internal_vad);
Hanna Silend4dbe452022-11-30 15:16:21 +01002263 submodules_.gain_controller2->SetCaptureOutputUsed(
2264 capture_.capture_output_used);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002265 }
2266}
2267
2268void AudioProcessingImpl::InitializeVoiceActivityDetector(
2269 bool config_has_changed) {
2270 if (!config_has_changed) {
2271 return;
2272 }
2273 const bool use_vad =
2274 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2275 config_.gain_controller2.enabled &&
2276 config_.gain_controller2.adaptive_digital.enabled;
2277 if (!use_vad) {
2278 submodules_.voice_activity_detector.reset();
2279 return;
2280 }
2281 if (!submodules_.voice_activity_detector || config_has_changed) {
2282 RTC_DCHECK(!!submodules_.gain_controller2);
2283 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2284 submodules_.voice_activity_detector =
2285 std::make_unique<VoiceActivityDetectorWrapper>(
2286 config_.gain_controller2.adaptive_digital.vad_reset_period_ms,
2287 submodules_.gain_controller2->GetCpuFeatures(),
2288 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002289 }
2290}
2291
saza0bad15f2019-10-16 11:46:11 +02002292void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002293 submodules_.noise_suppressor.reset();
2294
saza0bad15f2019-10-16 11:46:11 +02002295 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002296 auto map_level =
2297 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2298 using NoiseSuppresionConfig =
2299 AudioProcessing::Config::NoiseSuppression;
2300 switch (level) {
2301 case NoiseSuppresionConfig::kLow:
2302 return NsConfig::SuppressionLevel::k6dB;
2303 case NoiseSuppresionConfig::kModerate:
2304 return NsConfig::SuppressionLevel::k12dB;
2305 case NoiseSuppresionConfig::kHigh:
2306 return NsConfig::SuppressionLevel::k18dB;
2307 case NoiseSuppresionConfig::kVeryHigh:
2308 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002309 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002310 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002311 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002312
sazaaa42ecd2020-04-01 15:24:40 +02002313 NsConfig cfg;
2314 cfg.target_level = map_level(config_.noise_suppression.level);
2315 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2316 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002317 }
2318}
2319
Per Åhgrendb5d7282021-03-15 16:31:04 +00002320void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2321 if (config_.pre_amplifier.enabled ||
2322 config_.capture_level_adjustment.enabled) {
2323 // Use both the pre-amplifier and the capture level adjustment gains as
2324 // pre-gains.
2325 float pre_gain = 1.f;
2326 if (config_.pre_amplifier.enabled) {
2327 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2328 }
2329 if (config_.capture_level_adjustment.enabled) {
2330 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2331 }
2332
2333 submodules_.capture_levels_adjuster =
2334 std::make_unique<CaptureLevelsAdjuster>(
2335 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2336 config_.capture_level_adjustment.analog_mic_gain_emulation
2337 .initial_level,
2338 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002339 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002340 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002341 }
2342}
2343
ivoc9f4a4a02016-10-28 05:39:16 -07002344void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002345 if (submodules_.echo_detector) {
2346 submodules_.echo_detector->Initialize(
2347 proc_fullband_sample_rate_hz(), 1,
2348 formats_.render_processing_format.sample_rate_hz(), 1);
2349 }
ivoc9f4a4a02016-10-28 05:39:16 -07002350}
2351
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002352void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002353 if (submodules_.capture_analyzer) {
2354 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2355 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002356 }
2357}
2358
Sam Zackrisson0beac582017-09-25 12:04:02 +02002359void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002360 if (submodules_.capture_post_processor) {
2361 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002362 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002363 }
2364}
2365
Alex Loiko5825aa62017-12-18 16:02:40 +01002366void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002367 if (submodules_.render_pre_processor) {
2368 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002369 formats_.render_processing_format.sample_rate_hz(),
2370 formats_.render_processing_format.num_channels());
2371 }
2372}
2373
aleloi868f32f2017-05-23 07:20:05 -07002374void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2375 if (!aec_dump_) {
2376 return;
2377 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002378
2379 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002380 // TODO(peah): Add semicolon-separated concatenations of experiment
2381 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002382 if (!!submodules_.capture_post_processor) {
2383 experiments_description += "CapturePostProcessor;";
2384 }
2385 if (!!submodules_.render_pre_processor) {
2386 experiments_description += "RenderPreProcessor;";
2387 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002388 if (capture_nonlocked_.echo_controller_enabled) {
2389 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002390 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002391 if (config_.gain_controller2.enabled) {
2392 experiments_description += "GainController2;";
2393 }
aleloi868f32f2017-05-23 07:20:05 -07002394
2395 InternalAPMConfig apm_config;
2396
Per Åhgren200feba2019-03-06 04:16:46 +01002397 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002398 apm_config.aec_delay_agnostic_enabled = false;
2399 apm_config.aec_extended_filter_enabled = false;
2400 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002401
saza1d600522019-10-18 13:29:43 +02002402 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002403 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002404 submodules_.echo_control_mobile &&
2405 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002406 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002407 submodules_.echo_control_mobile
2408 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002409 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002410
Per Åhgren0695df12020-01-13 14:43:13 +01002411 apm_config.agc_enabled = !!submodules_.gain_control;
2412
2413 apm_config.agc_mode = submodules_.gain_control
2414 ? static_cast<int>(submodules_.gain_control->mode())
2415 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002416 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002417 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2418 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002419 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002420
2421 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2422
saza0bad15f2019-10-16 11:46:11 +02002423 apm_config.ns_enabled = config_.noise_suppression.enabled;
2424 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002425
2426 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002427 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002428 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002429 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2430 apm_config.pre_amplifier_fixed_gain_factor =
2431 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002432
2433 if (!forced && apm_config == apm_config_for_aec_dump_) {
2434 return;
2435 }
2436 aec_dump_->WriteConfig(apm_config);
2437 apm_config_for_aec_dump_ = apm_config;
2438}
2439
2440void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2441 const float* const* src) {
2442 RTC_DCHECK(aec_dump_);
2443 WriteAecDumpConfigMessage(false);
2444
2445 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2446 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2447 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002448 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002449 RecordAudioProcessingState();
2450}
2451
2452void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002453 const int16_t* const data,
2454 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002455 RTC_DCHECK(aec_dump_);
2456 WriteAecDumpConfigMessage(false);
2457
Per Åhgren645f24c2020-03-16 12:06:02 +01002458 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2459 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002460 RecordAudioProcessingState();
2461}
2462
2463void AudioProcessingImpl::RecordProcessedCaptureStream(
2464 const float* const* processed_capture_stream) {
2465 RTC_DCHECK(aec_dump_);
2466
2467 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2468 const size_t num_channels =
2469 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002470 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2471 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002472 aec_dump_->WriteCaptureStreamMessage();
2473}
2474
2475void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002476 const int16_t* const data,
2477 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002478 RTC_DCHECK(aec_dump_);
2479
Per Åhgren645f24c2020-03-16 12:06:02 +01002480 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002481 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002482 aec_dump_->WriteCaptureStreamMessage();
2483}
2484
2485void AudioProcessingImpl::RecordAudioProcessingState() {
2486 RTC_DCHECK(aec_dump_);
2487 AecDump::AudioProcessingState audio_proc_state;
2488 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002489 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002490 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002491 audio_proc_state.keypress = capture_.key_pressed;
2492 aec_dump_->AddAudioProcessingState(audio_proc_state);
2493}
2494
Per Åhgrenc0734712020-01-02 15:15:36 +01002495AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002496 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002497 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002498 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002499 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002500 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002501 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002502 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002503 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002504 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002505 prev_playout_volume(-1),
2506 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002507
2508AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2509
2510AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2511
2512AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2513
Per Åhgrencf4c8722019-12-30 14:32:14 +01002514AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2515 : stats_message_queue_(1) {}
2516
2517AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2518
2519AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002520 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002521 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2522 // If the message queue is full, return the cached stats.
2523 static_cast<void>(new_stats_available);
2524
2525 return cached_stats_;
2526}
2527
2528void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2529 const AudioProcessingStats& new_stats) {
2530 AudioProcessingStats stats_to_queue = new_stats;
2531 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2532 // If the message queue is full, discard the new stats.
2533 static_cast<void>(stats_message_passed);
2534}
2535
niklase@google.com470e71d2011-07-07 08:21:25 +00002536} // namespace webrtc