blob: c80cc76a3d8294448bd30a966e1527eae35f340e [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
Per Åhgrenc8626b62019-08-23 15:49:51 +020072// Identify the native processing rate that best handles a sample rate.
Per Åhgrenfcbe4072019-09-15 00:27:58 +020073int SuitableProcessRate(int minimum_rate,
74 int max_splitting_rate,
75 bool band_splitting_required) {
Per Åhgrenc8626b62019-08-23 15:49:51 +020076 const int uppermost_native_rate =
Per Åhgrenfcbe4072019-09-15 00:27:58 +020077 band_splitting_required ? max_splitting_rate : 48000;
Per Åhgrenc8626b62019-08-23 15:49:51 +020078 for (auto rate : {16000, 32000, 48000}) {
peah2ace3f92016-09-10 04:42:27 -070079 if (rate >= uppermost_native_rate) {
80 return uppermost_native_rate;
81 }
82 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -070083 return rate;
84 }
85 }
Artem Titovd3251962021-11-15 16:57:07 +010086 RTC_DCHECK_NOTREACHED();
peah2ace3f92016-09-10 04:42:27 -070087 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -070088}
89
Sam Zackrissonf0d1c032019-03-27 13:28:08 +010090GainControl::Mode Agc1ConfigModeToInterfaceMode(
91 AudioProcessing::Config::GainController1::Mode mode) {
92 using Agc1Config = AudioProcessing::Config::GainController1;
93 switch (mode) {
94 case Agc1Config::kAdaptiveAnalog:
95 return GainControl::kAdaptiveAnalog;
96 case Agc1Config::kAdaptiveDigital:
97 return GainControl::kAdaptiveDigital;
98 case Agc1Config::kFixedDigital:
99 return GainControl::kFixedDigital;
100 }
Karl Wibergc95b9392020-11-08 00:49:37 +0100101 RTC_CHECK_NOTREACHED();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100102}
103
Per Åhgren19775cb2021-03-12 23:08:09 +0000104bool MinimizeProcessingForUnusedOutput() {
105 return !field_trial::IsEnabled("WebRTC-MutedStateKillSwitch");
106}
107
peah9e6a2902017-05-15 07:19:21 -0700108// Maximum lengths that frame of samples being passed from the render side to
109// the capture side can have (does not apply to AEC3).
110static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
111static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
112
peah764e3642016-10-22 05:04:30 -0700113// Maximum number of frames to buffer in the render queue.
114// TODO(peah): Decrease this once we properly handle hugely unbalanced
115// reverse and forward call numbers.
116static const size_t kMaxNumFramesToBuffer = 100;
Alessio Bazzica3438a932020-10-14 12:47:50 +0200117
Sam Zackrisson03cb7e52021-12-06 15:40:04 +0100118void PackRenderAudioBufferForEchoDetector(const AudioBuffer& audio,
119 std::vector<float>& packed_buffer) {
120 packed_buffer.clear();
121 packed_buffer.insert(packed_buffer.end(), audio.channels_const()[0],
122 audio.channels_const()[0] + audio.num_frames());
123}
124
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100125// Options for gracefully handling processing errors.
126enum class FormatErrorOutputOption {
127 kOutputExactCopyOfInput,
128 kOutputBroadcastCopyOfFirstInputChannel,
129 kOutputSilence,
130 kDoNothing
131};
132
133enum class AudioFormatValidity {
134 // Format is supported by APM.
135 kValidAndSupported,
136 // Format has a reasonable interpretation but is not supported.
137 kValidButUnsupportedSampleRate,
138 // The remaining enums values signal that the audio does not have a reasonable
139 // interpretation and cannot be used.
140 kInvalidSampleRate,
141 kInvalidChannelCount
142};
143
144AudioFormatValidity ValidateAudioFormat(const StreamConfig& config) {
145 if (config.sample_rate_hz() < 0)
146 return AudioFormatValidity::kInvalidSampleRate;
147 if (config.num_channels() == 0)
148 return AudioFormatValidity::kInvalidChannelCount;
149
150 // Format has a reasonable interpretation, but may still be unsupported.
151 if (config.sample_rate_hz() < 8000 ||
152 config.sample_rate_hz() > AudioBuffer::kMaxSampleRate)
153 return AudioFormatValidity::kValidButUnsupportedSampleRate;
154
155 // Format is fully supported.
156 return AudioFormatValidity::kValidAndSupported;
157}
158
159int AudioFormatValidityToErrorCode(AudioFormatValidity validity) {
160 switch (validity) {
161 case AudioFormatValidity::kValidAndSupported:
162 return AudioProcessing::kNoError;
163 case AudioFormatValidity::kValidButUnsupportedSampleRate: // fall-through
164 case AudioFormatValidity::kInvalidSampleRate:
165 return AudioProcessing::kBadSampleRateError;
166 case AudioFormatValidity::kInvalidChannelCount:
167 return AudioProcessing::kBadNumberChannelsError;
168 }
169 RTC_DCHECK(false);
170}
171
172// Returns an AudioProcessing::Error together with the best possible option for
173// output audio content.
174std::pair<int, FormatErrorOutputOption> ChooseErrorOutputOption(
175 const StreamConfig& input_config,
176 const StreamConfig& output_config) {
177 AudioFormatValidity input_validity = ValidateAudioFormat(input_config);
178 AudioFormatValidity output_validity = ValidateAudioFormat(output_config);
179
Sam Zackrisson06cba442022-11-21 16:32:42 +0100180 if (input_validity == AudioFormatValidity::kValidAndSupported &&
181 output_validity == AudioFormatValidity::kValidAndSupported &&
182 (output_config.num_channels() == 1 ||
183 output_config.num_channels() == input_config.num_channels())) {
184 return {AudioProcessing::kNoError, FormatErrorOutputOption::kDoNothing};
185 }
186
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100187 int error_code = AudioFormatValidityToErrorCode(input_validity);
188 if (error_code == AudioProcessing::kNoError) {
189 error_code = AudioFormatValidityToErrorCode(output_validity);
190 }
Sam Zackrisson06cba442022-11-21 16:32:42 +0100191 if (error_code == AudioProcessing::kNoError) {
192 // The individual formats are valid but there is some error - must be
193 // channel mismatch.
194 error_code = AudioProcessing::kBadNumberChannelsError;
195 }
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100196
197 FormatErrorOutputOption output_option;
198 if (output_validity != AudioFormatValidity::kValidAndSupported &&
199 output_validity != AudioFormatValidity::kValidButUnsupportedSampleRate) {
200 // The output format is uninterpretable: cannot do anything.
201 output_option = FormatErrorOutputOption::kDoNothing;
202 } else if (input_validity != AudioFormatValidity::kValidAndSupported &&
203 input_validity !=
204 AudioFormatValidity::kValidButUnsupportedSampleRate) {
205 // The input format is uninterpretable: cannot use it, must output silence.
206 output_option = FormatErrorOutputOption::kOutputSilence;
207 } else if (input_config.sample_rate_hz() != output_config.sample_rate_hz()) {
208 // Sample rates do not match: Cannot copy input into output, output silence.
209 // Note: If the sample rates are in a supported range, we could resample.
210 // However, that would significantly increase complexity of this error
211 // handling code.
212 output_option = FormatErrorOutputOption::kOutputSilence;
213 } else if (input_config.num_channels() != output_config.num_channels()) {
214 // Channel counts do not match: We cannot easily map input channels to
215 // output channels.
216 output_option =
217 FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel;
218 } else {
219 // The formats match exactly.
220 RTC_DCHECK(input_config == output_config);
221 output_option = FormatErrorOutputOption::kOutputExactCopyOfInput;
222 }
223 return std::make_pair(error_code, output_option);
224}
225
226// Checks if the audio format is supported. If not, the output is populated in a
227// best-effort manner and an APM error code is returned.
228int HandleUnsupportedAudioFormats(const int16_t* const src,
229 const StreamConfig& input_config,
230 const StreamConfig& output_config,
231 int16_t* const dest) {
232 RTC_DCHECK(src);
233 RTC_DCHECK(dest);
234
235 auto [error_code, output_option] =
236 ChooseErrorOutputOption(input_config, output_config);
237 if (error_code == AudioProcessing::kNoError)
238 return AudioProcessing::kNoError;
239
240 const size_t num_output_channels = output_config.num_channels();
241 switch (output_option) {
242 case FormatErrorOutputOption::kOutputSilence:
243 memset(dest, 0, output_config.num_samples() * sizeof(int16_t));
244 break;
245 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
246 for (size_t i = 0; i < output_config.num_frames(); ++i) {
247 int16_t sample = src[input_config.num_channels() * i];
248 for (size_t ch = 0; ch < num_output_channels; ++ch) {
249 dest[ch + num_output_channels * i] = sample;
250 }
251 }
252 break;
253 case FormatErrorOutputOption::kOutputExactCopyOfInput:
254 memcpy(dest, src, output_config.num_samples() * sizeof(int16_t));
255 break;
256 case FormatErrorOutputOption::kDoNothing:
257 break;
258 }
259 return error_code;
260}
261
262// Checks if the audio format is supported. If not, the output is populated in a
263// best-effort manner and an APM error code is returned.
264int HandleUnsupportedAudioFormats(const float* const* src,
265 const StreamConfig& input_config,
266 const StreamConfig& output_config,
267 float* const* dest) {
268 RTC_DCHECK(src);
269 RTC_DCHECK(dest);
270 for (size_t i = 0; i < input_config.num_channels(); ++i) {
271 RTC_DCHECK(src[i]);
272 }
273 for (size_t i = 0; i < output_config.num_channels(); ++i) {
274 RTC_DCHECK(dest[i]);
275 }
276
277 auto [error_code, output_option] =
278 ChooseErrorOutputOption(input_config, output_config);
279 if (error_code == AudioProcessing::kNoError)
280 return AudioProcessing::kNoError;
281
282 const size_t num_output_channels = output_config.num_channels();
283 switch (output_option) {
284 case FormatErrorOutputOption::kOutputSilence:
285 for (size_t ch = 0; ch < num_output_channels; ++ch) {
286 memset(dest[ch], 0, output_config.num_frames() * sizeof(float));
287 }
288 break;
289 case FormatErrorOutputOption::kOutputBroadcastCopyOfFirstInputChannel:
290 for (size_t ch = 0; ch < num_output_channels; ++ch) {
291 memcpy(dest[ch], src[0], output_config.num_frames() * sizeof(float));
292 }
293 break;
294 case FormatErrorOutputOption::kOutputExactCopyOfInput:
295 for (size_t ch = 0; ch < num_output_channels; ++ch) {
296 memcpy(dest[ch], src[ch], output_config.num_frames() * sizeof(float));
297 }
298 break;
299 case FormatErrorOutputOption::kDoNothing:
300 break;
301 }
302 return error_code;
303}
304
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100305using DownmixMethod = AudioProcessing::Config::Pipeline::DownmixMethod;
306
307void SetDownmixMethod(AudioBuffer& buffer, DownmixMethod method) {
308 switch (method) {
309 case DownmixMethod::kAverageChannels:
310 buffer.set_downmixing_by_averaging();
311 break;
312 case DownmixMethod::kUseFirstChannel:
313 buffer.set_downmixing_to_specific_channel(/*channel=*/0);
314 break;
315 }
316}
317
318constexpr int kUnspecifiedDataDumpInputVolume = -100;
319
320} // namespace
321
322// Throughout webrtc, it's assumed that success is represented by zero.
323static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
324
325absl::optional<AudioProcessingImpl::GainController2ExperimentParams>
326AudioProcessingImpl::GetGainController2ExperimentParams() {
Hanna Silenca653552022-12-08 17:40:01 +0100327 constexpr char kFieldTrialName[] = "WebRTC-Audio-GainController2";
Hanna Silena6574902022-11-30 16:59:05 +0100328
Hanna Silenca653552022-12-08 17:40:01 +0100329 if (!field_trial::IsEnabled(kFieldTrialName)) {
Hanna Silena6574902022-11-30 16:59:05 +0100330 return absl::nullopt;
331 }
332
Hanna Silena6574902022-11-30 16:59:05 +0100333 FieldTrialFlag enabled("Enabled", false);
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100334
335 // Whether the gain control should switch to AGC2. Enabled by default.
336 FieldTrialParameter<bool> switch_to_agc2("switch_to_agc2", true);
337
338 // AGC2 input volume controller configuration.
339 constexpr InputVolumeController::Config kDefaultInputVolumeControllerConfig;
340 FieldTrialConstrained<int> min_input_volume(
341 "min_input_volume", kDefaultInputVolumeControllerConfig.min_input_volume,
342 0, 255);
Hanna Silena6574902022-11-30 16:59:05 +0100343 FieldTrialConstrained<int> clipped_level_min(
Hanna Silenca653552022-12-08 17:40:01 +0100344 "clipped_level_min",
345 kDefaultInputVolumeControllerConfig.clipped_level_min, 0, 255);
Hanna Silena6574902022-11-30 16:59:05 +0100346 FieldTrialConstrained<int> clipped_level_step(
Hanna Silenca653552022-12-08 17:40:01 +0100347 "clipped_level_step",
348 kDefaultInputVolumeControllerConfig.clipped_level_step, 0, 255);
Hanna Silena6574902022-11-30 16:59:05 +0100349 FieldTrialConstrained<double> clipped_ratio_threshold(
Hanna Silenca653552022-12-08 17:40:01 +0100350 "clipped_ratio_threshold",
351 kDefaultInputVolumeControllerConfig.clipped_ratio_threshold, 0, 1);
Hanna Silena6574902022-11-30 16:59:05 +0100352 FieldTrialConstrained<int> clipped_wait_frames(
Hanna Silenca653552022-12-08 17:40:01 +0100353 "clipped_wait_frames",
354 kDefaultInputVolumeControllerConfig.clipped_wait_frames, 0,
Hanna Silena6574902022-11-30 16:59:05 +0100355 absl::nullopt);
356 FieldTrialParameter<bool> enable_clipping_predictor(
Hanna Silenca653552022-12-08 17:40:01 +0100357 "enable_clipping_predictor",
358 kDefaultInputVolumeControllerConfig.enable_clipping_predictor);
Hanna Silena6574902022-11-30 16:59:05 +0100359 FieldTrialConstrained<int> target_range_max_dbfs(
Hanna Silenca653552022-12-08 17:40:01 +0100360 "target_range_max_dbfs",
361 kDefaultInputVolumeControllerConfig.target_range_max_dbfs, -90, 30);
Hanna Silena6574902022-11-30 16:59:05 +0100362 FieldTrialConstrained<int> target_range_min_dbfs(
Hanna Silenca653552022-12-08 17:40:01 +0100363 "target_range_min_dbfs",
364 kDefaultInputVolumeControllerConfig.target_range_min_dbfs, -90, 30);
Hanna Silena6574902022-11-30 16:59:05 +0100365 FieldTrialConstrained<int> update_input_volume_wait_frames(
366 "update_input_volume_wait_frames",
Hanna Silenca653552022-12-08 17:40:01 +0100367 kDefaultInputVolumeControllerConfig.update_input_volume_wait_frames, 0,
368 absl::nullopt);
Hanna Silena6574902022-11-30 16:59:05 +0100369 FieldTrialConstrained<double> speech_probability_threshold(
370 "speech_probability_threshold",
Hanna Silenca653552022-12-08 17:40:01 +0100371 kDefaultInputVolumeControllerConfig.speech_probability_threshold, 0, 1);
Hanna Silena6574902022-11-30 16:59:05 +0100372 FieldTrialConstrained<double> speech_ratio_threshold(
Hanna Silenca653552022-12-08 17:40:01 +0100373 "speech_ratio_threshold",
374 kDefaultInputVolumeControllerConfig.speech_ratio_threshold, 0, 1);
Hanna Silena6574902022-11-30 16:59:05 +0100375
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100376 // AGC2 adaptive digital controller configuration.
Hanna Silenca653552022-12-08 17:40:01 +0100377 constexpr AudioProcessing::Config::GainController2::AdaptiveDigital
378 kDefaultAdaptiveDigitalConfig;
Hanna Silenca653552022-12-08 17:40:01 +0100379 FieldTrialConstrained<double> headroom_db(
380 "headroom_db", kDefaultAdaptiveDigitalConfig.headroom_db, 0,
381 absl::nullopt);
382 FieldTrialConstrained<double> max_gain_db(
383 "max_gain_db", kDefaultAdaptiveDigitalConfig.max_gain_db, 0,
384 absl::nullopt);
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100385 FieldTrialConstrained<double> initial_gain_db(
386 "initial_gain_db", kDefaultAdaptiveDigitalConfig.initial_gain_db, 0,
387 absl::nullopt);
Hanna Silenca653552022-12-08 17:40:01 +0100388 FieldTrialConstrained<double> max_gain_change_db_per_second(
389 "max_gain_change_db_per_second",
390 kDefaultAdaptiveDigitalConfig.max_gain_change_db_per_second, 0,
391 absl::nullopt);
392 FieldTrialConstrained<double> max_output_noise_level_dbfs(
393 "max_output_noise_level_dbfs",
394 kDefaultAdaptiveDigitalConfig.max_output_noise_level_dbfs, absl::nullopt,
395 0);
396
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100397 // Transient suppressor.
398 FieldTrialParameter<bool> disallow_transient_suppressor_usage(
399 "disallow_transient_suppressor_usage", false);
400
Hanna Silenca653552022-12-08 17:40:01 +0100401 // Field-trial based override for the input volume controller and adaptive
402 // digital configs.
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100403 ParseFieldTrial(
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100404 {&enabled, &switch_to_agc2, &min_input_volume, &clipped_level_min,
405 &clipped_level_step, &clipped_ratio_threshold, &clipped_wait_frames,
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100406 &enable_clipping_predictor, &target_range_max_dbfs,
407 &target_range_min_dbfs, &update_input_volume_wait_frames,
408 &speech_probability_threshold, &speech_ratio_threshold, &headroom_db,
409 &max_gain_db, &initial_gain_db, &max_gain_change_db_per_second,
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100410 &max_output_noise_level_dbfs, &disallow_transient_suppressor_usage},
411 field_trial::FindFullName(kFieldTrialName));
Hanna Silena6574902022-11-30 16:59:05 +0100412 // Checked already by `IsEnabled()` before parsing, therefore always true.
413 RTC_DCHECK(enabled);
414
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100415 const bool do_not_change_agc_config = !switch_to_agc2.Get();
416 if (do_not_change_agc_config && !disallow_transient_suppressor_usage.Get()) {
417 // Return an unspecifed value since, in this case, both the AGC2 and TS
418 // configurations won't be adjusted.
419 return absl::nullopt;
420 }
421 using Params = AudioProcessingImpl::GainController2ExperimentParams;
422 if (do_not_change_agc_config) {
423 // Return a value that leaves the AGC2 config unchanged and that always
424 // disables TS.
425 return Params{.agc2_config = absl::nullopt,
426 .disallow_transient_suppressor_usage = true};
427 }
428 // Return a value that switches all the gain control to AGC2.
429 return Params{
430 .agc2_config =
431 Params::Agc2Config{
432 .input_volume_controller =
433 {
434 .min_input_volume = min_input_volume.Get(),
435 .clipped_level_min = clipped_level_min.Get(),
436 .clipped_level_step = clipped_level_step.Get(),
437 .clipped_ratio_threshold =
438 static_cast<float>(clipped_ratio_threshold.Get()),
439 .clipped_wait_frames = clipped_wait_frames.Get(),
440 .enable_clipping_predictor =
441 enable_clipping_predictor.Get(),
442 .target_range_max_dbfs = target_range_max_dbfs.Get(),
443 .target_range_min_dbfs = target_range_min_dbfs.Get(),
444 .update_input_volume_wait_frames =
445 update_input_volume_wait_frames.Get(),
446 .speech_probability_threshold = static_cast<float>(
447 speech_probability_threshold.Get()),
448 .speech_ratio_threshold =
449 static_cast<float>(speech_ratio_threshold.Get()),
450 },
451 .adaptive_digital_controller =
452 {
453 .headroom_db = static_cast<float>(headroom_db.Get()),
454 .max_gain_db = static_cast<float>(max_gain_db.Get()),
455 .initial_gain_db =
456 static_cast<float>(initial_gain_db.Get()),
457 .max_gain_change_db_per_second = static_cast<float>(
458 max_gain_change_db_per_second.Get()),
459 .max_output_noise_level_dbfs =
460 static_cast<float>(max_output_noise_level_dbfs.Get()),
461 }},
462 .disallow_transient_suppressor_usage =
463 disallow_transient_suppressor_usage.Get()};
Hanna Silena6574902022-11-30 16:59:05 +0100464}
465
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100466AudioProcessing::Config AudioProcessingImpl::AdjustConfig(
Hanna Silena6574902022-11-30 16:59:05 +0100467 const AudioProcessing::Config& config,
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100468 const absl::optional<AudioProcessingImpl::GainController2ExperimentParams>&
469 experiment_params) {
470 if (!experiment_params.has_value() ||
471 (!experiment_params->agc2_config.has_value() &&
472 !experiment_params->disallow_transient_suppressor_usage)) {
473 // When the experiment parameters are unspecified or when the AGC and TS
474 // configuration are not overridden, return the unmodified configuration.
475 return config;
476 }
477
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100478 AudioProcessing::Config adjusted_config = config;
479
480 // Override the transient suppressor configuration.
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100481 if (experiment_params->disallow_transient_suppressor_usage) {
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100482 adjusted_config.transient_suppression.enabled = false;
483 }
484
485 // Override the auto gain control configuration if the AGC1 analog gain
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100486 // controller is active and `experiment_params->agc2_config` is specified.
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100487 const bool agc1_analog_enabled =
Hanna Silena6574902022-11-30 16:59:05 +0100488 config.gain_controller1.enabled &&
489 (config.gain_controller1.mode ==
490 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
491 config.gain_controller1.analog_gain_controller.enabled);
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100492 if (agc1_analog_enabled && experiment_params->agc2_config.has_value()) {
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100493 // Check that the unadjusted AGC config meets the preconditions.
494 const bool hybrid_agc_config_detected =
495 config.gain_controller1.enabled &&
496 config.gain_controller1.analog_gain_controller.enabled &&
497 !config.gain_controller1.analog_gain_controller
498 .enable_digital_adaptive &&
499 config.gain_controller2.enabled &&
500 config.gain_controller2.adaptive_digital.enabled;
501 const bool full_agc1_config_detected =
502 config.gain_controller1.enabled &&
503 config.gain_controller1.analog_gain_controller.enabled &&
504 config.gain_controller1.analog_gain_controller
505 .enable_digital_adaptive &&
506 !config.gain_controller2.enabled;
507 const bool one_and_only_one_input_volume_controller =
508 hybrid_agc_config_detected != full_agc1_config_detected;
Alessio Bazzica40b5bd72023-01-16 20:19:48 +0100509 const bool agc2_input_volume_controller_enabled =
510 config.gain_controller2.enabled &&
511 config.gain_controller2.input_volume_controller.enabled;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100512 if (!one_and_only_one_input_volume_controller ||
Alessio Bazzica40b5bd72023-01-16 20:19:48 +0100513 agc2_input_volume_controller_enabled) {
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100514 RTC_LOG(LS_ERROR) << "Cannot adjust AGC config (precondition failed)";
515 if (!one_and_only_one_input_volume_controller)
516 RTC_LOG(LS_ERROR)
517 << "One and only one input volume controller must be enabled.";
Alessio Bazzica40b5bd72023-01-16 20:19:48 +0100518 if (agc2_input_volume_controller_enabled)
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100519 RTC_LOG(LS_ERROR)
520 << "The AGC2 input volume controller must be disabled.";
521 } else {
522 adjusted_config.gain_controller1.enabled = false;
523 adjusted_config.gain_controller1.analog_gain_controller.enabled = false;
Hanna Silenca653552022-12-08 17:40:01 +0100524
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100525 adjusted_config.gain_controller2.enabled = true;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100526 adjusted_config.gain_controller2.input_volume_controller.enabled = true;
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100527 adjusted_config.gain_controller2.adaptive_digital =
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100528 experiment_params->agc2_config->adaptive_digital_controller;
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100529 adjusted_config.gain_controller2.adaptive_digital.enabled = true;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100530 }
Hanna Silena6574902022-11-30 16:59:05 +0100531 }
532
Hanna Silena6574902022-11-30 16:59:05 +0100533 return adjusted_config;
534}
535
Alessio Bazzica40b5bd72023-01-16 20:19:48 +0100536bool AudioProcessingImpl::UseApmVadSubModule(
537 const AudioProcessing::Config& config,
538 const absl::optional<GainController2ExperimentParams>& experiment_params) {
539 // The VAD as an APM sub-module is needed only in one case, that is when TS
540 // and AGC2 are both enabled and when the AGC2 experiment is running and its
541 // parameters require to fully switch the gain control to AGC2.
542 return config.transient_suppression.enabled &&
543 config.gain_controller2.enabled &&
544 (config.gain_controller2.input_volume_controller.enabled ||
545 config.gain_controller2.adaptive_digital.enabled) &&
546 experiment_params.has_value() &&
547 experiment_params->agc2_config.has_value();
Alessio Bazzica504bd592022-12-01 13:26:26 +0100548}
549
saza1d600522019-10-18 13:29:43 +0200550AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100551 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200552 bool render_pre_processor_enabled,
553 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100554 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200555 render_pre_processor_enabled_(render_pre_processor_enabled),
556 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700557
saza1d600522019-10-18 13:29:43 +0200558bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200559 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700560 bool mobile_echo_controller_enabled,
561 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700562 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700563 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200564 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000565 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200566 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700567 bool transient_suppressor_enabled) {
568 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200569 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700570 changed |=
571 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
572 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
573 changed |=
peah2ace3f92016-09-10 04:42:27 -0700574 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200575 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200576 changed |=
577 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000578 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200579 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700580 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
581 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200582 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700583 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
584 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700585 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700586 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200587 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000588 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200589 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700590 transient_suppressor_enabled_ = transient_suppressor_enabled;
591 }
592
593 changed |= first_update_;
594 first_update_ = false;
595 return changed;
596}
597
saza1d600522019-10-18 13:29:43 +0200598bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700599 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000600 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700601}
602
saza1d600522019-10-18 13:29:43 +0200603bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
604 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200605 // If echo controller is present, assume it performs active processing.
606 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
607}
608
saza1d600522019-10-18 13:29:43 +0200609bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200610 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100611 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
612 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200613 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700614}
615
saza1d600522019-10-18 13:29:43 +0200616bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700617 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200618 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000619 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700620}
621
saza1d600522019-10-18 13:29:43 +0200622bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200623 return capture_analyzer_enabled_;
624}
625
saza1d600522019-10-18 13:29:43 +0200626bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700627 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100628 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
629 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700630}
631
saza1d600522019-10-18 13:29:43 +0200632bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100633 const {
634 return render_pre_processor_enabled_;
635}
636
saza1d600522019-10-18 13:29:43 +0200637bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700638 const {
peah2ace3f92016-09-10 04:42:27 -0700639 return false;
peah2ace3f92016-09-10 04:42:27 -0700640}
641
saza1d600522019-10-18 13:29:43 +0200642bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100643 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
644 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200645}
646
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200647AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200648 : AudioProcessingImpl(/*config=*/{},
649 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200650 /*render_pre_processor=*/nullptr,
651 /*echo_control_factory=*/nullptr,
652 /*echo_detector=*/nullptr,
653 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000654
Niels Möller7a669002022-06-27 09:47:02 +0200655std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100656
Sam Zackrisson0beac582017-09-25 12:04:02 +0200657AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200658 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100659 std::unique_ptr<CustomProcessing> capture_post_processor,
660 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200661 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200662 rtc::scoped_refptr<EchoDetector> echo_detector,
663 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200664 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100665 use_setup_specific_default_aec3_config_(
666 UseSetupSpecificDefaultAec3Congfig()),
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100667 gain_controller2_experiment_params_(GetGainController2ExperimentParams()),
Alessio Bazzica40b5bd72023-01-16 20:19:48 +0100668 transient_suppressor_vad_mode_(TransientSuppressor::VadMode::kDefault),
Per Åhgren652ada52021-03-03 10:52:44 +0000669 capture_runtime_settings_(RuntimeSettingQueueSize()),
670 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200671 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
672 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200673 echo_control_factory_(std::move(echo_control_factory)),
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100674 config_(AdjustConfig(config, gain_controller2_experiment_params_)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200675 submodule_states_(!!capture_post_processor,
676 !!render_pre_processor,
677 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200678 submodules_(std::move(capture_post_processor),
679 std::move(render_pre_processor),
680 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100681 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100682 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200683 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
684 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100685 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000686 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200687 MinimizeProcessingForUnusedOutput(),
688 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000689 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200690 capture_nonlocked_(),
691 applied_input_volume_stats_reporter_(
692 InputVolumeStatsReporter::InputVolumeType::kApplied),
693 recommended_input_volume_stats_reporter_(
694 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200695 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100696 "\nEcho control factory: "
697 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200698 << "\nEcho detector: " << !!submodules_.echo_detector
699 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
700 << "\nCapture post processor: "
701 << !!submodules_.capture_post_processor
702 << "\nRender pre processor: "
703 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100704 if (!DenormalDisabler::IsSupported()) {
705 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
706 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200707
Hanna Silena6574902022-11-30 16:59:05 +0100708 RTC_LOG(LS_INFO) << "AudioProcessing: " << config_.ToString();
709
Sam Zackrisson421c8592019-02-11 13:39:46 +0100710 // Mark Echo Controller enabled if a factory is injected.
711 capture_nonlocked_.echo_controller_enabled =
712 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000713
Per Åhgren0ade9832020-09-01 23:57:20 +0200714 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000715}
716
Per Åhgren0e3198e2019-11-18 08:52:22 +0100717AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000718
niklase@google.com470e71d2011-07-07 08:21:25 +0000719int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800720 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200721 MutexLock lock_render(&mutex_render_);
722 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200723 InitializeLocked();
724 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
Michael Graczyk86c6d332015-07-23 11:41:39 -0700727int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800728 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200729 MutexLock lock_render(&mutex_render_);
730 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100731 InitializeLocked(processing_config);
732 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000733}
734
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100735void AudioProcessingImpl::MaybeInitializeRender(
736 const StreamConfig& input_config,
737 const StreamConfig& output_config) {
738 ProcessingConfig processing_config = formats_.api_format;
739 processing_config.reverse_input_stream() = input_config;
740 processing_config.reverse_output_stream() = output_config;
741
Oskar Sundbom4b276482019-05-23 14:28:00 +0200742 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100743 return;
peah192164e2015-11-17 02:16:45 -0800744 }
peahdf3efa82015-11-28 12:35:15 -0800745
Markus Handell0df0fae2020-07-07 15:53:34 +0200746 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100747 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800748}
749
Per Åhgren0ade9832020-09-01 23:57:20 +0200750void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200751 UpdateActiveSubmoduleStates();
752
Per Åhgrend47941e2019-08-22 11:51:13 +0200753 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800754 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200755 ? formats_.render_processing_format.sample_rate_hz()
756 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800757 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
758 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200759 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800760 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200761 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700762 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200763 render_audiobuffer_sample_rate_hz,
764 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700765 if (formats_.api_format.reverse_input_stream() !=
766 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800767 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800768 formats_.api_format.reverse_input_stream().num_channels(),
769 formats_.api_format.reverse_input_stream().num_frames(),
770 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800771 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700772 } else {
peahdf3efa82015-11-28 12:35:15 -0800773 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700774 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700775 } else {
peahdf3efa82015-11-28 12:35:15 -0800776 render_.render_audio.reset(nullptr);
777 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700778 }
peahce4d9152017-05-19 01:28:05 -0700779
Per Åhgrend47941e2019-08-22 11:51:13 +0200780 capture_.capture_audio.reset(new AudioBuffer(
781 formats_.api_format.input_stream().sample_rate_hz(),
782 formats_.api_format.input_stream().num_channels(),
783 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
784 formats_.api_format.output_stream().num_channels(),
785 formats_.api_format.output_stream().sample_rate_hz(),
786 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100787 SetDownmixMethod(*capture_.capture_audio,
788 config_.pipeline.capture_downmix_method);
niklase@google.com470e71d2011-07-07 08:21:25 +0000789
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200790 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
791 formats_.api_format.output_stream().sample_rate_hz() &&
792 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
793 capture_.capture_fullband_audio.reset(
794 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
795 formats_.api_format.input_stream().num_channels(),
796 formats_.api_format.output_stream().sample_rate_hz(),
797 formats_.api_format.output_stream().num_channels(),
798 formats_.api_format.output_stream().sample_rate_hz(),
799 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100800 SetDownmixMethod(*capture_.capture_fullband_audio,
801 config_.pipeline.capture_downmix_method);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200802 } else {
803 capture_.capture_fullband_audio.reset();
804 }
805
peah764e3642016-10-22 05:04:30 -0700806 AllocateRenderQueue();
807
Per Åhgren0695df12020-01-13 14:43:13 +0100808 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100809 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100810 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700811 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200812 InitializeEchoController();
Alessio Bazzica40b5bd72023-01-16 20:19:48 +0100813 InitializeGainController2();
814 InitializeVoiceActivityDetector();
saza0bad15f2019-10-16 11:46:11 +0200815 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200816 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200817 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100818 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000819 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800820
aleloi868f32f2017-05-23 07:20:05 -0700821 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200822 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700823 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000824}
825
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100826void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200827 UpdateActiveSubmoduleStates();
828
peahdf3efa82015-11-28 12:35:15 -0800829 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000830
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200831 // Choose maximum rate to use for the split filtering.
832 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
833 config_.pipeline.maximum_internal_processing_rate == 32000);
834 int max_splitting_rate = 48000;
835 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
836 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
837 }
838
Per Åhgrenc8626b62019-08-23 15:49:51 +0200839 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700840 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700841 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200842 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700843 submodule_states_.CaptureMultiBandSubModulesActive() ||
844 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200845 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000846
peahde65ddc2016-09-16 15:02:15 -0700847 capture_nonlocked_.capture_processing_format =
848 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700849
peah2ce640f2017-04-07 03:57:48 -0700850 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200851 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200852 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700853 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
854 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200855 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700856 submodule_states_.CaptureMultiBandSubModulesActive() ||
857 submodule_states_.RenderMultiBandSubModulesActive());
858 } else {
859 render_processing_rate = capture_processing_rate;
860 }
861
peahde65ddc2016-09-16 15:02:15 -0700862 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700863 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700864 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
865 kSampleRate8kHz) {
866 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000867 } else {
peahde65ddc2016-09-16 15:02:15 -0700868 render_processing_rate =
869 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000870 }
871
Per Åhgrenc8626b62019-08-23 15:49:51 +0200872 RTC_DCHECK_NE(8000, render_processing_rate);
873
peahce4d9152017-05-19 01:28:05 -0700874 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200875 // By default, downmix the render stream to mono for analysis. This has been
876 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100877 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
878 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200879 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100880 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200881 ? formats_.api_format.reverse_input_stream().num_channels()
882 : 1;
883 formats_.render_processing_format =
884 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700885 } else {
886 formats_.render_processing_format = StreamConfig(
887 formats_.api_format.reverse_input_stream().sample_rate_hz(),
888 formats_.api_format.reverse_input_stream().num_channels());
889 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000890
peahde65ddc2016-09-16 15:02:15 -0700891 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
892 kSampleRate32kHz ||
893 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
894 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800895 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000896 } else {
peahdf3efa82015-11-28 12:35:15 -0800897 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700898 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000899 }
900
Per Åhgren0ade9832020-09-01 23:57:20 +0200901 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000902}
903
peah88ac8532016-09-12 16:47:25 -0700904void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700905 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200906 MutexLock lock_render(&mutex_render_);
907 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700908
Hanna Silena6574902022-11-30 16:59:05 +0100909 const auto adjusted_config =
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100910 AdjustConfig(config, gain_controller2_experiment_params_);
Hanna Silena6574902022-11-30 16:59:05 +0100911 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: "
912 << adjusted_config.ToString();
913
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200914 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100915 config_.pipeline.multi_channel_render !=
Hanna Silena6574902022-11-30 16:59:05 +0100916 adjusted_config.pipeline.multi_channel_render ||
Per Åhgrene14cb992019-11-27 09:34:22 +0100917 config_.pipeline.multi_channel_capture !=
Hanna Silena6574902022-11-30 16:59:05 +0100918 adjusted_config.pipeline.multi_channel_capture ||
Per Åhgrenc0424252019-12-10 13:04:15 +0100919 config_.pipeline.maximum_internal_processing_rate !=
Alessio Bazzica504bd592022-12-01 13:26:26 +0100920 adjusted_config.pipeline.maximum_internal_processing_rate ||
921 config_.pipeline.capture_downmix_method !=
922 adjusted_config.pipeline.capture_downmix_method;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200923
Per Åhgren200feba2019-03-06 04:16:46 +0100924 const bool aec_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100925 config_.echo_canceller.enabled !=
926 adjusted_config.echo_canceller.enabled ||
927 config_.echo_canceller.mobile_mode !=
928 adjusted_config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100929
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100930 const bool agc1_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100931 config_.gain_controller1 != adjusted_config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100932
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100933 const bool agc2_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100934 config_.gain_controller2 != adjusted_config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100935
saza0bad15f2019-10-16 11:46:11 +0200936 const bool ns_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100937 config_.noise_suppression.enabled !=
938 adjusted_config.noise_suppression.enabled ||
939 config_.noise_suppression.level !=
940 adjusted_config.noise_suppression.level;
saza0bad15f2019-10-16 11:46:11 +0200941
Per Åhgrenc0734712020-01-02 15:15:36 +0100942 const bool ts_config_changed = config_.transient_suppression.enabled !=
Hanna Silena6574902022-11-30 16:59:05 +0100943 adjusted_config.transient_suppression.enabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100944
Per Åhgren0f14db22020-01-03 14:27:14 +0100945 const bool pre_amplifier_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100946 config_.pre_amplifier.enabled != adjusted_config.pre_amplifier.enabled ||
Per Åhgren0f14db22020-01-03 14:27:14 +0100947 config_.pre_amplifier.fixed_gain_factor !=
Hanna Silena6574902022-11-30 16:59:05 +0100948 adjusted_config.pre_amplifier.fixed_gain_factor;
Per Åhgren0f14db22020-01-03 14:27:14 +0100949
Per Åhgrendb5d7282021-03-15 16:31:04 +0000950 const bool gain_adjustment_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100951 config_.capture_level_adjustment !=
952 adjusted_config.capture_level_adjustment;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000953
Hanna Silena6574902022-11-30 16:59:05 +0100954 config_ = adjusted_config;
Yves Gerey499bc6c2018-10-10 18:29:07 +0200955
Per Åhgren200feba2019-03-06 04:16:46 +0100956 if (aec_config_changed) {
957 InitializeEchoController();
958 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200959
saza0bad15f2019-10-16 11:46:11 +0200960 if (ns_config_changed) {
961 InitializeNoiseSuppressor();
962 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100963
Per Åhgrenc0734712020-01-02 15:15:36 +0100964 if (ts_config_changed) {
965 InitializeTransientSuppressor();
966 }
967
Per Åhgren0f14db22020-01-03 14:27:14 +0100968 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800969
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100970 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100971 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100972 }
973
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100974 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700975 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200976 RTC_LOG(LS_ERROR)
977 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700978 config_.gain_controller2 = AudioProcessing::Config::GainController2();
979 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100980
Alessio Bazzica40b5bd72023-01-16 20:19:48 +0100981 if (agc2_config_changed || ts_config_changed) {
982 // AGC2 also depends on TS because of the possible dependency on the APM VAD
983 // sub-module.
984 InitializeGainController2();
985 InitializeVoiceActivityDetector();
986 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100987
Per Åhgrendb5d7282021-03-15 16:31:04 +0000988 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
989 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100990 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100991
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200992 // Reinitialization must happen after all submodule configuration to avoid
993 // additional reinitializations on the next capture / render processing call.
994 if (pipeline_config_changed) {
995 InitializeLocked(formats_.api_format);
996 }
peah88ac8532016-09-12 16:47:25 -0700997}
998
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200999void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
1000 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001001 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +02001002 submodule_creation_overrides_ = overrides;
1003}
1004
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001005int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001006 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001007 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +00001008}
1009
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001010int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
1011 return capture_.capture_fullband_audio
1012 ? capture_.capture_fullband_audio->num_frames() * 100
1013 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
1014}
1015
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001016int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001017 // Used as callback from submodules, hence locking is not allowed.
1018 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +00001019}
1020
Peter Kasting69558702016-01-12 16:26:35 -08001021size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001022 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001023 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001024}
1025
Peter Kasting69558702016-01-12 16:26:35 -08001026size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001027 // Used as callback from submodules, hence locking is not allowed.
1028 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001029}
1030
Peter Kasting69558702016-01-12 16:26:35 -08001031size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -08001032 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +01001033 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1034 constants_.multi_channel_capture_support;
1035 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001036 return 1;
1037 }
1038 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -08001039}
1040
Peter Kasting69558702016-01-12 16:26:35 -08001041size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001042 // Used as callback from submodules, hence locking is not allowed.
1043 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001044}
1045
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001046void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001047 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +01001048 HandleCaptureOutputUsedSetting(!muted);
1049}
1050
1051void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
1052 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001053 capture_.capture_output_used =
1054 capture_output_used || !constants_.minimize_processing_for_unused_output;
1055
saza1d600522019-10-18 13:29:43 +02001056 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001057 submodules_.agc_manager->HandleCaptureOutputUsedChange(
1058 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001059 }
Per Åhgren652ada52021-03-03 10:52:44 +00001060 if (submodules_.echo_controller) {
1061 submodules_.echo_controller->SetCaptureOutputUsage(
1062 capture_.capture_output_used);
1063 }
Per Åhgren15179a92021-03-12 14:12:44 +00001064 if (submodules_.noise_suppressor) {
1065 submodules_.noise_suppressor->SetCaptureOutputUsage(
1066 capture_.capture_output_used);
1067 }
Hanna Silend4dbe452022-11-30 15:16:21 +01001068 if (submodules_.gain_controller2) {
1069 submodules_.gain_controller2->SetCaptureOutputUsed(
1070 capture_.capture_output_used);
1071 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001072}
1073
Alessio Bazzicac054e782018-04-16 12:10:09 +02001074void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001075 PostRuntimeSetting(setting);
1076}
1077
1078bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +02001079 switch (setting.type()) {
1080 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001081 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +01001082 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001083 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001084 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001085 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001086 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +02001087 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001088 return capture_runtime_settings_enqueuer_.Enqueue(setting);
1089 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1090 bool enqueueing_successful;
1091 enqueueing_successful =
1092 capture_runtime_settings_enqueuer_.Enqueue(setting);
1093 enqueueing_successful =
1094 render_runtime_settings_enqueuer_.Enqueue(setting) &&
1095 enqueueing_successful;
1096 return enqueueing_successful;
1097 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001098 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001099 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001100 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +02001101 }
1102 // The language allows the enum to have a non-enumerator
1103 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +01001104 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001105 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001106}
1107
1108AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
1109 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001110 : runtime_settings_(*runtime_settings) {
1111 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001112}
1113
1114AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
1115 default;
1116
Per Åhgren0a144a72021-02-09 08:47:51 +01001117bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +02001118 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +00001119 const bool successful_insert = runtime_settings_.Insert(&setting);
1120
1121 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001122 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +02001123 }
Per Åhgren652ada52021-03-03 10:52:44 +00001124 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001125}
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001126
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001127void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001128 const StreamConfig& input_config,
1129 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001130 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001131 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001132 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001133 // Acquire the capture lock in order to access api_format. The lock is
1134 // released immediately, as we may need to acquire the render lock as part
1135 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +02001136 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001137 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001138 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +00001139 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001140
Oskar Sundbom4b276482019-05-23 14:28:00 +02001141 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001142 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -08001143 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001144
1145 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001146 reinitialization_required = true;
1147 }
1148
1149 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001150 MutexLock lock_render(&mutex_render_);
1151 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +02001152 // Reread the API format since the render format may have changed.
1153 processing_config = formats_.api_format;
1154 processing_config.input_stream() = input_config;
1155 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001156 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001157 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001158}
1159
1160int AudioProcessingImpl::ProcessStream(const float* const* src,
1161 const StreamConfig& input_config,
1162 const StreamConfig& output_config,
1163 float* const* dest) {
1164 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001165 DenormalDisabler denormal_disabler;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001166 RETURN_ON_ERR(
1167 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1168 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001169
Markus Handell0df0fae2020-07-07 15:53:34 +02001170 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001171
aleloi868f32f2017-05-23 07:20:05 -07001172 if (aec_dump_) {
1173 RecordUnprocessedCaptureStream(src);
1174 }
1175
peahdf3efa82015-11-28 12:35:15 -08001176 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001177 if (capture_.capture_fullband_audio) {
1178 capture_.capture_fullband_audio->CopyFrom(
1179 src, formats_.api_format.input_stream());
1180 }
peahde65ddc2016-09-16 15:02:15 -07001181 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001182 if (capture_.capture_fullband_audio) {
1183 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1184 dest);
1185 } else {
1186 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1187 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001188
aleloi868f32f2017-05-23 07:20:05 -07001189 if (aec_dump_) {
1190 RecordProcessedCaptureStream(dest);
1191 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001192 return kNoError;
1193}
1194
Alex Loiko73ec0192018-05-15 10:52:28 +02001195void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001196 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +00001197 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +02001198 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001199 if (aec_dump_) {
1200 aec_dump_->WriteRuntimeSetting(setting);
1201 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001202 switch (setting.type()) {
1203 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001204 if (config_.pre_amplifier.enabled ||
1205 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +02001206 float value;
1207 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001208 // If the pre-amplifier is used, apply the new gain to the
1209 // pre-amplifier regardless if the capture level adjustment is
1210 // activated. This approach allows both functionalities to coexist
1211 // until they have been properly merged.
1212 if (config_.pre_amplifier.enabled) {
1213 config_.pre_amplifier.fixed_gain_factor = value;
1214 } else {
1215 config_.capture_level_adjustment.pre_gain_factor = value;
1216 }
1217
1218 // Use both the pre-amplifier and the capture level adjustment gains
1219 // as pre-gains.
1220 float gain = 1.f;
1221 if (config_.pre_amplifier.enabled) {
1222 gain *= config_.pre_amplifier.fixed_gain_factor;
1223 }
1224 if (config_.capture_level_adjustment.enabled) {
1225 gain *= config_.capture_level_adjustment.pre_gain_factor;
1226 }
1227
1228 submodules_.capture_levels_adjuster->SetPreGain(gain);
1229 }
1230 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
1231 break;
1232 case RuntimeSetting::Type::kCapturePostGain:
1233 if (config_.capture_level_adjustment.enabled) {
1234 float value;
1235 setting.GetFloat(&value);
1236 config_.capture_level_adjustment.post_gain_factor = value;
1237 submodules_.capture_levels_adjuster->SetPostGain(
1238 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001239 }
1240 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001241 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001242 case RuntimeSetting::Type::kCaptureCompressionGain: {
Hanna Silend4dbe452022-11-30 15:16:21 +01001243 if (!submodules_.agc_manager &&
1244 !(submodules_.gain_controller2 &&
1245 config_.gain_controller2.input_volume_controller.enabled)) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001246 float value;
1247 setting.GetFloat(&value);
1248 int int_value = static_cast<int>(value + .5f);
1249 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001250 if (submodules_.gain_control) {
1251 int error =
1252 submodules_.gain_control->set_compression_gain_db(int_value);
1253 RTC_DCHECK_EQ(kNoError, error);
1254 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001255 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001256 break;
1257 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001258 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001259 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001260 float value;
1261 setting.GetFloat(&value);
1262 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001263 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001264 }
1265 break;
1266 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001267 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1268 int value;
1269 setting.GetInt(&value);
1270 capture_.playout_volume = value;
1271 break;
1272 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001273 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001274 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001275 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001276 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001277 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001278 break;
1279 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001280 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001281 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001282 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001283 bool value;
1284 setting.GetBool(&value);
1285 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001286 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001287 }
Per Åhgren652ada52021-03-03 10:52:44 +00001288 ++num_settings_processed;
1289 }
1290
1291 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1292 // Handle overrun of the runtime settings queue, which likely will has
1293 // caused settings to be discarded.
1294 HandleOverrunInCaptureRuntimeSettingsQueue();
1295 }
1296}
1297
1298void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1299 // Fall back to a safe state for the case when a setting for capture output
1300 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001301 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001302}
1303
1304void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1305 RuntimeSetting setting;
1306 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001307 if (aec_dump_) {
1308 aec_dump_->WriteRuntimeSetting(setting);
1309 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001310 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001311 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001312 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001313 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001314 if (submodules_.render_pre_processor) {
1315 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001316 }
1317 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001318 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001319 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001320 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001321 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001322 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001323 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001324 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001325 break;
1326 }
1327 }
1328}
1329
peah9e6a2902017-05-15 07:19:21 -07001330void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001331 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001332
saza1d600522019-10-18 13:29:43 +02001333 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001334 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1335 num_reverse_channels(),
1336 &aecm_render_queue_buffer_);
1337 RTC_DCHECK(aecm_render_signal_queue_);
1338 // Insert the samples into the queue.
1339 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1340 // The data queue is full and needs to be emptied.
1341 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001342
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001343 // Retry the insert (should always work).
1344 bool result =
1345 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1346 RTC_DCHECK(result);
1347 }
peah764e3642016-10-22 05:04:30 -07001348 }
peah701d6282016-10-25 05:42:20 -07001349
Per Åhgren0695df12020-01-13 14:43:13 +01001350 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001351 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001352 // Insert the samples into the queue.
1353 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1354 // The data queue is full and needs to be emptied.
1355 EmptyQueuedRenderAudio();
1356
1357 // Retry the insert (should always work).
1358 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1359 RTC_DCHECK(result);
1360 }
1361 }
peah9e6a2902017-05-15 07:19:21 -07001362}
ivoc9f4a4a02016-10-28 05:39:16 -07001363
peah9e6a2902017-05-15 07:19:21 -07001364void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001365 if (submodules_.echo_detector) {
1366 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1367 RTC_DCHECK(red_render_signal_queue_);
1368 // Insert the samples into the queue.
1369 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1370 // The data queue is full and needs to be emptied.
1371 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001372
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001373 // Retry the insert (should always work).
1374 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1375 RTC_DCHECK(result);
1376 }
ivoc9f4a4a02016-10-28 05:39:16 -07001377 }
peah764e3642016-10-22 05:04:30 -07001378}
1379
1380void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001381 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001382 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001383
ivoc9f4a4a02016-10-28 05:39:16 -07001384 const size_t new_red_render_queue_element_max_size =
1385 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1386
peaha0624602016-10-25 04:45:24 -07001387 // Reallocate the queues if the queue item sizes are too small to fit the
1388 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001389
1390 if (agc_render_queue_element_max_size_ <
1391 new_agc_render_queue_element_max_size) {
1392 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1393
1394 std::vector<int16_t> template_queue_element(
1395 agc_render_queue_element_max_size_);
1396
1397 agc_render_signal_queue_.reset(
1398 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1399 kMaxNumFramesToBuffer, template_queue_element,
1400 RenderQueueItemVerifier<int16_t>(
1401 agc_render_queue_element_max_size_)));
1402
1403 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1404 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1405 } else {
1406 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001407 }
ivoc9f4a4a02016-10-28 05:39:16 -07001408
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001409 if (submodules_.echo_detector) {
1410 if (red_render_queue_element_max_size_ <
1411 new_red_render_queue_element_max_size) {
1412 red_render_queue_element_max_size_ =
1413 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001414
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001415 std::vector<float> template_queue_element(
1416 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001417
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001418 red_render_signal_queue_.reset(
1419 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1420 kMaxNumFramesToBuffer, template_queue_element,
1421 RenderQueueItemVerifier<float>(
1422 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001423
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001424 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1425 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1426 } else {
1427 red_render_signal_queue_->Clear();
1428 }
ivoc9f4a4a02016-10-28 05:39:16 -07001429 }
peah764e3642016-10-22 05:04:30 -07001430}
1431
1432void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001433 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001434 EmptyQueuedRenderAudioLocked();
1435}
1436
1437void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001438 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001439 RTC_DCHECK(aecm_render_signal_queue_);
1440 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001441 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001442 aecm_capture_queue_buffer_);
1443 }
peah701d6282016-10-25 05:42:20 -07001444 }
1445
Per Åhgren0695df12020-01-13 14:43:13 +01001446 if (submodules_.gain_control) {
1447 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1448 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1449 }
peah764e3642016-10-22 05:04:30 -07001450 }
ivoc9f4a4a02016-10-28 05:39:16 -07001451
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001452 if (submodules_.echo_detector) {
1453 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1454 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1455 }
ivoc9f4a4a02016-10-28 05:39:16 -07001456 }
peah764e3642016-10-22 05:04:30 -07001457}
1458
Per Åhgren645f24c2020-03-16 12:06:02 +01001459int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1460 const StreamConfig& input_config,
1461 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001462 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001463 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001464
1465 RETURN_ON_ERR(
1466 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1467 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001468
Markus Handell0df0fae2020-07-07 15:53:34 +02001469 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001470 DenormalDisabler denormal_disabler;
niklase@google.com470e71d2011-07-07 08:21:25 +00001471
aleloi868f32f2017-05-23 07:20:05 -07001472 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001473 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001474 }
1475
Per Åhgren645f24c2020-03-16 12:06:02 +01001476 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001477 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001478 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001479 }
peahde65ddc2016-09-16 15:02:15 -07001480 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001481 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001482 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001483 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001484 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001485 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001486 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001487 }
Per Åhgrena1351272019-08-15 12:15:46 +02001488 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001489
aleloi868f32f2017-05-23 07:20:05 -07001490 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001491 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001492 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001493 return kNoError;
1494}
1495
peahde65ddc2016-09-16 15:02:15 -07001496int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001497 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001498 HandleCaptureRuntimeSettings();
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001499 DenormalDisabler denormal_disabler;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001500
peahb58a1582016-03-15 09:34:24 -07001501 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001502 // TODO(peah): Simplify once the public API Enable functions for these
1503 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001504 RTC_DCHECK_LE(
1505 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001506
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001507 data_dumper_->DumpRaw(
1508 "applied_input_volume",
1509 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1510
peahde65ddc2016-09-16 15:02:15 -07001511 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001512 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001513
Per Åhgrenc0424252019-12-10 13:04:15 +01001514 if (submodules_.high_pass_filter &&
1515 config_.high_pass_filter.apply_in_full_band &&
1516 !constants_.enforce_split_band_hpf) {
1517 submodules_.high_pass_filter->Process(capture_buffer,
1518 /*use_split_band_data=*/false);
1519 }
1520
Per Åhgrendb5d7282021-03-15 16:31:04 +00001521 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001522 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001523 // When the input volume is emulated, retrieve the volume applied to the
1524 // input audio and notify that to APM so that the volume is passed to the
1525 // active AGC.
1526 set_stream_analog_level_locked(
1527 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001528 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001529 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1530 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001531 }
1532
Per Åhgren928146f2019-08-20 09:19:21 +02001533 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001534 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001535 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001536 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1537 if (log_rms) {
1538 capture_rms_interval_counter_ = 0;
1539 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001540 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1541 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1542 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1543 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001544 }
1545
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001546 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001547 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001548 *capture_.applied_input_volume);
1549 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001550
saza1d600522019-10-18 13:29:43 +02001551 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001552 // Determine if the echo path gain has changed by checking all the gains
1553 // applied before AEC.
1554 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001555
Per Åhgrendb5d7282021-03-15 16:31:04 +00001556 // Detect and flag any change in the capture level adjustment pre-gain.
1557 if (submodules_.capture_levels_adjuster) {
1558 float pre_adjustment_gain =
1559 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001560 capture_.echo_path_gain_change =
1561 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001562 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001563 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001564 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001565 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001566
1567 // Detect volume change.
1568 capture_.echo_path_gain_change =
1569 capture_.echo_path_gain_change ||
1570 (capture_.prev_playout_volume != capture_.playout_volume &&
1571 capture_.prev_playout_volume >= 0);
1572 capture_.prev_playout_volume = capture_.playout_volume;
1573
saza1d600522019-10-18 13:29:43 +02001574 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001575 }
1576
Per Åhgren0695df12020-01-13 14:43:13 +01001577 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001578 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001579 }
1580
Hanna Silend4dbe452022-11-30 15:16:21 +01001581 if (submodules_.gain_controller2 &&
1582 config_.gain_controller2.input_volume_controller.enabled) {
1583 // Expect the volume to be available if the input controller is enabled.
1584 RTC_DCHECK(capture_.applied_input_volume.has_value());
1585 if (capture_.applied_input_volume.has_value()) {
1586 submodules_.gain_controller2->Analyze(*capture_.applied_input_volume,
1587 *capture_buffer);
1588 }
1589 }
1590
peah2ace3f92016-09-10 04:42:27 -07001591 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1592 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001593 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1594 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001595 }
1596
Per Åhgrene14cb992019-11-27 09:34:22 +01001597 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1598 constants_.multi_channel_capture_support;
1599 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001600 // Force down-mixing of the number of channels after the detection of
1601 // capture signal saturation.
1602 // TODO(peah): Look into ensuring that this kind of tampering with the
1603 // AudioBuffer functionality should not be needed.
1604 capture_buffer->set_num_channels(1);
1605 }
1606
Per Åhgrenc0424252019-12-10 13:04:15 +01001607 if (submodules_.high_pass_filter &&
1608 (!config_.high_pass_filter.apply_in_full_band ||
1609 constants_.enforce_split_band_hpf)) {
1610 submodules_.high_pass_filter->Process(capture_buffer,
1611 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001612 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001613
Per Åhgren0695df12020-01-13 14:43:13 +01001614 if (submodules_.gain_control) {
1615 RETURN_ON_ERR(
1616 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1617 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001618
Per Åhgren8ad9e742020-01-30 07:40:58 +01001619 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1620 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1621 submodules_.noise_suppressor) {
1622 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001623 }
peahb58a1582016-03-15 09:34:24 -07001624
saza1d600522019-10-18 13:29:43 +02001625 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001626 // Ensure that the stream delay was set before the call to the
1627 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001628 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001629 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001630 }
1631
saza1d600522019-10-18 13:29:43 +02001632 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001633 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001634 }
peahe0eae3c2016-12-14 01:16:23 -08001635
saza1d600522019-10-18 13:29:43 +02001636 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001637 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001638 } else {
saza1d600522019-10-18 13:29:43 +02001639 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001640 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1641
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001642 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001643 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001644 }
1645
saza1d600522019-10-18 13:29:43 +02001646 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001647 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001648 }
1649
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001650 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001651 linear_aec_buffer && submodules_.noise_suppressor) {
1652 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001653 }
1654
saza1d600522019-10-18 13:29:43 +02001655 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001656 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001657 }
Per Åhgren46537a32017-06-07 10:08:10 +02001658 }
ivoc9f4a4a02016-10-28 05:39:16 -07001659
Per Åhgren0695df12020-01-13 14:43:13 +01001660 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001661 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001662
1663 absl::optional<int> new_digital_gain =
1664 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001665 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001666 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1667 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001668 }
Per Åhgren0695df12020-01-13 14:43:13 +01001669
1670 if (submodules_.gain_control) {
1671 // TODO(peah): Add reporting from AEC3 whether there is echo.
1672 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1673 capture_buffer, /*stream_has_echo*/ false));
1674 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001675
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001676 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1677 SampleRateSupportsMultiBand(
1678 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1679 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001680 }
1681
Per Åhgren19775cb2021-03-12 23:08:09 +00001682 if (capture_.capture_output_used) {
1683 if (capture_.capture_fullband_audio) {
1684 const auto& ec = submodules_.echo_controller;
1685 bool ec_active = ec ? ec->ActiveProcessing() : false;
1686 // Only update the fullband buffer if the multiband processing has changed
1687 // the signal. Keep the original signal otherwise.
1688 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1689 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1690 }
1691 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001692 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001693
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001694 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001695 submodules_.echo_detector->AnalyzeCaptureAudio(
1696 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1697 capture_buffer->num_frames()));
1698 }
1699
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001700 absl::optional<float> voice_probability;
1701 if (!!submodules_.voice_activity_detector) {
1702 voice_probability = submodules_.voice_activity_detector->Analyze(
1703 AudioFrameView<const float>(capture_buffer->channels(),
1704 capture_buffer->num_channels(),
1705 capture_buffer->num_frames()));
1706 }
1707
Per Åhgren19775cb2021-03-12 23:08:09 +00001708 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001709 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001710 switch (transient_suppressor_vad_mode_) {
1711 case TransientSuppressor::VadMode::kDefault:
1712 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001713 transient_suppressor_voice_probability =
1714 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001715 }
1716 break;
1717 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001718 RTC_DCHECK(voice_probability.has_value());
1719 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001720 break;
1721 case TransientSuppressor::VadMode::kNoVad:
1722 // The transient suppressor will ignore `voice_probability`.
1723 break;
1724 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001725 float delayed_voice_probability =
1726 submodules_.transient_suppressor->Suppress(
1727 capture_buffer->channels()[0], capture_buffer->num_frames(),
1728 capture_buffer->num_channels(),
1729 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1730 capture_buffer->num_frames_per_band(),
1731 /*reference_data=*/nullptr, /*reference_length=*/0,
1732 transient_suppressor_voice_probability, capture_.key_pressed);
1733 if (voice_probability.has_value()) {
1734 *voice_probability = delayed_voice_probability;
1735 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001736 }
1737
Artem Titov0b489302021-07-28 20:50:03 +02001738 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001739 if (submodules_.capture_analyzer) {
1740 submodules_.capture_analyzer->Analyze(capture_buffer);
1741 }
1742
1743 if (submodules_.gain_controller2) {
Hanna Silend4dbe452022-11-30 15:16:21 +01001744 // TODO(bugs.webrtc.org/7494): Let AGC2 detect applied input volume
1745 // changes.
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001746 submodules_.gain_controller2->Process(
1747 voice_probability, capture_.applied_input_volume_changed,
1748 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001749 }
1750
1751 if (submodules_.capture_post_processor) {
1752 submodules_.capture_post_processor->Process(capture_buffer);
1753 }
1754
Per Åhgren19775cb2021-03-12 23:08:09 +00001755 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1756 capture_buffer->channels_const()[0],
1757 capture_nonlocked_.capture_processing_format.num_frames()));
1758 if (log_rms) {
1759 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1760 RTC_HISTOGRAM_COUNTS_LINEAR(
1761 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1762 RmsLevel::kMinLevelDb, 64);
1763 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1764 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1765 }
1766
Per Åhgren19775cb2021-03-12 23:08:09 +00001767 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001768 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001769 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1770 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1771 capture_.stats.residual_echo_likelihood_recent_max =
1772 ed_metrics.echo_likelihood_recent_max;
1773 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001774 }
1775
Per Åhgren19775cb2021-03-12 23:08:09 +00001776 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001777 if (submodules_.echo_controller) {
1778 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1779 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1780 capture_.stats.echo_return_loss_enhancement =
1781 ec_metrics.echo_return_loss_enhancement;
1782 capture_.stats.delay_ms = ec_metrics.delay_ms;
1783 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001784
1785 // Pass stats for reporting.
1786 stats_reporter_.UpdateStatistics(capture_.stats);
1787
Alessio Bazzica533e4612022-09-07 16:58:33 +02001788 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001789 if (capture_.recommended_input_volume.has_value()) {
1790 recommended_input_volume_stats_reporter_.UpdateStatistics(
1791 *capture_.recommended_input_volume);
1792 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001793
Per Åhgrendb5d7282021-03-15 16:31:04 +00001794 if (submodules_.capture_levels_adjuster) {
1795 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1796 *capture_buffer);
1797
Per Åhgrendb5d7282021-03-15 16:31:04 +00001798 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001799 // If the input volume emulation is used, retrieve the recommended input
1800 // volume and set that to emulate the input volume on the next processed
1801 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001802 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001803 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001804 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001805 }
1806 }
1807
Per Åhgren55bc0772021-03-12 14:18:36 +00001808 // Temporarily set the output to zero after the stream has been unmuted
1809 // (capture output is again used). The purpose of this is to avoid clicks and
1810 // artefacts in the audio that results when the processing again is
1811 // reactivated after unmuting.
1812 if (!capture_.capture_output_used_last_frame &&
1813 capture_.capture_output_used) {
1814 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1815 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1816 capture_buffer->num_frames());
1817 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1818 }
1819 }
1820 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1821
peahdf3efa82015-11-28 12:35:15 -08001822 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001823
Alessio Bazzica533e4612022-09-07 16:58:33 +02001824 data_dumper_->DumpRaw("recommended_input_volume",
1825 capture_.recommended_input_volume.value_or(
1826 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001827
niklase@google.com470e71d2011-07-07 08:21:25 +00001828 return kNoError;
1829}
1830
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001831int AudioProcessingImpl::AnalyzeReverseStream(
1832 const float* const* data,
1833 const StreamConfig& reverse_config) {
1834 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001835 MutexLock lock(&mutex_render_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001836 DenormalDisabler denormal_disabler;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001837 RTC_DCHECK(data);
1838 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1839 RTC_DCHECK(data[i]);
1840 }
1841 RETURN_ON_ERR(
1842 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1843
1844 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001845 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1846}
1847
peahde65ddc2016-09-16 15:02:15 -07001848int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1849 const StreamConfig& input_config,
1850 const StreamConfig& output_config,
1851 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001852 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001853 MutexLock lock(&mutex_render_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001854 DenormalDisabler denormal_disabler;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001855 RETURN_ON_ERR(
1856 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1857
1858 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001859
peahde65ddc2016-09-16 15:02:15 -07001860 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001861
Alex Loiko5825aa62017-12-18 16:02:40 +01001862 if (submodule_states_.RenderMultiBandProcessingActive() ||
1863 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001864 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1865 dest);
peah2ace3f92016-09-10 04:42:27 -07001866 } else if (formats_.api_format.reverse_input_stream() !=
1867 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001868 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1869 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001870 } else {
peahde65ddc2016-09-16 15:02:15 -07001871 CopyAudioIfNeeded(src, input_config.num_frames(),
1872 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001873 }
1874
1875 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001876}
1877
peahdf3efa82015-11-28 12:35:15 -08001878int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001879 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001880 const StreamConfig& input_config,
1881 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001882 if (aec_dump_) {
1883 const size_t channel_size =
1884 formats_.api_format.reverse_input_stream().num_frames();
1885 const size_t num_channels =
1886 formats_.api_format.reverse_input_stream().num_channels();
1887 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001888 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001889 }
peahdf3efa82015-11-28 12:35:15 -08001890 render_.render_audio->CopyFrom(src,
1891 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001892 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001893}
1894
Per Åhgren645f24c2020-03-16 12:06:02 +01001895int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1896 const StreamConfig& input_config,
1897 const StreamConfig& output_config,
1898 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001899 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001900
Markus Handell0df0fae2020-07-07 15:53:34 +02001901 MutexLock lock(&mutex_render_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001902 DenormalDisabler denormal_disabler;
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001903
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001904 RETURN_ON_ERR(
1905 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1906 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001907
aleloi868f32f2017-05-23 07:20:05 -07001908 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001909 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1910 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001911 }
1912
Per Åhgren645f24c2020-03-16 12:06:02 +01001913 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001914 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001915 if (submodule_states_.RenderMultiBandProcessingActive() ||
1916 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001917 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001918 }
aluebsb0319552016-03-17 20:39:53 -07001919 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001920}
niklase@google.com470e71d2011-07-07 08:21:25 +00001921
peahde65ddc2016-09-16 15:02:15 -07001922int AudioProcessingImpl::ProcessRenderStreamLocked() {
1923 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001924
Alex Loiko73ec0192018-05-15 10:52:28 +02001925 HandleRenderRuntimeSettings();
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001926 DenormalDisabler denormal_disabler;
Alex Loiko73ec0192018-05-15 10:52:28 +02001927
saza1d600522019-10-18 13:29:43 +02001928 if (submodules_.render_pre_processor) {
1929 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001930 }
1931
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001932 QueueNonbandedRenderAudio(render_buffer);
1933
peah2ace3f92016-09-10 04:42:27 -07001934 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001935 SampleRateSupportsMultiBand(
1936 formats_.render_processing_format.sample_rate_hz())) {
1937 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001938 }
1939
peahce4d9152017-05-19 01:28:05 -07001940 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1941 QueueBandedRenderAudio(render_buffer);
1942 }
1943
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001944 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001945 if (submodules_.echo_controller) {
1946 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001947 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001948
peah2ace3f92016-09-10 04:42:27 -07001949 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001950 SampleRateSupportsMultiBand(
1951 formats_.render_processing_format.sample_rate_hz())) {
1952 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001953 }
1954
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001955 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001956}
1957
1958int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001959 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001960 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001961 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001962
niklase@google.com470e71d2011-07-07 08:21:25 +00001963 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001964 delay = 0;
1965 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001966 }
1967
1968 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1969 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001970 delay = 500;
1971 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001972 }
1973
peahdf3efa82015-11-28 12:35:15 -08001974 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001975 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001976}
1977
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001978bool AudioProcessingImpl::GetLinearAecOutput(
1979 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001980 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001981 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1982
1983 RTC_DCHECK(linear_aec_buffer);
1984 if (linear_aec_buffer) {
1985 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1986 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1987
1988 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1989 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1990 rtc::ArrayView<const float> channel_view =
1991 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1992 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001993 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1994 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001995 }
1996 return true;
1997 }
1998 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001999 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002000 return false;
2001}
2002
niklase@google.com470e71d2011-07-07 08:21:25 +00002003int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08002004 // Used as callback from submodules, hence locking is not allowed.
2005 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00002006}
2007
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002008void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02002009 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08002010 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002011}
2012
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002013void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02002014 MutexLock lock_capture(&mutex_capture_);
2015 set_stream_analog_level_locked(level);
2016}
2017
2018void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002019 capture_.applied_input_volume_changed =
2020 capture_.applied_input_volume.has_value() &&
2021 *capture_.applied_input_volume != level;
2022 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002023
Alessio Bazzica533e4612022-09-07 16:58:33 +02002024 // Invalidate any previously recommended input volume which will be updated by
2025 // `ProcessStream()`.
2026 capture_.recommended_input_volume = absl::nullopt;
2027
Per Åhgren0e3198e2019-11-18 08:52:22 +01002028 if (submodules_.agc_manager) {
2029 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002030 return;
2031 }
2032
2033 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01002034 int error = submodules_.gain_control->set_stream_analog_level(level);
2035 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002036 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002037 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002038}
2039
2040int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002041 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002042 if (!capture_.applied_input_volume.has_value()) {
2043 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
2044 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02002045 // Input volume to recommend when `set_stream_analog_level()` is not called.
2046 constexpr int kFallBackInputVolume = 255;
2047 // When APM has no input volume to recommend, return the latest applied input
2048 // volume that has been observed in order to possibly produce no input volume
2049 // change. If no applied input volume has been observed, return a fall-back
2050 // value.
2051 return capture_.recommended_input_volume.value_or(
2052 capture_.applied_input_volume.value_or(kFallBackInputVolume));
2053}
2054
2055void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
2056 if (!capture_.applied_input_volume.has_value()) {
2057 // When `set_stream_analog_level()` is not called, no input level can be
2058 // recommended.
2059 capture_.recommended_input_volume = absl::nullopt;
2060 return;
2061 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002062
Per Åhgrendb5d7282021-03-15 16:31:04 +00002063 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002064 capture_.recommended_input_volume =
2065 submodules_.agc_manager->recommended_analog_level();
2066 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002067 }
2068
2069 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002070 capture_.recommended_input_volume =
2071 submodules_.gain_control->stream_analog_level();
2072 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002073 }
2074
Hanna Silend4dbe452022-11-30 15:16:21 +01002075 if (submodules_.gain_controller2 &&
2076 config_.gain_controller2.input_volume_controller.enabled) {
2077 capture_.recommended_input_volume =
Hanna Silen597a2ba2022-12-14 12:48:37 +01002078 submodules_.gain_controller2->recommended_input_volume();
Hanna Silend4dbe452022-11-30 15:16:21 +01002079 return;
2080 }
2081
Alessio Bazzica533e4612022-09-07 16:58:33 +02002082 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002083}
2084
Ali Tofigh1fa87c42022-07-25 22:07:08 +02002085bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
2086 int64_t max_log_size_bytes,
2087 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02002088 std::unique_ptr<AecDump> aec_dump =
2089 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02002090 if (!aec_dump) {
2091 return false;
2092 }
2093
2094 AttachAecDump(std::move(aec_dump));
2095 return true;
2096}
2097
2098bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
2099 int64_t max_log_size_bytes,
2100 rtc::TaskQueue* worker_queue) {
2101 std::unique_ptr<AecDump> aec_dump =
2102 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
2103 if (!aec_dump) {
2104 return false;
2105 }
2106
2107 AttachAecDump(std::move(aec_dump));
2108 return true;
2109}
2110
aleloi868f32f2017-05-23 07:20:05 -07002111void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
2112 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02002113 MutexLock lock_render(&mutex_render_);
2114 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002115
2116 // The previously attached AecDump will be destroyed with the
2117 // 'aec_dump' parameter, which is after locks are released.
2118 aec_dump_.swap(aec_dump);
2119 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02002120 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07002121}
2122
2123void AudioProcessingImpl::DetachAecDump() {
2124 // The d-tor of a task-queue based AecDump blocks until all pending
2125 // tasks are done. This construction avoids blocking while holding
2126 // the render and capture locks.
2127 std::unique_ptr<AecDump> aec_dump = nullptr;
2128 {
Markus Handell0df0fae2020-07-07 15:53:34 +02002129 MutexLock lock_render(&mutex_render_);
2130 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002131 aec_dump = std::move(aec_dump_);
2132 }
2133}
2134
peah8271d042016-11-22 07:24:52 -08002135AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002136 MutexLock lock_render(&mutex_render_);
2137 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08002138 return config_;
2139}
2140
peah2ace3f92016-09-10 04:42:27 -07002141bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
2142 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002143 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002144 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02002145 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00002146 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
2147 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00002148 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07002149}
2150
Per Åhgrenc0734712020-01-02 15:15:36 +01002151void AudioProcessingImpl::InitializeTransientSuppressor() {
Alessio Bazzica40b5bd72023-01-16 20:19:48 +01002152 // Choose the VAD mode for TS and detect a VAD mode change.
2153 const TransientSuppressor::VadMode previous_vad_mode =
2154 transient_suppressor_vad_mode_;
2155 transient_suppressor_vad_mode_ = TransientSuppressor::VadMode::kDefault;
2156 if (UseApmVadSubModule(config_, gain_controller2_experiment_params_)) {
2157 transient_suppressor_vad_mode_ = TransientSuppressor::VadMode::kRnnVad;
2158 }
2159 const bool vad_mode_changed =
2160 previous_vad_mode != transient_suppressor_vad_mode_;
2161
Gustaf Ullberga399c822021-05-18 12:17:56 +02002162 if (config_.transient_suppression.enabled &&
2163 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02002164 // Attempt to create a transient suppressor, if one is not already created.
Alessio Bazzica40b5bd72023-01-16 20:19:48 +01002165 if (!submodules_.transient_suppressor || vad_mode_changed) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01002166 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02002167 submodule_creation_overrides_, transient_suppressor_vad_mode_,
2168 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2169 num_proc_channels());
2170 if (!submodules_.transient_suppressor) {
2171 RTC_LOG(LS_WARNING)
2172 << "No transient suppressor created (probably disabled)";
2173 }
2174 } else {
sazaaa42ecd2020-04-01 15:24:40 +02002175 submodules_.transient_suppressor->Initialize(
2176 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2177 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02002178 }
Per Åhgrenc0734712020-01-02 15:15:36 +01002179 } else {
2180 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002181 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002182}
2183
Per Åhgren0f14db22020-01-03 14:27:14 +01002184void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01002185 bool high_pass_filter_needed_by_aec =
2186 config_.echo_canceller.enabled &&
2187 config_.echo_canceller.enforce_high_pass_filtering &&
2188 !config_.echo_canceller.mobile_mode;
2189 if (submodule_states_.HighPassFilteringRequired() ||
2190 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01002191 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
2192 !constants_.enforce_split_band_hpf;
2193 int rate = use_full_band ? proc_fullband_sample_rate_hz()
2194 : proc_split_sample_rate_hz();
2195 size_t num_channels =
2196 use_full_band ? num_output_channels() : num_proc_channels();
2197
Per Åhgren0f14db22020-01-03 14:27:14 +01002198 if (!submodules_.high_pass_filter ||
2199 rate != submodules_.high_pass_filter->sample_rate_hz() ||
2200 forced_reset ||
2201 num_channels != submodules_.high_pass_filter->num_channels()) {
2202 submodules_.high_pass_filter.reset(
2203 new HighPassFilter(rate, num_channels));
2204 }
peah8271d042016-11-22 07:24:52 -08002205 } else {
saza1d600522019-10-18 13:29:43 +02002206 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08002207 }
2208}
alessiob3ec96df2017-05-22 06:57:06 -07002209
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02002210void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002211 bool use_echo_controller =
2212 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002213 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002214
2215 if (use_echo_controller) {
2216 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01002217 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01002218 submodules_.echo_controller = echo_control_factory_->Create(
2219 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01002220 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01002221 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002222 EchoCanceller3Config config;
2223 absl::optional<EchoCanceller3Config> multichannel_config;
2224 if (use_setup_specific_default_aec3_config_) {
2225 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
2226 }
saza1d600522019-10-18 13:29:43 +02002227 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002228 config, multichannel_config, proc_sample_rate_hz(),
2229 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01002230 }
2231
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002232 // Setup the storage for returning the linear AEC output.
2233 if (config_.echo_canceller.export_linear_aec_output) {
2234 constexpr int kLinearOutputRateHz = 16000;
2235 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
2236 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
2237 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
2238 } else {
2239 capture_.linear_aec_output.reset();
2240 }
2241
Per Åhgren200feba2019-03-06 04:16:46 +01002242 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002243
saza1d600522019-10-18 13:29:43 +02002244 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002245 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002246 return;
peahe0eae3c2016-12-14 01:16:23 -08002247 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002248
saza1d600522019-10-18 13:29:43 +02002249 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002250 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002251 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002252
2253 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02002254 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002255 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002256 return;
2257 }
2258
2259 if (config_.echo_canceller.mobile_mode) {
2260 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002261 size_t max_element_size =
2262 std::max(static_cast<size_t>(1),
2263 kMaxAllowedValuesOfSamplesPerBand *
2264 EchoControlMobileImpl::NumCancellersRequired(
2265 num_output_channels(), num_reverse_channels()));
2266
2267 std::vector<int16_t> template_queue_element(max_element_size);
2268
2269 aecm_render_signal_queue_.reset(
2270 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2271 kMaxNumFramesToBuffer, template_queue_element,
2272 RenderQueueItemVerifier<int16_t>(max_element_size)));
2273
2274 aecm_render_queue_buffer_.resize(max_element_size);
2275 aecm_capture_queue_buffer_.resize(max_element_size);
2276
saza1d600522019-10-18 13:29:43 +02002277 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002278
saza1d600522019-10-18 13:29:43 +02002279 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2280 num_reverse_channels(),
2281 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002282 return;
2283 }
2284
saza1d600522019-10-18 13:29:43 +02002285 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002286 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002287}
peah8271d042016-11-22 07:24:52 -08002288
Per Åhgren0695df12020-01-13 14:43:13 +01002289void AudioProcessingImpl::InitializeGainController1() {
Hanna Silend4dbe452022-11-30 15:16:21 +01002290 if (config_.gain_controller2.enabled &&
2291 config_.gain_controller2.input_volume_controller.enabled &&
2292 config_.gain_controller1.enabled &&
2293 (config_.gain_controller1.mode ==
2294 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
2295 config_.gain_controller1.analog_gain_controller.enabled)) {
2296 RTC_LOG(LS_ERROR) << "APM configuration not valid: "
2297 << "Multiple input volume controllers enabled.";
2298 }
2299
Per Åhgren0695df12020-01-13 14:43:13 +01002300 if (!config_.gain_controller1.enabled) {
2301 submodules_.agc_manager.reset();
2302 submodules_.gain_control.reset();
2303 return;
2304 }
2305
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002306 RTC_HISTOGRAM_BOOLEAN(
2307 "WebRTC.Audio.GainController.Analog.Enabled",
2308 config_.gain_controller1.analog_gain_controller.enabled);
2309
Per Åhgren0695df12020-01-13 14:43:13 +01002310 if (!submodules_.gain_control) {
2311 submodules_.gain_control.reset(new GainControlImpl());
2312 }
2313
2314 submodules_.gain_control->Initialize(num_proc_channels(),
2315 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002316 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2317 int error = submodules_.gain_control->set_mode(
2318 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2319 RTC_DCHECK_EQ(kNoError, error);
2320 error = submodules_.gain_control->set_target_level_dbfs(
2321 config_.gain_controller1.target_level_dbfs);
2322 RTC_DCHECK_EQ(kNoError, error);
2323 error = submodules_.gain_control->set_compression_gain_db(
2324 config_.gain_controller1.compression_gain_db);
2325 RTC_DCHECK_EQ(kNoError, error);
2326 error = submodules_.gain_control->enable_limiter(
2327 config_.gain_controller1.enable_limiter);
2328 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002329 constexpr int kAnalogLevelMinimum = 0;
2330 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002331 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002332 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002333 RTC_DCHECK_EQ(kNoError, error);
2334
2335 submodules_.agc_manager.reset();
2336 return;
2337 }
2338
2339 if (!submodules_.agc_manager.get() ||
2340 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002341 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002342 int stream_analog_level = -1;
2343 const bool re_creation = !!submodules_.agc_manager;
2344 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002345 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002346 }
2347 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002348 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002349 if (re_creation) {
2350 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2351 }
2352 }
2353 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002354 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002355 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2356 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002357}
2358
Alessio Bazzica40b5bd72023-01-16 20:19:48 +01002359void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica38901042021-10-14 12:14:21 +02002360 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002361 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002362 return;
2363 }
Alessio Bazzica40b5bd72023-01-16 20:19:48 +01002364 // Override the input volume controller configuration if the AGC2 experiment
2365 // is running and its parameters require to fully switch the gain control to
2366 // AGC2.
2367 const bool input_volume_controller_config_overridden =
2368 gain_controller2_experiment_params_.has_value() &&
2369 gain_controller2_experiment_params_->agc2_config.has_value();
2370 const InputVolumeController::Config input_volume_controller_config =
2371 input_volume_controller_config_overridden
2372 ? gain_controller2_experiment_params_->agc2_config
2373 ->input_volume_controller
2374 : InputVolumeController::Config{};
2375 // If the APM VAD sub-module is not used, let AGC2 use its internal VAD.
2376 const bool use_internal_vad =
2377 !UseApmVadSubModule(config_, gain_controller2_experiment_params_);
2378 submodules_.gain_controller2 = std::make_unique<GainController2>(
2379 config_.gain_controller2, input_volume_controller_config,
2380 proc_fullband_sample_rate_hz(), num_proc_channels(), use_internal_vad);
2381 submodules_.gain_controller2->SetCaptureOutputUsed(
2382 capture_.capture_output_used);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002383}
2384
Alessio Bazzica40b5bd72023-01-16 20:19:48 +01002385void AudioProcessingImpl::InitializeVoiceActivityDetector() {
2386 if (!UseApmVadSubModule(config_, gain_controller2_experiment_params_)) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002387 submodules_.voice_activity_detector.reset();
2388 return;
2389 }
Alessio Bazzica40b5bd72023-01-16 20:19:48 +01002390
2391 if (!submodules_.voice_activity_detector) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002392 RTC_DCHECK(!!submodules_.gain_controller2);
2393 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2394 submodules_.voice_activity_detector =
2395 std::make_unique<VoiceActivityDetectorWrapper>(
Hanna Silen0c1ad292022-06-16 16:35:45 +02002396 submodules_.gain_controller2->GetCpuFeatures(),
2397 proc_fullband_sample_rate_hz());
Alessio Bazzica40b5bd72023-01-16 20:19:48 +01002398 } else {
2399 submodules_.voice_activity_detector->Initialize(
2400 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002401 }
2402}
2403
saza0bad15f2019-10-16 11:46:11 +02002404void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002405 submodules_.noise_suppressor.reset();
2406
saza0bad15f2019-10-16 11:46:11 +02002407 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002408 auto map_level =
2409 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2410 using NoiseSuppresionConfig =
2411 AudioProcessing::Config::NoiseSuppression;
2412 switch (level) {
2413 case NoiseSuppresionConfig::kLow:
2414 return NsConfig::SuppressionLevel::k6dB;
2415 case NoiseSuppresionConfig::kModerate:
2416 return NsConfig::SuppressionLevel::k12dB;
2417 case NoiseSuppresionConfig::kHigh:
2418 return NsConfig::SuppressionLevel::k18dB;
2419 case NoiseSuppresionConfig::kVeryHigh:
2420 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002421 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002422 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002423 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002424
sazaaa42ecd2020-04-01 15:24:40 +02002425 NsConfig cfg;
2426 cfg.target_level = map_level(config_.noise_suppression.level);
2427 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2428 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002429 }
2430}
2431
Per Åhgrendb5d7282021-03-15 16:31:04 +00002432void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2433 if (config_.pre_amplifier.enabled ||
2434 config_.capture_level_adjustment.enabled) {
2435 // Use both the pre-amplifier and the capture level adjustment gains as
2436 // pre-gains.
2437 float pre_gain = 1.f;
2438 if (config_.pre_amplifier.enabled) {
2439 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2440 }
2441 if (config_.capture_level_adjustment.enabled) {
2442 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2443 }
2444
2445 submodules_.capture_levels_adjuster =
2446 std::make_unique<CaptureLevelsAdjuster>(
2447 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2448 config_.capture_level_adjustment.analog_mic_gain_emulation
2449 .initial_level,
2450 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002451 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002452 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002453 }
2454}
2455
ivoc9f4a4a02016-10-28 05:39:16 -07002456void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002457 if (submodules_.echo_detector) {
2458 submodules_.echo_detector->Initialize(
2459 proc_fullband_sample_rate_hz(), 1,
2460 formats_.render_processing_format.sample_rate_hz(), 1);
2461 }
ivoc9f4a4a02016-10-28 05:39:16 -07002462}
2463
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002464void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002465 if (submodules_.capture_analyzer) {
2466 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2467 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002468 }
2469}
2470
Sam Zackrisson0beac582017-09-25 12:04:02 +02002471void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002472 if (submodules_.capture_post_processor) {
2473 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002474 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002475 }
2476}
2477
Alex Loiko5825aa62017-12-18 16:02:40 +01002478void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002479 if (submodules_.render_pre_processor) {
2480 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002481 formats_.render_processing_format.sample_rate_hz(),
2482 formats_.render_processing_format.num_channels());
2483 }
2484}
2485
aleloi868f32f2017-05-23 07:20:05 -07002486void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2487 if (!aec_dump_) {
2488 return;
2489 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002490
2491 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002492 // TODO(peah): Add semicolon-separated concatenations of experiment
2493 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002494 if (!!submodules_.capture_post_processor) {
2495 experiments_description += "CapturePostProcessor;";
2496 }
2497 if (!!submodules_.render_pre_processor) {
2498 experiments_description += "RenderPreProcessor;";
2499 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002500 if (capture_nonlocked_.echo_controller_enabled) {
2501 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002502 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002503 if (config_.gain_controller2.enabled) {
2504 experiments_description += "GainController2;";
2505 }
aleloi868f32f2017-05-23 07:20:05 -07002506
2507 InternalAPMConfig apm_config;
2508
Per Åhgren200feba2019-03-06 04:16:46 +01002509 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002510 apm_config.aec_delay_agnostic_enabled = false;
2511 apm_config.aec_extended_filter_enabled = false;
2512 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002513
saza1d600522019-10-18 13:29:43 +02002514 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002515 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002516 submodules_.echo_control_mobile &&
2517 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002518 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002519 submodules_.echo_control_mobile
2520 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002521 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002522
Per Åhgren0695df12020-01-13 14:43:13 +01002523 apm_config.agc_enabled = !!submodules_.gain_control;
2524
2525 apm_config.agc_mode = submodules_.gain_control
2526 ? static_cast<int>(submodules_.gain_control->mode())
2527 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002528 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002529 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2530 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002531 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002532
2533 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2534
saza0bad15f2019-10-16 11:46:11 +02002535 apm_config.ns_enabled = config_.noise_suppression.enabled;
2536 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002537
2538 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002539 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002540 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002541 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2542 apm_config.pre_amplifier_fixed_gain_factor =
2543 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002544
2545 if (!forced && apm_config == apm_config_for_aec_dump_) {
2546 return;
2547 }
2548 aec_dump_->WriteConfig(apm_config);
2549 apm_config_for_aec_dump_ = apm_config;
2550}
2551
2552void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2553 const float* const* src) {
2554 RTC_DCHECK(aec_dump_);
2555 WriteAecDumpConfigMessage(false);
2556
2557 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2558 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2559 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002560 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002561 RecordAudioProcessingState();
2562}
2563
2564void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002565 const int16_t* const data,
2566 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002567 RTC_DCHECK(aec_dump_);
2568 WriteAecDumpConfigMessage(false);
2569
Per Åhgren645f24c2020-03-16 12:06:02 +01002570 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2571 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002572 RecordAudioProcessingState();
2573}
2574
2575void AudioProcessingImpl::RecordProcessedCaptureStream(
2576 const float* const* processed_capture_stream) {
2577 RTC_DCHECK(aec_dump_);
2578
2579 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2580 const size_t num_channels =
2581 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002582 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2583 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002584 aec_dump_->WriteCaptureStreamMessage();
2585}
2586
2587void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002588 const int16_t* const data,
2589 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002590 RTC_DCHECK(aec_dump_);
2591
Per Åhgren645f24c2020-03-16 12:06:02 +01002592 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002593 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002594 aec_dump_->WriteCaptureStreamMessage();
2595}
2596
2597void AudioProcessingImpl::RecordAudioProcessingState() {
2598 RTC_DCHECK(aec_dump_);
2599 AecDump::AudioProcessingState audio_proc_state;
2600 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002601 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002602 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002603 audio_proc_state.keypress = capture_.key_pressed;
2604 aec_dump_->AddAudioProcessingState(audio_proc_state);
2605}
2606
Per Åhgrenc0734712020-01-02 15:15:36 +01002607AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002608 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002609 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002610 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002611 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002612 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002613 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002614 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002615 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002616 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002617 prev_playout_volume(-1),
2618 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002619
2620AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2621
2622AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2623
2624AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2625
Per Åhgrencf4c8722019-12-30 14:32:14 +01002626AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2627 : stats_message_queue_(1) {}
2628
2629AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2630
2631AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002632 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002633 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2634 // If the message queue is full, return the cached stats.
2635 static_cast<void>(new_stats_available);
2636
2637 return cached_stats_;
2638}
2639
2640void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2641 const AudioProcessingStats& new_stats) {
2642 AudioProcessingStats stats_to_queue = new_stats;
2643 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2644 // If the message queue is full, discard the new stats.
2645 static_cast<void>(stats_message_passed);
2646}
2647
niklase@google.com470e71d2011-07-07 08:21:25 +00002648} // namespace webrtc