blob: 18d4ad9c4cc7a59110ae0823dbc8d57e6d7e0f11 [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 Silenca653552022-12-08 17:40:01 +0100328const absl::optional<AudioProcessingImpl::GainController2ConfigOverride>
329GetGainController2ConfigOverride() {
330 constexpr char kFieldTrialName[] = "WebRTC-Audio-GainController2";
Hanna Silena6574902022-11-30 16:59:05 +0100331
Hanna Silenca653552022-12-08 17:40:01 +0100332 if (!field_trial::IsEnabled(kFieldTrialName)) {
Hanna Silena6574902022-11-30 16:59:05 +0100333 return absl::nullopt;
334 }
335
Hanna Silenca653552022-12-08 17:40:01 +0100336 constexpr InputVolumeController::Config kDefaultInputVolumeControllerConfig;
Hanna Silena6574902022-11-30 16:59:05 +0100337
338 FieldTrialFlag enabled("Enabled", false);
339 FieldTrialConstrained<int> clipped_level_min(
Hanna Silenca653552022-12-08 17:40:01 +0100340 "clipped_level_min",
341 kDefaultInputVolumeControllerConfig.clipped_level_min, 0, 255);
Hanna Silena6574902022-11-30 16:59:05 +0100342 FieldTrialConstrained<int> clipped_level_step(
Hanna Silenca653552022-12-08 17:40:01 +0100343 "clipped_level_step",
344 kDefaultInputVolumeControllerConfig.clipped_level_step, 0, 255);
Hanna Silena6574902022-11-30 16:59:05 +0100345 FieldTrialConstrained<double> clipped_ratio_threshold(
Hanna Silenca653552022-12-08 17:40:01 +0100346 "clipped_ratio_threshold",
347 kDefaultInputVolumeControllerConfig.clipped_ratio_threshold, 0, 1);
Hanna Silena6574902022-11-30 16:59:05 +0100348 FieldTrialConstrained<int> clipped_wait_frames(
Hanna Silenca653552022-12-08 17:40:01 +0100349 "clipped_wait_frames",
350 kDefaultInputVolumeControllerConfig.clipped_wait_frames, 0,
Hanna Silena6574902022-11-30 16:59:05 +0100351 absl::nullopt);
352 FieldTrialParameter<bool> enable_clipping_predictor(
Hanna Silenca653552022-12-08 17:40:01 +0100353 "enable_clipping_predictor",
354 kDefaultInputVolumeControllerConfig.enable_clipping_predictor);
Hanna Silena6574902022-11-30 16:59:05 +0100355 FieldTrialConstrained<int> target_range_max_dbfs(
Hanna Silenca653552022-12-08 17:40:01 +0100356 "target_range_max_dbfs",
357 kDefaultInputVolumeControllerConfig.target_range_max_dbfs, -90, 30);
Hanna Silena6574902022-11-30 16:59:05 +0100358 FieldTrialConstrained<int> target_range_min_dbfs(
Hanna Silenca653552022-12-08 17:40:01 +0100359 "target_range_min_dbfs",
360 kDefaultInputVolumeControllerConfig.target_range_min_dbfs, -90, 30);
Hanna Silena6574902022-11-30 16:59:05 +0100361 FieldTrialConstrained<int> update_input_volume_wait_frames(
362 "update_input_volume_wait_frames",
Hanna Silenca653552022-12-08 17:40:01 +0100363 kDefaultInputVolumeControllerConfig.update_input_volume_wait_frames, 0,
364 absl::nullopt);
Hanna Silena6574902022-11-30 16:59:05 +0100365 FieldTrialConstrained<double> speech_probability_threshold(
366 "speech_probability_threshold",
Hanna Silenca653552022-12-08 17:40:01 +0100367 kDefaultInputVolumeControllerConfig.speech_probability_threshold, 0, 1);
Hanna Silena6574902022-11-30 16:59:05 +0100368 FieldTrialConstrained<double> speech_ratio_threshold(
Hanna Silenca653552022-12-08 17:40:01 +0100369 "speech_ratio_threshold",
370 kDefaultInputVolumeControllerConfig.speech_ratio_threshold, 0, 1);
Hanna Silena6574902022-11-30 16:59:05 +0100371
Hanna Silenca653552022-12-08 17:40:01 +0100372 constexpr AudioProcessing::Config::GainController2::AdaptiveDigital
373 kDefaultAdaptiveDigitalConfig;
374
375 FieldTrialConstrained<double> headroom_db(
376 "headroom_db", kDefaultAdaptiveDigitalConfig.headroom_db, 0,
377 absl::nullopt);
378 FieldTrialConstrained<double> max_gain_db(
379 "max_gain_db", kDefaultAdaptiveDigitalConfig.max_gain_db, 0,
380 absl::nullopt);
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100381 FieldTrialConstrained<double> initial_gain_db(
382 "initial_gain_db", kDefaultAdaptiveDigitalConfig.initial_gain_db, 0,
383 absl::nullopt);
Hanna Silenca653552022-12-08 17:40:01 +0100384 FieldTrialConstrained<double> max_gain_change_db_per_second(
385 "max_gain_change_db_per_second",
386 kDefaultAdaptiveDigitalConfig.max_gain_change_db_per_second, 0,
387 absl::nullopt);
388 FieldTrialConstrained<double> max_output_noise_level_dbfs(
389 "max_output_noise_level_dbfs",
390 kDefaultAdaptiveDigitalConfig.max_output_noise_level_dbfs, absl::nullopt,
391 0);
392
393 // Field-trial based override for the input volume controller and adaptive
394 // digital configs.
Hanna Silena6574902022-11-30 16:59:05 +0100395 const std::string field_trial_name =
Hanna Silenca653552022-12-08 17:40:01 +0100396 field_trial::FindFullName(kFieldTrialName);
Hanna Silena6574902022-11-30 16:59:05 +0100397
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100398 ParseFieldTrial(
399 {&enabled, &clipped_level_min, &clipped_level_step,
400 &clipped_ratio_threshold, &clipped_wait_frames,
401 &enable_clipping_predictor, &target_range_max_dbfs,
402 &target_range_min_dbfs, &update_input_volume_wait_frames,
403 &speech_probability_threshold, &speech_ratio_threshold, &headroom_db,
404 &max_gain_db, &initial_gain_db, &max_gain_change_db_per_second,
405 &max_output_noise_level_dbfs},
406 field_trial_name);
Hanna Silena6574902022-11-30 16:59:05 +0100407
408 // Checked already by `IsEnabled()` before parsing, therefore always true.
409 RTC_DCHECK(enabled);
410
Hanna Silenca653552022-12-08 17:40:01 +0100411 return AudioProcessingImpl::GainController2ConfigOverride{
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100412 .input_volume_controller_config =
413 {
414 .clipped_level_min = static_cast<int>(clipped_level_min.Get()),
415 .clipped_level_step = static_cast<int>(clipped_level_step.Get()),
416 .clipped_ratio_threshold =
417 static_cast<float>(clipped_ratio_threshold.Get()),
418 .clipped_wait_frames =
419 static_cast<int>(clipped_wait_frames.Get()),
420 .enable_clipping_predictor =
421 static_cast<bool>(enable_clipping_predictor.Get()),
422 .target_range_max_dbfs =
423 static_cast<int>(target_range_max_dbfs.Get()),
424 .target_range_min_dbfs =
425 static_cast<int>(target_range_min_dbfs.Get()),
426 .update_input_volume_wait_frames =
427 static_cast<int>(update_input_volume_wait_frames.Get()),
428 .speech_probability_threshold =
429 static_cast<float>(speech_probability_threshold.Get()),
430 .speech_ratio_threshold =
431 static_cast<float>(speech_ratio_threshold.Get()),
432 },
433 .adaptive_digital_config =
434 {
435 .headroom_db = static_cast<float>(headroom_db.Get()),
436 .max_gain_db = static_cast<float>(max_gain_db.Get()),
437 .initial_gain_db = static_cast<float>(initial_gain_db.Get()),
438 .max_gain_change_db_per_second =
439 static_cast<float>(max_gain_change_db_per_second.Get()),
440 .max_output_noise_level_dbfs =
441 static_cast<float>(max_output_noise_level_dbfs.Get()),
442 },
Hanna Silena6574902022-11-30 16:59:05 +0100443 };
444}
445
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100446// If `disallow_transient_supporessor_usage` is true, disables transient
Hanna Silenca653552022-12-08 17:40:01 +0100447// suppression. When `gain_controller2_config_override` is specified,
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100448// switches all gain control to AGC2.
449AudioProcessing::Config AdjustConfig(
Hanna Silena6574902022-11-30 16:59:05 +0100450 const AudioProcessing::Config& config,
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100451 bool disallow_transient_supporessor_usage,
Hanna Silenca653552022-12-08 17:40:01 +0100452 const absl::optional<AudioProcessingImpl::GainController2ConfigOverride>&
453 gain_controller2_config_override) {
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100454 AudioProcessing::Config adjusted_config = config;
455
456 // Override the transient suppressor configuration.
457 if (disallow_transient_supporessor_usage) {
458 adjusted_config.transient_suppression.enabled = false;
459 }
460
461 // Override the auto gain control configuration if the AGC1 analog gain
Hanna Silenca653552022-12-08 17:40:01 +0100462 // controller is active and `gain_controller2_config_override` is
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100463 // specified.
464 const bool agc1_analog_enabled =
Hanna Silena6574902022-11-30 16:59:05 +0100465 config.gain_controller1.enabled &&
466 (config.gain_controller1.mode ==
467 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
468 config.gain_controller1.analog_gain_controller.enabled);
Hanna Silenca653552022-12-08 17:40:01 +0100469 if (agc1_analog_enabled && gain_controller2_config_override.has_value()) {
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100470 // Check that the unadjusted AGC config meets the preconditions.
471 const bool hybrid_agc_config_detected =
472 config.gain_controller1.enabled &&
473 config.gain_controller1.analog_gain_controller.enabled &&
474 !config.gain_controller1.analog_gain_controller
475 .enable_digital_adaptive &&
476 config.gain_controller2.enabled &&
477 config.gain_controller2.adaptive_digital.enabled;
478 const bool full_agc1_config_detected =
479 config.gain_controller1.enabled &&
480 config.gain_controller1.analog_gain_controller.enabled &&
481 config.gain_controller1.analog_gain_controller
482 .enable_digital_adaptive &&
483 !config.gain_controller2.enabled;
484 const bool one_and_only_one_input_volume_controller =
485 hybrid_agc_config_detected != full_agc1_config_detected;
486 if (!one_and_only_one_input_volume_controller ||
487 config.gain_controller2.input_volume_controller.enabled) {
488 RTC_LOG(LS_ERROR) << "Cannot adjust AGC config (precondition failed)";
489 if (!one_and_only_one_input_volume_controller)
490 RTC_LOG(LS_ERROR)
491 << "One and only one input volume controller must be enabled.";
492 if (config.gain_controller2.input_volume_controller.enabled)
493 RTC_LOG(LS_ERROR)
494 << "The AGC2 input volume controller must be disabled.";
495 } else {
496 adjusted_config.gain_controller1.enabled = false;
497 adjusted_config.gain_controller1.analog_gain_controller.enabled = false;
Hanna Silenca653552022-12-08 17:40:01 +0100498
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100499 adjusted_config.gain_controller2.enabled = true;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100500 adjusted_config.gain_controller2.input_volume_controller.enabled = true;
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100501 adjusted_config.gain_controller2.adaptive_digital =
Hanna Silenca653552022-12-08 17:40:01 +0100502 gain_controller2_config_override->adaptive_digital_config;
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100503 adjusted_config.gain_controller2.adaptive_digital.enabled = true;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100504 }
Hanna Silena6574902022-11-30 16:59:05 +0100505 }
506
Hanna Silena6574902022-11-30 16:59:05 +0100507 return adjusted_config;
508}
509
Alessio Bazzica504bd592022-12-01 13:26:26 +0100510using DownmixMethod = AudioProcessing::Config::Pipeline::DownmixMethod;
511
512void SetDownmixMethod(AudioBuffer& buffer, DownmixMethod method) {
513 switch (method) {
514 case DownmixMethod::kAverageChannels:
515 buffer.set_downmixing_by_averaging();
516 break;
517 case DownmixMethod::kUseFirstChannel:
518 buffer.set_downmixing_to_specific_channel(/*channel=*/0);
519 break;
520 }
521}
522
Hanna Silena6574902022-11-30 16:59:05 +0100523constexpr int kUnspecifiedDataDumpInputVolume = -100;
524
Michael Graczyk86c6d332015-07-23 11:41:39 -0700525} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000526
527// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000528static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000529
saza1d600522019-10-18 13:29:43 +0200530AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100531 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200532 bool render_pre_processor_enabled,
533 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100534 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200535 render_pre_processor_enabled_(render_pre_processor_enabled),
536 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700537
saza1d600522019-10-18 13:29:43 +0200538bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200539 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700540 bool mobile_echo_controller_enabled,
541 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700542 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700543 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200544 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000545 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200546 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700547 bool transient_suppressor_enabled) {
548 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200549 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700550 changed |=
551 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
552 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
553 changed |=
peah2ace3f92016-09-10 04:42:27 -0700554 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200555 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200556 changed |=
557 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000558 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200559 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700560 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
561 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200562 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700563 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
564 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700565 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700566 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200567 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000568 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200569 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700570 transient_suppressor_enabled_ = transient_suppressor_enabled;
571 }
572
573 changed |= first_update_;
574 first_update_ = false;
575 return changed;
576}
577
saza1d600522019-10-18 13:29:43 +0200578bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700579 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000580 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700581}
582
saza1d600522019-10-18 13:29:43 +0200583bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
584 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200585 // If echo controller is present, assume it performs active processing.
586 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
587}
588
saza1d600522019-10-18 13:29:43 +0200589bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200590 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100591 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
592 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200593 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700594}
595
saza1d600522019-10-18 13:29:43 +0200596bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700597 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200598 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000599 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700600}
601
saza1d600522019-10-18 13:29:43 +0200602bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200603 return capture_analyzer_enabled_;
604}
605
saza1d600522019-10-18 13:29:43 +0200606bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700607 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100608 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
609 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700610}
611
saza1d600522019-10-18 13:29:43 +0200612bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100613 const {
614 return render_pre_processor_enabled_;
615}
616
saza1d600522019-10-18 13:29:43 +0200617bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700618 const {
peah2ace3f92016-09-10 04:42:27 -0700619 return false;
peah2ace3f92016-09-10 04:42:27 -0700620}
621
saza1d600522019-10-18 13:29:43 +0200622bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100623 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
624 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200625}
626
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200627AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200628 : AudioProcessingImpl(/*config=*/{},
629 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200630 /*render_pre_processor=*/nullptr,
631 /*echo_control_factory=*/nullptr,
632 /*echo_detector=*/nullptr,
633 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000634
Niels Möller7a669002022-06-27 09:47:02 +0200635std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100636
Sam Zackrisson0beac582017-09-25 12:04:02 +0200637AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200638 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100639 std::unique_ptr<CustomProcessing> capture_post_processor,
640 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200641 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200642 rtc::scoped_refptr<EchoDetector> echo_detector,
643 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200644 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100645 use_setup_specific_default_aec3_config_(
646 UseSetupSpecificDefaultAec3Congfig()),
Hanna Silenca653552022-12-08 17:40:01 +0100647 gain_controller2_config_override_(GetGainController2ConfigOverride()),
Alessio Bazzica0441bb62021-08-10 15:23:23 +0200648 use_denormal_disabler_(
649 !field_trial::IsEnabled("WebRTC-ApmDenormalDisablerKillSwitch")),
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100650 disallow_transient_supporessor_usage_(
651 field_trial::IsEnabled("WebRTC-ApmTransientSuppressorKillSwitch")),
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +0100652 transient_suppressor_vad_mode_(GetTransientSuppressorVadMode()),
Per Åhgren652ada52021-03-03 10:52:44 +0000653 capture_runtime_settings_(RuntimeSettingQueueSize()),
654 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200655 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
656 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200657 echo_control_factory_(std::move(echo_control_factory)),
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100658 config_(AdjustConfig(config,
659 disallow_transient_supporessor_usage_,
Hanna Silenca653552022-12-08 17:40:01 +0100660 gain_controller2_config_override_)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200661 submodule_states_(!!capture_post_processor,
662 !!render_pre_processor,
663 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200664 submodules_(std::move(capture_post_processor),
665 std::move(render_pre_processor),
666 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100667 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100668 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200669 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
670 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100671 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000672 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200673 MinimizeProcessingForUnusedOutput(),
674 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000675 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200676 capture_nonlocked_(),
677 applied_input_volume_stats_reporter_(
678 InputVolumeStatsReporter::InputVolumeType::kApplied),
679 recommended_input_volume_stats_reporter_(
680 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200681 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100682 "\nEcho control factory: "
683 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200684 << "\nEcho detector: " << !!submodules_.echo_detector
685 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
686 << "\nCapture post processor: "
687 << !!submodules_.capture_post_processor
688 << "\nRender pre processor: "
689 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100690 if (!DenormalDisabler::IsSupported()) {
691 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
692 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200693
Hanna Silena6574902022-11-30 16:59:05 +0100694 RTC_LOG(LS_INFO) << "AudioProcessing: " << config_.ToString();
695
Sam Zackrisson421c8592019-02-11 13:39:46 +0100696 // Mark Echo Controller enabled if a factory is injected.
697 capture_nonlocked_.echo_controller_enabled =
698 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000699
Per Åhgren0ade9832020-09-01 23:57:20 +0200700 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000701}
702
Per Åhgren0e3198e2019-11-18 08:52:22 +0100703AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000704
niklase@google.com470e71d2011-07-07 08:21:25 +0000705int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800706 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200707 MutexLock lock_render(&mutex_render_);
708 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200709 InitializeLocked();
710 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000711}
712
Michael Graczyk86c6d332015-07-23 11:41:39 -0700713int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800714 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200715 MutexLock lock_render(&mutex_render_);
716 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100717 InitializeLocked(processing_config);
718 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000719}
720
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100721void AudioProcessingImpl::MaybeInitializeRender(
722 const StreamConfig& input_config,
723 const StreamConfig& output_config) {
724 ProcessingConfig processing_config = formats_.api_format;
725 processing_config.reverse_input_stream() = input_config;
726 processing_config.reverse_output_stream() = output_config;
727
Oskar Sundbom4b276482019-05-23 14:28:00 +0200728 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100729 return;
peah192164e2015-11-17 02:16:45 -0800730 }
peahdf3efa82015-11-28 12:35:15 -0800731
Markus Handell0df0fae2020-07-07 15:53:34 +0200732 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100733 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800734}
735
Per Åhgren0ade9832020-09-01 23:57:20 +0200736void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200737 UpdateActiveSubmoduleStates();
738
Per Åhgrend47941e2019-08-22 11:51:13 +0200739 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800740 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200741 ? formats_.render_processing_format.sample_rate_hz()
742 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800743 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
744 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200745 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800746 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200747 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700748 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200749 render_audiobuffer_sample_rate_hz,
750 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700751 if (formats_.api_format.reverse_input_stream() !=
752 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800753 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800754 formats_.api_format.reverse_input_stream().num_channels(),
755 formats_.api_format.reverse_input_stream().num_frames(),
756 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800757 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700758 } else {
peahdf3efa82015-11-28 12:35:15 -0800759 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700760 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700761 } else {
peahdf3efa82015-11-28 12:35:15 -0800762 render_.render_audio.reset(nullptr);
763 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700764 }
peahce4d9152017-05-19 01:28:05 -0700765
Per Åhgrend47941e2019-08-22 11:51:13 +0200766 capture_.capture_audio.reset(new AudioBuffer(
767 formats_.api_format.input_stream().sample_rate_hz(),
768 formats_.api_format.input_stream().num_channels(),
769 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
770 formats_.api_format.output_stream().num_channels(),
771 formats_.api_format.output_stream().sample_rate_hz(),
772 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100773 SetDownmixMethod(*capture_.capture_audio,
774 config_.pipeline.capture_downmix_method);
niklase@google.com470e71d2011-07-07 08:21:25 +0000775
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200776 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
777 formats_.api_format.output_stream().sample_rate_hz() &&
778 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
779 capture_.capture_fullband_audio.reset(
780 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
781 formats_.api_format.input_stream().num_channels(),
782 formats_.api_format.output_stream().sample_rate_hz(),
783 formats_.api_format.output_stream().num_channels(),
784 formats_.api_format.output_stream().sample_rate_hz(),
785 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100786 SetDownmixMethod(*capture_.capture_fullband_audio,
787 config_.pipeline.capture_downmix_method);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200788 } else {
789 capture_.capture_fullband_audio.reset();
790 }
791
peah764e3642016-10-22 05:04:30 -0700792 AllocateRenderQueue();
793
Per Åhgren0695df12020-01-13 14:43:13 +0100794 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100795 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100796 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700797 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200798 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200799 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200800 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200801 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200802 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200803 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100804 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000805 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800806
aleloi868f32f2017-05-23 07:20:05 -0700807 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200808 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700809 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000810}
811
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100812void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200813 UpdateActiveSubmoduleStates();
814
peahdf3efa82015-11-28 12:35:15 -0800815 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000816
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200817 // Choose maximum rate to use for the split filtering.
818 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
819 config_.pipeline.maximum_internal_processing_rate == 32000);
820 int max_splitting_rate = 48000;
821 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
822 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
823 }
824
Per Åhgrenc8626b62019-08-23 15:49:51 +0200825 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700826 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700827 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200828 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700829 submodule_states_.CaptureMultiBandSubModulesActive() ||
830 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200831 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000832
peahde65ddc2016-09-16 15:02:15 -0700833 capture_nonlocked_.capture_processing_format =
834 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700835
peah2ce640f2017-04-07 03:57:48 -0700836 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200837 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200838 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700839 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
840 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200841 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700842 submodule_states_.CaptureMultiBandSubModulesActive() ||
843 submodule_states_.RenderMultiBandSubModulesActive());
844 } else {
845 render_processing_rate = capture_processing_rate;
846 }
847
peahde65ddc2016-09-16 15:02:15 -0700848 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700849 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700850 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
851 kSampleRate8kHz) {
852 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000853 } else {
peahde65ddc2016-09-16 15:02:15 -0700854 render_processing_rate =
855 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000856 }
857
Per Åhgrenc8626b62019-08-23 15:49:51 +0200858 RTC_DCHECK_NE(8000, render_processing_rate);
859
peahce4d9152017-05-19 01:28:05 -0700860 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200861 // By default, downmix the render stream to mono for analysis. This has been
862 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100863 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
864 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200865 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100866 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200867 ? formats_.api_format.reverse_input_stream().num_channels()
868 : 1;
869 formats_.render_processing_format =
870 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700871 } else {
872 formats_.render_processing_format = StreamConfig(
873 formats_.api_format.reverse_input_stream().sample_rate_hz(),
874 formats_.api_format.reverse_input_stream().num_channels());
875 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000876
peahde65ddc2016-09-16 15:02:15 -0700877 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
878 kSampleRate32kHz ||
879 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
880 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800881 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000882 } else {
peahdf3efa82015-11-28 12:35:15 -0800883 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700884 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000885 }
886
Per Åhgren0ade9832020-09-01 23:57:20 +0200887 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000888}
889
peah88ac8532016-09-12 16:47:25 -0700890void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700891 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200892 MutexLock lock_render(&mutex_render_);
893 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700894
Hanna Silena6574902022-11-30 16:59:05 +0100895 const auto adjusted_config =
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100896 AdjustConfig(config, disallow_transient_supporessor_usage_,
Hanna Silenca653552022-12-08 17:40:01 +0100897 gain_controller2_config_override_);
Hanna Silena6574902022-11-30 16:59:05 +0100898 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: "
899 << adjusted_config.ToString();
900
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200901 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100902 config_.pipeline.multi_channel_render !=
Hanna Silena6574902022-11-30 16:59:05 +0100903 adjusted_config.pipeline.multi_channel_render ||
Per Åhgrene14cb992019-11-27 09:34:22 +0100904 config_.pipeline.multi_channel_capture !=
Hanna Silena6574902022-11-30 16:59:05 +0100905 adjusted_config.pipeline.multi_channel_capture ||
Per Åhgrenc0424252019-12-10 13:04:15 +0100906 config_.pipeline.maximum_internal_processing_rate !=
Alessio Bazzica504bd592022-12-01 13:26:26 +0100907 adjusted_config.pipeline.maximum_internal_processing_rate ||
908 config_.pipeline.capture_downmix_method !=
909 adjusted_config.pipeline.capture_downmix_method;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200910
Per Åhgren200feba2019-03-06 04:16:46 +0100911 const bool aec_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100912 config_.echo_canceller.enabled !=
913 adjusted_config.echo_canceller.enabled ||
914 config_.echo_canceller.mobile_mode !=
915 adjusted_config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100916
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100917 const bool agc1_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100918 config_.gain_controller1 != adjusted_config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100919
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100920 const bool agc2_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100921 config_.gain_controller2 != adjusted_config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100922
saza0bad15f2019-10-16 11:46:11 +0200923 const bool ns_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100924 config_.noise_suppression.enabled !=
925 adjusted_config.noise_suppression.enabled ||
926 config_.noise_suppression.level !=
927 adjusted_config.noise_suppression.level;
saza0bad15f2019-10-16 11:46:11 +0200928
Per Åhgrenc0734712020-01-02 15:15:36 +0100929 const bool ts_config_changed = config_.transient_suppression.enabled !=
Hanna Silena6574902022-11-30 16:59:05 +0100930 adjusted_config.transient_suppression.enabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100931
Per Åhgren0f14db22020-01-03 14:27:14 +0100932 const bool pre_amplifier_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100933 config_.pre_amplifier.enabled != adjusted_config.pre_amplifier.enabled ||
Per Åhgren0f14db22020-01-03 14:27:14 +0100934 config_.pre_amplifier.fixed_gain_factor !=
Hanna Silena6574902022-11-30 16:59:05 +0100935 adjusted_config.pre_amplifier.fixed_gain_factor;
Per Åhgren0f14db22020-01-03 14:27:14 +0100936
Per Åhgrendb5d7282021-03-15 16:31:04 +0000937 const bool gain_adjustment_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100938 config_.capture_level_adjustment !=
939 adjusted_config.capture_level_adjustment;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000940
Hanna Silena6574902022-11-30 16:59:05 +0100941 config_ = adjusted_config;
Yves Gerey499bc6c2018-10-10 18:29:07 +0200942
Per Åhgren200feba2019-03-06 04:16:46 +0100943 if (aec_config_changed) {
944 InitializeEchoController();
945 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200946
saza0bad15f2019-10-16 11:46:11 +0200947 if (ns_config_changed) {
948 InitializeNoiseSuppressor();
949 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100950
Per Åhgrenc0734712020-01-02 15:15:36 +0100951 if (ts_config_changed) {
952 InitializeTransientSuppressor();
953 }
954
Per Åhgren0f14db22020-01-03 14:27:14 +0100955 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800956
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100957 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100958 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100959 }
960
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100961 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700962 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200963 RTC_LOG(LS_ERROR)
964 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700965 config_.gain_controller2 = AudioProcessing::Config::GainController2();
966 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100967
Alessio Bazzica38901042021-10-14 12:14:21 +0200968 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200969 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100970
Per Åhgrendb5d7282021-03-15 16:31:04 +0000971 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
972 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100973 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100974
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200975 // Reinitialization must happen after all submodule configuration to avoid
976 // additional reinitializations on the next capture / render processing call.
977 if (pipeline_config_changed) {
978 InitializeLocked(formats_.api_format);
979 }
peah88ac8532016-09-12 16:47:25 -0700980}
981
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200982void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
983 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200984 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200985 submodule_creation_overrides_ = overrides;
986}
987
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000988int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800989 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700990 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000991}
992
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200993int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
994 return capture_.capture_fullband_audio
995 ? capture_.capture_fullband_audio->num_frames() * 100
996 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
997}
998
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000999int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001000 // Used as callback from submodules, hence locking is not allowed.
1001 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +00001002}
1003
Peter Kasting69558702016-01-12 16:26:35 -08001004size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001005 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001006 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001007}
1008
Peter Kasting69558702016-01-12 16:26:35 -08001009size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001010 // Used as callback from submodules, hence locking is not allowed.
1011 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001012}
1013
Peter Kasting69558702016-01-12 16:26:35 -08001014size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -08001015 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +01001016 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1017 constants_.multi_channel_capture_support;
1018 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001019 return 1;
1020 }
1021 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -08001022}
1023
Peter Kasting69558702016-01-12 16:26:35 -08001024size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001025 // Used as callback from submodules, hence locking is not allowed.
1026 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001027}
1028
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001029void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001030 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +01001031 HandleCaptureOutputUsedSetting(!muted);
1032}
1033
1034void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
1035 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001036 capture_.capture_output_used =
1037 capture_output_used || !constants_.minimize_processing_for_unused_output;
1038
saza1d600522019-10-18 13:29:43 +02001039 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001040 submodules_.agc_manager->HandleCaptureOutputUsedChange(
1041 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001042 }
Per Åhgren652ada52021-03-03 10:52:44 +00001043 if (submodules_.echo_controller) {
1044 submodules_.echo_controller->SetCaptureOutputUsage(
1045 capture_.capture_output_used);
1046 }
Per Åhgren15179a92021-03-12 14:12:44 +00001047 if (submodules_.noise_suppressor) {
1048 submodules_.noise_suppressor->SetCaptureOutputUsage(
1049 capture_.capture_output_used);
1050 }
Hanna Silend4dbe452022-11-30 15:16:21 +01001051 if (submodules_.gain_controller2) {
1052 submodules_.gain_controller2->SetCaptureOutputUsed(
1053 capture_.capture_output_used);
1054 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001055}
1056
Alessio Bazzicac054e782018-04-16 12:10:09 +02001057void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001058 PostRuntimeSetting(setting);
1059}
1060
1061bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +02001062 switch (setting.type()) {
1063 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001064 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +01001065 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001066 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001067 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001068 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001069 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +02001070 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001071 return capture_runtime_settings_enqueuer_.Enqueue(setting);
1072 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1073 bool enqueueing_successful;
1074 enqueueing_successful =
1075 capture_runtime_settings_enqueuer_.Enqueue(setting);
1076 enqueueing_successful =
1077 render_runtime_settings_enqueuer_.Enqueue(setting) &&
1078 enqueueing_successful;
1079 return enqueueing_successful;
1080 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001081 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001082 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001083 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +02001084 }
1085 // The language allows the enum to have a non-enumerator
1086 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +01001087 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001088 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001089}
1090
1091AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
1092 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001093 : runtime_settings_(*runtime_settings) {
1094 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001095}
1096
1097AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
1098 default;
1099
Per Åhgren0a144a72021-02-09 08:47:51 +01001100bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +02001101 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +00001102 const bool successful_insert = runtime_settings_.Insert(&setting);
1103
1104 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001105 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +02001106 }
Per Åhgren652ada52021-03-03 10:52:44 +00001107 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001108}
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001109
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001110void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001111 const StreamConfig& input_config,
1112 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001113 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001114 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001115 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001116 // Acquire the capture lock in order to access api_format. The lock is
1117 // released immediately, as we may need to acquire the render lock as part
1118 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +02001119 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001120 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001121 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +00001122 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001123
Oskar Sundbom4b276482019-05-23 14:28:00 +02001124 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001125 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -08001126 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001127
1128 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001129 reinitialization_required = true;
1130 }
1131
1132 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001133 MutexLock lock_render(&mutex_render_);
1134 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +02001135 // Reread the API format since the render format may have changed.
1136 processing_config = formats_.api_format;
1137 processing_config.input_stream() = input_config;
1138 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001139 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001140 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001141}
1142
1143int AudioProcessingImpl::ProcessStream(const float* const* src,
1144 const StreamConfig& input_config,
1145 const StreamConfig& output_config,
1146 float* const* dest) {
1147 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001148 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1149 RETURN_ON_ERR(
1150 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1151 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001152
Markus Handell0df0fae2020-07-07 15:53:34 +02001153 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001154
aleloi868f32f2017-05-23 07:20:05 -07001155 if (aec_dump_) {
1156 RecordUnprocessedCaptureStream(src);
1157 }
1158
peahdf3efa82015-11-28 12:35:15 -08001159 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001160 if (capture_.capture_fullband_audio) {
1161 capture_.capture_fullband_audio->CopyFrom(
1162 src, formats_.api_format.input_stream());
1163 }
peahde65ddc2016-09-16 15:02:15 -07001164 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001165 if (capture_.capture_fullband_audio) {
1166 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1167 dest);
1168 } else {
1169 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1170 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001171
aleloi868f32f2017-05-23 07:20:05 -07001172 if (aec_dump_) {
1173 RecordProcessedCaptureStream(dest);
1174 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001175 return kNoError;
1176}
1177
Alex Loiko73ec0192018-05-15 10:52:28 +02001178void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001179 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +00001180 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +02001181 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001182 if (aec_dump_) {
1183 aec_dump_->WriteRuntimeSetting(setting);
1184 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001185 switch (setting.type()) {
1186 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001187 if (config_.pre_amplifier.enabled ||
1188 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +02001189 float value;
1190 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001191 // If the pre-amplifier is used, apply the new gain to the
1192 // pre-amplifier regardless if the capture level adjustment is
1193 // activated. This approach allows both functionalities to coexist
1194 // until they have been properly merged.
1195 if (config_.pre_amplifier.enabled) {
1196 config_.pre_amplifier.fixed_gain_factor = value;
1197 } else {
1198 config_.capture_level_adjustment.pre_gain_factor = value;
1199 }
1200
1201 // Use both the pre-amplifier and the capture level adjustment gains
1202 // as pre-gains.
1203 float gain = 1.f;
1204 if (config_.pre_amplifier.enabled) {
1205 gain *= config_.pre_amplifier.fixed_gain_factor;
1206 }
1207 if (config_.capture_level_adjustment.enabled) {
1208 gain *= config_.capture_level_adjustment.pre_gain_factor;
1209 }
1210
1211 submodules_.capture_levels_adjuster->SetPreGain(gain);
1212 }
1213 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
1214 break;
1215 case RuntimeSetting::Type::kCapturePostGain:
1216 if (config_.capture_level_adjustment.enabled) {
1217 float value;
1218 setting.GetFloat(&value);
1219 config_.capture_level_adjustment.post_gain_factor = value;
1220 submodules_.capture_levels_adjuster->SetPostGain(
1221 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001222 }
1223 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001224 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001225 case RuntimeSetting::Type::kCaptureCompressionGain: {
Hanna Silend4dbe452022-11-30 15:16:21 +01001226 if (!submodules_.agc_manager &&
1227 !(submodules_.gain_controller2 &&
1228 config_.gain_controller2.input_volume_controller.enabled)) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001229 float value;
1230 setting.GetFloat(&value);
1231 int int_value = static_cast<int>(value + .5f);
1232 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001233 if (submodules_.gain_control) {
1234 int error =
1235 submodules_.gain_control->set_compression_gain_db(int_value);
1236 RTC_DCHECK_EQ(kNoError, error);
1237 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001238 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001239 break;
1240 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001241 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001242 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001243 float value;
1244 setting.GetFloat(&value);
1245 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001246 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001247 }
1248 break;
1249 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001250 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1251 int value;
1252 setting.GetInt(&value);
1253 capture_.playout_volume = value;
1254 break;
1255 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001256 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001257 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001258 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001259 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001260 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001261 break;
1262 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001263 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001264 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001265 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001266 bool value;
1267 setting.GetBool(&value);
1268 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001269 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001270 }
Per Åhgren652ada52021-03-03 10:52:44 +00001271 ++num_settings_processed;
1272 }
1273
1274 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1275 // Handle overrun of the runtime settings queue, which likely will has
1276 // caused settings to be discarded.
1277 HandleOverrunInCaptureRuntimeSettingsQueue();
1278 }
1279}
1280
1281void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1282 // Fall back to a safe state for the case when a setting for capture output
1283 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001284 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001285}
1286
1287void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1288 RuntimeSetting setting;
1289 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001290 if (aec_dump_) {
1291 aec_dump_->WriteRuntimeSetting(setting);
1292 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001293 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001294 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001295 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001296 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001297 if (submodules_.render_pre_processor) {
1298 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001299 }
1300 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001301 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001302 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001303 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001304 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001305 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001306 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001307 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001308 break;
1309 }
1310 }
1311}
1312
peah9e6a2902017-05-15 07:19:21 -07001313void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001314 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001315
saza1d600522019-10-18 13:29:43 +02001316 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001317 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1318 num_reverse_channels(),
1319 &aecm_render_queue_buffer_);
1320 RTC_DCHECK(aecm_render_signal_queue_);
1321 // Insert the samples into the queue.
1322 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1323 // The data queue is full and needs to be emptied.
1324 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001325
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001326 // Retry the insert (should always work).
1327 bool result =
1328 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1329 RTC_DCHECK(result);
1330 }
peah764e3642016-10-22 05:04:30 -07001331 }
peah701d6282016-10-25 05:42:20 -07001332
Per Åhgren0695df12020-01-13 14:43:13 +01001333 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001334 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001335 // Insert the samples into the queue.
1336 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1337 // The data queue is full and needs to be emptied.
1338 EmptyQueuedRenderAudio();
1339
1340 // Retry the insert (should always work).
1341 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1342 RTC_DCHECK(result);
1343 }
1344 }
peah9e6a2902017-05-15 07:19:21 -07001345}
ivoc9f4a4a02016-10-28 05:39:16 -07001346
peah9e6a2902017-05-15 07:19:21 -07001347void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001348 if (submodules_.echo_detector) {
1349 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1350 RTC_DCHECK(red_render_signal_queue_);
1351 // Insert the samples into the queue.
1352 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1353 // The data queue is full and needs to be emptied.
1354 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001355
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001356 // Retry the insert (should always work).
1357 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1358 RTC_DCHECK(result);
1359 }
ivoc9f4a4a02016-10-28 05:39:16 -07001360 }
peah764e3642016-10-22 05:04:30 -07001361}
1362
1363void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001364 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001365 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001366
ivoc9f4a4a02016-10-28 05:39:16 -07001367 const size_t new_red_render_queue_element_max_size =
1368 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1369
peaha0624602016-10-25 04:45:24 -07001370 // Reallocate the queues if the queue item sizes are too small to fit the
1371 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001372
1373 if (agc_render_queue_element_max_size_ <
1374 new_agc_render_queue_element_max_size) {
1375 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1376
1377 std::vector<int16_t> template_queue_element(
1378 agc_render_queue_element_max_size_);
1379
1380 agc_render_signal_queue_.reset(
1381 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1382 kMaxNumFramesToBuffer, template_queue_element,
1383 RenderQueueItemVerifier<int16_t>(
1384 agc_render_queue_element_max_size_)));
1385
1386 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1387 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1388 } else {
1389 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001390 }
ivoc9f4a4a02016-10-28 05:39:16 -07001391
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001392 if (submodules_.echo_detector) {
1393 if (red_render_queue_element_max_size_ <
1394 new_red_render_queue_element_max_size) {
1395 red_render_queue_element_max_size_ =
1396 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001397
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001398 std::vector<float> template_queue_element(
1399 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001400
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001401 red_render_signal_queue_.reset(
1402 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1403 kMaxNumFramesToBuffer, template_queue_element,
1404 RenderQueueItemVerifier<float>(
1405 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001406
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001407 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1408 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1409 } else {
1410 red_render_signal_queue_->Clear();
1411 }
ivoc9f4a4a02016-10-28 05:39:16 -07001412 }
peah764e3642016-10-22 05:04:30 -07001413}
1414
1415void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001416 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001417 EmptyQueuedRenderAudioLocked();
1418}
1419
1420void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001421 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001422 RTC_DCHECK(aecm_render_signal_queue_);
1423 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001424 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001425 aecm_capture_queue_buffer_);
1426 }
peah701d6282016-10-25 05:42:20 -07001427 }
1428
Per Åhgren0695df12020-01-13 14:43:13 +01001429 if (submodules_.gain_control) {
1430 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1431 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1432 }
peah764e3642016-10-22 05:04:30 -07001433 }
ivoc9f4a4a02016-10-28 05:39:16 -07001434
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001435 if (submodules_.echo_detector) {
1436 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1437 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1438 }
ivoc9f4a4a02016-10-28 05:39:16 -07001439 }
peah764e3642016-10-22 05:04:30 -07001440}
1441
Per Åhgren645f24c2020-03-16 12:06:02 +01001442int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1443 const StreamConfig& input_config,
1444 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001445 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001446 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001447
1448 RETURN_ON_ERR(
1449 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1450 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001451
Markus Handell0df0fae2020-07-07 15:53:34 +02001452 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001453 DenormalDisabler denormal_disabler(use_denormal_disabler_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001454
aleloi868f32f2017-05-23 07:20:05 -07001455 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001456 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001457 }
1458
Per Åhgren645f24c2020-03-16 12:06:02 +01001459 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001460 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001461 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001462 }
peahde65ddc2016-09-16 15:02:15 -07001463 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001464 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001465 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001466 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001467 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001468 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001469 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001470 }
Per Åhgrena1351272019-08-15 12:15:46 +02001471 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001472
aleloi868f32f2017-05-23 07:20:05 -07001473 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001474 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001475 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001476 return kNoError;
1477}
1478
peahde65ddc2016-09-16 15:02:15 -07001479int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001480 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001481 HandleCaptureRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001482 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001483
peahb58a1582016-03-15 09:34:24 -07001484 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001485 // TODO(peah): Simplify once the public API Enable functions for these
1486 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001487 RTC_DCHECK_LE(
1488 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001489
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001490 data_dumper_->DumpRaw(
1491 "applied_input_volume",
1492 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1493
peahde65ddc2016-09-16 15:02:15 -07001494 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001495 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001496
Per Åhgrenc0424252019-12-10 13:04:15 +01001497 if (submodules_.high_pass_filter &&
1498 config_.high_pass_filter.apply_in_full_band &&
1499 !constants_.enforce_split_band_hpf) {
1500 submodules_.high_pass_filter->Process(capture_buffer,
1501 /*use_split_band_data=*/false);
1502 }
1503
Per Åhgrendb5d7282021-03-15 16:31:04 +00001504 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001505 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001506 // When the input volume is emulated, retrieve the volume applied to the
1507 // input audio and notify that to APM so that the volume is passed to the
1508 // active AGC.
1509 set_stream_analog_level_locked(
1510 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001511 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001512 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1513 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001514 }
1515
Per Åhgren928146f2019-08-20 09:19:21 +02001516 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001517 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001518 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001519 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1520 if (log_rms) {
1521 capture_rms_interval_counter_ = 0;
1522 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001523 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1524 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1525 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1526 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001527 }
1528
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001529 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001530 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001531 *capture_.applied_input_volume);
1532 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001533
saza1d600522019-10-18 13:29:43 +02001534 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001535 // Determine if the echo path gain has changed by checking all the gains
1536 // applied before AEC.
1537 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001538
Per Åhgrendb5d7282021-03-15 16:31:04 +00001539 // Detect and flag any change in the capture level adjustment pre-gain.
1540 if (submodules_.capture_levels_adjuster) {
1541 float pre_adjustment_gain =
1542 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001543 capture_.echo_path_gain_change =
1544 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001545 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001546 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001547 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001548 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001549
1550 // Detect volume change.
1551 capture_.echo_path_gain_change =
1552 capture_.echo_path_gain_change ||
1553 (capture_.prev_playout_volume != capture_.playout_volume &&
1554 capture_.prev_playout_volume >= 0);
1555 capture_.prev_playout_volume = capture_.playout_volume;
1556
saza1d600522019-10-18 13:29:43 +02001557 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001558 }
1559
Per Åhgren0695df12020-01-13 14:43:13 +01001560 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001561 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001562 }
1563
Hanna Silend4dbe452022-11-30 15:16:21 +01001564 if (submodules_.gain_controller2 &&
1565 config_.gain_controller2.input_volume_controller.enabled) {
1566 // Expect the volume to be available if the input controller is enabled.
1567 RTC_DCHECK(capture_.applied_input_volume.has_value());
1568 if (capture_.applied_input_volume.has_value()) {
1569 submodules_.gain_controller2->Analyze(*capture_.applied_input_volume,
1570 *capture_buffer);
1571 }
1572 }
1573
peah2ace3f92016-09-10 04:42:27 -07001574 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1575 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001576 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1577 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001578 }
1579
Per Åhgrene14cb992019-11-27 09:34:22 +01001580 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1581 constants_.multi_channel_capture_support;
1582 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001583 // Force down-mixing of the number of channels after the detection of
1584 // capture signal saturation.
1585 // TODO(peah): Look into ensuring that this kind of tampering with the
1586 // AudioBuffer functionality should not be needed.
1587 capture_buffer->set_num_channels(1);
1588 }
1589
Per Åhgrenc0424252019-12-10 13:04:15 +01001590 if (submodules_.high_pass_filter &&
1591 (!config_.high_pass_filter.apply_in_full_band ||
1592 constants_.enforce_split_band_hpf)) {
1593 submodules_.high_pass_filter->Process(capture_buffer,
1594 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001595 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001596
Per Åhgren0695df12020-01-13 14:43:13 +01001597 if (submodules_.gain_control) {
1598 RETURN_ON_ERR(
1599 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1600 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001601
Per Åhgren8ad9e742020-01-30 07:40:58 +01001602 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1603 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1604 submodules_.noise_suppressor) {
1605 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001606 }
peahb58a1582016-03-15 09:34:24 -07001607
saza1d600522019-10-18 13:29:43 +02001608 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001609 // Ensure that the stream delay was set before the call to the
1610 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001611 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001612 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001613 }
1614
saza1d600522019-10-18 13:29:43 +02001615 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001616 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001617 }
peahe0eae3c2016-12-14 01:16:23 -08001618
saza1d600522019-10-18 13:29:43 +02001619 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001620 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001621 } else {
saza1d600522019-10-18 13:29:43 +02001622 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001623 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1624
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001625 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001626 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001627 }
1628
saza1d600522019-10-18 13:29:43 +02001629 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001630 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001631 }
1632
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001633 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001634 linear_aec_buffer && submodules_.noise_suppressor) {
1635 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001636 }
1637
saza1d600522019-10-18 13:29:43 +02001638 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001639 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001640 }
Per Åhgren46537a32017-06-07 10:08:10 +02001641 }
ivoc9f4a4a02016-10-28 05:39:16 -07001642
Per Åhgren0695df12020-01-13 14:43:13 +01001643 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001644 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001645
1646 absl::optional<int> new_digital_gain =
1647 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001648 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001649 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1650 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001651 }
Per Åhgren0695df12020-01-13 14:43:13 +01001652
1653 if (submodules_.gain_control) {
1654 // TODO(peah): Add reporting from AEC3 whether there is echo.
1655 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1656 capture_buffer, /*stream_has_echo*/ false));
1657 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001658
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001659 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1660 SampleRateSupportsMultiBand(
1661 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1662 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001663 }
1664
Per Åhgren19775cb2021-03-12 23:08:09 +00001665 if (capture_.capture_output_used) {
1666 if (capture_.capture_fullband_audio) {
1667 const auto& ec = submodules_.echo_controller;
1668 bool ec_active = ec ? ec->ActiveProcessing() : false;
1669 // Only update the fullband buffer if the multiband processing has changed
1670 // the signal. Keep the original signal otherwise.
1671 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1672 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1673 }
1674 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001675 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001676
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001677 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001678 submodules_.echo_detector->AnalyzeCaptureAudio(
1679 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1680 capture_buffer->num_frames()));
1681 }
1682
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001683 absl::optional<float> voice_probability;
1684 if (!!submodules_.voice_activity_detector) {
1685 voice_probability = submodules_.voice_activity_detector->Analyze(
1686 AudioFrameView<const float>(capture_buffer->channels(),
1687 capture_buffer->num_channels(),
1688 capture_buffer->num_frames()));
1689 }
1690
Per Åhgren19775cb2021-03-12 23:08:09 +00001691 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001692 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001693 switch (transient_suppressor_vad_mode_) {
1694 case TransientSuppressor::VadMode::kDefault:
1695 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001696 transient_suppressor_voice_probability =
1697 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001698 }
1699 break;
1700 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001701 RTC_DCHECK(voice_probability.has_value());
1702 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001703 break;
1704 case TransientSuppressor::VadMode::kNoVad:
1705 // The transient suppressor will ignore `voice_probability`.
1706 break;
1707 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001708 float delayed_voice_probability =
1709 submodules_.transient_suppressor->Suppress(
1710 capture_buffer->channels()[0], capture_buffer->num_frames(),
1711 capture_buffer->num_channels(),
1712 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1713 capture_buffer->num_frames_per_band(),
1714 /*reference_data=*/nullptr, /*reference_length=*/0,
1715 transient_suppressor_voice_probability, capture_.key_pressed);
1716 if (voice_probability.has_value()) {
1717 *voice_probability = delayed_voice_probability;
1718 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001719 }
1720
Artem Titov0b489302021-07-28 20:50:03 +02001721 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001722 if (submodules_.capture_analyzer) {
1723 submodules_.capture_analyzer->Analyze(capture_buffer);
1724 }
1725
1726 if (submodules_.gain_controller2) {
Hanna Silend4dbe452022-11-30 15:16:21 +01001727 // TODO(bugs.webrtc.org/7494): Let AGC2 detect applied input volume
1728 // changes.
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001729 submodules_.gain_controller2->Process(
1730 voice_probability, capture_.applied_input_volume_changed,
1731 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001732 }
1733
1734 if (submodules_.capture_post_processor) {
1735 submodules_.capture_post_processor->Process(capture_buffer);
1736 }
1737
Per Åhgren19775cb2021-03-12 23:08:09 +00001738 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1739 capture_buffer->channels_const()[0],
1740 capture_nonlocked_.capture_processing_format.num_frames()));
1741 if (log_rms) {
1742 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1743 RTC_HISTOGRAM_COUNTS_LINEAR(
1744 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1745 RmsLevel::kMinLevelDb, 64);
1746 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1747 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1748 }
1749
Per Åhgren19775cb2021-03-12 23:08:09 +00001750 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001751 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001752 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1753 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1754 capture_.stats.residual_echo_likelihood_recent_max =
1755 ed_metrics.echo_likelihood_recent_max;
1756 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001757 }
1758
Per Åhgren19775cb2021-03-12 23:08:09 +00001759 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001760 if (submodules_.echo_controller) {
1761 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1762 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1763 capture_.stats.echo_return_loss_enhancement =
1764 ec_metrics.echo_return_loss_enhancement;
1765 capture_.stats.delay_ms = ec_metrics.delay_ms;
1766 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001767
1768 // Pass stats for reporting.
1769 stats_reporter_.UpdateStatistics(capture_.stats);
1770
Alessio Bazzica533e4612022-09-07 16:58:33 +02001771 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001772 if (capture_.recommended_input_volume.has_value()) {
1773 recommended_input_volume_stats_reporter_.UpdateStatistics(
1774 *capture_.recommended_input_volume);
1775 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001776
Per Åhgrendb5d7282021-03-15 16:31:04 +00001777 if (submodules_.capture_levels_adjuster) {
1778 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1779 *capture_buffer);
1780
Per Åhgrendb5d7282021-03-15 16:31:04 +00001781 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001782 // If the input volume emulation is used, retrieve the recommended input
1783 // volume and set that to emulate the input volume on the next processed
1784 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001785 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001786 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001787 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001788 }
1789 }
1790
Per Åhgren55bc0772021-03-12 14:18:36 +00001791 // Temporarily set the output to zero after the stream has been unmuted
1792 // (capture output is again used). The purpose of this is to avoid clicks and
1793 // artefacts in the audio that results when the processing again is
1794 // reactivated after unmuting.
1795 if (!capture_.capture_output_used_last_frame &&
1796 capture_.capture_output_used) {
1797 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1798 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1799 capture_buffer->num_frames());
1800 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1801 }
1802 }
1803 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1804
peahdf3efa82015-11-28 12:35:15 -08001805 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001806
Alessio Bazzica533e4612022-09-07 16:58:33 +02001807 data_dumper_->DumpRaw("recommended_input_volume",
1808 capture_.recommended_input_volume.value_or(
1809 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001810
niklase@google.com470e71d2011-07-07 08:21:25 +00001811 return kNoError;
1812}
1813
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001814int AudioProcessingImpl::AnalyzeReverseStream(
1815 const float* const* data,
1816 const StreamConfig& reverse_config) {
1817 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001818 MutexLock lock(&mutex_render_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001819 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1820 RTC_DCHECK(data);
1821 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1822 RTC_DCHECK(data[i]);
1823 }
1824 RETURN_ON_ERR(
1825 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1826
1827 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001828 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1829}
1830
peahde65ddc2016-09-16 15:02:15 -07001831int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1832 const StreamConfig& input_config,
1833 const StreamConfig& output_config,
1834 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001835 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001836 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001837 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001838 RETURN_ON_ERR(
1839 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1840
1841 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001842
peahde65ddc2016-09-16 15:02:15 -07001843 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001844
Alex Loiko5825aa62017-12-18 16:02:40 +01001845 if (submodule_states_.RenderMultiBandProcessingActive() ||
1846 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001847 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1848 dest);
peah2ace3f92016-09-10 04:42:27 -07001849 } else if (formats_.api_format.reverse_input_stream() !=
1850 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001851 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1852 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001853 } else {
peahde65ddc2016-09-16 15:02:15 -07001854 CopyAudioIfNeeded(src, input_config.num_frames(),
1855 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001856 }
1857
1858 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001859}
1860
peahdf3efa82015-11-28 12:35:15 -08001861int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001862 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001863 const StreamConfig& input_config,
1864 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001865 if (aec_dump_) {
1866 const size_t channel_size =
1867 formats_.api_format.reverse_input_stream().num_frames();
1868 const size_t num_channels =
1869 formats_.api_format.reverse_input_stream().num_channels();
1870 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001871 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001872 }
peahdf3efa82015-11-28 12:35:15 -08001873 render_.render_audio->CopyFrom(src,
1874 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001875 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001876}
1877
Per Åhgren645f24c2020-03-16 12:06:02 +01001878int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1879 const StreamConfig& input_config,
1880 const StreamConfig& output_config,
1881 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001882 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001883
Markus Handell0df0fae2020-07-07 15:53:34 +02001884 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001885 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1886
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001887 RETURN_ON_ERR(
1888 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1889 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001890
aleloi868f32f2017-05-23 07:20:05 -07001891 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001892 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1893 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001894 }
1895
Per Åhgren645f24c2020-03-16 12:06:02 +01001896 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001897 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001898 if (submodule_states_.RenderMultiBandProcessingActive() ||
1899 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001900 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001901 }
aluebsb0319552016-03-17 20:39:53 -07001902 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001903}
niklase@google.com470e71d2011-07-07 08:21:25 +00001904
peahde65ddc2016-09-16 15:02:15 -07001905int AudioProcessingImpl::ProcessRenderStreamLocked() {
1906 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001907
Alex Loiko73ec0192018-05-15 10:52:28 +02001908 HandleRenderRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001909 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alex Loiko73ec0192018-05-15 10:52:28 +02001910
saza1d600522019-10-18 13:29:43 +02001911 if (submodules_.render_pre_processor) {
1912 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001913 }
1914
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001915 QueueNonbandedRenderAudio(render_buffer);
1916
peah2ace3f92016-09-10 04:42:27 -07001917 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001918 SampleRateSupportsMultiBand(
1919 formats_.render_processing_format.sample_rate_hz())) {
1920 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001921 }
1922
peahce4d9152017-05-19 01:28:05 -07001923 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1924 QueueBandedRenderAudio(render_buffer);
1925 }
1926
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001927 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001928 if (submodules_.echo_controller) {
1929 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001930 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001931
peah2ace3f92016-09-10 04:42:27 -07001932 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001933 SampleRateSupportsMultiBand(
1934 formats_.render_processing_format.sample_rate_hz())) {
1935 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001936 }
1937
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001938 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001939}
1940
1941int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001942 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001943 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001944 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001945
niklase@google.com470e71d2011-07-07 08:21:25 +00001946 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001947 delay = 0;
1948 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001949 }
1950
1951 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1952 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001953 delay = 500;
1954 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001955 }
1956
peahdf3efa82015-11-28 12:35:15 -08001957 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001958 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001959}
1960
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001961bool AudioProcessingImpl::GetLinearAecOutput(
1962 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001963 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001964 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1965
1966 RTC_DCHECK(linear_aec_buffer);
1967 if (linear_aec_buffer) {
1968 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1969 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1970
1971 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1972 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1973 rtc::ArrayView<const float> channel_view =
1974 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1975 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001976 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1977 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001978 }
1979 return true;
1980 }
1981 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001982 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001983 return false;
1984}
1985
niklase@google.com470e71d2011-07-07 08:21:25 +00001986int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001987 // Used as callback from submodules, hence locking is not allowed.
1988 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001989}
1990
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001991void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001992 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001993 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001994}
1995
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001996void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001997 MutexLock lock_capture(&mutex_capture_);
1998 set_stream_analog_level_locked(level);
1999}
2000
2001void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002002 capture_.applied_input_volume_changed =
2003 capture_.applied_input_volume.has_value() &&
2004 *capture_.applied_input_volume != level;
2005 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002006
Alessio Bazzica533e4612022-09-07 16:58:33 +02002007 // Invalidate any previously recommended input volume which will be updated by
2008 // `ProcessStream()`.
2009 capture_.recommended_input_volume = absl::nullopt;
2010
Per Åhgren0e3198e2019-11-18 08:52:22 +01002011 if (submodules_.agc_manager) {
2012 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002013 return;
2014 }
2015
2016 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01002017 int error = submodules_.gain_control->set_stream_analog_level(level);
2018 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002019 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002020 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002021}
2022
2023int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002024 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002025 if (!capture_.applied_input_volume.has_value()) {
2026 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
2027 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02002028 // Input volume to recommend when `set_stream_analog_level()` is not called.
2029 constexpr int kFallBackInputVolume = 255;
2030 // When APM has no input volume to recommend, return the latest applied input
2031 // volume that has been observed in order to possibly produce no input volume
2032 // change. If no applied input volume has been observed, return a fall-back
2033 // value.
2034 return capture_.recommended_input_volume.value_or(
2035 capture_.applied_input_volume.value_or(kFallBackInputVolume));
2036}
2037
2038void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
2039 if (!capture_.applied_input_volume.has_value()) {
2040 // When `set_stream_analog_level()` is not called, no input level can be
2041 // recommended.
2042 capture_.recommended_input_volume = absl::nullopt;
2043 return;
2044 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002045
Per Åhgrendb5d7282021-03-15 16:31:04 +00002046 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002047 capture_.recommended_input_volume =
2048 submodules_.agc_manager->recommended_analog_level();
2049 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002050 }
2051
2052 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002053 capture_.recommended_input_volume =
2054 submodules_.gain_control->stream_analog_level();
2055 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002056 }
2057
Hanna Silend4dbe452022-11-30 15:16:21 +01002058 if (submodules_.gain_controller2 &&
2059 config_.gain_controller2.input_volume_controller.enabled) {
2060 capture_.recommended_input_volume =
2061 submodules_.gain_controller2->GetRecommendedInputVolume();
2062 return;
2063 }
2064
Alessio Bazzica533e4612022-09-07 16:58:33 +02002065 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002066}
2067
Ali Tofigh1fa87c42022-07-25 22:07:08 +02002068bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
2069 int64_t max_log_size_bytes,
2070 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02002071 std::unique_ptr<AecDump> aec_dump =
2072 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02002073 if (!aec_dump) {
2074 return false;
2075 }
2076
2077 AttachAecDump(std::move(aec_dump));
2078 return true;
2079}
2080
2081bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
2082 int64_t max_log_size_bytes,
2083 rtc::TaskQueue* worker_queue) {
2084 std::unique_ptr<AecDump> aec_dump =
2085 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
2086 if (!aec_dump) {
2087 return false;
2088 }
2089
2090 AttachAecDump(std::move(aec_dump));
2091 return true;
2092}
2093
aleloi868f32f2017-05-23 07:20:05 -07002094void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
2095 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02002096 MutexLock lock_render(&mutex_render_);
2097 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002098
2099 // The previously attached AecDump will be destroyed with the
2100 // 'aec_dump' parameter, which is after locks are released.
2101 aec_dump_.swap(aec_dump);
2102 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02002103 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07002104}
2105
2106void AudioProcessingImpl::DetachAecDump() {
2107 // The d-tor of a task-queue based AecDump blocks until all pending
2108 // tasks are done. This construction avoids blocking while holding
2109 // the render and capture locks.
2110 std::unique_ptr<AecDump> aec_dump = nullptr;
2111 {
Markus Handell0df0fae2020-07-07 15:53:34 +02002112 MutexLock lock_render(&mutex_render_);
2113 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002114 aec_dump = std::move(aec_dump_);
2115 }
2116}
2117
peah8271d042016-11-22 07:24:52 -08002118AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002119 MutexLock lock_render(&mutex_render_);
2120 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08002121 return config_;
2122}
2123
peah2ace3f92016-09-10 04:42:27 -07002124bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
2125 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002126 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002127 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02002128 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00002129 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
2130 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00002131 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07002132}
2133
Per Åhgrenc0734712020-01-02 15:15:36 +01002134void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02002135 if (config_.transient_suppression.enabled &&
2136 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02002137 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01002138 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01002139 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02002140 submodule_creation_overrides_, transient_suppressor_vad_mode_,
2141 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2142 num_proc_channels());
2143 if (!submodules_.transient_suppressor) {
2144 RTC_LOG(LS_WARNING)
2145 << "No transient suppressor created (probably disabled)";
2146 }
2147 } else {
sazaaa42ecd2020-04-01 15:24:40 +02002148 submodules_.transient_suppressor->Initialize(
2149 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2150 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02002151 }
Per Åhgrenc0734712020-01-02 15:15:36 +01002152 } else {
2153 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002154 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002155}
2156
Per Åhgren0f14db22020-01-03 14:27:14 +01002157void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01002158 bool high_pass_filter_needed_by_aec =
2159 config_.echo_canceller.enabled &&
2160 config_.echo_canceller.enforce_high_pass_filtering &&
2161 !config_.echo_canceller.mobile_mode;
2162 if (submodule_states_.HighPassFilteringRequired() ||
2163 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01002164 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
2165 !constants_.enforce_split_band_hpf;
2166 int rate = use_full_band ? proc_fullband_sample_rate_hz()
2167 : proc_split_sample_rate_hz();
2168 size_t num_channels =
2169 use_full_band ? num_output_channels() : num_proc_channels();
2170
Per Åhgren0f14db22020-01-03 14:27:14 +01002171 if (!submodules_.high_pass_filter ||
2172 rate != submodules_.high_pass_filter->sample_rate_hz() ||
2173 forced_reset ||
2174 num_channels != submodules_.high_pass_filter->num_channels()) {
2175 submodules_.high_pass_filter.reset(
2176 new HighPassFilter(rate, num_channels));
2177 }
peah8271d042016-11-22 07:24:52 -08002178 } else {
saza1d600522019-10-18 13:29:43 +02002179 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08002180 }
2181}
alessiob3ec96df2017-05-22 06:57:06 -07002182
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02002183void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002184 bool use_echo_controller =
2185 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002186 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002187
2188 if (use_echo_controller) {
2189 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01002190 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01002191 submodules_.echo_controller = echo_control_factory_->Create(
2192 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01002193 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01002194 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002195 EchoCanceller3Config config;
2196 absl::optional<EchoCanceller3Config> multichannel_config;
2197 if (use_setup_specific_default_aec3_config_) {
2198 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
2199 }
saza1d600522019-10-18 13:29:43 +02002200 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002201 config, multichannel_config, proc_sample_rate_hz(),
2202 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01002203 }
2204
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002205 // Setup the storage for returning the linear AEC output.
2206 if (config_.echo_canceller.export_linear_aec_output) {
2207 constexpr int kLinearOutputRateHz = 16000;
2208 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
2209 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
2210 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
2211 } else {
2212 capture_.linear_aec_output.reset();
2213 }
2214
Per Åhgren200feba2019-03-06 04:16:46 +01002215 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002216
saza1d600522019-10-18 13:29:43 +02002217 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002218 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002219 return;
peahe0eae3c2016-12-14 01:16:23 -08002220 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002221
saza1d600522019-10-18 13:29:43 +02002222 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002223 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002224 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002225
2226 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02002227 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002228 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002229 return;
2230 }
2231
2232 if (config_.echo_canceller.mobile_mode) {
2233 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002234 size_t max_element_size =
2235 std::max(static_cast<size_t>(1),
2236 kMaxAllowedValuesOfSamplesPerBand *
2237 EchoControlMobileImpl::NumCancellersRequired(
2238 num_output_channels(), num_reverse_channels()));
2239
2240 std::vector<int16_t> template_queue_element(max_element_size);
2241
2242 aecm_render_signal_queue_.reset(
2243 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2244 kMaxNumFramesToBuffer, template_queue_element,
2245 RenderQueueItemVerifier<int16_t>(max_element_size)));
2246
2247 aecm_render_queue_buffer_.resize(max_element_size);
2248 aecm_capture_queue_buffer_.resize(max_element_size);
2249
saza1d600522019-10-18 13:29:43 +02002250 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002251
saza1d600522019-10-18 13:29:43 +02002252 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2253 num_reverse_channels(),
2254 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002255 return;
2256 }
2257
saza1d600522019-10-18 13:29:43 +02002258 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002259 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002260}
peah8271d042016-11-22 07:24:52 -08002261
Per Åhgren0695df12020-01-13 14:43:13 +01002262void AudioProcessingImpl::InitializeGainController1() {
Hanna Silend4dbe452022-11-30 15:16:21 +01002263 if (config_.gain_controller2.enabled &&
2264 config_.gain_controller2.input_volume_controller.enabled &&
2265 config_.gain_controller1.enabled &&
2266 (config_.gain_controller1.mode ==
2267 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
2268 config_.gain_controller1.analog_gain_controller.enabled)) {
2269 RTC_LOG(LS_ERROR) << "APM configuration not valid: "
2270 << "Multiple input volume controllers enabled.";
2271 }
2272
Per Åhgren0695df12020-01-13 14:43:13 +01002273 if (!config_.gain_controller1.enabled) {
2274 submodules_.agc_manager.reset();
2275 submodules_.gain_control.reset();
2276 return;
2277 }
2278
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002279 RTC_HISTOGRAM_BOOLEAN(
2280 "WebRTC.Audio.GainController.Analog.Enabled",
2281 config_.gain_controller1.analog_gain_controller.enabled);
2282
Per Åhgren0695df12020-01-13 14:43:13 +01002283 if (!submodules_.gain_control) {
2284 submodules_.gain_control.reset(new GainControlImpl());
2285 }
2286
2287 submodules_.gain_control->Initialize(num_proc_channels(),
2288 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002289 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2290 int error = submodules_.gain_control->set_mode(
2291 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2292 RTC_DCHECK_EQ(kNoError, error);
2293 error = submodules_.gain_control->set_target_level_dbfs(
2294 config_.gain_controller1.target_level_dbfs);
2295 RTC_DCHECK_EQ(kNoError, error);
2296 error = submodules_.gain_control->set_compression_gain_db(
2297 config_.gain_controller1.compression_gain_db);
2298 RTC_DCHECK_EQ(kNoError, error);
2299 error = submodules_.gain_control->enable_limiter(
2300 config_.gain_controller1.enable_limiter);
2301 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002302 constexpr int kAnalogLevelMinimum = 0;
2303 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002304 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002305 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002306 RTC_DCHECK_EQ(kNoError, error);
2307
2308 submodules_.agc_manager.reset();
2309 return;
2310 }
2311
2312 if (!submodules_.agc_manager.get() ||
2313 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002314 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002315 int stream_analog_level = -1;
2316 const bool re_creation = !!submodules_.agc_manager;
2317 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002318 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002319 }
2320 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002321 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002322 if (re_creation) {
2323 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2324 }
2325 }
2326 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002327 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002328 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2329 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002330}
2331
Alessio Bazzica38901042021-10-14 12:14:21 +02002332void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2333 if (!config_has_changed) {
2334 return;
2335 }
2336 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002337 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002338 return;
2339 }
2340 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002341 const bool use_internal_vad =
2342 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica38901042021-10-14 12:14:21 +02002343 submodules_.gain_controller2 = std::make_unique<GainController2>(
Hanna Silena6574902022-11-30 16:59:05 +01002344 config_.gain_controller2,
Hanna Silenca653552022-12-08 17:40:01 +01002345 gain_controller2_config_override_.has_value()
2346 ? gain_controller2_config_override_->input_volume_controller_config
2347 : InputVolumeController::Config{},
Hanna Silena6574902022-11-30 16:59:05 +01002348 proc_fullband_sample_rate_hz(), num_input_channels(), use_internal_vad);
Hanna Silend4dbe452022-11-30 15:16:21 +01002349 submodules_.gain_controller2->SetCaptureOutputUsed(
2350 capture_.capture_output_used);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002351 }
2352}
2353
2354void AudioProcessingImpl::InitializeVoiceActivityDetector(
2355 bool config_has_changed) {
2356 if (!config_has_changed) {
2357 return;
2358 }
2359 const bool use_vad =
2360 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2361 config_.gain_controller2.enabled &&
Alessio Bazzica17e14fd2022-12-07 17:08:45 +01002362 (config_.gain_controller2.adaptive_digital.enabled ||
2363 config_.gain_controller2.input_volume_controller.enabled);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002364 if (!use_vad) {
2365 submodules_.voice_activity_detector.reset();
2366 return;
2367 }
2368 if (!submodules_.voice_activity_detector || config_has_changed) {
2369 RTC_DCHECK(!!submodules_.gain_controller2);
2370 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2371 submodules_.voice_activity_detector =
2372 std::make_unique<VoiceActivityDetectorWrapper>(
Hanna Silen0c1ad292022-06-16 16:35:45 +02002373 submodules_.gain_controller2->GetCpuFeatures(),
2374 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002375 }
2376}
2377
saza0bad15f2019-10-16 11:46:11 +02002378void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002379 submodules_.noise_suppressor.reset();
2380
saza0bad15f2019-10-16 11:46:11 +02002381 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002382 auto map_level =
2383 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2384 using NoiseSuppresionConfig =
2385 AudioProcessing::Config::NoiseSuppression;
2386 switch (level) {
2387 case NoiseSuppresionConfig::kLow:
2388 return NsConfig::SuppressionLevel::k6dB;
2389 case NoiseSuppresionConfig::kModerate:
2390 return NsConfig::SuppressionLevel::k12dB;
2391 case NoiseSuppresionConfig::kHigh:
2392 return NsConfig::SuppressionLevel::k18dB;
2393 case NoiseSuppresionConfig::kVeryHigh:
2394 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002395 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002396 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002397 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002398
sazaaa42ecd2020-04-01 15:24:40 +02002399 NsConfig cfg;
2400 cfg.target_level = map_level(config_.noise_suppression.level);
2401 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2402 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002403 }
2404}
2405
Per Åhgrendb5d7282021-03-15 16:31:04 +00002406void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2407 if (config_.pre_amplifier.enabled ||
2408 config_.capture_level_adjustment.enabled) {
2409 // Use both the pre-amplifier and the capture level adjustment gains as
2410 // pre-gains.
2411 float pre_gain = 1.f;
2412 if (config_.pre_amplifier.enabled) {
2413 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2414 }
2415 if (config_.capture_level_adjustment.enabled) {
2416 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2417 }
2418
2419 submodules_.capture_levels_adjuster =
2420 std::make_unique<CaptureLevelsAdjuster>(
2421 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2422 config_.capture_level_adjustment.analog_mic_gain_emulation
2423 .initial_level,
2424 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002425 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002426 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002427 }
2428}
2429
ivoc9f4a4a02016-10-28 05:39:16 -07002430void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002431 if (submodules_.echo_detector) {
2432 submodules_.echo_detector->Initialize(
2433 proc_fullband_sample_rate_hz(), 1,
2434 formats_.render_processing_format.sample_rate_hz(), 1);
2435 }
ivoc9f4a4a02016-10-28 05:39:16 -07002436}
2437
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002438void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002439 if (submodules_.capture_analyzer) {
2440 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2441 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002442 }
2443}
2444
Sam Zackrisson0beac582017-09-25 12:04:02 +02002445void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002446 if (submodules_.capture_post_processor) {
2447 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002448 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002449 }
2450}
2451
Alex Loiko5825aa62017-12-18 16:02:40 +01002452void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002453 if (submodules_.render_pre_processor) {
2454 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002455 formats_.render_processing_format.sample_rate_hz(),
2456 formats_.render_processing_format.num_channels());
2457 }
2458}
2459
aleloi868f32f2017-05-23 07:20:05 -07002460void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2461 if (!aec_dump_) {
2462 return;
2463 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002464
2465 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002466 // TODO(peah): Add semicolon-separated concatenations of experiment
2467 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002468 if (!!submodules_.capture_post_processor) {
2469 experiments_description += "CapturePostProcessor;";
2470 }
2471 if (!!submodules_.render_pre_processor) {
2472 experiments_description += "RenderPreProcessor;";
2473 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002474 if (capture_nonlocked_.echo_controller_enabled) {
2475 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002476 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002477 if (config_.gain_controller2.enabled) {
2478 experiments_description += "GainController2;";
2479 }
aleloi868f32f2017-05-23 07:20:05 -07002480
2481 InternalAPMConfig apm_config;
2482
Per Åhgren200feba2019-03-06 04:16:46 +01002483 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002484 apm_config.aec_delay_agnostic_enabled = false;
2485 apm_config.aec_extended_filter_enabled = false;
2486 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002487
saza1d600522019-10-18 13:29:43 +02002488 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002489 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002490 submodules_.echo_control_mobile &&
2491 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002492 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002493 submodules_.echo_control_mobile
2494 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002495 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002496
Per Åhgren0695df12020-01-13 14:43:13 +01002497 apm_config.agc_enabled = !!submodules_.gain_control;
2498
2499 apm_config.agc_mode = submodules_.gain_control
2500 ? static_cast<int>(submodules_.gain_control->mode())
2501 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002502 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002503 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2504 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002505 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002506
2507 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2508
saza0bad15f2019-10-16 11:46:11 +02002509 apm_config.ns_enabled = config_.noise_suppression.enabled;
2510 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002511
2512 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002513 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002514 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002515 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2516 apm_config.pre_amplifier_fixed_gain_factor =
2517 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002518
2519 if (!forced && apm_config == apm_config_for_aec_dump_) {
2520 return;
2521 }
2522 aec_dump_->WriteConfig(apm_config);
2523 apm_config_for_aec_dump_ = apm_config;
2524}
2525
2526void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2527 const float* const* src) {
2528 RTC_DCHECK(aec_dump_);
2529 WriteAecDumpConfigMessage(false);
2530
2531 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2532 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2533 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002534 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002535 RecordAudioProcessingState();
2536}
2537
2538void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002539 const int16_t* const data,
2540 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002541 RTC_DCHECK(aec_dump_);
2542 WriteAecDumpConfigMessage(false);
2543
Per Åhgren645f24c2020-03-16 12:06:02 +01002544 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2545 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002546 RecordAudioProcessingState();
2547}
2548
2549void AudioProcessingImpl::RecordProcessedCaptureStream(
2550 const float* const* processed_capture_stream) {
2551 RTC_DCHECK(aec_dump_);
2552
2553 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2554 const size_t num_channels =
2555 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002556 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2557 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002558 aec_dump_->WriteCaptureStreamMessage();
2559}
2560
2561void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002562 const int16_t* const data,
2563 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002564 RTC_DCHECK(aec_dump_);
2565
Per Åhgren645f24c2020-03-16 12:06:02 +01002566 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002567 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002568 aec_dump_->WriteCaptureStreamMessage();
2569}
2570
2571void AudioProcessingImpl::RecordAudioProcessingState() {
2572 RTC_DCHECK(aec_dump_);
2573 AecDump::AudioProcessingState audio_proc_state;
2574 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002575 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002576 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002577 audio_proc_state.keypress = capture_.key_pressed;
2578 aec_dump_->AddAudioProcessingState(audio_proc_state);
2579}
2580
Per Åhgrenc0734712020-01-02 15:15:36 +01002581AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002582 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002583 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002584 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002585 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002586 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002587 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002588 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002589 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002590 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002591 prev_playout_volume(-1),
2592 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002593
2594AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2595
2596AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2597
2598AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2599
Per Åhgrencf4c8722019-12-30 14:32:14 +01002600AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2601 : stats_message_queue_(1) {}
2602
2603AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2604
2605AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002606 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002607 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2608 // If the message queue is full, return the cached stats.
2609 static_cast<void>(new_stats_available);
2610
2611 return cached_stats_;
2612}
2613
2614void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2615 const AudioProcessingStats& new_stats) {
2616 AudioProcessingStats stats_to_queue = new_stats;
2617 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2618 // If the message queue is full, discard the new stats.
2619 static_cast<void>(stats_message_passed);
2620}
2621
niklase@google.com470e71d2011-07-07 08:21:25 +00002622} // namespace webrtc