blob: 3200ea4d9c7fa675e562e388fa90850c8483238c [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);
381 FieldTrialConstrained<double> max_gain_change_db_per_second(
382 "max_gain_change_db_per_second",
383 kDefaultAdaptiveDigitalConfig.max_gain_change_db_per_second, 0,
384 absl::nullopt);
385 FieldTrialConstrained<double> max_output_noise_level_dbfs(
386 "max_output_noise_level_dbfs",
387 kDefaultAdaptiveDigitalConfig.max_output_noise_level_dbfs, absl::nullopt,
388 0);
389
390 // Field-trial based override for the input volume controller and adaptive
391 // digital configs.
Hanna Silena6574902022-11-30 16:59:05 +0100392 const std::string field_trial_name =
Hanna Silenca653552022-12-08 17:40:01 +0100393 field_trial::FindFullName(kFieldTrialName);
Hanna Silena6574902022-11-30 16:59:05 +0100394
395 ParseFieldTrial({&enabled, &clipped_level_min, &clipped_level_step,
396 &clipped_ratio_threshold, &clipped_wait_frames,
397 &enable_clipping_predictor, &target_range_max_dbfs,
398 &target_range_min_dbfs, &update_input_volume_wait_frames,
Hanna Silenca653552022-12-08 17:40:01 +0100399 &speech_probability_threshold, &speech_ratio_threshold,
400 &headroom_db, &max_gain_db, &max_gain_change_db_per_second,
401 &max_output_noise_level_dbfs},
Hanna Silena6574902022-11-30 16:59:05 +0100402 field_trial_name);
403
404 // Checked already by `IsEnabled()` before parsing, therefore always true.
405 RTC_DCHECK(enabled);
406
Hanna Silenca653552022-12-08 17:40:01 +0100407 return AudioProcessingImpl::GainController2ConfigOverride{
408 InputVolumeController::Config{
409 .clipped_level_min = static_cast<int>(clipped_level_min.Get()),
410 .clipped_level_step = static_cast<int>(clipped_level_step.Get()),
411 .clipped_ratio_threshold =
412 static_cast<float>(clipped_ratio_threshold.Get()),
413 .clipped_wait_frames = static_cast<int>(clipped_wait_frames.Get()),
414 .enable_clipping_predictor =
415 static_cast<bool>(enable_clipping_predictor.Get()),
416 .target_range_max_dbfs =
417 static_cast<int>(target_range_max_dbfs.Get()),
418 .target_range_min_dbfs =
419 static_cast<int>(target_range_min_dbfs.Get()),
420 .update_input_volume_wait_frames =
421 static_cast<int>(update_input_volume_wait_frames.Get()),
422 .speech_probability_threshold =
423 static_cast<float>(speech_probability_threshold.Get()),
424 .speech_ratio_threshold =
425 static_cast<float>(speech_ratio_threshold.Get()),
426 },
427 AudioProcessingImpl::GainController2ConfigOverride::AdaptiveDigitalConfig{
428 .headroom_db = static_cast<float>(headroom_db.Get()),
429 .max_gain_db = static_cast<float>(max_gain_db.Get()),
430 .max_gain_change_db_per_second =
431 static_cast<float>(max_gain_change_db_per_second.Get()),
432 .max_output_noise_level_dbfs =
433 static_cast<float>(max_output_noise_level_dbfs.Get()),
434 },
Hanna Silena6574902022-11-30 16:59:05 +0100435 };
436}
437
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100438// If `disallow_transient_supporessor_usage` is true, disables transient
Hanna Silenca653552022-12-08 17:40:01 +0100439// suppression. When `gain_controller2_config_override` is specified,
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100440// switches all gain control to AGC2.
441AudioProcessing::Config AdjustConfig(
Hanna Silena6574902022-11-30 16:59:05 +0100442 const AudioProcessing::Config& config,
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100443 bool disallow_transient_supporessor_usage,
Hanna Silenca653552022-12-08 17:40:01 +0100444 const absl::optional<AudioProcessingImpl::GainController2ConfigOverride>&
445 gain_controller2_config_override) {
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100446 AudioProcessing::Config adjusted_config = config;
447
448 // Override the transient suppressor configuration.
449 if (disallow_transient_supporessor_usage) {
450 adjusted_config.transient_suppression.enabled = false;
451 }
452
453 // Override the auto gain control configuration if the AGC1 analog gain
Hanna Silenca653552022-12-08 17:40:01 +0100454 // controller is active and `gain_controller2_config_override` is
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100455 // specified.
456 const bool agc1_analog_enabled =
Hanna Silena6574902022-11-30 16:59:05 +0100457 config.gain_controller1.enabled &&
458 (config.gain_controller1.mode ==
459 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
460 config.gain_controller1.analog_gain_controller.enabled);
Hanna Silenca653552022-12-08 17:40:01 +0100461 if (agc1_analog_enabled && gain_controller2_config_override.has_value()) {
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100462 // Check that the unadjusted AGC config meets the preconditions.
463 const bool hybrid_agc_config_detected =
464 config.gain_controller1.enabled &&
465 config.gain_controller1.analog_gain_controller.enabled &&
466 !config.gain_controller1.analog_gain_controller
467 .enable_digital_adaptive &&
468 config.gain_controller2.enabled &&
469 config.gain_controller2.adaptive_digital.enabled;
470 const bool full_agc1_config_detected =
471 config.gain_controller1.enabled &&
472 config.gain_controller1.analog_gain_controller.enabled &&
473 config.gain_controller1.analog_gain_controller
474 .enable_digital_adaptive &&
475 !config.gain_controller2.enabled;
476 const bool one_and_only_one_input_volume_controller =
477 hybrid_agc_config_detected != full_agc1_config_detected;
478 if (!one_and_only_one_input_volume_controller ||
479 config.gain_controller2.input_volume_controller.enabled) {
480 RTC_LOG(LS_ERROR) << "Cannot adjust AGC config (precondition failed)";
481 if (!one_and_only_one_input_volume_controller)
482 RTC_LOG(LS_ERROR)
483 << "One and only one input volume controller must be enabled.";
484 if (config.gain_controller2.input_volume_controller.enabled)
485 RTC_LOG(LS_ERROR)
486 << "The AGC2 input volume controller must be disabled.";
487 } else {
488 adjusted_config.gain_controller1.enabled = false;
489 adjusted_config.gain_controller1.analog_gain_controller.enabled = false;
Hanna Silenca653552022-12-08 17:40:01 +0100490
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100491 adjusted_config.gain_controller2.enabled = true;
492 adjusted_config.gain_controller2.adaptive_digital.enabled = true;
493 adjusted_config.gain_controller2.input_volume_controller.enabled = true;
Hanna Silenca653552022-12-08 17:40:01 +0100494
495 auto& adjusted_adaptive_digital = // Alias.
496 adjusted_config.gain_controller2.adaptive_digital;
497 const auto& adaptive_digital_override = // Alias.
498 gain_controller2_config_override->adaptive_digital_config;
499 adjusted_adaptive_digital.headroom_db =
500 adaptive_digital_override.headroom_db;
501 adjusted_adaptive_digital.max_gain_db =
502 adaptive_digital_override.max_gain_db;
503 adjusted_adaptive_digital.max_gain_change_db_per_second =
504 adaptive_digital_override.max_gain_change_db_per_second;
505 adjusted_adaptive_digital.max_output_noise_level_dbfs =
506 adaptive_digital_override.max_output_noise_level_dbfs;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100507 }
Hanna Silena6574902022-11-30 16:59:05 +0100508 }
509
Hanna Silena6574902022-11-30 16:59:05 +0100510 return adjusted_config;
511}
512
Alessio Bazzica504bd592022-12-01 13:26:26 +0100513using DownmixMethod = AudioProcessing::Config::Pipeline::DownmixMethod;
514
515void SetDownmixMethod(AudioBuffer& buffer, DownmixMethod method) {
516 switch (method) {
517 case DownmixMethod::kAverageChannels:
518 buffer.set_downmixing_by_averaging();
519 break;
520 case DownmixMethod::kUseFirstChannel:
521 buffer.set_downmixing_to_specific_channel(/*channel=*/0);
522 break;
523 }
524}
525
Hanna Silena6574902022-11-30 16:59:05 +0100526constexpr int kUnspecifiedDataDumpInputVolume = -100;
527
Michael Graczyk86c6d332015-07-23 11:41:39 -0700528} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000529
530// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000531static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000532
saza1d600522019-10-18 13:29:43 +0200533AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100534 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200535 bool render_pre_processor_enabled,
536 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100537 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200538 render_pre_processor_enabled_(render_pre_processor_enabled),
539 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700540
saza1d600522019-10-18 13:29:43 +0200541bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200542 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700543 bool mobile_echo_controller_enabled,
544 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700545 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700546 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200547 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000548 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200549 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700550 bool transient_suppressor_enabled) {
551 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200552 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700553 changed |=
554 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
555 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
556 changed |=
peah2ace3f92016-09-10 04:42:27 -0700557 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200558 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200559 changed |=
560 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000561 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200562 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700563 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
564 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200565 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700566 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
567 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700568 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700569 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200570 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000571 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200572 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700573 transient_suppressor_enabled_ = transient_suppressor_enabled;
574 }
575
576 changed |= first_update_;
577 first_update_ = false;
578 return changed;
579}
580
saza1d600522019-10-18 13:29:43 +0200581bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700582 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000583 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700584}
585
saza1d600522019-10-18 13:29:43 +0200586bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
587 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200588 // If echo controller is present, assume it performs active processing.
589 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
590}
591
saza1d600522019-10-18 13:29:43 +0200592bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200593 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100594 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
595 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200596 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700597}
598
saza1d600522019-10-18 13:29:43 +0200599bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700600 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200601 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000602 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700603}
604
saza1d600522019-10-18 13:29:43 +0200605bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200606 return capture_analyzer_enabled_;
607}
608
saza1d600522019-10-18 13:29:43 +0200609bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700610 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100611 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
612 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700613}
614
saza1d600522019-10-18 13:29:43 +0200615bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100616 const {
617 return render_pre_processor_enabled_;
618}
619
saza1d600522019-10-18 13:29:43 +0200620bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700621 const {
peah2ace3f92016-09-10 04:42:27 -0700622 return false;
peah2ace3f92016-09-10 04:42:27 -0700623}
624
saza1d600522019-10-18 13:29:43 +0200625bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100626 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
627 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200628}
629
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200630AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200631 : AudioProcessingImpl(/*config=*/{},
632 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200633 /*render_pre_processor=*/nullptr,
634 /*echo_control_factory=*/nullptr,
635 /*echo_detector=*/nullptr,
636 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000637
Niels Möller7a669002022-06-27 09:47:02 +0200638std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100639
Sam Zackrisson0beac582017-09-25 12:04:02 +0200640AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200641 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100642 std::unique_ptr<CustomProcessing> capture_post_processor,
643 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200644 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200645 rtc::scoped_refptr<EchoDetector> echo_detector,
646 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200647 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100648 use_setup_specific_default_aec3_config_(
649 UseSetupSpecificDefaultAec3Congfig()),
Hanna Silenca653552022-12-08 17:40:01 +0100650 gain_controller2_config_override_(GetGainController2ConfigOverride()),
Alessio Bazzica0441bb62021-08-10 15:23:23 +0200651 use_denormal_disabler_(
652 !field_trial::IsEnabled("WebRTC-ApmDenormalDisablerKillSwitch")),
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100653 disallow_transient_supporessor_usage_(
654 field_trial::IsEnabled("WebRTC-ApmTransientSuppressorKillSwitch")),
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +0100655 transient_suppressor_vad_mode_(GetTransientSuppressorVadMode()),
Per Åhgren652ada52021-03-03 10:52:44 +0000656 capture_runtime_settings_(RuntimeSettingQueueSize()),
657 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200658 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
659 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200660 echo_control_factory_(std::move(echo_control_factory)),
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100661 config_(AdjustConfig(config,
662 disallow_transient_supporessor_usage_,
Hanna Silenca653552022-12-08 17:40:01 +0100663 gain_controller2_config_override_)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200664 submodule_states_(!!capture_post_processor,
665 !!render_pre_processor,
666 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200667 submodules_(std::move(capture_post_processor),
668 std::move(render_pre_processor),
669 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100670 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100671 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200672 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
673 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100674 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000675 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200676 MinimizeProcessingForUnusedOutput(),
677 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000678 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200679 capture_nonlocked_(),
680 applied_input_volume_stats_reporter_(
681 InputVolumeStatsReporter::InputVolumeType::kApplied),
682 recommended_input_volume_stats_reporter_(
683 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200684 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100685 "\nEcho control factory: "
686 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200687 << "\nEcho detector: " << !!submodules_.echo_detector
688 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
689 << "\nCapture post processor: "
690 << !!submodules_.capture_post_processor
691 << "\nRender pre processor: "
692 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100693 if (!DenormalDisabler::IsSupported()) {
694 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
695 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200696
Hanna Silena6574902022-11-30 16:59:05 +0100697 RTC_LOG(LS_INFO) << "AudioProcessing: " << config_.ToString();
698
Sam Zackrisson421c8592019-02-11 13:39:46 +0100699 // Mark Echo Controller enabled if a factory is injected.
700 capture_nonlocked_.echo_controller_enabled =
701 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000702
Per Åhgren0ade9832020-09-01 23:57:20 +0200703 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000704}
705
Per Åhgren0e3198e2019-11-18 08:52:22 +0100706AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000707
niklase@google.com470e71d2011-07-07 08:21:25 +0000708int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800709 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200710 MutexLock lock_render(&mutex_render_);
711 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200712 InitializeLocked();
713 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000714}
715
Michael Graczyk86c6d332015-07-23 11:41:39 -0700716int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800717 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200718 MutexLock lock_render(&mutex_render_);
719 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100720 InitializeLocked(processing_config);
721 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000722}
723
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100724void AudioProcessingImpl::MaybeInitializeRender(
725 const StreamConfig& input_config,
726 const StreamConfig& output_config) {
727 ProcessingConfig processing_config = formats_.api_format;
728 processing_config.reverse_input_stream() = input_config;
729 processing_config.reverse_output_stream() = output_config;
730
Oskar Sundbom4b276482019-05-23 14:28:00 +0200731 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100732 return;
peah192164e2015-11-17 02:16:45 -0800733 }
peahdf3efa82015-11-28 12:35:15 -0800734
Markus Handell0df0fae2020-07-07 15:53:34 +0200735 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100736 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800737}
738
Per Åhgren0ade9832020-09-01 23:57:20 +0200739void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200740 UpdateActiveSubmoduleStates();
741
Per Åhgrend47941e2019-08-22 11:51:13 +0200742 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800743 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200744 ? formats_.render_processing_format.sample_rate_hz()
745 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800746 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
747 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200748 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800749 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200750 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700751 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200752 render_audiobuffer_sample_rate_hz,
753 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700754 if (formats_.api_format.reverse_input_stream() !=
755 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800756 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800757 formats_.api_format.reverse_input_stream().num_channels(),
758 formats_.api_format.reverse_input_stream().num_frames(),
759 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800760 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700761 } else {
peahdf3efa82015-11-28 12:35:15 -0800762 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700763 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700764 } else {
peahdf3efa82015-11-28 12:35:15 -0800765 render_.render_audio.reset(nullptr);
766 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700767 }
peahce4d9152017-05-19 01:28:05 -0700768
Per Åhgrend47941e2019-08-22 11:51:13 +0200769 capture_.capture_audio.reset(new AudioBuffer(
770 formats_.api_format.input_stream().sample_rate_hz(),
771 formats_.api_format.input_stream().num_channels(),
772 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
773 formats_.api_format.output_stream().num_channels(),
774 formats_.api_format.output_stream().sample_rate_hz(),
775 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100776 SetDownmixMethod(*capture_.capture_audio,
777 config_.pipeline.capture_downmix_method);
niklase@google.com470e71d2011-07-07 08:21:25 +0000778
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200779 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
780 formats_.api_format.output_stream().sample_rate_hz() &&
781 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
782 capture_.capture_fullband_audio.reset(
783 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
784 formats_.api_format.input_stream().num_channels(),
785 formats_.api_format.output_stream().sample_rate_hz(),
786 formats_.api_format.output_stream().num_channels(),
787 formats_.api_format.output_stream().sample_rate_hz(),
788 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100789 SetDownmixMethod(*capture_.capture_fullband_audio,
790 config_.pipeline.capture_downmix_method);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200791 } else {
792 capture_.capture_fullband_audio.reset();
793 }
794
peah764e3642016-10-22 05:04:30 -0700795 AllocateRenderQueue();
796
Per Åhgren0695df12020-01-13 14:43:13 +0100797 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100798 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100799 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700800 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200801 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200802 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200803 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200804 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200805 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200806 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100807 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000808 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800809
aleloi868f32f2017-05-23 07:20:05 -0700810 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200811 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700812 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000813}
814
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100815void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200816 UpdateActiveSubmoduleStates();
817
peahdf3efa82015-11-28 12:35:15 -0800818 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000819
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200820 // Choose maximum rate to use for the split filtering.
821 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
822 config_.pipeline.maximum_internal_processing_rate == 32000);
823 int max_splitting_rate = 48000;
824 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
825 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
826 }
827
Per Åhgrenc8626b62019-08-23 15:49:51 +0200828 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700829 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700830 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200831 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700832 submodule_states_.CaptureMultiBandSubModulesActive() ||
833 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200834 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000835
peahde65ddc2016-09-16 15:02:15 -0700836 capture_nonlocked_.capture_processing_format =
837 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700838
peah2ce640f2017-04-07 03:57:48 -0700839 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200840 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200841 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700842 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
843 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200844 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700845 submodule_states_.CaptureMultiBandSubModulesActive() ||
846 submodule_states_.RenderMultiBandSubModulesActive());
847 } else {
848 render_processing_rate = capture_processing_rate;
849 }
850
peahde65ddc2016-09-16 15:02:15 -0700851 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700852 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700853 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
854 kSampleRate8kHz) {
855 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000856 } else {
peahde65ddc2016-09-16 15:02:15 -0700857 render_processing_rate =
858 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000859 }
860
Per Åhgrenc8626b62019-08-23 15:49:51 +0200861 RTC_DCHECK_NE(8000, render_processing_rate);
862
peahce4d9152017-05-19 01:28:05 -0700863 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200864 // By default, downmix the render stream to mono for analysis. This has been
865 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100866 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
867 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200868 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100869 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200870 ? formats_.api_format.reverse_input_stream().num_channels()
871 : 1;
872 formats_.render_processing_format =
873 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700874 } else {
875 formats_.render_processing_format = StreamConfig(
876 formats_.api_format.reverse_input_stream().sample_rate_hz(),
877 formats_.api_format.reverse_input_stream().num_channels());
878 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000879
peahde65ddc2016-09-16 15:02:15 -0700880 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
881 kSampleRate32kHz ||
882 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
883 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800884 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000885 } else {
peahdf3efa82015-11-28 12:35:15 -0800886 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700887 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000888 }
889
Per Åhgren0ade9832020-09-01 23:57:20 +0200890 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000891}
892
peah88ac8532016-09-12 16:47:25 -0700893void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700894 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200895 MutexLock lock_render(&mutex_render_);
896 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700897
Hanna Silena6574902022-11-30 16:59:05 +0100898 const auto adjusted_config =
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100899 AdjustConfig(config, disallow_transient_supporessor_usage_,
Hanna Silenca653552022-12-08 17:40:01 +0100900 gain_controller2_config_override_);
Hanna Silena6574902022-11-30 16:59:05 +0100901 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: "
902 << adjusted_config.ToString();
903
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200904 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100905 config_.pipeline.multi_channel_render !=
Hanna Silena6574902022-11-30 16:59:05 +0100906 adjusted_config.pipeline.multi_channel_render ||
Per Åhgrene14cb992019-11-27 09:34:22 +0100907 config_.pipeline.multi_channel_capture !=
Hanna Silena6574902022-11-30 16:59:05 +0100908 adjusted_config.pipeline.multi_channel_capture ||
Per Åhgrenc0424252019-12-10 13:04:15 +0100909 config_.pipeline.maximum_internal_processing_rate !=
Alessio Bazzica504bd592022-12-01 13:26:26 +0100910 adjusted_config.pipeline.maximum_internal_processing_rate ||
911 config_.pipeline.capture_downmix_method !=
912 adjusted_config.pipeline.capture_downmix_method;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200913
Per Åhgren200feba2019-03-06 04:16:46 +0100914 const bool aec_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100915 config_.echo_canceller.enabled !=
916 adjusted_config.echo_canceller.enabled ||
917 config_.echo_canceller.mobile_mode !=
918 adjusted_config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100919
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100920 const bool agc1_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100921 config_.gain_controller1 != adjusted_config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100922
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100923 const bool agc2_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100924 config_.gain_controller2 != adjusted_config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100925
saza0bad15f2019-10-16 11:46:11 +0200926 const bool ns_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100927 config_.noise_suppression.enabled !=
928 adjusted_config.noise_suppression.enabled ||
929 config_.noise_suppression.level !=
930 adjusted_config.noise_suppression.level;
saza0bad15f2019-10-16 11:46:11 +0200931
Per Åhgrenc0734712020-01-02 15:15:36 +0100932 const bool ts_config_changed = config_.transient_suppression.enabled !=
Hanna Silena6574902022-11-30 16:59:05 +0100933 adjusted_config.transient_suppression.enabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100934
Per Åhgren0f14db22020-01-03 14:27:14 +0100935 const bool pre_amplifier_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100936 config_.pre_amplifier.enabled != adjusted_config.pre_amplifier.enabled ||
Per Åhgren0f14db22020-01-03 14:27:14 +0100937 config_.pre_amplifier.fixed_gain_factor !=
Hanna Silena6574902022-11-30 16:59:05 +0100938 adjusted_config.pre_amplifier.fixed_gain_factor;
Per Åhgren0f14db22020-01-03 14:27:14 +0100939
Per Åhgrendb5d7282021-03-15 16:31:04 +0000940 const bool gain_adjustment_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100941 config_.capture_level_adjustment !=
942 adjusted_config.capture_level_adjustment;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000943
Hanna Silena6574902022-11-30 16:59:05 +0100944 config_ = adjusted_config;
Yves Gerey499bc6c2018-10-10 18:29:07 +0200945
Per Åhgren200feba2019-03-06 04:16:46 +0100946 if (aec_config_changed) {
947 InitializeEchoController();
948 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200949
saza0bad15f2019-10-16 11:46:11 +0200950 if (ns_config_changed) {
951 InitializeNoiseSuppressor();
952 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100953
Per Åhgrenc0734712020-01-02 15:15:36 +0100954 if (ts_config_changed) {
955 InitializeTransientSuppressor();
956 }
957
Per Åhgren0f14db22020-01-03 14:27:14 +0100958 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800959
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100960 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100961 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100962 }
963
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100964 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700965 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200966 RTC_LOG(LS_ERROR)
967 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700968 config_.gain_controller2 = AudioProcessing::Config::GainController2();
969 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100970
Alessio Bazzica38901042021-10-14 12:14:21 +0200971 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200972 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100973
Per Åhgrendb5d7282021-03-15 16:31:04 +0000974 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
975 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100976 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100977
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200978 // Reinitialization must happen after all submodule configuration to avoid
979 // additional reinitializations on the next capture / render processing call.
980 if (pipeline_config_changed) {
981 InitializeLocked(formats_.api_format);
982 }
peah88ac8532016-09-12 16:47:25 -0700983}
984
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200985void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
986 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200987 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200988 submodule_creation_overrides_ = overrides;
989}
990
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000991int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800992 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700993 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000994}
995
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200996int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
997 return capture_.capture_fullband_audio
998 ? capture_.capture_fullband_audio->num_frames() * 100
999 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
1000}
1001
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001002int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001003 // Used as callback from submodules, hence locking is not allowed.
1004 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +00001005}
1006
Peter Kasting69558702016-01-12 16:26:35 -08001007size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001008 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001009 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001010}
1011
Peter Kasting69558702016-01-12 16:26:35 -08001012size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001013 // Used as callback from submodules, hence locking is not allowed.
1014 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001015}
1016
Peter Kasting69558702016-01-12 16:26:35 -08001017size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -08001018 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +01001019 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1020 constants_.multi_channel_capture_support;
1021 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001022 return 1;
1023 }
1024 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -08001025}
1026
Peter Kasting69558702016-01-12 16:26:35 -08001027size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001028 // Used as callback from submodules, hence locking is not allowed.
1029 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001030}
1031
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001032void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001033 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +01001034 HandleCaptureOutputUsedSetting(!muted);
1035}
1036
1037void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
1038 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001039 capture_.capture_output_used =
1040 capture_output_used || !constants_.minimize_processing_for_unused_output;
1041
saza1d600522019-10-18 13:29:43 +02001042 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001043 submodules_.agc_manager->HandleCaptureOutputUsedChange(
1044 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001045 }
Per Åhgren652ada52021-03-03 10:52:44 +00001046 if (submodules_.echo_controller) {
1047 submodules_.echo_controller->SetCaptureOutputUsage(
1048 capture_.capture_output_used);
1049 }
Per Åhgren15179a92021-03-12 14:12:44 +00001050 if (submodules_.noise_suppressor) {
1051 submodules_.noise_suppressor->SetCaptureOutputUsage(
1052 capture_.capture_output_used);
1053 }
Hanna Silend4dbe452022-11-30 15:16:21 +01001054 if (submodules_.gain_controller2) {
1055 submodules_.gain_controller2->SetCaptureOutputUsed(
1056 capture_.capture_output_used);
1057 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001058}
1059
Alessio Bazzicac054e782018-04-16 12:10:09 +02001060void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001061 PostRuntimeSetting(setting);
1062}
1063
1064bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +02001065 switch (setting.type()) {
1066 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001067 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +01001068 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001069 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001070 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001071 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001072 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +02001073 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001074 return capture_runtime_settings_enqueuer_.Enqueue(setting);
1075 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1076 bool enqueueing_successful;
1077 enqueueing_successful =
1078 capture_runtime_settings_enqueuer_.Enqueue(setting);
1079 enqueueing_successful =
1080 render_runtime_settings_enqueuer_.Enqueue(setting) &&
1081 enqueueing_successful;
1082 return enqueueing_successful;
1083 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001084 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001085 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001086 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +02001087 }
1088 // The language allows the enum to have a non-enumerator
1089 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +01001090 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001091 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001092}
1093
1094AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
1095 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001096 : runtime_settings_(*runtime_settings) {
1097 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001098}
1099
1100AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
1101 default;
1102
Per Åhgren0a144a72021-02-09 08:47:51 +01001103bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +02001104 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +00001105 const bool successful_insert = runtime_settings_.Insert(&setting);
1106
1107 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001108 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +02001109 }
Per Åhgren652ada52021-03-03 10:52:44 +00001110 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001111}
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001112
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001113void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001114 const StreamConfig& input_config,
1115 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001116 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001117 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001118 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001119 // Acquire the capture lock in order to access api_format. The lock is
1120 // released immediately, as we may need to acquire the render lock as part
1121 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +02001122 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001123 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001124 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +00001125 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001126
Oskar Sundbom4b276482019-05-23 14:28:00 +02001127 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001128 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -08001129 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001130
1131 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001132 reinitialization_required = true;
1133 }
1134
1135 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001136 MutexLock lock_render(&mutex_render_);
1137 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +02001138 // Reread the API format since the render format may have changed.
1139 processing_config = formats_.api_format;
1140 processing_config.input_stream() = input_config;
1141 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001142 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001143 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001144}
1145
1146int AudioProcessingImpl::ProcessStream(const float* const* src,
1147 const StreamConfig& input_config,
1148 const StreamConfig& output_config,
1149 float* const* dest) {
1150 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001151 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1152 RETURN_ON_ERR(
1153 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1154 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001155
Markus Handell0df0fae2020-07-07 15:53:34 +02001156 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001157
aleloi868f32f2017-05-23 07:20:05 -07001158 if (aec_dump_) {
1159 RecordUnprocessedCaptureStream(src);
1160 }
1161
peahdf3efa82015-11-28 12:35:15 -08001162 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001163 if (capture_.capture_fullband_audio) {
1164 capture_.capture_fullband_audio->CopyFrom(
1165 src, formats_.api_format.input_stream());
1166 }
peahde65ddc2016-09-16 15:02:15 -07001167 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001168 if (capture_.capture_fullband_audio) {
1169 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1170 dest);
1171 } else {
1172 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1173 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001174
aleloi868f32f2017-05-23 07:20:05 -07001175 if (aec_dump_) {
1176 RecordProcessedCaptureStream(dest);
1177 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001178 return kNoError;
1179}
1180
Alex Loiko73ec0192018-05-15 10:52:28 +02001181void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001182 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +00001183 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +02001184 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001185 if (aec_dump_) {
1186 aec_dump_->WriteRuntimeSetting(setting);
1187 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001188 switch (setting.type()) {
1189 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001190 if (config_.pre_amplifier.enabled ||
1191 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +02001192 float value;
1193 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001194 // If the pre-amplifier is used, apply the new gain to the
1195 // pre-amplifier regardless if the capture level adjustment is
1196 // activated. This approach allows both functionalities to coexist
1197 // until they have been properly merged.
1198 if (config_.pre_amplifier.enabled) {
1199 config_.pre_amplifier.fixed_gain_factor = value;
1200 } else {
1201 config_.capture_level_adjustment.pre_gain_factor = value;
1202 }
1203
1204 // Use both the pre-amplifier and the capture level adjustment gains
1205 // as pre-gains.
1206 float gain = 1.f;
1207 if (config_.pre_amplifier.enabled) {
1208 gain *= config_.pre_amplifier.fixed_gain_factor;
1209 }
1210 if (config_.capture_level_adjustment.enabled) {
1211 gain *= config_.capture_level_adjustment.pre_gain_factor;
1212 }
1213
1214 submodules_.capture_levels_adjuster->SetPreGain(gain);
1215 }
1216 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
1217 break;
1218 case RuntimeSetting::Type::kCapturePostGain:
1219 if (config_.capture_level_adjustment.enabled) {
1220 float value;
1221 setting.GetFloat(&value);
1222 config_.capture_level_adjustment.post_gain_factor = value;
1223 submodules_.capture_levels_adjuster->SetPostGain(
1224 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001225 }
1226 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001227 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001228 case RuntimeSetting::Type::kCaptureCompressionGain: {
Hanna Silend4dbe452022-11-30 15:16:21 +01001229 if (!submodules_.agc_manager &&
1230 !(submodules_.gain_controller2 &&
1231 config_.gain_controller2.input_volume_controller.enabled)) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001232 float value;
1233 setting.GetFloat(&value);
1234 int int_value = static_cast<int>(value + .5f);
1235 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001236 if (submodules_.gain_control) {
1237 int error =
1238 submodules_.gain_control->set_compression_gain_db(int_value);
1239 RTC_DCHECK_EQ(kNoError, error);
1240 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001241 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001242 break;
1243 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001244 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001245 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001246 float value;
1247 setting.GetFloat(&value);
1248 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001249 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001250 }
1251 break;
1252 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001253 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1254 int value;
1255 setting.GetInt(&value);
1256 capture_.playout_volume = value;
1257 break;
1258 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001259 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001260 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001261 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001262 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001263 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001264 break;
1265 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001266 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001267 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001268 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001269 bool value;
1270 setting.GetBool(&value);
1271 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001272 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001273 }
Per Åhgren652ada52021-03-03 10:52:44 +00001274 ++num_settings_processed;
1275 }
1276
1277 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1278 // Handle overrun of the runtime settings queue, which likely will has
1279 // caused settings to be discarded.
1280 HandleOverrunInCaptureRuntimeSettingsQueue();
1281 }
1282}
1283
1284void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1285 // Fall back to a safe state for the case when a setting for capture output
1286 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001287 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001288}
1289
1290void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1291 RuntimeSetting setting;
1292 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001293 if (aec_dump_) {
1294 aec_dump_->WriteRuntimeSetting(setting);
1295 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001296 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001297 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001298 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001299 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001300 if (submodules_.render_pre_processor) {
1301 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001302 }
1303 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001304 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001305 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001306 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001307 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001308 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001309 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001310 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001311 break;
1312 }
1313 }
1314}
1315
peah9e6a2902017-05-15 07:19:21 -07001316void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001317 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001318
saza1d600522019-10-18 13:29:43 +02001319 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001320 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1321 num_reverse_channels(),
1322 &aecm_render_queue_buffer_);
1323 RTC_DCHECK(aecm_render_signal_queue_);
1324 // Insert the samples into the queue.
1325 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1326 // The data queue is full and needs to be emptied.
1327 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001328
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001329 // Retry the insert (should always work).
1330 bool result =
1331 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1332 RTC_DCHECK(result);
1333 }
peah764e3642016-10-22 05:04:30 -07001334 }
peah701d6282016-10-25 05:42:20 -07001335
Per Åhgren0695df12020-01-13 14:43:13 +01001336 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001337 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001338 // Insert the samples into the queue.
1339 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1340 // The data queue is full and needs to be emptied.
1341 EmptyQueuedRenderAudio();
1342
1343 // Retry the insert (should always work).
1344 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1345 RTC_DCHECK(result);
1346 }
1347 }
peah9e6a2902017-05-15 07:19:21 -07001348}
ivoc9f4a4a02016-10-28 05:39:16 -07001349
peah9e6a2902017-05-15 07:19:21 -07001350void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001351 if (submodules_.echo_detector) {
1352 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1353 RTC_DCHECK(red_render_signal_queue_);
1354 // Insert the samples into the queue.
1355 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1356 // The data queue is full and needs to be emptied.
1357 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001358
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001359 // Retry the insert (should always work).
1360 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1361 RTC_DCHECK(result);
1362 }
ivoc9f4a4a02016-10-28 05:39:16 -07001363 }
peah764e3642016-10-22 05:04:30 -07001364}
1365
1366void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001367 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001368 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001369
ivoc9f4a4a02016-10-28 05:39:16 -07001370 const size_t new_red_render_queue_element_max_size =
1371 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1372
peaha0624602016-10-25 04:45:24 -07001373 // Reallocate the queues if the queue item sizes are too small to fit the
1374 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001375
1376 if (agc_render_queue_element_max_size_ <
1377 new_agc_render_queue_element_max_size) {
1378 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1379
1380 std::vector<int16_t> template_queue_element(
1381 agc_render_queue_element_max_size_);
1382
1383 agc_render_signal_queue_.reset(
1384 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1385 kMaxNumFramesToBuffer, template_queue_element,
1386 RenderQueueItemVerifier<int16_t>(
1387 agc_render_queue_element_max_size_)));
1388
1389 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1390 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1391 } else {
1392 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001393 }
ivoc9f4a4a02016-10-28 05:39:16 -07001394
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001395 if (submodules_.echo_detector) {
1396 if (red_render_queue_element_max_size_ <
1397 new_red_render_queue_element_max_size) {
1398 red_render_queue_element_max_size_ =
1399 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001400
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001401 std::vector<float> template_queue_element(
1402 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001403
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001404 red_render_signal_queue_.reset(
1405 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1406 kMaxNumFramesToBuffer, template_queue_element,
1407 RenderQueueItemVerifier<float>(
1408 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001409
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001410 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1411 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1412 } else {
1413 red_render_signal_queue_->Clear();
1414 }
ivoc9f4a4a02016-10-28 05:39:16 -07001415 }
peah764e3642016-10-22 05:04:30 -07001416}
1417
1418void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001419 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001420 EmptyQueuedRenderAudioLocked();
1421}
1422
1423void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001424 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001425 RTC_DCHECK(aecm_render_signal_queue_);
1426 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001427 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001428 aecm_capture_queue_buffer_);
1429 }
peah701d6282016-10-25 05:42:20 -07001430 }
1431
Per Åhgren0695df12020-01-13 14:43:13 +01001432 if (submodules_.gain_control) {
1433 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1434 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1435 }
peah764e3642016-10-22 05:04:30 -07001436 }
ivoc9f4a4a02016-10-28 05:39:16 -07001437
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001438 if (submodules_.echo_detector) {
1439 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1440 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1441 }
ivoc9f4a4a02016-10-28 05:39:16 -07001442 }
peah764e3642016-10-22 05:04:30 -07001443}
1444
Per Åhgren645f24c2020-03-16 12:06:02 +01001445int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1446 const StreamConfig& input_config,
1447 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001448 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001449 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001450
1451 RETURN_ON_ERR(
1452 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1453 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001454
Markus Handell0df0fae2020-07-07 15:53:34 +02001455 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001456 DenormalDisabler denormal_disabler(use_denormal_disabler_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001457
aleloi868f32f2017-05-23 07:20:05 -07001458 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001459 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001460 }
1461
Per Åhgren645f24c2020-03-16 12:06:02 +01001462 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001463 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001464 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001465 }
peahde65ddc2016-09-16 15:02:15 -07001466 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001467 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001468 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001469 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001470 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001471 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001472 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001473 }
Per Åhgrena1351272019-08-15 12:15:46 +02001474 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001475
aleloi868f32f2017-05-23 07:20:05 -07001476 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001477 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001478 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001479 return kNoError;
1480}
1481
peahde65ddc2016-09-16 15:02:15 -07001482int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001483 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001484 HandleCaptureRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001485 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001486
peahb58a1582016-03-15 09:34:24 -07001487 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001488 // TODO(peah): Simplify once the public API Enable functions for these
1489 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001490 RTC_DCHECK_LE(
1491 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001492
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001493 data_dumper_->DumpRaw(
1494 "applied_input_volume",
1495 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1496
peahde65ddc2016-09-16 15:02:15 -07001497 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001498 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001499
Per Åhgrenc0424252019-12-10 13:04:15 +01001500 if (submodules_.high_pass_filter &&
1501 config_.high_pass_filter.apply_in_full_band &&
1502 !constants_.enforce_split_band_hpf) {
1503 submodules_.high_pass_filter->Process(capture_buffer,
1504 /*use_split_band_data=*/false);
1505 }
1506
Per Åhgrendb5d7282021-03-15 16:31:04 +00001507 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001508 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001509 // When the input volume is emulated, retrieve the volume applied to the
1510 // input audio and notify that to APM so that the volume is passed to the
1511 // active AGC.
1512 set_stream_analog_level_locked(
1513 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001514 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001515 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1516 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001517 }
1518
Per Åhgren928146f2019-08-20 09:19:21 +02001519 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001520 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001521 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001522 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1523 if (log_rms) {
1524 capture_rms_interval_counter_ = 0;
1525 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001526 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1527 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1528 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1529 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001530 }
1531
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001532 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001533 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001534 *capture_.applied_input_volume);
1535 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001536
saza1d600522019-10-18 13:29:43 +02001537 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001538 // Determine if the echo path gain has changed by checking all the gains
1539 // applied before AEC.
1540 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001541
Per Åhgrendb5d7282021-03-15 16:31:04 +00001542 // Detect and flag any change in the capture level adjustment pre-gain.
1543 if (submodules_.capture_levels_adjuster) {
1544 float pre_adjustment_gain =
1545 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001546 capture_.echo_path_gain_change =
1547 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001548 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001549 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001550 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001551 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001552
1553 // Detect volume change.
1554 capture_.echo_path_gain_change =
1555 capture_.echo_path_gain_change ||
1556 (capture_.prev_playout_volume != capture_.playout_volume &&
1557 capture_.prev_playout_volume >= 0);
1558 capture_.prev_playout_volume = capture_.playout_volume;
1559
saza1d600522019-10-18 13:29:43 +02001560 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001561 }
1562
Per Åhgren0695df12020-01-13 14:43:13 +01001563 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001564 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001565 }
1566
Hanna Silend4dbe452022-11-30 15:16:21 +01001567 if (submodules_.gain_controller2 &&
1568 config_.gain_controller2.input_volume_controller.enabled) {
1569 // Expect the volume to be available if the input controller is enabled.
1570 RTC_DCHECK(capture_.applied_input_volume.has_value());
1571 if (capture_.applied_input_volume.has_value()) {
1572 submodules_.gain_controller2->Analyze(*capture_.applied_input_volume,
1573 *capture_buffer);
1574 }
1575 }
1576
peah2ace3f92016-09-10 04:42:27 -07001577 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1578 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001579 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1580 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001581 }
1582
Per Åhgrene14cb992019-11-27 09:34:22 +01001583 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1584 constants_.multi_channel_capture_support;
1585 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001586 // Force down-mixing of the number of channels after the detection of
1587 // capture signal saturation.
1588 // TODO(peah): Look into ensuring that this kind of tampering with the
1589 // AudioBuffer functionality should not be needed.
1590 capture_buffer->set_num_channels(1);
1591 }
1592
Per Åhgrenc0424252019-12-10 13:04:15 +01001593 if (submodules_.high_pass_filter &&
1594 (!config_.high_pass_filter.apply_in_full_band ||
1595 constants_.enforce_split_band_hpf)) {
1596 submodules_.high_pass_filter->Process(capture_buffer,
1597 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001598 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001599
Per Åhgren0695df12020-01-13 14:43:13 +01001600 if (submodules_.gain_control) {
1601 RETURN_ON_ERR(
1602 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1603 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001604
Per Åhgren8ad9e742020-01-30 07:40:58 +01001605 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1606 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1607 submodules_.noise_suppressor) {
1608 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001609 }
peahb58a1582016-03-15 09:34:24 -07001610
saza1d600522019-10-18 13:29:43 +02001611 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001612 // Ensure that the stream delay was set before the call to the
1613 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001614 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001615 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001616 }
1617
saza1d600522019-10-18 13:29:43 +02001618 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001619 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001620 }
peahe0eae3c2016-12-14 01:16:23 -08001621
saza1d600522019-10-18 13:29:43 +02001622 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001623 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001624 } else {
saza1d600522019-10-18 13:29:43 +02001625 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001626 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1627
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001628 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001629 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001630 }
1631
saza1d600522019-10-18 13:29:43 +02001632 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001633 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001634 }
1635
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001636 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001637 linear_aec_buffer && submodules_.noise_suppressor) {
1638 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001639 }
1640
saza1d600522019-10-18 13:29:43 +02001641 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001642 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001643 }
Per Åhgren46537a32017-06-07 10:08:10 +02001644 }
ivoc9f4a4a02016-10-28 05:39:16 -07001645
Per Åhgren0695df12020-01-13 14:43:13 +01001646 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001647 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001648
1649 absl::optional<int> new_digital_gain =
1650 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001651 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001652 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1653 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001654 }
Per Åhgren0695df12020-01-13 14:43:13 +01001655
1656 if (submodules_.gain_control) {
1657 // TODO(peah): Add reporting from AEC3 whether there is echo.
1658 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1659 capture_buffer, /*stream_has_echo*/ false));
1660 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001661
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001662 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1663 SampleRateSupportsMultiBand(
1664 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1665 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001666 }
1667
Per Åhgren19775cb2021-03-12 23:08:09 +00001668 if (capture_.capture_output_used) {
1669 if (capture_.capture_fullband_audio) {
1670 const auto& ec = submodules_.echo_controller;
1671 bool ec_active = ec ? ec->ActiveProcessing() : false;
1672 // Only update the fullband buffer if the multiband processing has changed
1673 // the signal. Keep the original signal otherwise.
1674 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1675 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1676 }
1677 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001678 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001679
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001680 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001681 submodules_.echo_detector->AnalyzeCaptureAudio(
1682 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1683 capture_buffer->num_frames()));
1684 }
1685
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001686 absl::optional<float> voice_probability;
1687 if (!!submodules_.voice_activity_detector) {
1688 voice_probability = submodules_.voice_activity_detector->Analyze(
1689 AudioFrameView<const float>(capture_buffer->channels(),
1690 capture_buffer->num_channels(),
1691 capture_buffer->num_frames()));
1692 }
1693
Per Åhgren19775cb2021-03-12 23:08:09 +00001694 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001695 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001696 switch (transient_suppressor_vad_mode_) {
1697 case TransientSuppressor::VadMode::kDefault:
1698 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001699 transient_suppressor_voice_probability =
1700 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001701 }
1702 break;
1703 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001704 RTC_DCHECK(voice_probability.has_value());
1705 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001706 break;
1707 case TransientSuppressor::VadMode::kNoVad:
1708 // The transient suppressor will ignore `voice_probability`.
1709 break;
1710 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001711 float delayed_voice_probability =
1712 submodules_.transient_suppressor->Suppress(
1713 capture_buffer->channels()[0], capture_buffer->num_frames(),
1714 capture_buffer->num_channels(),
1715 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1716 capture_buffer->num_frames_per_band(),
1717 /*reference_data=*/nullptr, /*reference_length=*/0,
1718 transient_suppressor_voice_probability, capture_.key_pressed);
1719 if (voice_probability.has_value()) {
1720 *voice_probability = delayed_voice_probability;
1721 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001722 }
1723
Artem Titov0b489302021-07-28 20:50:03 +02001724 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001725 if (submodules_.capture_analyzer) {
1726 submodules_.capture_analyzer->Analyze(capture_buffer);
1727 }
1728
1729 if (submodules_.gain_controller2) {
Hanna Silend4dbe452022-11-30 15:16:21 +01001730 // TODO(bugs.webrtc.org/7494): Let AGC2 detect applied input volume
1731 // changes.
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001732 submodules_.gain_controller2->Process(
1733 voice_probability, capture_.applied_input_volume_changed,
1734 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001735 }
1736
1737 if (submodules_.capture_post_processor) {
1738 submodules_.capture_post_processor->Process(capture_buffer);
1739 }
1740
Per Åhgren19775cb2021-03-12 23:08:09 +00001741 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1742 capture_buffer->channels_const()[0],
1743 capture_nonlocked_.capture_processing_format.num_frames()));
1744 if (log_rms) {
1745 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1746 RTC_HISTOGRAM_COUNTS_LINEAR(
1747 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1748 RmsLevel::kMinLevelDb, 64);
1749 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1750 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1751 }
1752
Per Åhgren19775cb2021-03-12 23:08:09 +00001753 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001754 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001755 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1756 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1757 capture_.stats.residual_echo_likelihood_recent_max =
1758 ed_metrics.echo_likelihood_recent_max;
1759 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001760 }
1761
Per Åhgren19775cb2021-03-12 23:08:09 +00001762 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001763 if (submodules_.echo_controller) {
1764 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1765 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1766 capture_.stats.echo_return_loss_enhancement =
1767 ec_metrics.echo_return_loss_enhancement;
1768 capture_.stats.delay_ms = ec_metrics.delay_ms;
1769 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001770
1771 // Pass stats for reporting.
1772 stats_reporter_.UpdateStatistics(capture_.stats);
1773
Alessio Bazzica533e4612022-09-07 16:58:33 +02001774 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001775 if (capture_.recommended_input_volume.has_value()) {
1776 recommended_input_volume_stats_reporter_.UpdateStatistics(
1777 *capture_.recommended_input_volume);
1778 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001779
Per Åhgrendb5d7282021-03-15 16:31:04 +00001780 if (submodules_.capture_levels_adjuster) {
1781 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1782 *capture_buffer);
1783
Per Åhgrendb5d7282021-03-15 16:31:04 +00001784 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001785 // If the input volume emulation is used, retrieve the recommended input
1786 // volume and set that to emulate the input volume on the next processed
1787 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001788 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001789 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001790 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001791 }
1792 }
1793
Per Åhgren55bc0772021-03-12 14:18:36 +00001794 // Temporarily set the output to zero after the stream has been unmuted
1795 // (capture output is again used). The purpose of this is to avoid clicks and
1796 // artefacts in the audio that results when the processing again is
1797 // reactivated after unmuting.
1798 if (!capture_.capture_output_used_last_frame &&
1799 capture_.capture_output_used) {
1800 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1801 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1802 capture_buffer->num_frames());
1803 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1804 }
1805 }
1806 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1807
peahdf3efa82015-11-28 12:35:15 -08001808 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001809
Alessio Bazzica533e4612022-09-07 16:58:33 +02001810 data_dumper_->DumpRaw("recommended_input_volume",
1811 capture_.recommended_input_volume.value_or(
1812 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001813
niklase@google.com470e71d2011-07-07 08:21:25 +00001814 return kNoError;
1815}
1816
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001817int AudioProcessingImpl::AnalyzeReverseStream(
1818 const float* const* data,
1819 const StreamConfig& reverse_config) {
1820 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001821 MutexLock lock(&mutex_render_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001822 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1823 RTC_DCHECK(data);
1824 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1825 RTC_DCHECK(data[i]);
1826 }
1827 RETURN_ON_ERR(
1828 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1829
1830 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001831 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1832}
1833
peahde65ddc2016-09-16 15:02:15 -07001834int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1835 const StreamConfig& input_config,
1836 const StreamConfig& output_config,
1837 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001838 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001839 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001840 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001841 RETURN_ON_ERR(
1842 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1843
1844 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001845
peahde65ddc2016-09-16 15:02:15 -07001846 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001847
Alex Loiko5825aa62017-12-18 16:02:40 +01001848 if (submodule_states_.RenderMultiBandProcessingActive() ||
1849 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001850 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1851 dest);
peah2ace3f92016-09-10 04:42:27 -07001852 } else if (formats_.api_format.reverse_input_stream() !=
1853 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001854 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1855 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001856 } else {
peahde65ddc2016-09-16 15:02:15 -07001857 CopyAudioIfNeeded(src, input_config.num_frames(),
1858 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001859 }
1860
1861 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001862}
1863
peahdf3efa82015-11-28 12:35:15 -08001864int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001865 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001866 const StreamConfig& input_config,
1867 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001868 if (aec_dump_) {
1869 const size_t channel_size =
1870 formats_.api_format.reverse_input_stream().num_frames();
1871 const size_t num_channels =
1872 formats_.api_format.reverse_input_stream().num_channels();
1873 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001874 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001875 }
peahdf3efa82015-11-28 12:35:15 -08001876 render_.render_audio->CopyFrom(src,
1877 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001878 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001879}
1880
Per Åhgren645f24c2020-03-16 12:06:02 +01001881int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1882 const StreamConfig& input_config,
1883 const StreamConfig& output_config,
1884 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001885 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001886
Markus Handell0df0fae2020-07-07 15:53:34 +02001887 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001888 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1889
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001890 RETURN_ON_ERR(
1891 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1892 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001893
aleloi868f32f2017-05-23 07:20:05 -07001894 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001895 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1896 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001897 }
1898
Per Åhgren645f24c2020-03-16 12:06:02 +01001899 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001900 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001901 if (submodule_states_.RenderMultiBandProcessingActive() ||
1902 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001903 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001904 }
aluebsb0319552016-03-17 20:39:53 -07001905 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001906}
niklase@google.com470e71d2011-07-07 08:21:25 +00001907
peahde65ddc2016-09-16 15:02:15 -07001908int AudioProcessingImpl::ProcessRenderStreamLocked() {
1909 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001910
Alex Loiko73ec0192018-05-15 10:52:28 +02001911 HandleRenderRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001912 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alex Loiko73ec0192018-05-15 10:52:28 +02001913
saza1d600522019-10-18 13:29:43 +02001914 if (submodules_.render_pre_processor) {
1915 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001916 }
1917
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001918 QueueNonbandedRenderAudio(render_buffer);
1919
peah2ace3f92016-09-10 04:42:27 -07001920 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001921 SampleRateSupportsMultiBand(
1922 formats_.render_processing_format.sample_rate_hz())) {
1923 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001924 }
1925
peahce4d9152017-05-19 01:28:05 -07001926 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1927 QueueBandedRenderAudio(render_buffer);
1928 }
1929
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001930 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001931 if (submodules_.echo_controller) {
1932 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001933 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001934
peah2ace3f92016-09-10 04:42:27 -07001935 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001936 SampleRateSupportsMultiBand(
1937 formats_.render_processing_format.sample_rate_hz())) {
1938 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001939 }
1940
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001941 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001942}
1943
1944int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001945 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001946 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001947 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001948
niklase@google.com470e71d2011-07-07 08:21:25 +00001949 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001950 delay = 0;
1951 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001952 }
1953
1954 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1955 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001956 delay = 500;
1957 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001958 }
1959
peahdf3efa82015-11-28 12:35:15 -08001960 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001961 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001962}
1963
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001964bool AudioProcessingImpl::GetLinearAecOutput(
1965 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001966 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001967 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1968
1969 RTC_DCHECK(linear_aec_buffer);
1970 if (linear_aec_buffer) {
1971 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1972 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1973
1974 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1975 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1976 rtc::ArrayView<const float> channel_view =
1977 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1978 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001979 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1980 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001981 }
1982 return true;
1983 }
1984 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001985 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001986 return false;
1987}
1988
niklase@google.com470e71d2011-07-07 08:21:25 +00001989int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001990 // Used as callback from submodules, hence locking is not allowed.
1991 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001992}
1993
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001994void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001995 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001996 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001997}
1998
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001999void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02002000 MutexLock lock_capture(&mutex_capture_);
2001 set_stream_analog_level_locked(level);
2002}
2003
2004void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002005 capture_.applied_input_volume_changed =
2006 capture_.applied_input_volume.has_value() &&
2007 *capture_.applied_input_volume != level;
2008 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002009
Alessio Bazzica533e4612022-09-07 16:58:33 +02002010 // Invalidate any previously recommended input volume which will be updated by
2011 // `ProcessStream()`.
2012 capture_.recommended_input_volume = absl::nullopt;
2013
Per Åhgren0e3198e2019-11-18 08:52:22 +01002014 if (submodules_.agc_manager) {
2015 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002016 return;
2017 }
2018
2019 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01002020 int error = submodules_.gain_control->set_stream_analog_level(level);
2021 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002022 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002023 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002024}
2025
2026int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002027 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002028 if (!capture_.applied_input_volume.has_value()) {
2029 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
2030 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02002031 // Input volume to recommend when `set_stream_analog_level()` is not called.
2032 constexpr int kFallBackInputVolume = 255;
2033 // When APM has no input volume to recommend, return the latest applied input
2034 // volume that has been observed in order to possibly produce no input volume
2035 // change. If no applied input volume has been observed, return a fall-back
2036 // value.
2037 return capture_.recommended_input_volume.value_or(
2038 capture_.applied_input_volume.value_or(kFallBackInputVolume));
2039}
2040
2041void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
2042 if (!capture_.applied_input_volume.has_value()) {
2043 // When `set_stream_analog_level()` is not called, no input level can be
2044 // recommended.
2045 capture_.recommended_input_volume = absl::nullopt;
2046 return;
2047 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002048
Per Åhgrendb5d7282021-03-15 16:31:04 +00002049 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002050 capture_.recommended_input_volume =
2051 submodules_.agc_manager->recommended_analog_level();
2052 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002053 }
2054
2055 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002056 capture_.recommended_input_volume =
2057 submodules_.gain_control->stream_analog_level();
2058 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002059 }
2060
Hanna Silend4dbe452022-11-30 15:16:21 +01002061 if (submodules_.gain_controller2 &&
2062 config_.gain_controller2.input_volume_controller.enabled) {
2063 capture_.recommended_input_volume =
2064 submodules_.gain_controller2->GetRecommendedInputVolume();
2065 return;
2066 }
2067
Alessio Bazzica533e4612022-09-07 16:58:33 +02002068 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002069}
2070
Ali Tofigh1fa87c42022-07-25 22:07:08 +02002071bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
2072 int64_t max_log_size_bytes,
2073 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02002074 std::unique_ptr<AecDump> aec_dump =
2075 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02002076 if (!aec_dump) {
2077 return false;
2078 }
2079
2080 AttachAecDump(std::move(aec_dump));
2081 return true;
2082}
2083
2084bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
2085 int64_t max_log_size_bytes,
2086 rtc::TaskQueue* worker_queue) {
2087 std::unique_ptr<AecDump> aec_dump =
2088 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
2089 if (!aec_dump) {
2090 return false;
2091 }
2092
2093 AttachAecDump(std::move(aec_dump));
2094 return true;
2095}
2096
aleloi868f32f2017-05-23 07:20:05 -07002097void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
2098 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02002099 MutexLock lock_render(&mutex_render_);
2100 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002101
2102 // The previously attached AecDump will be destroyed with the
2103 // 'aec_dump' parameter, which is after locks are released.
2104 aec_dump_.swap(aec_dump);
2105 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02002106 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07002107}
2108
2109void AudioProcessingImpl::DetachAecDump() {
2110 // The d-tor of a task-queue based AecDump blocks until all pending
2111 // tasks are done. This construction avoids blocking while holding
2112 // the render and capture locks.
2113 std::unique_ptr<AecDump> aec_dump = nullptr;
2114 {
Markus Handell0df0fae2020-07-07 15:53:34 +02002115 MutexLock lock_render(&mutex_render_);
2116 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002117 aec_dump = std::move(aec_dump_);
2118 }
2119}
2120
peah8271d042016-11-22 07:24:52 -08002121AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002122 MutexLock lock_render(&mutex_render_);
2123 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08002124 return config_;
2125}
2126
peah2ace3f92016-09-10 04:42:27 -07002127bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
2128 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002129 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002130 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02002131 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00002132 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
2133 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00002134 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07002135}
2136
Per Åhgrenc0734712020-01-02 15:15:36 +01002137void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02002138 if (config_.transient_suppression.enabled &&
2139 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02002140 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01002141 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01002142 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02002143 submodule_creation_overrides_, transient_suppressor_vad_mode_,
2144 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2145 num_proc_channels());
2146 if (!submodules_.transient_suppressor) {
2147 RTC_LOG(LS_WARNING)
2148 << "No transient suppressor created (probably disabled)";
2149 }
2150 } else {
sazaaa42ecd2020-04-01 15:24:40 +02002151 submodules_.transient_suppressor->Initialize(
2152 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2153 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02002154 }
Per Åhgrenc0734712020-01-02 15:15:36 +01002155 } else {
2156 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002157 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002158}
2159
Per Åhgren0f14db22020-01-03 14:27:14 +01002160void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01002161 bool high_pass_filter_needed_by_aec =
2162 config_.echo_canceller.enabled &&
2163 config_.echo_canceller.enforce_high_pass_filtering &&
2164 !config_.echo_canceller.mobile_mode;
2165 if (submodule_states_.HighPassFilteringRequired() ||
2166 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01002167 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
2168 !constants_.enforce_split_band_hpf;
2169 int rate = use_full_band ? proc_fullband_sample_rate_hz()
2170 : proc_split_sample_rate_hz();
2171 size_t num_channels =
2172 use_full_band ? num_output_channels() : num_proc_channels();
2173
Per Åhgren0f14db22020-01-03 14:27:14 +01002174 if (!submodules_.high_pass_filter ||
2175 rate != submodules_.high_pass_filter->sample_rate_hz() ||
2176 forced_reset ||
2177 num_channels != submodules_.high_pass_filter->num_channels()) {
2178 submodules_.high_pass_filter.reset(
2179 new HighPassFilter(rate, num_channels));
2180 }
peah8271d042016-11-22 07:24:52 -08002181 } else {
saza1d600522019-10-18 13:29:43 +02002182 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08002183 }
2184}
alessiob3ec96df2017-05-22 06:57:06 -07002185
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02002186void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002187 bool use_echo_controller =
2188 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002189 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002190
2191 if (use_echo_controller) {
2192 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01002193 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01002194 submodules_.echo_controller = echo_control_factory_->Create(
2195 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01002196 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01002197 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002198 EchoCanceller3Config config;
2199 absl::optional<EchoCanceller3Config> multichannel_config;
2200 if (use_setup_specific_default_aec3_config_) {
2201 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
2202 }
saza1d600522019-10-18 13:29:43 +02002203 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002204 config, multichannel_config, proc_sample_rate_hz(),
2205 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01002206 }
2207
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002208 // Setup the storage for returning the linear AEC output.
2209 if (config_.echo_canceller.export_linear_aec_output) {
2210 constexpr int kLinearOutputRateHz = 16000;
2211 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
2212 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
2213 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
2214 } else {
2215 capture_.linear_aec_output.reset();
2216 }
2217
Per Åhgren200feba2019-03-06 04:16:46 +01002218 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002219
saza1d600522019-10-18 13:29:43 +02002220 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002221 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002222 return;
peahe0eae3c2016-12-14 01:16:23 -08002223 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002224
saza1d600522019-10-18 13:29:43 +02002225 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002226 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002227 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002228
2229 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02002230 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002231 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002232 return;
2233 }
2234
2235 if (config_.echo_canceller.mobile_mode) {
2236 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002237 size_t max_element_size =
2238 std::max(static_cast<size_t>(1),
2239 kMaxAllowedValuesOfSamplesPerBand *
2240 EchoControlMobileImpl::NumCancellersRequired(
2241 num_output_channels(), num_reverse_channels()));
2242
2243 std::vector<int16_t> template_queue_element(max_element_size);
2244
2245 aecm_render_signal_queue_.reset(
2246 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2247 kMaxNumFramesToBuffer, template_queue_element,
2248 RenderQueueItemVerifier<int16_t>(max_element_size)));
2249
2250 aecm_render_queue_buffer_.resize(max_element_size);
2251 aecm_capture_queue_buffer_.resize(max_element_size);
2252
saza1d600522019-10-18 13:29:43 +02002253 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002254
saza1d600522019-10-18 13:29:43 +02002255 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2256 num_reverse_channels(),
2257 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002258 return;
2259 }
2260
saza1d600522019-10-18 13:29:43 +02002261 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002262 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002263}
peah8271d042016-11-22 07:24:52 -08002264
Per Åhgren0695df12020-01-13 14:43:13 +01002265void AudioProcessingImpl::InitializeGainController1() {
Hanna Silend4dbe452022-11-30 15:16:21 +01002266 if (config_.gain_controller2.enabled &&
2267 config_.gain_controller2.input_volume_controller.enabled &&
2268 config_.gain_controller1.enabled &&
2269 (config_.gain_controller1.mode ==
2270 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
2271 config_.gain_controller1.analog_gain_controller.enabled)) {
2272 RTC_LOG(LS_ERROR) << "APM configuration not valid: "
2273 << "Multiple input volume controllers enabled.";
2274 }
2275
Per Åhgren0695df12020-01-13 14:43:13 +01002276 if (!config_.gain_controller1.enabled) {
2277 submodules_.agc_manager.reset();
2278 submodules_.gain_control.reset();
2279 return;
2280 }
2281
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002282 RTC_HISTOGRAM_BOOLEAN(
2283 "WebRTC.Audio.GainController.Analog.Enabled",
2284 config_.gain_controller1.analog_gain_controller.enabled);
2285
Per Åhgren0695df12020-01-13 14:43:13 +01002286 if (!submodules_.gain_control) {
2287 submodules_.gain_control.reset(new GainControlImpl());
2288 }
2289
2290 submodules_.gain_control->Initialize(num_proc_channels(),
2291 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002292 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2293 int error = submodules_.gain_control->set_mode(
2294 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2295 RTC_DCHECK_EQ(kNoError, error);
2296 error = submodules_.gain_control->set_target_level_dbfs(
2297 config_.gain_controller1.target_level_dbfs);
2298 RTC_DCHECK_EQ(kNoError, error);
2299 error = submodules_.gain_control->set_compression_gain_db(
2300 config_.gain_controller1.compression_gain_db);
2301 RTC_DCHECK_EQ(kNoError, error);
2302 error = submodules_.gain_control->enable_limiter(
2303 config_.gain_controller1.enable_limiter);
2304 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002305 constexpr int kAnalogLevelMinimum = 0;
2306 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002307 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002308 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002309 RTC_DCHECK_EQ(kNoError, error);
2310
2311 submodules_.agc_manager.reset();
2312 return;
2313 }
2314
2315 if (!submodules_.agc_manager.get() ||
2316 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002317 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002318 int stream_analog_level = -1;
2319 const bool re_creation = !!submodules_.agc_manager;
2320 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002321 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002322 }
2323 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002324 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002325 if (re_creation) {
2326 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2327 }
2328 }
2329 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002330 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002331 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2332 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002333}
2334
Alessio Bazzica38901042021-10-14 12:14:21 +02002335void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2336 if (!config_has_changed) {
2337 return;
2338 }
2339 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002340 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002341 return;
2342 }
2343 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002344 const bool use_internal_vad =
2345 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica38901042021-10-14 12:14:21 +02002346 submodules_.gain_controller2 = std::make_unique<GainController2>(
Hanna Silena6574902022-11-30 16:59:05 +01002347 config_.gain_controller2,
Hanna Silenca653552022-12-08 17:40:01 +01002348 gain_controller2_config_override_.has_value()
2349 ? gain_controller2_config_override_->input_volume_controller_config
2350 : InputVolumeController::Config{},
Hanna Silena6574902022-11-30 16:59:05 +01002351 proc_fullband_sample_rate_hz(), num_input_channels(), use_internal_vad);
Hanna Silend4dbe452022-11-30 15:16:21 +01002352 submodules_.gain_controller2->SetCaptureOutputUsed(
2353 capture_.capture_output_used);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002354 }
2355}
2356
2357void AudioProcessingImpl::InitializeVoiceActivityDetector(
2358 bool config_has_changed) {
2359 if (!config_has_changed) {
2360 return;
2361 }
2362 const bool use_vad =
2363 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2364 config_.gain_controller2.enabled &&
Alessio Bazzica17e14fd2022-12-07 17:08:45 +01002365 (config_.gain_controller2.adaptive_digital.enabled ||
2366 config_.gain_controller2.input_volume_controller.enabled);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002367 if (!use_vad) {
2368 submodules_.voice_activity_detector.reset();
2369 return;
2370 }
2371 if (!submodules_.voice_activity_detector || config_has_changed) {
2372 RTC_DCHECK(!!submodules_.gain_controller2);
2373 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2374 submodules_.voice_activity_detector =
2375 std::make_unique<VoiceActivityDetectorWrapper>(
2376 config_.gain_controller2.adaptive_digital.vad_reset_period_ms,
2377 submodules_.gain_controller2->GetCpuFeatures(),
2378 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002379 }
2380}
2381
saza0bad15f2019-10-16 11:46:11 +02002382void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002383 submodules_.noise_suppressor.reset();
2384
saza0bad15f2019-10-16 11:46:11 +02002385 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002386 auto map_level =
2387 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2388 using NoiseSuppresionConfig =
2389 AudioProcessing::Config::NoiseSuppression;
2390 switch (level) {
2391 case NoiseSuppresionConfig::kLow:
2392 return NsConfig::SuppressionLevel::k6dB;
2393 case NoiseSuppresionConfig::kModerate:
2394 return NsConfig::SuppressionLevel::k12dB;
2395 case NoiseSuppresionConfig::kHigh:
2396 return NsConfig::SuppressionLevel::k18dB;
2397 case NoiseSuppresionConfig::kVeryHigh:
2398 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002399 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002400 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002401 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002402
sazaaa42ecd2020-04-01 15:24:40 +02002403 NsConfig cfg;
2404 cfg.target_level = map_level(config_.noise_suppression.level);
2405 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2406 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002407 }
2408}
2409
Per Åhgrendb5d7282021-03-15 16:31:04 +00002410void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2411 if (config_.pre_amplifier.enabled ||
2412 config_.capture_level_adjustment.enabled) {
2413 // Use both the pre-amplifier and the capture level adjustment gains as
2414 // pre-gains.
2415 float pre_gain = 1.f;
2416 if (config_.pre_amplifier.enabled) {
2417 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2418 }
2419 if (config_.capture_level_adjustment.enabled) {
2420 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2421 }
2422
2423 submodules_.capture_levels_adjuster =
2424 std::make_unique<CaptureLevelsAdjuster>(
2425 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2426 config_.capture_level_adjustment.analog_mic_gain_emulation
2427 .initial_level,
2428 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002429 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002430 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002431 }
2432}
2433
ivoc9f4a4a02016-10-28 05:39:16 -07002434void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002435 if (submodules_.echo_detector) {
2436 submodules_.echo_detector->Initialize(
2437 proc_fullband_sample_rate_hz(), 1,
2438 formats_.render_processing_format.sample_rate_hz(), 1);
2439 }
ivoc9f4a4a02016-10-28 05:39:16 -07002440}
2441
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002442void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002443 if (submodules_.capture_analyzer) {
2444 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2445 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002446 }
2447}
2448
Sam Zackrisson0beac582017-09-25 12:04:02 +02002449void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002450 if (submodules_.capture_post_processor) {
2451 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002452 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002453 }
2454}
2455
Alex Loiko5825aa62017-12-18 16:02:40 +01002456void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002457 if (submodules_.render_pre_processor) {
2458 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002459 formats_.render_processing_format.sample_rate_hz(),
2460 formats_.render_processing_format.num_channels());
2461 }
2462}
2463
aleloi868f32f2017-05-23 07:20:05 -07002464void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2465 if (!aec_dump_) {
2466 return;
2467 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002468
2469 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002470 // TODO(peah): Add semicolon-separated concatenations of experiment
2471 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002472 if (!!submodules_.capture_post_processor) {
2473 experiments_description += "CapturePostProcessor;";
2474 }
2475 if (!!submodules_.render_pre_processor) {
2476 experiments_description += "RenderPreProcessor;";
2477 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002478 if (capture_nonlocked_.echo_controller_enabled) {
2479 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002480 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002481 if (config_.gain_controller2.enabled) {
2482 experiments_description += "GainController2;";
2483 }
aleloi868f32f2017-05-23 07:20:05 -07002484
2485 InternalAPMConfig apm_config;
2486
Per Åhgren200feba2019-03-06 04:16:46 +01002487 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002488 apm_config.aec_delay_agnostic_enabled = false;
2489 apm_config.aec_extended_filter_enabled = false;
2490 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002491
saza1d600522019-10-18 13:29:43 +02002492 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002493 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002494 submodules_.echo_control_mobile &&
2495 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002496 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002497 submodules_.echo_control_mobile
2498 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002499 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002500
Per Åhgren0695df12020-01-13 14:43:13 +01002501 apm_config.agc_enabled = !!submodules_.gain_control;
2502
2503 apm_config.agc_mode = submodules_.gain_control
2504 ? static_cast<int>(submodules_.gain_control->mode())
2505 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002506 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002507 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2508 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002509 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002510
2511 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2512
saza0bad15f2019-10-16 11:46:11 +02002513 apm_config.ns_enabled = config_.noise_suppression.enabled;
2514 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002515
2516 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002517 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002518 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002519 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2520 apm_config.pre_amplifier_fixed_gain_factor =
2521 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002522
2523 if (!forced && apm_config == apm_config_for_aec_dump_) {
2524 return;
2525 }
2526 aec_dump_->WriteConfig(apm_config);
2527 apm_config_for_aec_dump_ = apm_config;
2528}
2529
2530void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2531 const float* const* src) {
2532 RTC_DCHECK(aec_dump_);
2533 WriteAecDumpConfigMessage(false);
2534
2535 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2536 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2537 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002538 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002539 RecordAudioProcessingState();
2540}
2541
2542void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002543 const int16_t* const data,
2544 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002545 RTC_DCHECK(aec_dump_);
2546 WriteAecDumpConfigMessage(false);
2547
Per Åhgren645f24c2020-03-16 12:06:02 +01002548 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2549 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002550 RecordAudioProcessingState();
2551}
2552
2553void AudioProcessingImpl::RecordProcessedCaptureStream(
2554 const float* const* processed_capture_stream) {
2555 RTC_DCHECK(aec_dump_);
2556
2557 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2558 const size_t num_channels =
2559 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002560 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2561 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002562 aec_dump_->WriteCaptureStreamMessage();
2563}
2564
2565void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002566 const int16_t* const data,
2567 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002568 RTC_DCHECK(aec_dump_);
2569
Per Åhgren645f24c2020-03-16 12:06:02 +01002570 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002571 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002572 aec_dump_->WriteCaptureStreamMessage();
2573}
2574
2575void AudioProcessingImpl::RecordAudioProcessingState() {
2576 RTC_DCHECK(aec_dump_);
2577 AecDump::AudioProcessingState audio_proc_state;
2578 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002579 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002580 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002581 audio_proc_state.keypress = capture_.key_pressed;
2582 aec_dump_->AddAudioProcessingState(audio_proc_state);
2583}
2584
Per Åhgrenc0734712020-01-02 15:15:36 +01002585AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002586 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002587 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002588 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002589 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002590 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002591 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002592 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002593 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002594 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002595 prev_playout_volume(-1),
2596 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002597
2598AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2599
2600AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2601
2602AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2603
Per Åhgrencf4c8722019-12-30 14:32:14 +01002604AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2605 : stats_message_queue_(1) {}
2606
2607AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2608
2609AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002610 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002611 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2612 // If the message queue is full, return the cached stats.
2613 static_cast<void>(new_stats_available);
2614
2615 return cached_stats_;
2616}
2617
2618void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2619 const AudioProcessingStats& new_stats) {
2620 AudioProcessingStats stats_to_queue = new_stats;
2621 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2622 // If the message queue is full, discard the new stats.
2623 static_cast<void>(stats_message_passed);
2624}
2625
niklase@google.com470e71d2011-07-07 08:21:25 +00002626} // namespace webrtc