blob: e92ae6dffd281ce0bff05dff62ed38bb354adda7 [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;
509 if (!one_and_only_one_input_volume_controller ||
510 config.gain_controller2.input_volume_controller.enabled) {
511 RTC_LOG(LS_ERROR) << "Cannot adjust AGC config (precondition failed)";
512 if (!one_and_only_one_input_volume_controller)
513 RTC_LOG(LS_ERROR)
514 << "One and only one input volume controller must be enabled.";
515 if (config.gain_controller2.input_volume_controller.enabled)
516 RTC_LOG(LS_ERROR)
517 << "The AGC2 input volume controller must be disabled.";
518 } else {
519 adjusted_config.gain_controller1.enabled = false;
520 adjusted_config.gain_controller1.analog_gain_controller.enabled = false;
Hanna Silenca653552022-12-08 17:40:01 +0100521
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100522 adjusted_config.gain_controller2.enabled = true;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100523 adjusted_config.gain_controller2.input_volume_controller.enabled = true;
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100524 adjusted_config.gain_controller2.adaptive_digital =
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100525 experiment_params->agc2_config->adaptive_digital_controller;
Alessio Bazzicadfba28e2022-12-09 10:02:41 +0100526 adjusted_config.gain_controller2.adaptive_digital.enabled = true;
Alessio Bazzica352f38c2022-12-07 16:13:35 +0100527 }
Hanna Silena6574902022-11-30 16:59:05 +0100528 }
529
Hanna Silena6574902022-11-30 16:59:05 +0100530 return adjusted_config;
531}
532
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100533TransientSuppressor::VadMode AudioProcessingImpl::GetTransientSuppressorVadMode(
534 const absl::optional<AudioProcessingImpl::GainController2ExperimentParams>&
535 params) {
536 if (params.has_value() && params->agc2_config.has_value() &&
537 !params->disallow_transient_suppressor_usage) {
538 // When the experiment is active, the gain control switches to AGC2 and TS
539 // can be active, use the RNN VAD to control TS. This choice will also
540 // disable the internal RNN VAD in AGC2.
541 return TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica504bd592022-12-01 13:26:26 +0100542 }
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100543 // If TS is disabled, the returned value does not matter. If enabled, use the
544 // default VAD.
545 return TransientSuppressor::VadMode::kDefault;
Alessio Bazzica504bd592022-12-01 13:26:26 +0100546}
547
saza1d600522019-10-18 13:29:43 +0200548AudioProcessingImpl::SubmoduleStates::SubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100549 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200550 bool render_pre_processor_enabled,
551 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100552 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200553 render_pre_processor_enabled_(render_pre_processor_enabled),
554 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700555
saza1d600522019-10-18 13:29:43 +0200556bool AudioProcessingImpl::SubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200557 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700558 bool mobile_echo_controller_enabled,
559 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700560 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700561 bool gain_controller2_enabled,
Hanna Silen0c1ad292022-06-16 16:35:45 +0200562 bool voice_activity_detector_enabled,
Per Åhgrendb5d7282021-03-15 16:31:04 +0000563 bool gain_adjustment_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200564 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700565 bool transient_suppressor_enabled) {
566 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200567 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700568 changed |=
569 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
570 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
571 changed |=
peah2ace3f92016-09-10 04:42:27 -0700572 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
Per Åhgren6ee75fd2019-04-26 11:33:37 +0200573 changed |= (gain_controller2_enabled != gain_controller2_enabled_);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200574 changed |=
575 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
Per Åhgrendb5d7282021-03-15 16:31:04 +0000576 changed |= (gain_adjustment_enabled != gain_adjustment_enabled_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200577 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700578 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
579 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200580 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700581 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
582 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700583 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700584 gain_controller2_enabled_ = gain_controller2_enabled;
Hanna Silen0c1ad292022-06-16 16:35:45 +0200585 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000586 gain_adjustment_enabled_ = gain_adjustment_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200587 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700588 transient_suppressor_enabled_ = transient_suppressor_enabled;
589 }
590
591 changed |= first_update_;
592 first_update_ = false;
593 return changed;
594}
595
saza1d600522019-10-18 13:29:43 +0200596bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700597 const {
Alessio Bazzica1db0a262022-02-15 14:18:09 +0000598 return CaptureMultiBandProcessingPresent();
peah2ace3f92016-09-10 04:42:27 -0700599}
600
saza1d600522019-10-18 13:29:43 +0200601bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingPresent()
602 const {
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200603 // If echo controller is present, assume it performs active processing.
604 return CaptureMultiBandProcessingActive(/*ec_processing_active=*/true);
605}
606
saza1d600522019-10-18 13:29:43 +0200607bool AudioProcessingImpl::SubmoduleStates::CaptureMultiBandProcessingActive(
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200608 bool ec_processing_active) const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100609 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
610 noise_suppressor_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullberg8675eee2019-10-09 13:34:36 +0200611 (echo_controller_enabled_ && ec_processing_active);
peah2ace3f92016-09-10 04:42:27 -0700612}
613
saza1d600522019-10-18 13:29:43 +0200614bool AudioProcessingImpl::SubmoduleStates::CaptureFullBandProcessingActive()
peah23ac8b42017-05-23 05:33:56 -0700615 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200616 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
Per Åhgrendb5d7282021-03-15 16:31:04 +0000617 gain_adjustment_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700618}
619
saza1d600522019-10-18 13:29:43 +0200620bool AudioProcessingImpl::SubmoduleStates::CaptureAnalyzerActive() const {
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200621 return capture_analyzer_enabled_;
622}
623
saza1d600522019-10-18 13:29:43 +0200624bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandSubModulesActive()
peah2ace3f92016-09-10 04:42:27 -0700625 const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100626 return RenderMultiBandProcessingActive() || mobile_echo_controller_enabled_ ||
627 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700628}
629
saza1d600522019-10-18 13:29:43 +0200630bool AudioProcessingImpl::SubmoduleStates::RenderFullBandProcessingActive()
Alex Loiko5825aa62017-12-18 16:02:40 +0100631 const {
632 return render_pre_processor_enabled_;
633}
634
saza1d600522019-10-18 13:29:43 +0200635bool AudioProcessingImpl::SubmoduleStates::RenderMultiBandProcessingActive()
peah2ace3f92016-09-10 04:42:27 -0700636 const {
peah2ace3f92016-09-10 04:42:27 -0700637 return false;
peah2ace3f92016-09-10 04:42:27 -0700638}
639
saza1d600522019-10-18 13:29:43 +0200640bool AudioProcessingImpl::SubmoduleStates::HighPassFilteringRequired() const {
Per Åhgren62ea0aa2019-12-09 10:18:44 +0100641 return high_pass_filter_enabled_ || mobile_echo_controller_enabled_ ||
642 noise_suppressor_enabled_;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200643}
644
Alessio Bazzicabe1b8982021-09-17 08:26:10 +0200645AudioProcessingImpl::AudioProcessingImpl()
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200646 : AudioProcessingImpl(/*config=*/{},
647 /*capture_post_processor=*/nullptr,
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200648 /*render_pre_processor=*/nullptr,
649 /*echo_control_factory=*/nullptr,
650 /*echo_detector=*/nullptr,
651 /*capture_analyzer=*/nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000652
Niels Möller7a669002022-06-27 09:47:02 +0200653std::atomic<int> AudioProcessingImpl::instance_count_(0);
Per Åhgren13735822018-02-12 21:42:56 +0100654
Sam Zackrisson0beac582017-09-25 12:04:02 +0200655AudioProcessingImpl::AudioProcessingImpl(
Alessio Bazzica20a9ac62021-10-14 10:55:08 +0200656 const AudioProcessing::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100657 std::unique_ptr<CustomProcessing> capture_post_processor,
658 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200659 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200660 rtc::scoped_refptr<EchoDetector> echo_detector,
661 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Niels Möller7a669002022-06-27 09:47:02 +0200662 : data_dumper_(new ApmDataDumper(instance_count_.fetch_add(1) + 1)),
Per Åhgrenb2b58d82019-12-02 14:59:40 +0100663 use_setup_specific_default_aec3_config_(
664 UseSetupSpecificDefaultAec3Congfig()),
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100665 gain_controller2_experiment_params_(GetGainController2ExperimentParams()),
Alessio Bazzica0441bb62021-08-10 15:23:23 +0200666 use_denormal_disabler_(
667 !field_trial::IsEnabled("WebRTC-ApmDenormalDisablerKillSwitch")),
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100668 transient_suppressor_vad_mode_(
669 GetTransientSuppressorVadMode(gain_controller2_experiment_params_)),
Per Åhgren652ada52021-03-03 10:52:44 +0000670 capture_runtime_settings_(RuntimeSettingQueueSize()),
671 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200672 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
673 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200674 echo_control_factory_(std::move(echo_control_factory)),
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100675 config_(AdjustConfig(config, gain_controller2_experiment_params_)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200676 submodule_states_(!!capture_post_processor,
677 !!render_pre_processor,
678 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200679 submodules_(std::move(capture_post_processor),
680 std::move(render_pre_processor),
681 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100682 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100683 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200684 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
685 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100686 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000687 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200688 MinimizeProcessingForUnusedOutput(),
689 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000690 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200691 capture_nonlocked_(),
692 applied_input_volume_stats_reporter_(
693 InputVolumeStatsReporter::InputVolumeType::kApplied),
694 recommended_input_volume_stats_reporter_(
695 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200696 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100697 "\nEcho control factory: "
698 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200699 << "\nEcho detector: " << !!submodules_.echo_detector
700 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
701 << "\nCapture post processor: "
702 << !!submodules_.capture_post_processor
703 << "\nRender pre processor: "
704 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100705 if (!DenormalDisabler::IsSupported()) {
706 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
707 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200708
Hanna Silena6574902022-11-30 16:59:05 +0100709 RTC_LOG(LS_INFO) << "AudioProcessing: " << config_.ToString();
710
Sam Zackrisson421c8592019-02-11 13:39:46 +0100711 // Mark Echo Controller enabled if a factory is injected.
712 capture_nonlocked_.echo_controller_enabled =
713 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000714
Per Åhgren0ade9832020-09-01 23:57:20 +0200715 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000716}
717
Per Åhgren0e3198e2019-11-18 08:52:22 +0100718AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000719
niklase@google.com470e71d2011-07-07 08:21:25 +0000720int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800721 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200722 MutexLock lock_render(&mutex_render_);
723 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200724 InitializeLocked();
725 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000726}
727
Michael Graczyk86c6d332015-07-23 11:41:39 -0700728int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800729 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200730 MutexLock lock_render(&mutex_render_);
731 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100732 InitializeLocked(processing_config);
733 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000734}
735
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100736void AudioProcessingImpl::MaybeInitializeRender(
737 const StreamConfig& input_config,
738 const StreamConfig& output_config) {
739 ProcessingConfig processing_config = formats_.api_format;
740 processing_config.reverse_input_stream() = input_config;
741 processing_config.reverse_output_stream() = output_config;
742
Oskar Sundbom4b276482019-05-23 14:28:00 +0200743 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100744 return;
peah192164e2015-11-17 02:16:45 -0800745 }
peahdf3efa82015-11-28 12:35:15 -0800746
Markus Handell0df0fae2020-07-07 15:53:34 +0200747 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100748 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800749}
750
Per Åhgren0ade9832020-09-01 23:57:20 +0200751void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200752 UpdateActiveSubmoduleStates();
753
Per Åhgrend47941e2019-08-22 11:51:13 +0200754 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800755 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200756 ? formats_.render_processing_format.sample_rate_hz()
757 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800758 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
759 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200760 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800761 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200762 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700763 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200764 render_audiobuffer_sample_rate_hz,
765 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700766 if (formats_.api_format.reverse_input_stream() !=
767 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800768 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800769 formats_.api_format.reverse_input_stream().num_channels(),
770 formats_.api_format.reverse_input_stream().num_frames(),
771 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800772 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700773 } else {
peahdf3efa82015-11-28 12:35:15 -0800774 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700775 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700776 } else {
peahdf3efa82015-11-28 12:35:15 -0800777 render_.render_audio.reset(nullptr);
778 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700779 }
peahce4d9152017-05-19 01:28:05 -0700780
Per Åhgrend47941e2019-08-22 11:51:13 +0200781 capture_.capture_audio.reset(new AudioBuffer(
782 formats_.api_format.input_stream().sample_rate_hz(),
783 formats_.api_format.input_stream().num_channels(),
784 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
785 formats_.api_format.output_stream().num_channels(),
786 formats_.api_format.output_stream().sample_rate_hz(),
787 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100788 SetDownmixMethod(*capture_.capture_audio,
789 config_.pipeline.capture_downmix_method);
niklase@google.com470e71d2011-07-07 08:21:25 +0000790
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200791 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
792 formats_.api_format.output_stream().sample_rate_hz() &&
793 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
794 capture_.capture_fullband_audio.reset(
795 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
796 formats_.api_format.input_stream().num_channels(),
797 formats_.api_format.output_stream().sample_rate_hz(),
798 formats_.api_format.output_stream().num_channels(),
799 formats_.api_format.output_stream().sample_rate_hz(),
800 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100801 SetDownmixMethod(*capture_.capture_fullband_audio,
802 config_.pipeline.capture_downmix_method);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200803 } else {
804 capture_.capture_fullband_audio.reset();
805 }
806
peah764e3642016-10-22 05:04:30 -0700807 AllocateRenderQueue();
808
Per Åhgren0695df12020-01-13 14:43:13 +0100809 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100810 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100811 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700812 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200813 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200814 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200815 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200816 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200817 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200818 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100819 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000820 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800821
aleloi868f32f2017-05-23 07:20:05 -0700822 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200823 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700824 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000825}
826
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100827void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200828 UpdateActiveSubmoduleStates();
829
peahdf3efa82015-11-28 12:35:15 -0800830 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000831
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200832 // Choose maximum rate to use for the split filtering.
833 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
834 config_.pipeline.maximum_internal_processing_rate == 32000);
835 int max_splitting_rate = 48000;
836 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
837 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
838 }
839
Per Åhgrenc8626b62019-08-23 15:49:51 +0200840 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700841 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700842 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200843 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700844 submodule_states_.CaptureMultiBandSubModulesActive() ||
845 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200846 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000847
peahde65ddc2016-09-16 15:02:15 -0700848 capture_nonlocked_.capture_processing_format =
849 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700850
peah2ce640f2017-04-07 03:57:48 -0700851 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200852 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200853 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700854 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
855 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200856 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700857 submodule_states_.CaptureMultiBandSubModulesActive() ||
858 submodule_states_.RenderMultiBandSubModulesActive());
859 } else {
860 render_processing_rate = capture_processing_rate;
861 }
862
peahde65ddc2016-09-16 15:02:15 -0700863 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700864 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700865 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
866 kSampleRate8kHz) {
867 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000868 } else {
peahde65ddc2016-09-16 15:02:15 -0700869 render_processing_rate =
870 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000871 }
872
Per Åhgrenc8626b62019-08-23 15:49:51 +0200873 RTC_DCHECK_NE(8000, render_processing_rate);
874
peahce4d9152017-05-19 01:28:05 -0700875 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200876 // By default, downmix the render stream to mono for analysis. This has been
877 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100878 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
879 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200880 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100881 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200882 ? formats_.api_format.reverse_input_stream().num_channels()
883 : 1;
884 formats_.render_processing_format =
885 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700886 } else {
887 formats_.render_processing_format = StreamConfig(
888 formats_.api_format.reverse_input_stream().sample_rate_hz(),
889 formats_.api_format.reverse_input_stream().num_channels());
890 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000891
peahde65ddc2016-09-16 15:02:15 -0700892 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
893 kSampleRate32kHz ||
894 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
895 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800896 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000897 } else {
peahdf3efa82015-11-28 12:35:15 -0800898 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700899 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000900 }
901
Per Åhgren0ade9832020-09-01 23:57:20 +0200902 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000903}
904
peah88ac8532016-09-12 16:47:25 -0700905void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700906 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200907 MutexLock lock_render(&mutex_render_);
908 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700909
Hanna Silena6574902022-11-30 16:59:05 +0100910 const auto adjusted_config =
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100911 AdjustConfig(config, gain_controller2_experiment_params_);
Hanna Silena6574902022-11-30 16:59:05 +0100912 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: "
913 << adjusted_config.ToString();
914
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200915 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100916 config_.pipeline.multi_channel_render !=
Hanna Silena6574902022-11-30 16:59:05 +0100917 adjusted_config.pipeline.multi_channel_render ||
Per Åhgrene14cb992019-11-27 09:34:22 +0100918 config_.pipeline.multi_channel_capture !=
Hanna Silena6574902022-11-30 16:59:05 +0100919 adjusted_config.pipeline.multi_channel_capture ||
Per Åhgrenc0424252019-12-10 13:04:15 +0100920 config_.pipeline.maximum_internal_processing_rate !=
Alessio Bazzica504bd592022-12-01 13:26:26 +0100921 adjusted_config.pipeline.maximum_internal_processing_rate ||
922 config_.pipeline.capture_downmix_method !=
923 adjusted_config.pipeline.capture_downmix_method;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200924
Per Åhgren200feba2019-03-06 04:16:46 +0100925 const bool aec_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100926 config_.echo_canceller.enabled !=
927 adjusted_config.echo_canceller.enabled ||
928 config_.echo_canceller.mobile_mode !=
929 adjusted_config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100930
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100931 const bool agc1_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100932 config_.gain_controller1 != adjusted_config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100933
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100934 const bool agc2_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100935 config_.gain_controller2 != adjusted_config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100936
saza0bad15f2019-10-16 11:46:11 +0200937 const bool ns_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100938 config_.noise_suppression.enabled !=
939 adjusted_config.noise_suppression.enabled ||
940 config_.noise_suppression.level !=
941 adjusted_config.noise_suppression.level;
saza0bad15f2019-10-16 11:46:11 +0200942
Per Åhgrenc0734712020-01-02 15:15:36 +0100943 const bool ts_config_changed = config_.transient_suppression.enabled !=
Hanna Silena6574902022-11-30 16:59:05 +0100944 adjusted_config.transient_suppression.enabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100945
Per Åhgren0f14db22020-01-03 14:27:14 +0100946 const bool pre_amplifier_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100947 config_.pre_amplifier.enabled != adjusted_config.pre_amplifier.enabled ||
Per Åhgren0f14db22020-01-03 14:27:14 +0100948 config_.pre_amplifier.fixed_gain_factor !=
Hanna Silena6574902022-11-30 16:59:05 +0100949 adjusted_config.pre_amplifier.fixed_gain_factor;
Per Åhgren0f14db22020-01-03 14:27:14 +0100950
Per Åhgrendb5d7282021-03-15 16:31:04 +0000951 const bool gain_adjustment_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100952 config_.capture_level_adjustment !=
953 adjusted_config.capture_level_adjustment;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000954
Hanna Silena6574902022-11-30 16:59:05 +0100955 config_ = adjusted_config;
Yves Gerey499bc6c2018-10-10 18:29:07 +0200956
Per Åhgren200feba2019-03-06 04:16:46 +0100957 if (aec_config_changed) {
958 InitializeEchoController();
959 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200960
saza0bad15f2019-10-16 11:46:11 +0200961 if (ns_config_changed) {
962 InitializeNoiseSuppressor();
963 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100964
Per Åhgrenc0734712020-01-02 15:15:36 +0100965 if (ts_config_changed) {
966 InitializeTransientSuppressor();
967 }
968
Per Åhgren0f14db22020-01-03 14:27:14 +0100969 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800970
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100971 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100972 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100973 }
974
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100975 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700976 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200977 RTC_LOG(LS_ERROR)
978 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700979 config_.gain_controller2 = AudioProcessing::Config::GainController2();
980 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100981
Alessio Bazzica38901042021-10-14 12:14:21 +0200982 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200983 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100984
Per Åhgrendb5d7282021-03-15 16:31:04 +0000985 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
986 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100987 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100988
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200989 // Reinitialization must happen after all submodule configuration to avoid
990 // additional reinitializations on the next capture / render processing call.
991 if (pipeline_config_changed) {
992 InitializeLocked(formats_.api_format);
993 }
peah88ac8532016-09-12 16:47:25 -0700994}
995
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200996void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
997 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200998 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200999 submodule_creation_overrides_ = overrides;
1000}
1001
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001002int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001003 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001004 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +00001005}
1006
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001007int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
1008 return capture_.capture_fullband_audio
1009 ? capture_.capture_fullband_audio->num_frames() * 100
1010 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
1011}
1012
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001013int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001014 // Used as callback from submodules, hence locking is not allowed.
1015 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +00001016}
1017
Peter Kasting69558702016-01-12 16:26:35 -08001018size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001019 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001020 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001021}
1022
Peter Kasting69558702016-01-12 16:26:35 -08001023size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001024 // Used as callback from submodules, hence locking is not allowed.
1025 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001026}
1027
Peter Kasting69558702016-01-12 16:26:35 -08001028size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -08001029 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +01001030 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1031 constants_.multi_channel_capture_support;
1032 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001033 return 1;
1034 }
1035 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -08001036}
1037
Peter Kasting69558702016-01-12 16:26:35 -08001038size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001039 // Used as callback from submodules, hence locking is not allowed.
1040 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001041}
1042
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001043void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001044 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +01001045 HandleCaptureOutputUsedSetting(!muted);
1046}
1047
1048void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
1049 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001050 capture_.capture_output_used =
1051 capture_output_used || !constants_.minimize_processing_for_unused_output;
1052
saza1d600522019-10-18 13:29:43 +02001053 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001054 submodules_.agc_manager->HandleCaptureOutputUsedChange(
1055 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001056 }
Per Åhgren652ada52021-03-03 10:52:44 +00001057 if (submodules_.echo_controller) {
1058 submodules_.echo_controller->SetCaptureOutputUsage(
1059 capture_.capture_output_used);
1060 }
Per Åhgren15179a92021-03-12 14:12:44 +00001061 if (submodules_.noise_suppressor) {
1062 submodules_.noise_suppressor->SetCaptureOutputUsage(
1063 capture_.capture_output_used);
1064 }
Hanna Silend4dbe452022-11-30 15:16:21 +01001065 if (submodules_.gain_controller2) {
1066 submodules_.gain_controller2->SetCaptureOutputUsed(
1067 capture_.capture_output_used);
1068 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001069}
1070
Alessio Bazzicac054e782018-04-16 12:10:09 +02001071void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001072 PostRuntimeSetting(setting);
1073}
1074
1075bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +02001076 switch (setting.type()) {
1077 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001078 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +01001079 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001080 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001081 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001082 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001083 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +02001084 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001085 return capture_runtime_settings_enqueuer_.Enqueue(setting);
1086 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1087 bool enqueueing_successful;
1088 enqueueing_successful =
1089 capture_runtime_settings_enqueuer_.Enqueue(setting);
1090 enqueueing_successful =
1091 render_runtime_settings_enqueuer_.Enqueue(setting) &&
1092 enqueueing_successful;
1093 return enqueueing_successful;
1094 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001095 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001096 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001097 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +02001098 }
1099 // The language allows the enum to have a non-enumerator
1100 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +01001101 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001102 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001103}
1104
1105AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
1106 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001107 : runtime_settings_(*runtime_settings) {
1108 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001109}
1110
1111AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
1112 default;
1113
Per Åhgren0a144a72021-02-09 08:47:51 +01001114bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +02001115 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +00001116 const bool successful_insert = runtime_settings_.Insert(&setting);
1117
1118 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001119 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +02001120 }
Per Åhgren652ada52021-03-03 10:52:44 +00001121 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001122}
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001123
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001124void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001125 const StreamConfig& input_config,
1126 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001127 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001128 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001129 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001130 // Acquire the capture lock in order to access api_format. The lock is
1131 // released immediately, as we may need to acquire the render lock as part
1132 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +02001133 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001134 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001135 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +00001136 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001137
Oskar Sundbom4b276482019-05-23 14:28:00 +02001138 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001139 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -08001140 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001141
1142 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001143 reinitialization_required = true;
1144 }
1145
1146 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001147 MutexLock lock_render(&mutex_render_);
1148 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +02001149 // Reread the API format since the render format may have changed.
1150 processing_config = formats_.api_format;
1151 processing_config.input_stream() = input_config;
1152 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001153 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001154 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001155}
1156
1157int AudioProcessingImpl::ProcessStream(const float* const* src,
1158 const StreamConfig& input_config,
1159 const StreamConfig& output_config,
1160 float* const* dest) {
1161 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001162 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1163 RETURN_ON_ERR(
1164 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1165 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001166
Markus Handell0df0fae2020-07-07 15:53:34 +02001167 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001168
aleloi868f32f2017-05-23 07:20:05 -07001169 if (aec_dump_) {
1170 RecordUnprocessedCaptureStream(src);
1171 }
1172
peahdf3efa82015-11-28 12:35:15 -08001173 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001174 if (capture_.capture_fullband_audio) {
1175 capture_.capture_fullband_audio->CopyFrom(
1176 src, formats_.api_format.input_stream());
1177 }
peahde65ddc2016-09-16 15:02:15 -07001178 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001179 if (capture_.capture_fullband_audio) {
1180 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1181 dest);
1182 } else {
1183 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1184 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001185
aleloi868f32f2017-05-23 07:20:05 -07001186 if (aec_dump_) {
1187 RecordProcessedCaptureStream(dest);
1188 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001189 return kNoError;
1190}
1191
Alex Loiko73ec0192018-05-15 10:52:28 +02001192void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001193 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +00001194 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +02001195 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001196 if (aec_dump_) {
1197 aec_dump_->WriteRuntimeSetting(setting);
1198 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001199 switch (setting.type()) {
1200 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001201 if (config_.pre_amplifier.enabled ||
1202 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +02001203 float value;
1204 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001205 // If the pre-amplifier is used, apply the new gain to the
1206 // pre-amplifier regardless if the capture level adjustment is
1207 // activated. This approach allows both functionalities to coexist
1208 // until they have been properly merged.
1209 if (config_.pre_amplifier.enabled) {
1210 config_.pre_amplifier.fixed_gain_factor = value;
1211 } else {
1212 config_.capture_level_adjustment.pre_gain_factor = value;
1213 }
1214
1215 // Use both the pre-amplifier and the capture level adjustment gains
1216 // as pre-gains.
1217 float gain = 1.f;
1218 if (config_.pre_amplifier.enabled) {
1219 gain *= config_.pre_amplifier.fixed_gain_factor;
1220 }
1221 if (config_.capture_level_adjustment.enabled) {
1222 gain *= config_.capture_level_adjustment.pre_gain_factor;
1223 }
1224
1225 submodules_.capture_levels_adjuster->SetPreGain(gain);
1226 }
1227 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
1228 break;
1229 case RuntimeSetting::Type::kCapturePostGain:
1230 if (config_.capture_level_adjustment.enabled) {
1231 float value;
1232 setting.GetFloat(&value);
1233 config_.capture_level_adjustment.post_gain_factor = value;
1234 submodules_.capture_levels_adjuster->SetPostGain(
1235 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001236 }
1237 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001238 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001239 case RuntimeSetting::Type::kCaptureCompressionGain: {
Hanna Silend4dbe452022-11-30 15:16:21 +01001240 if (!submodules_.agc_manager &&
1241 !(submodules_.gain_controller2 &&
1242 config_.gain_controller2.input_volume_controller.enabled)) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001243 float value;
1244 setting.GetFloat(&value);
1245 int int_value = static_cast<int>(value + .5f);
1246 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001247 if (submodules_.gain_control) {
1248 int error =
1249 submodules_.gain_control->set_compression_gain_db(int_value);
1250 RTC_DCHECK_EQ(kNoError, error);
1251 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001252 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001253 break;
1254 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001255 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001256 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001257 float value;
1258 setting.GetFloat(&value);
1259 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001260 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001261 }
1262 break;
1263 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001264 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1265 int value;
1266 setting.GetInt(&value);
1267 capture_.playout_volume = value;
1268 break;
1269 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001270 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001271 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001272 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001273 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001274 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001275 break;
1276 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001277 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001278 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001279 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001280 bool value;
1281 setting.GetBool(&value);
1282 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001283 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001284 }
Per Åhgren652ada52021-03-03 10:52:44 +00001285 ++num_settings_processed;
1286 }
1287
1288 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1289 // Handle overrun of the runtime settings queue, which likely will has
1290 // caused settings to be discarded.
1291 HandleOverrunInCaptureRuntimeSettingsQueue();
1292 }
1293}
1294
1295void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1296 // Fall back to a safe state for the case when a setting for capture output
1297 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001298 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001299}
1300
1301void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1302 RuntimeSetting setting;
1303 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001304 if (aec_dump_) {
1305 aec_dump_->WriteRuntimeSetting(setting);
1306 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001307 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001308 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001309 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001310 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001311 if (submodules_.render_pre_processor) {
1312 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001313 }
1314 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001315 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001316 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001317 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001318 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001319 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001320 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001321 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001322 break;
1323 }
1324 }
1325}
1326
peah9e6a2902017-05-15 07:19:21 -07001327void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001328 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001329
saza1d600522019-10-18 13:29:43 +02001330 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001331 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1332 num_reverse_channels(),
1333 &aecm_render_queue_buffer_);
1334 RTC_DCHECK(aecm_render_signal_queue_);
1335 // Insert the samples into the queue.
1336 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1337 // The data queue is full and needs to be emptied.
1338 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001339
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001340 // Retry the insert (should always work).
1341 bool result =
1342 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1343 RTC_DCHECK(result);
1344 }
peah764e3642016-10-22 05:04:30 -07001345 }
peah701d6282016-10-25 05:42:20 -07001346
Per Åhgren0695df12020-01-13 14:43:13 +01001347 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001348 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001349 // Insert the samples into the queue.
1350 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1351 // The data queue is full and needs to be emptied.
1352 EmptyQueuedRenderAudio();
1353
1354 // Retry the insert (should always work).
1355 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1356 RTC_DCHECK(result);
1357 }
1358 }
peah9e6a2902017-05-15 07:19:21 -07001359}
ivoc9f4a4a02016-10-28 05:39:16 -07001360
peah9e6a2902017-05-15 07:19:21 -07001361void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001362 if (submodules_.echo_detector) {
1363 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1364 RTC_DCHECK(red_render_signal_queue_);
1365 // Insert the samples into the queue.
1366 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1367 // The data queue is full and needs to be emptied.
1368 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001369
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001370 // Retry the insert (should always work).
1371 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1372 RTC_DCHECK(result);
1373 }
ivoc9f4a4a02016-10-28 05:39:16 -07001374 }
peah764e3642016-10-22 05:04:30 -07001375}
1376
1377void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001378 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001379 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001380
ivoc9f4a4a02016-10-28 05:39:16 -07001381 const size_t new_red_render_queue_element_max_size =
1382 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1383
peaha0624602016-10-25 04:45:24 -07001384 // Reallocate the queues if the queue item sizes are too small to fit the
1385 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001386
1387 if (agc_render_queue_element_max_size_ <
1388 new_agc_render_queue_element_max_size) {
1389 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1390
1391 std::vector<int16_t> template_queue_element(
1392 agc_render_queue_element_max_size_);
1393
1394 agc_render_signal_queue_.reset(
1395 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1396 kMaxNumFramesToBuffer, template_queue_element,
1397 RenderQueueItemVerifier<int16_t>(
1398 agc_render_queue_element_max_size_)));
1399
1400 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1401 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1402 } else {
1403 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001404 }
ivoc9f4a4a02016-10-28 05:39:16 -07001405
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001406 if (submodules_.echo_detector) {
1407 if (red_render_queue_element_max_size_ <
1408 new_red_render_queue_element_max_size) {
1409 red_render_queue_element_max_size_ =
1410 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001411
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001412 std::vector<float> template_queue_element(
1413 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001414
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001415 red_render_signal_queue_.reset(
1416 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1417 kMaxNumFramesToBuffer, template_queue_element,
1418 RenderQueueItemVerifier<float>(
1419 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001420
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001421 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1422 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1423 } else {
1424 red_render_signal_queue_->Clear();
1425 }
ivoc9f4a4a02016-10-28 05:39:16 -07001426 }
peah764e3642016-10-22 05:04:30 -07001427}
1428
1429void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001430 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001431 EmptyQueuedRenderAudioLocked();
1432}
1433
1434void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001435 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001436 RTC_DCHECK(aecm_render_signal_queue_);
1437 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001438 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001439 aecm_capture_queue_buffer_);
1440 }
peah701d6282016-10-25 05:42:20 -07001441 }
1442
Per Åhgren0695df12020-01-13 14:43:13 +01001443 if (submodules_.gain_control) {
1444 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1445 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1446 }
peah764e3642016-10-22 05:04:30 -07001447 }
ivoc9f4a4a02016-10-28 05:39:16 -07001448
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001449 if (submodules_.echo_detector) {
1450 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1451 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1452 }
ivoc9f4a4a02016-10-28 05:39:16 -07001453 }
peah764e3642016-10-22 05:04:30 -07001454}
1455
Per Åhgren645f24c2020-03-16 12:06:02 +01001456int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1457 const StreamConfig& input_config,
1458 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001459 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001460 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001461
1462 RETURN_ON_ERR(
1463 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1464 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001465
Markus Handell0df0fae2020-07-07 15:53:34 +02001466 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001467 DenormalDisabler denormal_disabler(use_denormal_disabler_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001468
aleloi868f32f2017-05-23 07:20:05 -07001469 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001470 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001471 }
1472
Per Åhgren645f24c2020-03-16 12:06:02 +01001473 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001474 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001475 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001476 }
peahde65ddc2016-09-16 15:02:15 -07001477 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001478 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001479 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001480 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001481 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001482 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001483 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001484 }
Per Åhgrena1351272019-08-15 12:15:46 +02001485 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001486
aleloi868f32f2017-05-23 07:20:05 -07001487 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001488 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001489 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001490 return kNoError;
1491}
1492
peahde65ddc2016-09-16 15:02:15 -07001493int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001494 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001495 HandleCaptureRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001496 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001497
peahb58a1582016-03-15 09:34:24 -07001498 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001499 // TODO(peah): Simplify once the public API Enable functions for these
1500 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001501 RTC_DCHECK_LE(
1502 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001503
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001504 data_dumper_->DumpRaw(
1505 "applied_input_volume",
1506 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1507
peahde65ddc2016-09-16 15:02:15 -07001508 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001509 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001510
Per Åhgrenc0424252019-12-10 13:04:15 +01001511 if (submodules_.high_pass_filter &&
1512 config_.high_pass_filter.apply_in_full_band &&
1513 !constants_.enforce_split_band_hpf) {
1514 submodules_.high_pass_filter->Process(capture_buffer,
1515 /*use_split_band_data=*/false);
1516 }
1517
Per Åhgrendb5d7282021-03-15 16:31:04 +00001518 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001519 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001520 // When the input volume is emulated, retrieve the volume applied to the
1521 // input audio and notify that to APM so that the volume is passed to the
1522 // active AGC.
1523 set_stream_analog_level_locked(
1524 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001525 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001526 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1527 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001528 }
1529
Per Åhgren928146f2019-08-20 09:19:21 +02001530 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001531 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001532 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001533 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1534 if (log_rms) {
1535 capture_rms_interval_counter_ = 0;
1536 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001537 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1538 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1539 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1540 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001541 }
1542
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001543 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001544 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001545 *capture_.applied_input_volume);
1546 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001547
saza1d600522019-10-18 13:29:43 +02001548 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001549 // Determine if the echo path gain has changed by checking all the gains
1550 // applied before AEC.
1551 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001552
Per Åhgrendb5d7282021-03-15 16:31:04 +00001553 // Detect and flag any change in the capture level adjustment pre-gain.
1554 if (submodules_.capture_levels_adjuster) {
1555 float pre_adjustment_gain =
1556 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001557 capture_.echo_path_gain_change =
1558 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001559 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001560 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001561 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001562 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001563
1564 // Detect volume change.
1565 capture_.echo_path_gain_change =
1566 capture_.echo_path_gain_change ||
1567 (capture_.prev_playout_volume != capture_.playout_volume &&
1568 capture_.prev_playout_volume >= 0);
1569 capture_.prev_playout_volume = capture_.playout_volume;
1570
saza1d600522019-10-18 13:29:43 +02001571 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001572 }
1573
Per Åhgren0695df12020-01-13 14:43:13 +01001574 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001575 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001576 }
1577
Hanna Silend4dbe452022-11-30 15:16:21 +01001578 if (submodules_.gain_controller2 &&
1579 config_.gain_controller2.input_volume_controller.enabled) {
1580 // Expect the volume to be available if the input controller is enabled.
1581 RTC_DCHECK(capture_.applied_input_volume.has_value());
1582 if (capture_.applied_input_volume.has_value()) {
1583 submodules_.gain_controller2->Analyze(*capture_.applied_input_volume,
1584 *capture_buffer);
1585 }
1586 }
1587
peah2ace3f92016-09-10 04:42:27 -07001588 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1589 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001590 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1591 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001592 }
1593
Per Åhgrene14cb992019-11-27 09:34:22 +01001594 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1595 constants_.multi_channel_capture_support;
1596 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001597 // Force down-mixing of the number of channels after the detection of
1598 // capture signal saturation.
1599 // TODO(peah): Look into ensuring that this kind of tampering with the
1600 // AudioBuffer functionality should not be needed.
1601 capture_buffer->set_num_channels(1);
1602 }
1603
Per Åhgrenc0424252019-12-10 13:04:15 +01001604 if (submodules_.high_pass_filter &&
1605 (!config_.high_pass_filter.apply_in_full_band ||
1606 constants_.enforce_split_band_hpf)) {
1607 submodules_.high_pass_filter->Process(capture_buffer,
1608 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001609 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001610
Per Åhgren0695df12020-01-13 14:43:13 +01001611 if (submodules_.gain_control) {
1612 RETURN_ON_ERR(
1613 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1614 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001615
Per Åhgren8ad9e742020-01-30 07:40:58 +01001616 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1617 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1618 submodules_.noise_suppressor) {
1619 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001620 }
peahb58a1582016-03-15 09:34:24 -07001621
saza1d600522019-10-18 13:29:43 +02001622 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001623 // Ensure that the stream delay was set before the call to the
1624 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001625 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001626 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001627 }
1628
saza1d600522019-10-18 13:29:43 +02001629 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001630 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001631 }
peahe0eae3c2016-12-14 01:16:23 -08001632
saza1d600522019-10-18 13:29:43 +02001633 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001634 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001635 } else {
saza1d600522019-10-18 13:29:43 +02001636 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001637 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1638
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001639 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001640 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001641 }
1642
saza1d600522019-10-18 13:29:43 +02001643 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001644 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001645 }
1646
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001647 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001648 linear_aec_buffer && submodules_.noise_suppressor) {
1649 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001650 }
1651
saza1d600522019-10-18 13:29:43 +02001652 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001653 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001654 }
Per Åhgren46537a32017-06-07 10:08:10 +02001655 }
ivoc9f4a4a02016-10-28 05:39:16 -07001656
Per Åhgren0695df12020-01-13 14:43:13 +01001657 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001658 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001659
1660 absl::optional<int> new_digital_gain =
1661 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001662 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001663 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1664 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001665 }
Per Åhgren0695df12020-01-13 14:43:13 +01001666
1667 if (submodules_.gain_control) {
1668 // TODO(peah): Add reporting from AEC3 whether there is echo.
1669 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1670 capture_buffer, /*stream_has_echo*/ false));
1671 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001672
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001673 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1674 SampleRateSupportsMultiBand(
1675 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1676 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001677 }
1678
Per Åhgren19775cb2021-03-12 23:08:09 +00001679 if (capture_.capture_output_used) {
1680 if (capture_.capture_fullband_audio) {
1681 const auto& ec = submodules_.echo_controller;
1682 bool ec_active = ec ? ec->ActiveProcessing() : false;
1683 // Only update the fullband buffer if the multiband processing has changed
1684 // the signal. Keep the original signal otherwise.
1685 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1686 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1687 }
1688 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001689 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001690
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001691 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001692 submodules_.echo_detector->AnalyzeCaptureAudio(
1693 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1694 capture_buffer->num_frames()));
1695 }
1696
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001697 absl::optional<float> voice_probability;
1698 if (!!submodules_.voice_activity_detector) {
1699 voice_probability = submodules_.voice_activity_detector->Analyze(
1700 AudioFrameView<const float>(capture_buffer->channels(),
1701 capture_buffer->num_channels(),
1702 capture_buffer->num_frames()));
1703 }
1704
Per Åhgren19775cb2021-03-12 23:08:09 +00001705 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001706 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001707 switch (transient_suppressor_vad_mode_) {
1708 case TransientSuppressor::VadMode::kDefault:
1709 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001710 transient_suppressor_voice_probability =
1711 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001712 }
1713 break;
1714 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001715 RTC_DCHECK(voice_probability.has_value());
1716 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001717 break;
1718 case TransientSuppressor::VadMode::kNoVad:
1719 // The transient suppressor will ignore `voice_probability`.
1720 break;
1721 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001722 float delayed_voice_probability =
1723 submodules_.transient_suppressor->Suppress(
1724 capture_buffer->channels()[0], capture_buffer->num_frames(),
1725 capture_buffer->num_channels(),
1726 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1727 capture_buffer->num_frames_per_band(),
1728 /*reference_data=*/nullptr, /*reference_length=*/0,
1729 transient_suppressor_voice_probability, capture_.key_pressed);
1730 if (voice_probability.has_value()) {
1731 *voice_probability = delayed_voice_probability;
1732 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001733 }
1734
Artem Titov0b489302021-07-28 20:50:03 +02001735 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001736 if (submodules_.capture_analyzer) {
1737 submodules_.capture_analyzer->Analyze(capture_buffer);
1738 }
1739
1740 if (submodules_.gain_controller2) {
Hanna Silend4dbe452022-11-30 15:16:21 +01001741 // TODO(bugs.webrtc.org/7494): Let AGC2 detect applied input volume
1742 // changes.
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001743 submodules_.gain_controller2->Process(
1744 voice_probability, capture_.applied_input_volume_changed,
1745 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001746 }
1747
1748 if (submodules_.capture_post_processor) {
1749 submodules_.capture_post_processor->Process(capture_buffer);
1750 }
1751
Per Åhgren19775cb2021-03-12 23:08:09 +00001752 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1753 capture_buffer->channels_const()[0],
1754 capture_nonlocked_.capture_processing_format.num_frames()));
1755 if (log_rms) {
1756 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1757 RTC_HISTOGRAM_COUNTS_LINEAR(
1758 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1759 RmsLevel::kMinLevelDb, 64);
1760 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1761 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1762 }
1763
Per Åhgren19775cb2021-03-12 23:08:09 +00001764 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001765 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001766 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1767 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1768 capture_.stats.residual_echo_likelihood_recent_max =
1769 ed_metrics.echo_likelihood_recent_max;
1770 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001771 }
1772
Per Åhgren19775cb2021-03-12 23:08:09 +00001773 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001774 if (submodules_.echo_controller) {
1775 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1776 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1777 capture_.stats.echo_return_loss_enhancement =
1778 ec_metrics.echo_return_loss_enhancement;
1779 capture_.stats.delay_ms = ec_metrics.delay_ms;
1780 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001781
1782 // Pass stats for reporting.
1783 stats_reporter_.UpdateStatistics(capture_.stats);
1784
Alessio Bazzica533e4612022-09-07 16:58:33 +02001785 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001786 if (capture_.recommended_input_volume.has_value()) {
1787 recommended_input_volume_stats_reporter_.UpdateStatistics(
1788 *capture_.recommended_input_volume);
1789 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001790
Per Åhgrendb5d7282021-03-15 16:31:04 +00001791 if (submodules_.capture_levels_adjuster) {
1792 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1793 *capture_buffer);
1794
Per Åhgrendb5d7282021-03-15 16:31:04 +00001795 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001796 // If the input volume emulation is used, retrieve the recommended input
1797 // volume and set that to emulate the input volume on the next processed
1798 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001799 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001800 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001801 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001802 }
1803 }
1804
Per Åhgren55bc0772021-03-12 14:18:36 +00001805 // Temporarily set the output to zero after the stream has been unmuted
1806 // (capture output is again used). The purpose of this is to avoid clicks and
1807 // artefacts in the audio that results when the processing again is
1808 // reactivated after unmuting.
1809 if (!capture_.capture_output_used_last_frame &&
1810 capture_.capture_output_used) {
1811 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1812 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1813 capture_buffer->num_frames());
1814 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1815 }
1816 }
1817 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1818
peahdf3efa82015-11-28 12:35:15 -08001819 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001820
Alessio Bazzica533e4612022-09-07 16:58:33 +02001821 data_dumper_->DumpRaw("recommended_input_volume",
1822 capture_.recommended_input_volume.value_or(
1823 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001824
niklase@google.com470e71d2011-07-07 08:21:25 +00001825 return kNoError;
1826}
1827
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001828int AudioProcessingImpl::AnalyzeReverseStream(
1829 const float* const* data,
1830 const StreamConfig& reverse_config) {
1831 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001832 MutexLock lock(&mutex_render_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001833 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1834 RTC_DCHECK(data);
1835 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1836 RTC_DCHECK(data[i]);
1837 }
1838 RETURN_ON_ERR(
1839 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1840
1841 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001842 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1843}
1844
peahde65ddc2016-09-16 15:02:15 -07001845int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1846 const StreamConfig& input_config,
1847 const StreamConfig& output_config,
1848 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001849 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001850 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001851 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001852 RETURN_ON_ERR(
1853 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1854
1855 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001856
peahde65ddc2016-09-16 15:02:15 -07001857 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001858
Alex Loiko5825aa62017-12-18 16:02:40 +01001859 if (submodule_states_.RenderMultiBandProcessingActive() ||
1860 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001861 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1862 dest);
peah2ace3f92016-09-10 04:42:27 -07001863 } else if (formats_.api_format.reverse_input_stream() !=
1864 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001865 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1866 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001867 } else {
peahde65ddc2016-09-16 15:02:15 -07001868 CopyAudioIfNeeded(src, input_config.num_frames(),
1869 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001870 }
1871
1872 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001873}
1874
peahdf3efa82015-11-28 12:35:15 -08001875int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001876 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001877 const StreamConfig& input_config,
1878 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001879 if (aec_dump_) {
1880 const size_t channel_size =
1881 formats_.api_format.reverse_input_stream().num_frames();
1882 const size_t num_channels =
1883 formats_.api_format.reverse_input_stream().num_channels();
1884 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001885 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001886 }
peahdf3efa82015-11-28 12:35:15 -08001887 render_.render_audio->CopyFrom(src,
1888 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001889 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001890}
1891
Per Åhgren645f24c2020-03-16 12:06:02 +01001892int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1893 const StreamConfig& input_config,
1894 const StreamConfig& output_config,
1895 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001896 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001897
Markus Handell0df0fae2020-07-07 15:53:34 +02001898 MutexLock lock(&mutex_render_);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001899 DenormalDisabler denormal_disabler(use_denormal_disabler_);
1900
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001901 RETURN_ON_ERR(
1902 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1903 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001904
aleloi868f32f2017-05-23 07:20:05 -07001905 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001906 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1907 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001908 }
1909
Per Åhgren645f24c2020-03-16 12:06:02 +01001910 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001911 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001912 if (submodule_states_.RenderMultiBandProcessingActive() ||
1913 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001914 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001915 }
aluebsb0319552016-03-17 20:39:53 -07001916 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001917}
niklase@google.com470e71d2011-07-07 08:21:25 +00001918
peahde65ddc2016-09-16 15:02:15 -07001919int AudioProcessingImpl::ProcessRenderStreamLocked() {
1920 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001921
Alex Loiko73ec0192018-05-15 10:52:28 +02001922 HandleRenderRuntimeSettings();
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001923 DenormalDisabler denormal_disabler(use_denormal_disabler_);
Alex Loiko73ec0192018-05-15 10:52:28 +02001924
saza1d600522019-10-18 13:29:43 +02001925 if (submodules_.render_pre_processor) {
1926 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001927 }
1928
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001929 QueueNonbandedRenderAudio(render_buffer);
1930
peah2ace3f92016-09-10 04:42:27 -07001931 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001932 SampleRateSupportsMultiBand(
1933 formats_.render_processing_format.sample_rate_hz())) {
1934 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001935 }
1936
peahce4d9152017-05-19 01:28:05 -07001937 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1938 QueueBandedRenderAudio(render_buffer);
1939 }
1940
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001941 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001942 if (submodules_.echo_controller) {
1943 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001944 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001945
peah2ace3f92016-09-10 04:42:27 -07001946 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001947 SampleRateSupportsMultiBand(
1948 formats_.render_processing_format.sample_rate_hz())) {
1949 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001950 }
1951
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001952 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001953}
1954
1955int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001956 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001957 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001958 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001959
niklase@google.com470e71d2011-07-07 08:21:25 +00001960 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001961 delay = 0;
1962 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001963 }
1964
1965 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1966 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001967 delay = 500;
1968 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001969 }
1970
peahdf3efa82015-11-28 12:35:15 -08001971 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001972 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001973}
1974
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001975bool AudioProcessingImpl::GetLinearAecOutput(
1976 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001977 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001978 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1979
1980 RTC_DCHECK(linear_aec_buffer);
1981 if (linear_aec_buffer) {
1982 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1983 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1984
1985 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1986 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1987 rtc::ArrayView<const float> channel_view =
1988 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1989 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001990 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1991 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001992 }
1993 return true;
1994 }
1995 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001996 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001997 return false;
1998}
1999
niklase@google.com470e71d2011-07-07 08:21:25 +00002000int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08002001 // Used as callback from submodules, hence locking is not allowed.
2002 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00002003}
2004
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002005void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02002006 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08002007 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002008}
2009
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002010void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02002011 MutexLock lock_capture(&mutex_capture_);
2012 set_stream_analog_level_locked(level);
2013}
2014
2015void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002016 capture_.applied_input_volume_changed =
2017 capture_.applied_input_volume.has_value() &&
2018 *capture_.applied_input_volume != level;
2019 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002020
Alessio Bazzica533e4612022-09-07 16:58:33 +02002021 // Invalidate any previously recommended input volume which will be updated by
2022 // `ProcessStream()`.
2023 capture_.recommended_input_volume = absl::nullopt;
2024
Per Åhgren0e3198e2019-11-18 08:52:22 +01002025 if (submodules_.agc_manager) {
2026 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002027 return;
2028 }
2029
2030 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01002031 int error = submodules_.gain_control->set_stream_analog_level(level);
2032 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002033 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002034 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002035}
2036
2037int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002038 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002039 if (!capture_.applied_input_volume.has_value()) {
2040 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
2041 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02002042 // Input volume to recommend when `set_stream_analog_level()` is not called.
2043 constexpr int kFallBackInputVolume = 255;
2044 // When APM has no input volume to recommend, return the latest applied input
2045 // volume that has been observed in order to possibly produce no input volume
2046 // change. If no applied input volume has been observed, return a fall-back
2047 // value.
2048 return capture_.recommended_input_volume.value_or(
2049 capture_.applied_input_volume.value_or(kFallBackInputVolume));
2050}
2051
2052void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
2053 if (!capture_.applied_input_volume.has_value()) {
2054 // When `set_stream_analog_level()` is not called, no input level can be
2055 // recommended.
2056 capture_.recommended_input_volume = absl::nullopt;
2057 return;
2058 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002059
Per Åhgrendb5d7282021-03-15 16:31:04 +00002060 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002061 capture_.recommended_input_volume =
2062 submodules_.agc_manager->recommended_analog_level();
2063 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002064 }
2065
2066 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002067 capture_.recommended_input_volume =
2068 submodules_.gain_control->stream_analog_level();
2069 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002070 }
2071
Hanna Silend4dbe452022-11-30 15:16:21 +01002072 if (submodules_.gain_controller2 &&
2073 config_.gain_controller2.input_volume_controller.enabled) {
2074 capture_.recommended_input_volume =
Hanna Silen597a2ba2022-12-14 12:48:37 +01002075 submodules_.gain_controller2->recommended_input_volume();
Hanna Silend4dbe452022-11-30 15:16:21 +01002076 return;
2077 }
2078
Alessio Bazzica533e4612022-09-07 16:58:33 +02002079 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002080}
2081
Ali Tofigh1fa87c42022-07-25 22:07:08 +02002082bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
2083 int64_t max_log_size_bytes,
2084 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02002085 std::unique_ptr<AecDump> aec_dump =
2086 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02002087 if (!aec_dump) {
2088 return false;
2089 }
2090
2091 AttachAecDump(std::move(aec_dump));
2092 return true;
2093}
2094
2095bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
2096 int64_t max_log_size_bytes,
2097 rtc::TaskQueue* worker_queue) {
2098 std::unique_ptr<AecDump> aec_dump =
2099 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
2100 if (!aec_dump) {
2101 return false;
2102 }
2103
2104 AttachAecDump(std::move(aec_dump));
2105 return true;
2106}
2107
aleloi868f32f2017-05-23 07:20:05 -07002108void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
2109 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02002110 MutexLock lock_render(&mutex_render_);
2111 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002112
2113 // The previously attached AecDump will be destroyed with the
2114 // 'aec_dump' parameter, which is after locks are released.
2115 aec_dump_.swap(aec_dump);
2116 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02002117 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07002118}
2119
2120void AudioProcessingImpl::DetachAecDump() {
2121 // The d-tor of a task-queue based AecDump blocks until all pending
2122 // tasks are done. This construction avoids blocking while holding
2123 // the render and capture locks.
2124 std::unique_ptr<AecDump> aec_dump = nullptr;
2125 {
Markus Handell0df0fae2020-07-07 15:53:34 +02002126 MutexLock lock_render(&mutex_render_);
2127 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002128 aec_dump = std::move(aec_dump_);
2129 }
2130}
2131
peah8271d042016-11-22 07:24:52 -08002132AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002133 MutexLock lock_render(&mutex_render_);
2134 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08002135 return config_;
2136}
2137
peah2ace3f92016-09-10 04:42:27 -07002138bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
2139 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002140 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002141 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02002142 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00002143 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
2144 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00002145 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07002146}
2147
Per Åhgrenc0734712020-01-02 15:15:36 +01002148void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02002149 if (config_.transient_suppression.enabled &&
2150 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02002151 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01002152 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01002153 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02002154 submodule_creation_overrides_, transient_suppressor_vad_mode_,
2155 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2156 num_proc_channels());
2157 if (!submodules_.transient_suppressor) {
2158 RTC_LOG(LS_WARNING)
2159 << "No transient suppressor created (probably disabled)";
2160 }
2161 } else {
sazaaa42ecd2020-04-01 15:24:40 +02002162 submodules_.transient_suppressor->Initialize(
2163 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2164 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02002165 }
Per Åhgrenc0734712020-01-02 15:15:36 +01002166 } else {
2167 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002168 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002169}
2170
Per Åhgren0f14db22020-01-03 14:27:14 +01002171void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01002172 bool high_pass_filter_needed_by_aec =
2173 config_.echo_canceller.enabled &&
2174 config_.echo_canceller.enforce_high_pass_filtering &&
2175 !config_.echo_canceller.mobile_mode;
2176 if (submodule_states_.HighPassFilteringRequired() ||
2177 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01002178 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
2179 !constants_.enforce_split_band_hpf;
2180 int rate = use_full_band ? proc_fullband_sample_rate_hz()
2181 : proc_split_sample_rate_hz();
2182 size_t num_channels =
2183 use_full_band ? num_output_channels() : num_proc_channels();
2184
Per Åhgren0f14db22020-01-03 14:27:14 +01002185 if (!submodules_.high_pass_filter ||
2186 rate != submodules_.high_pass_filter->sample_rate_hz() ||
2187 forced_reset ||
2188 num_channels != submodules_.high_pass_filter->num_channels()) {
2189 submodules_.high_pass_filter.reset(
2190 new HighPassFilter(rate, num_channels));
2191 }
peah8271d042016-11-22 07:24:52 -08002192 } else {
saza1d600522019-10-18 13:29:43 +02002193 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08002194 }
2195}
alessiob3ec96df2017-05-22 06:57:06 -07002196
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02002197void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002198 bool use_echo_controller =
2199 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002200 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002201
2202 if (use_echo_controller) {
2203 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01002204 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01002205 submodules_.echo_controller = echo_control_factory_->Create(
2206 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01002207 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01002208 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002209 EchoCanceller3Config config;
2210 absl::optional<EchoCanceller3Config> multichannel_config;
2211 if (use_setup_specific_default_aec3_config_) {
2212 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
2213 }
saza1d600522019-10-18 13:29:43 +02002214 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002215 config, multichannel_config, proc_sample_rate_hz(),
2216 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01002217 }
2218
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002219 // Setup the storage for returning the linear AEC output.
2220 if (config_.echo_canceller.export_linear_aec_output) {
2221 constexpr int kLinearOutputRateHz = 16000;
2222 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
2223 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
2224 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
2225 } else {
2226 capture_.linear_aec_output.reset();
2227 }
2228
Per Åhgren200feba2019-03-06 04:16:46 +01002229 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002230
saza1d600522019-10-18 13:29:43 +02002231 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002232 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002233 return;
peahe0eae3c2016-12-14 01:16:23 -08002234 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002235
saza1d600522019-10-18 13:29:43 +02002236 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002237 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002238 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002239
2240 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02002241 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002242 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002243 return;
2244 }
2245
2246 if (config_.echo_canceller.mobile_mode) {
2247 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002248 size_t max_element_size =
2249 std::max(static_cast<size_t>(1),
2250 kMaxAllowedValuesOfSamplesPerBand *
2251 EchoControlMobileImpl::NumCancellersRequired(
2252 num_output_channels(), num_reverse_channels()));
2253
2254 std::vector<int16_t> template_queue_element(max_element_size);
2255
2256 aecm_render_signal_queue_.reset(
2257 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2258 kMaxNumFramesToBuffer, template_queue_element,
2259 RenderQueueItemVerifier<int16_t>(max_element_size)));
2260
2261 aecm_render_queue_buffer_.resize(max_element_size);
2262 aecm_capture_queue_buffer_.resize(max_element_size);
2263
saza1d600522019-10-18 13:29:43 +02002264 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002265
saza1d600522019-10-18 13:29:43 +02002266 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2267 num_reverse_channels(),
2268 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002269 return;
2270 }
2271
saza1d600522019-10-18 13:29:43 +02002272 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002273 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002274}
peah8271d042016-11-22 07:24:52 -08002275
Per Åhgren0695df12020-01-13 14:43:13 +01002276void AudioProcessingImpl::InitializeGainController1() {
Hanna Silend4dbe452022-11-30 15:16:21 +01002277 if (config_.gain_controller2.enabled &&
2278 config_.gain_controller2.input_volume_controller.enabled &&
2279 config_.gain_controller1.enabled &&
2280 (config_.gain_controller1.mode ==
2281 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
2282 config_.gain_controller1.analog_gain_controller.enabled)) {
2283 RTC_LOG(LS_ERROR) << "APM configuration not valid: "
2284 << "Multiple input volume controllers enabled.";
2285 }
2286
Per Åhgren0695df12020-01-13 14:43:13 +01002287 if (!config_.gain_controller1.enabled) {
2288 submodules_.agc_manager.reset();
2289 submodules_.gain_control.reset();
2290 return;
2291 }
2292
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002293 RTC_HISTOGRAM_BOOLEAN(
2294 "WebRTC.Audio.GainController.Analog.Enabled",
2295 config_.gain_controller1.analog_gain_controller.enabled);
2296
Per Åhgren0695df12020-01-13 14:43:13 +01002297 if (!submodules_.gain_control) {
2298 submodules_.gain_control.reset(new GainControlImpl());
2299 }
2300
2301 submodules_.gain_control->Initialize(num_proc_channels(),
2302 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002303 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2304 int error = submodules_.gain_control->set_mode(
2305 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2306 RTC_DCHECK_EQ(kNoError, error);
2307 error = submodules_.gain_control->set_target_level_dbfs(
2308 config_.gain_controller1.target_level_dbfs);
2309 RTC_DCHECK_EQ(kNoError, error);
2310 error = submodules_.gain_control->set_compression_gain_db(
2311 config_.gain_controller1.compression_gain_db);
2312 RTC_DCHECK_EQ(kNoError, error);
2313 error = submodules_.gain_control->enable_limiter(
2314 config_.gain_controller1.enable_limiter);
2315 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002316 constexpr int kAnalogLevelMinimum = 0;
2317 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002318 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002319 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002320 RTC_DCHECK_EQ(kNoError, error);
2321
2322 submodules_.agc_manager.reset();
2323 return;
2324 }
2325
2326 if (!submodules_.agc_manager.get() ||
2327 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002328 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002329 int stream_analog_level = -1;
2330 const bool re_creation = !!submodules_.agc_manager;
2331 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002332 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002333 }
2334 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002335 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002336 if (re_creation) {
2337 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2338 }
2339 }
2340 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002341 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002342 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2343 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002344}
2345
Alessio Bazzica38901042021-10-14 12:14:21 +02002346void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2347 if (!config_has_changed) {
2348 return;
2349 }
2350 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002351 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002352 return;
2353 }
2354 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002355 const bool use_internal_vad =
2356 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica3b51cd32022-12-14 16:36:10 +01002357 const bool input_volume_controller_config_overridden =
2358 gain_controller2_experiment_params_.has_value() &&
2359 gain_controller2_experiment_params_->agc2_config.has_value();
2360 const InputVolumeController::Config input_volume_controller_config =
2361 input_volume_controller_config_overridden
2362 ? gain_controller2_experiment_params_->agc2_config
2363 ->input_volume_controller
2364 : InputVolumeController::Config{};
Alessio Bazzica38901042021-10-14 12:14:21 +02002365 submodules_.gain_controller2 = std::make_unique<GainController2>(
Alessio Bazzica3b51cd32022-12-14 16:36:10 +01002366 config_.gain_controller2, input_volume_controller_config,
Alessio Bazzica2bfa7672022-12-09 14:16:30 +01002367 proc_fullband_sample_rate_hz(), num_proc_channels(), use_internal_vad);
Hanna Silend4dbe452022-11-30 15:16:21 +01002368 submodules_.gain_controller2->SetCaptureOutputUsed(
2369 capture_.capture_output_used);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002370 }
2371}
2372
2373void AudioProcessingImpl::InitializeVoiceActivityDetector(
2374 bool config_has_changed) {
2375 if (!config_has_changed) {
2376 return;
2377 }
2378 const bool use_vad =
2379 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2380 config_.gain_controller2.enabled &&
Alessio Bazzica17e14fd2022-12-07 17:08:45 +01002381 (config_.gain_controller2.adaptive_digital.enabled ||
2382 config_.gain_controller2.input_volume_controller.enabled);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002383 if (!use_vad) {
2384 submodules_.voice_activity_detector.reset();
2385 return;
2386 }
2387 if (!submodules_.voice_activity_detector || config_has_changed) {
2388 RTC_DCHECK(!!submodules_.gain_controller2);
2389 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2390 submodules_.voice_activity_detector =
2391 std::make_unique<VoiceActivityDetectorWrapper>(
Hanna Silen0c1ad292022-06-16 16:35:45 +02002392 submodules_.gain_controller2->GetCpuFeatures(),
2393 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002394 }
2395}
2396
saza0bad15f2019-10-16 11:46:11 +02002397void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002398 submodules_.noise_suppressor.reset();
2399
saza0bad15f2019-10-16 11:46:11 +02002400 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002401 auto map_level =
2402 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2403 using NoiseSuppresionConfig =
2404 AudioProcessing::Config::NoiseSuppression;
2405 switch (level) {
2406 case NoiseSuppresionConfig::kLow:
2407 return NsConfig::SuppressionLevel::k6dB;
2408 case NoiseSuppresionConfig::kModerate:
2409 return NsConfig::SuppressionLevel::k12dB;
2410 case NoiseSuppresionConfig::kHigh:
2411 return NsConfig::SuppressionLevel::k18dB;
2412 case NoiseSuppresionConfig::kVeryHigh:
2413 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002414 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002415 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002416 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002417
sazaaa42ecd2020-04-01 15:24:40 +02002418 NsConfig cfg;
2419 cfg.target_level = map_level(config_.noise_suppression.level);
2420 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2421 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002422 }
2423}
2424
Per Åhgrendb5d7282021-03-15 16:31:04 +00002425void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2426 if (config_.pre_amplifier.enabled ||
2427 config_.capture_level_adjustment.enabled) {
2428 // Use both the pre-amplifier and the capture level adjustment gains as
2429 // pre-gains.
2430 float pre_gain = 1.f;
2431 if (config_.pre_amplifier.enabled) {
2432 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2433 }
2434 if (config_.capture_level_adjustment.enabled) {
2435 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2436 }
2437
2438 submodules_.capture_levels_adjuster =
2439 std::make_unique<CaptureLevelsAdjuster>(
2440 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2441 config_.capture_level_adjustment.analog_mic_gain_emulation
2442 .initial_level,
2443 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002444 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002445 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002446 }
2447}
2448
ivoc9f4a4a02016-10-28 05:39:16 -07002449void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002450 if (submodules_.echo_detector) {
2451 submodules_.echo_detector->Initialize(
2452 proc_fullband_sample_rate_hz(), 1,
2453 formats_.render_processing_format.sample_rate_hz(), 1);
2454 }
ivoc9f4a4a02016-10-28 05:39:16 -07002455}
2456
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002457void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002458 if (submodules_.capture_analyzer) {
2459 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2460 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002461 }
2462}
2463
Sam Zackrisson0beac582017-09-25 12:04:02 +02002464void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002465 if (submodules_.capture_post_processor) {
2466 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002467 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002468 }
2469}
2470
Alex Loiko5825aa62017-12-18 16:02:40 +01002471void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002472 if (submodules_.render_pre_processor) {
2473 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002474 formats_.render_processing_format.sample_rate_hz(),
2475 formats_.render_processing_format.num_channels());
2476 }
2477}
2478
aleloi868f32f2017-05-23 07:20:05 -07002479void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2480 if (!aec_dump_) {
2481 return;
2482 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002483
2484 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002485 // TODO(peah): Add semicolon-separated concatenations of experiment
2486 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002487 if (!!submodules_.capture_post_processor) {
2488 experiments_description += "CapturePostProcessor;";
2489 }
2490 if (!!submodules_.render_pre_processor) {
2491 experiments_description += "RenderPreProcessor;";
2492 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002493 if (capture_nonlocked_.echo_controller_enabled) {
2494 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002495 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002496 if (config_.gain_controller2.enabled) {
2497 experiments_description += "GainController2;";
2498 }
aleloi868f32f2017-05-23 07:20:05 -07002499
2500 InternalAPMConfig apm_config;
2501
Per Åhgren200feba2019-03-06 04:16:46 +01002502 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002503 apm_config.aec_delay_agnostic_enabled = false;
2504 apm_config.aec_extended_filter_enabled = false;
2505 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002506
saza1d600522019-10-18 13:29:43 +02002507 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002508 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002509 submodules_.echo_control_mobile &&
2510 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002511 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002512 submodules_.echo_control_mobile
2513 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002514 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002515
Per Åhgren0695df12020-01-13 14:43:13 +01002516 apm_config.agc_enabled = !!submodules_.gain_control;
2517
2518 apm_config.agc_mode = submodules_.gain_control
2519 ? static_cast<int>(submodules_.gain_control->mode())
2520 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002521 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002522 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2523 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002524 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002525
2526 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2527
saza0bad15f2019-10-16 11:46:11 +02002528 apm_config.ns_enabled = config_.noise_suppression.enabled;
2529 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002530
2531 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002532 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002533 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002534 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2535 apm_config.pre_amplifier_fixed_gain_factor =
2536 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002537
2538 if (!forced && apm_config == apm_config_for_aec_dump_) {
2539 return;
2540 }
2541 aec_dump_->WriteConfig(apm_config);
2542 apm_config_for_aec_dump_ = apm_config;
2543}
2544
2545void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2546 const float* const* src) {
2547 RTC_DCHECK(aec_dump_);
2548 WriteAecDumpConfigMessage(false);
2549
2550 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2551 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2552 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002553 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002554 RecordAudioProcessingState();
2555}
2556
2557void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002558 const int16_t* const data,
2559 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002560 RTC_DCHECK(aec_dump_);
2561 WriteAecDumpConfigMessage(false);
2562
Per Åhgren645f24c2020-03-16 12:06:02 +01002563 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2564 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002565 RecordAudioProcessingState();
2566}
2567
2568void AudioProcessingImpl::RecordProcessedCaptureStream(
2569 const float* const* processed_capture_stream) {
2570 RTC_DCHECK(aec_dump_);
2571
2572 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2573 const size_t num_channels =
2574 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002575 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2576 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002577 aec_dump_->WriteCaptureStreamMessage();
2578}
2579
2580void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002581 const int16_t* const data,
2582 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002583 RTC_DCHECK(aec_dump_);
2584
Per Åhgren645f24c2020-03-16 12:06:02 +01002585 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002586 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002587 aec_dump_->WriteCaptureStreamMessage();
2588}
2589
2590void AudioProcessingImpl::RecordAudioProcessingState() {
2591 RTC_DCHECK(aec_dump_);
2592 AecDump::AudioProcessingState audio_proc_state;
2593 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002594 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002595 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002596 audio_proc_state.keypress = capture_.key_pressed;
2597 aec_dump_->AddAudioProcessingState(audio_proc_state);
2598}
2599
Per Åhgrenc0734712020-01-02 15:15:36 +01002600AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002601 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002602 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002603 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002604 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002605 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002606 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002607 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002608 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002609 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002610 prev_playout_volume(-1),
2611 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002612
2613AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2614
2615AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2616
2617AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2618
Per Åhgrencf4c8722019-12-30 14:32:14 +01002619AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2620 : stats_message_queue_(1) {}
2621
2622AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2623
2624AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002625 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002626 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2627 // If the message queue is full, return the cached stats.
2628 static_cast<void>(new_stats_available);
2629
2630 return cached_stats_;
2631}
2632
2633void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2634 const AudioProcessingStats& new_stats) {
2635 AudioProcessingStats stats_to_queue = new_stats;
2636 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2637 // If the message queue is full, discard the new stats.
2638 static_cast<void>(stats_message_passed);
2639}
2640
niklase@google.com470e71d2011-07-07 08:21:25 +00002641} // namespace webrtc