blob: 745e45ce72a3d3948de831f74efa420405840d41 [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 Bazzica3b51cd32022-12-14 16:36:10 +0100666 transient_suppressor_vad_mode_(
667 GetTransientSuppressorVadMode(gain_controller2_experiment_params_)),
Per Åhgren652ada52021-03-03 10:52:44 +0000668 capture_runtime_settings_(RuntimeSettingQueueSize()),
669 render_runtime_settings_(RuntimeSettingQueueSize()),
Alex Loiko73ec0192018-05-15 10:52:28 +0200670 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
671 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200672 echo_control_factory_(std::move(echo_control_factory)),
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100673 config_(AdjustConfig(config, gain_controller2_experiment_params_)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200674 submodule_states_(!!capture_post_processor,
675 !!render_pre_processor,
676 !!capture_analyzer),
saza1d600522019-10-18 13:29:43 +0200677 submodules_(std::move(capture_post_processor),
678 std::move(render_pre_processor),
679 std::move(echo_detector),
Per Åhgren3daedb62019-11-22 12:11:40 +0100680 std::move(capture_analyzer)),
Per Åhgren0695df12020-01-13 14:43:13 +0100681 constants_(!field_trial::IsEnabled(
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200682 "WebRTC-ApmExperimentalMultiChannelRenderKillSwitch"),
683 !field_trial::IsEnabled(
Per Åhgrenc0424252019-12-10 13:04:15 +0100684 "WebRTC-ApmExperimentalMultiChannelCaptureKillSwitch"),
Per Åhgren19775cb2021-03-12 23:08:09 +0000685 EnforceSplitBandHpf(),
Gustaf Ullberga399c822021-05-18 12:17:56 +0200686 MinimizeProcessingForUnusedOutput(),
687 field_trial::IsEnabled("WebRTC-TransientSuppressorForcedOff")),
Per Åhgren19775cb2021-03-12 23:08:09 +0000688 capture_(),
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +0200689 capture_nonlocked_(),
690 applied_input_volume_stats_reporter_(
691 InputVolumeStatsReporter::InputVolumeType::kApplied),
692 recommended_input_volume_stats_reporter_(
693 InputVolumeStatsReporter::InputVolumeType::kRecommended) {
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200694 RTC_LOG(LS_INFO) << "Injected APM submodules:"
Jonas Olssonb2b20312020-01-14 12:11:31 +0100695 "\nEcho control factory: "
696 << !!echo_control_factory_
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200697 << "\nEcho detector: " << !!submodules_.echo_detector
698 << "\nCapture analyzer: " << !!submodules_.capture_analyzer
699 << "\nCapture post processor: "
700 << !!submodules_.capture_post_processor
701 << "\nRender pre processor: "
702 << !!submodules_.render_pre_processor;
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100703 if (!DenormalDisabler::IsSupported()) {
704 RTC_LOG(LS_INFO) << "Denormal disabler unsupported";
705 }
Sam Zackrisson72cc71c2019-10-21 12:54:02 +0200706
Hanna Silena6574902022-11-30 16:59:05 +0100707 RTC_LOG(LS_INFO) << "AudioProcessing: " << config_.ToString();
708
Sam Zackrisson421c8592019-02-11 13:39:46 +0100709 // Mark Echo Controller enabled if a factory is injected.
710 capture_nonlocked_.echo_controller_enabled =
711 static_cast<bool>(echo_control_factory_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000712
Per Åhgren0ade9832020-09-01 23:57:20 +0200713 Initialize();
niklase@google.com470e71d2011-07-07 08:21:25 +0000714}
715
Per Åhgren0e3198e2019-11-18 08:52:22 +0100716AudioProcessingImpl::~AudioProcessingImpl() = default;
niklase@google.com470e71d2011-07-07 08:21:25 +0000717
niklase@google.com470e71d2011-07-07 08:21:25 +0000718int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800719 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200720 MutexLock lock_render(&mutex_render_);
721 MutexLock lock_capture(&mutex_capture_);
Per Åhgren0ade9832020-09-01 23:57:20 +0200722 InitializeLocked();
723 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +0000724}
725
Michael Graczyk86c6d332015-07-23 11:41:39 -0700726int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800727 // Run in a single-threaded manner during initialization.
Markus Handell0df0fae2020-07-07 15:53:34 +0200728 MutexLock lock_render(&mutex_render_);
729 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100730 InitializeLocked(processing_config);
731 return kNoError;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000732}
733
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100734void AudioProcessingImpl::MaybeInitializeRender(
735 const StreamConfig& input_config,
736 const StreamConfig& output_config) {
737 ProcessingConfig processing_config = formats_.api_format;
738 processing_config.reverse_input_stream() = input_config;
739 processing_config.reverse_output_stream() = output_config;
740
Oskar Sundbom4b276482019-05-23 14:28:00 +0200741 if (processing_config == formats_.api_format) {
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100742 return;
peah192164e2015-11-17 02:16:45 -0800743 }
peahdf3efa82015-11-28 12:35:15 -0800744
Markus Handell0df0fae2020-07-07 15:53:34 +0200745 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100746 InitializeLocked(processing_config);
peah192164e2015-11-17 02:16:45 -0800747}
748
Per Åhgren0ade9832020-09-01 23:57:20 +0200749void AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200750 UpdateActiveSubmoduleStates();
751
Per Åhgrend47941e2019-08-22 11:51:13 +0200752 const int render_audiobuffer_sample_rate_hz =
peahdf3efa82015-11-28 12:35:15 -0800753 formats_.api_format.reverse_output_stream().num_frames() == 0
Per Åhgrend47941e2019-08-22 11:51:13 +0200754 ? formats_.render_processing_format.sample_rate_hz()
755 : formats_.api_format.reverse_output_stream().sample_rate_hz();
peahdf3efa82015-11-28 12:35:15 -0800756 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
757 render_.render_audio.reset(new AudioBuffer(
Per Åhgrend47941e2019-08-22 11:51:13 +0200758 formats_.api_format.reverse_input_stream().sample_rate_hz(),
peahdf3efa82015-11-28 12:35:15 -0800759 formats_.api_format.reverse_input_stream().num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200760 formats_.render_processing_format.sample_rate_hz(),
peahde65ddc2016-09-16 15:02:15 -0700761 formats_.render_processing_format.num_channels(),
Per Åhgrend47941e2019-08-22 11:51:13 +0200762 render_audiobuffer_sample_rate_hz,
763 formats_.render_processing_format.num_channels()));
peah2ace3f92016-09-10 04:42:27 -0700764 if (formats_.api_format.reverse_input_stream() !=
765 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800766 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800767 formats_.api_format.reverse_input_stream().num_channels(),
768 formats_.api_format.reverse_input_stream().num_frames(),
769 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800770 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700771 } else {
peahdf3efa82015-11-28 12:35:15 -0800772 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700773 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700774 } else {
peahdf3efa82015-11-28 12:35:15 -0800775 render_.render_audio.reset(nullptr);
776 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700777 }
peahce4d9152017-05-19 01:28:05 -0700778
Per Åhgrend47941e2019-08-22 11:51:13 +0200779 capture_.capture_audio.reset(new AudioBuffer(
780 formats_.api_format.input_stream().sample_rate_hz(),
781 formats_.api_format.input_stream().num_channels(),
782 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
783 formats_.api_format.output_stream().num_channels(),
784 formats_.api_format.output_stream().sample_rate_hz(),
785 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100786 SetDownmixMethod(*capture_.capture_audio,
787 config_.pipeline.capture_downmix_method);
niklase@google.com470e71d2011-07-07 08:21:25 +0000788
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200789 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() <
790 formats_.api_format.output_stream().sample_rate_hz() &&
791 formats_.api_format.output_stream().sample_rate_hz() == 48000) {
792 capture_.capture_fullband_audio.reset(
793 new AudioBuffer(formats_.api_format.input_stream().sample_rate_hz(),
794 formats_.api_format.input_stream().num_channels(),
795 formats_.api_format.output_stream().sample_rate_hz(),
796 formats_.api_format.output_stream().num_channels(),
797 formats_.api_format.output_stream().sample_rate_hz(),
798 formats_.api_format.output_stream().num_channels()));
Alessio Bazzica504bd592022-12-01 13:26:26 +0100799 SetDownmixMethod(*capture_.capture_fullband_audio,
800 config_.pipeline.capture_downmix_method);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +0200801 } else {
802 capture_.capture_fullband_audio.reset();
803 }
804
peah764e3642016-10-22 05:04:30 -0700805 AllocateRenderQueue();
806
Per Åhgren0695df12020-01-13 14:43:13 +0100807 InitializeGainController1();
Per Åhgrenc0734712020-01-02 15:15:36 +0100808 InitializeTransientSuppressor();
Per Åhgren0f14db22020-01-03 14:27:14 +0100809 InitializeHighPassFilter(true);
ivoc9f4a4a02016-10-28 05:39:16 -0700810 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200811 InitializeEchoController();
Alessio Bazzica38901042021-10-14 12:14:21 +0200812 InitializeGainController2(/*config_has_changed=*/true);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200813 InitializeVoiceActivityDetector(/*config_has_changed=*/true);
saza0bad15f2019-10-16 11:46:11 +0200814 InitializeNoiseSuppressor();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200815 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200816 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100817 InitializePreProcessor();
Per Åhgrendb5d7282021-03-15 16:31:04 +0000818 InitializeCaptureLevelsAdjuster();
solenberg70f99032015-12-08 11:07:32 -0800819
aleloi868f32f2017-05-23 07:20:05 -0700820 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200821 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700822 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000823}
824
Sam Zackrisson5dd54822022-11-17 11:26:58 +0100825void AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200826 UpdateActiveSubmoduleStates();
827
peahdf3efa82015-11-28 12:35:15 -0800828 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000829
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200830 // Choose maximum rate to use for the split filtering.
831 RTC_DCHECK(config_.pipeline.maximum_internal_processing_rate == 48000 ||
832 config_.pipeline.maximum_internal_processing_rate == 32000);
833 int max_splitting_rate = 48000;
834 if (config_.pipeline.maximum_internal_processing_rate == 32000) {
835 max_splitting_rate = config_.pipeline.maximum_internal_processing_rate;
836 }
837
Per Åhgrenc8626b62019-08-23 15:49:51 +0200838 int capture_processing_rate = SuitableProcessRate(
peah423d2362016-04-09 16:06:52 -0700839 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700840 formats_.api_format.output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200841 max_splitting_rate,
peah2ace3f92016-09-10 04:42:27 -0700842 submodule_states_.CaptureMultiBandSubModulesActive() ||
843 submodule_states_.RenderMultiBandSubModulesActive());
Per Åhgrenc8626b62019-08-23 15:49:51 +0200844 RTC_DCHECK_NE(8000, capture_processing_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000845
peahde65ddc2016-09-16 15:02:15 -0700846 capture_nonlocked_.capture_processing_format =
847 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700848
peah2ce640f2017-04-07 03:57:48 -0700849 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200850 if (!capture_nonlocked_.echo_controller_enabled) {
Per Åhgrenc8626b62019-08-23 15:49:51 +0200851 render_processing_rate = SuitableProcessRate(
peah2ce640f2017-04-07 03:57:48 -0700852 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
853 formats_.api_format.reverse_output_stream().sample_rate_hz()),
Per Åhgrenfcbe4072019-09-15 00:27:58 +0200854 max_splitting_rate,
peah2ce640f2017-04-07 03:57:48 -0700855 submodule_states_.CaptureMultiBandSubModulesActive() ||
856 submodule_states_.RenderMultiBandSubModulesActive());
857 } else {
858 render_processing_rate = capture_processing_rate;
859 }
860
peahde65ddc2016-09-16 15:02:15 -0700861 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700862 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700863 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
864 kSampleRate8kHz) {
865 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000866 } else {
peahde65ddc2016-09-16 15:02:15 -0700867 render_processing_rate =
868 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000869 }
870
Per Åhgrenc8626b62019-08-23 15:49:51 +0200871 RTC_DCHECK_NE(8000, render_processing_rate);
872
peahce4d9152017-05-19 01:28:05 -0700873 if (submodule_states_.RenderMultiBandSubModulesActive()) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200874 // By default, downmix the render stream to mono for analysis. This has been
875 // demonstrated to work well for AEC in most practical scenarios.
Per Åhgrene14cb992019-11-27 09:34:22 +0100876 const bool multi_channel_render = config_.pipeline.multi_channel_render &&
877 constants_.multi_channel_render_support;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200878 int render_processing_num_channels =
Per Åhgrene14cb992019-11-27 09:34:22 +0100879 multi_channel_render
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200880 ? formats_.api_format.reverse_input_stream().num_channels()
881 : 1;
882 formats_.render_processing_format =
883 StreamConfig(render_processing_rate, render_processing_num_channels);
peahce4d9152017-05-19 01:28:05 -0700884 } else {
885 formats_.render_processing_format = StreamConfig(
886 formats_.api_format.reverse_input_stream().sample_rate_hz(),
887 formats_.api_format.reverse_input_stream().num_channels());
888 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000889
peahde65ddc2016-09-16 15:02:15 -0700890 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
891 kSampleRate32kHz ||
892 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
893 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800894 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000895 } else {
peahdf3efa82015-11-28 12:35:15 -0800896 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700897 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000898 }
899
Per Åhgren0ade9832020-09-01 23:57:20 +0200900 InitializeLocked();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000901}
902
peah88ac8532016-09-12 16:47:25 -0700903void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700904 // Run in a single-threaded manner when applying the settings.
Markus Handell0df0fae2020-07-07 15:53:34 +0200905 MutexLock lock_render(&mutex_render_);
906 MutexLock lock_capture(&mutex_capture_);
peah88ac8532016-09-12 16:47:25 -0700907
Hanna Silena6574902022-11-30 16:59:05 +0100908 const auto adjusted_config =
Alessio Bazzica3b51cd32022-12-14 16:36:10 +0100909 AdjustConfig(config, gain_controller2_experiment_params_);
Hanna Silena6574902022-11-30 16:59:05 +0100910 RTC_LOG(LS_INFO) << "AudioProcessing::ApplyConfig: "
911 << adjusted_config.ToString();
912
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200913 const bool pipeline_config_changed =
Per Åhgrene14cb992019-11-27 09:34:22 +0100914 config_.pipeline.multi_channel_render !=
Hanna Silena6574902022-11-30 16:59:05 +0100915 adjusted_config.pipeline.multi_channel_render ||
Per Åhgrene14cb992019-11-27 09:34:22 +0100916 config_.pipeline.multi_channel_capture !=
Hanna Silena6574902022-11-30 16:59:05 +0100917 adjusted_config.pipeline.multi_channel_capture ||
Per Åhgrenc0424252019-12-10 13:04:15 +0100918 config_.pipeline.maximum_internal_processing_rate !=
Alessio Bazzica504bd592022-12-01 13:26:26 +0100919 adjusted_config.pipeline.maximum_internal_processing_rate ||
920 config_.pipeline.capture_downmix_method !=
921 adjusted_config.pipeline.capture_downmix_method;
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200922
Per Åhgren200feba2019-03-06 04:16:46 +0100923 const bool aec_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100924 config_.echo_canceller.enabled !=
925 adjusted_config.echo_canceller.enabled ||
926 config_.echo_canceller.mobile_mode !=
927 adjusted_config.echo_canceller.mobile_mode;
Per Åhgren200feba2019-03-06 04:16:46 +0100928
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100929 const bool agc1_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100930 config_.gain_controller1 != adjusted_config.gain_controller1;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100931
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100932 const bool agc2_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100933 config_.gain_controller2 != adjusted_config.gain_controller2;
Per Åhgren2bd85ab2020-01-03 10:36:34 +0100934
saza0bad15f2019-10-16 11:46:11 +0200935 const bool ns_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100936 config_.noise_suppression.enabled !=
937 adjusted_config.noise_suppression.enabled ||
938 config_.noise_suppression.level !=
939 adjusted_config.noise_suppression.level;
saza0bad15f2019-10-16 11:46:11 +0200940
Per Åhgrenc0734712020-01-02 15:15:36 +0100941 const bool ts_config_changed = config_.transient_suppression.enabled !=
Hanna Silena6574902022-11-30 16:59:05 +0100942 adjusted_config.transient_suppression.enabled;
Per Åhgrenc0734712020-01-02 15:15:36 +0100943
Per Åhgren0f14db22020-01-03 14:27:14 +0100944 const bool pre_amplifier_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100945 config_.pre_amplifier.enabled != adjusted_config.pre_amplifier.enabled ||
Per Åhgren0f14db22020-01-03 14:27:14 +0100946 config_.pre_amplifier.fixed_gain_factor !=
Hanna Silena6574902022-11-30 16:59:05 +0100947 adjusted_config.pre_amplifier.fixed_gain_factor;
Per Åhgren0f14db22020-01-03 14:27:14 +0100948
Per Åhgrendb5d7282021-03-15 16:31:04 +0000949 const bool gain_adjustment_config_changed =
Hanna Silena6574902022-11-30 16:59:05 +0100950 config_.capture_level_adjustment !=
951 adjusted_config.capture_level_adjustment;
Per Åhgrendb5d7282021-03-15 16:31:04 +0000952
Hanna Silena6574902022-11-30 16:59:05 +0100953 config_ = adjusted_config;
Yves Gerey499bc6c2018-10-10 18:29:07 +0200954
Per Åhgren200feba2019-03-06 04:16:46 +0100955 if (aec_config_changed) {
956 InitializeEchoController();
957 }
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200958
saza0bad15f2019-10-16 11:46:11 +0200959 if (ns_config_changed) {
960 InitializeNoiseSuppressor();
961 }
Sam Zackrisson23513132019-01-11 15:10:32 +0100962
Per Åhgrenc0734712020-01-02 15:15:36 +0100963 if (ts_config_changed) {
964 InitializeTransientSuppressor();
965 }
966
Per Åhgren0f14db22020-01-03 14:27:14 +0100967 InitializeHighPassFilter(false);
peah8271d042016-11-22 07:24:52 -0800968
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100969 if (agc1_config_changed) {
Per Åhgren0695df12020-01-13 14:43:13 +0100970 InitializeGainController1();
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100971 }
972
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100973 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700974 if (!config_ok) {
Alessio Bazzica0c83e152020-10-14 12:49:54 +0200975 RTC_LOG(LS_ERROR)
976 << "Invalid Gain Controller 2 config; using the default config.";
alessiob3ec96df2017-05-22 06:57:06 -0700977 config_.gain_controller2 = AudioProcessing::Config::GainController2();
978 }
Per Åhgren0f14db22020-01-03 14:27:14 +0100979
Alessio Bazzica38901042021-10-14 12:14:21 +0200980 InitializeGainController2(agc2_config_changed);
Hanna Silen0c1ad292022-06-16 16:35:45 +0200981 InitializeVoiceActivityDetector(agc2_config_changed);
Per Åhgren0f14db22020-01-03 14:27:14 +0100982
Per Åhgrendb5d7282021-03-15 16:31:04 +0000983 if (pre_amplifier_config_changed || gain_adjustment_config_changed) {
984 InitializeCaptureLevelsAdjuster();
Per Åhgren0f14db22020-01-03 14:27:14 +0100985 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100986
Sam Zackrissonfeee1e42019-09-20 07:50:35 +0200987 // Reinitialization must happen after all submodule configuration to avoid
988 // additional reinitializations on the next capture / render processing call.
989 if (pipeline_config_changed) {
990 InitializeLocked(formats_.api_format);
991 }
peah88ac8532016-09-12 16:47:25 -0700992}
993
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200994void AudioProcessingImpl::OverrideSubmoduleCreationForTesting(
995 const ApmSubmoduleCreationOverrides& overrides) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200996 MutexLock lock(&mutex_capture_);
Sam Zackrissonb37e59d2020-04-27 08:39:33 +0200997 submodule_creation_overrides_ = overrides;
998}
999
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001000int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001001 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001002 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +00001003}
1004
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001005int AudioProcessingImpl::proc_fullband_sample_rate_hz() const {
1006 return capture_.capture_fullband_audio
1007 ? capture_.capture_fullband_audio->num_frames() * 100
1008 : capture_nonlocked_.capture_processing_format.sample_rate_hz();
1009}
1010
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001011int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -08001012 // Used as callback from submodules, hence locking is not allowed.
1013 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +00001014}
1015
Peter Kasting69558702016-01-12 16:26:35 -08001016size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001017 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -07001018 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001019}
1020
Peter Kasting69558702016-01-12 16:26:35 -08001021size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001022 // Used as callback from submodules, hence locking is not allowed.
1023 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001024}
1025
Peter Kasting69558702016-01-12 16:26:35 -08001026size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -08001027 // Used as callback from submodules, hence locking is not allowed.
Per Åhgrene14cb992019-11-27 09:34:22 +01001028 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1029 constants_.multi_channel_capture_support;
1030 if (capture_nonlocked_.echo_controller_enabled && !multi_channel_capture) {
Sam Zackrissonfeee1e42019-09-20 07:50:35 +02001031 return 1;
1032 }
1033 return num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -08001034}
1035
Peter Kasting69558702016-01-12 16:26:35 -08001036size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -08001037 // Used as callback from submodules, hence locking is not allowed.
1038 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +00001039}
1040
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001041void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001042 MutexLock lock(&mutex_capture_);
Per Åhgren0a144a72021-02-09 08:47:51 +01001043 HandleCaptureOutputUsedSetting(!muted);
1044}
1045
1046void AudioProcessingImpl::HandleCaptureOutputUsedSetting(
1047 bool capture_output_used) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001048 capture_.capture_output_used =
1049 capture_output_used || !constants_.minimize_processing_for_unused_output;
1050
saza1d600522019-10-18 13:29:43 +02001051 if (submodules_.agc_manager.get()) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001052 submodules_.agc_manager->HandleCaptureOutputUsedChange(
1053 capture_.capture_output_used);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001054 }
Per Åhgren652ada52021-03-03 10:52:44 +00001055 if (submodules_.echo_controller) {
1056 submodules_.echo_controller->SetCaptureOutputUsage(
1057 capture_.capture_output_used);
1058 }
Per Åhgren15179a92021-03-12 14:12:44 +00001059 if (submodules_.noise_suppressor) {
1060 submodules_.noise_suppressor->SetCaptureOutputUsage(
1061 capture_.capture_output_used);
1062 }
Hanna Silend4dbe452022-11-30 15:16:21 +01001063 if (submodules_.gain_controller2) {
1064 submodules_.gain_controller2->SetCaptureOutputUsed(
1065 capture_.capture_output_used);
1066 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001067}
1068
Alessio Bazzicac054e782018-04-16 12:10:09 +02001069void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Per Åhgren0a144a72021-02-09 08:47:51 +01001070 PostRuntimeSetting(setting);
1071}
1072
1073bool AudioProcessingImpl::PostRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +02001074 switch (setting.type()) {
1075 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001076 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Per Åhgren0a144a72021-02-09 08:47:51 +01001077 return render_runtime_settings_enqueuer_.Enqueue(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001078 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001079 case RuntimeSetting::Type::kCapturePostGain:
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001080 case RuntimeSetting::Type::kCaptureCompressionGain:
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001081 case RuntimeSetting::Type::kCaptureFixedPostGain:
Per Åhgren552d3e32020-08-12 08:46:47 +02001082 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001083 return capture_runtime_settings_enqueuer_.Enqueue(setting);
1084 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1085 bool enqueueing_successful;
1086 enqueueing_successful =
1087 capture_runtime_settings_enqueuer_.Enqueue(setting);
1088 enqueueing_successful =
1089 render_runtime_settings_enqueuer_.Enqueue(setting) &&
1090 enqueueing_successful;
1091 return enqueueing_successful;
1092 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001093 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001094 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001095 return true;
Alex Loiko73ec0192018-05-15 10:52:28 +02001096 }
1097 // The language allows the enum to have a non-enumerator
1098 // value. Check that this doesn't happen.
Artem Titovd3251962021-11-15 16:57:07 +01001099 RTC_DCHECK_NOTREACHED();
Per Åhgren0a144a72021-02-09 08:47:51 +01001100 return true;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001101}
1102
1103AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
1104 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001105 : runtime_settings_(*runtime_settings) {
1106 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +02001107}
1108
1109AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
1110 default;
1111
Per Åhgren0a144a72021-02-09 08:47:51 +01001112bool AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
Alessio Bazzicac054e782018-04-16 12:10:09 +02001113 RuntimeSetting setting) {
Per Åhgren652ada52021-03-03 10:52:44 +00001114 const bool successful_insert = runtime_settings_.Insert(&setting);
1115
1116 if (!successful_insert) {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001117 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
Alessio Bazzica0b10f462020-10-23 12:40:30 +02001118 }
Per Åhgren652ada52021-03-03 10:52:44 +00001119 return successful_insert;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001120}
andrew@webrtc.org17342e52014-02-12 22:28:31 +00001121
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001122void AudioProcessingImpl::MaybeInitializeCapture(
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001123 const StreamConfig& input_config,
1124 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001125 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001126 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001127 {
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001128 // Acquire the capture lock in order to access api_format. The lock is
1129 // released immediately, as we may need to acquire the render lock as part
1130 // of the conditional reinitialization.
Markus Handell0df0fae2020-07-07 15:53:34 +02001131 MutexLock lock_capture(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08001132 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001133 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +00001134 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001135
Oskar Sundbom4b276482019-05-23 14:28:00 +02001136 if (processing_config.input_stream() != input_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001137 reinitialization_required = true;
peahdf3efa82015-11-28 12:35:15 -08001138 }
Oskar Sundbom4b276482019-05-23 14:28:00 +02001139
1140 if (processing_config.output_stream() != output_config) {
Oskar Sundbom4b276482019-05-23 14:28:00 +02001141 reinitialization_required = true;
1142 }
1143
1144 if (reinitialization_required) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001145 MutexLock lock_render(&mutex_render_);
1146 MutexLock lock_capture(&mutex_capture_);
Sam Zackrisson5ed17522022-09-29 09:43:58 +02001147 // Reread the API format since the render format may have changed.
1148 processing_config = formats_.api_format;
1149 processing_config.input_stream() = input_config;
1150 processing_config.output_stream() = output_config;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001151 InitializeLocked(processing_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001152 }
Sam Zackrisson12e319a2020-01-03 14:54:20 +01001153}
1154
1155int AudioProcessingImpl::ProcessStream(const float* const* src,
1156 const StreamConfig& input_config,
1157 const StreamConfig& output_config,
1158 float* const* dest) {
1159 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001160 DenormalDisabler denormal_disabler;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001161 RETURN_ON_ERR(
1162 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1163 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001164
Markus Handell0df0fae2020-07-07 15:53:34 +02001165 MutexLock lock_capture(&mutex_capture_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001166
aleloi868f32f2017-05-23 07:20:05 -07001167 if (aec_dump_) {
1168 RecordUnprocessedCaptureStream(src);
1169 }
1170
peahdf3efa82015-11-28 12:35:15 -08001171 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001172 if (capture_.capture_fullband_audio) {
1173 capture_.capture_fullband_audio->CopyFrom(
1174 src, formats_.api_format.input_stream());
1175 }
peahde65ddc2016-09-16 15:02:15 -07001176 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001177 if (capture_.capture_fullband_audio) {
1178 capture_.capture_fullband_audio->CopyTo(formats_.api_format.output_stream(),
1179 dest);
1180 } else {
1181 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
1182 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001183
aleloi868f32f2017-05-23 07:20:05 -07001184 if (aec_dump_) {
1185 RecordProcessedCaptureStream(dest);
1186 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001187 return kNoError;
1188}
1189
Alex Loiko73ec0192018-05-15 10:52:28 +02001190void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +02001191 RuntimeSetting setting;
Per Åhgren652ada52021-03-03 10:52:44 +00001192 int num_settings_processed = 0;
Alex Loiko73ec0192018-05-15 10:52:28 +02001193 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001194 if (aec_dump_) {
1195 aec_dump_->WriteRuntimeSetting(setting);
1196 }
Alessio Bazzicac054e782018-04-16 12:10:09 +02001197 switch (setting.type()) {
1198 case RuntimeSetting::Type::kCapturePreGain:
Per Åhgrendb5d7282021-03-15 16:31:04 +00001199 if (config_.pre_amplifier.enabled ||
1200 config_.capture_level_adjustment.enabled) {
Alex Loikob5c9a792018-04-16 16:31:22 +02001201 float value;
1202 setting.GetFloat(&value);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001203 // If the pre-amplifier is used, apply the new gain to the
1204 // pre-amplifier regardless if the capture level adjustment is
1205 // activated. This approach allows both functionalities to coexist
1206 // until they have been properly merged.
1207 if (config_.pre_amplifier.enabled) {
1208 config_.pre_amplifier.fixed_gain_factor = value;
1209 } else {
1210 config_.capture_level_adjustment.pre_gain_factor = value;
1211 }
1212
1213 // Use both the pre-amplifier and the capture level adjustment gains
1214 // as pre-gains.
1215 float gain = 1.f;
1216 if (config_.pre_amplifier.enabled) {
1217 gain *= config_.pre_amplifier.fixed_gain_factor;
1218 }
1219 if (config_.capture_level_adjustment.enabled) {
1220 gain *= config_.capture_level_adjustment.pre_gain_factor;
1221 }
1222
1223 submodules_.capture_levels_adjuster->SetPreGain(gain);
1224 }
1225 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
1226 break;
1227 case RuntimeSetting::Type::kCapturePostGain:
1228 if (config_.capture_level_adjustment.enabled) {
1229 float value;
1230 setting.GetFloat(&value);
1231 config_.capture_level_adjustment.post_gain_factor = value;
1232 submodules_.capture_levels_adjuster->SetPostGain(
1233 config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02001234 }
1235 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +02001236 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001237 case RuntimeSetting::Type::kCaptureCompressionGain: {
Hanna Silend4dbe452022-11-30 15:16:21 +01001238 if (!submodules_.agc_manager &&
1239 !(submodules_.gain_controller2 &&
1240 config_.gain_controller2.input_volume_controller.enabled)) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01001241 float value;
1242 setting.GetFloat(&value);
1243 int int_value = static_cast<int>(value + .5f);
1244 config_.gain_controller1.compression_gain_db = int_value;
Per Åhgren0695df12020-01-13 14:43:13 +01001245 if (submodules_.gain_control) {
1246 int error =
1247 submodules_.gain_control->set_compression_gain_db(int_value);
1248 RTC_DCHECK_EQ(kNoError, error);
1249 }
Per Åhgren0e3198e2019-11-18 08:52:22 +01001250 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001251 break;
1252 }
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001253 case RuntimeSetting::Type::kCaptureFixedPostGain: {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01001254 if (submodules_.gain_controller2) {
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001255 float value;
1256 setting.GetFloat(&value);
1257 config_.gain_controller2.fixed_digital.gain_db = value;
Alessio Bazzica38901042021-10-14 12:14:21 +02001258 submodules_.gain_controller2->SetFixedGainDb(value);
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001259 }
1260 break;
1261 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001262 case RuntimeSetting::Type::kPlayoutVolumeChange: {
1263 int value;
1264 setting.GetInt(&value);
1265 capture_.playout_volume = value;
1266 break;
1267 }
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001268 case RuntimeSetting::Type::kPlayoutAudioDeviceChange:
Artem Titovd3251962021-11-15 16:57:07 +01001269 RTC_DCHECK_NOTREACHED();
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001270 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001271 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
Artem Titovd3251962021-11-15 16:57:07 +01001272 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001273 break;
1274 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001275 RTC_DCHECK_NOTREACHED();
Alex Loiko73ec0192018-05-15 10:52:28 +02001276 break;
Per Åhgren552d3e32020-08-12 08:46:47 +02001277 case RuntimeSetting::Type::kCaptureOutputUsed:
Per Åhgren0a144a72021-02-09 08:47:51 +01001278 bool value;
1279 setting.GetBool(&value);
1280 HandleCaptureOutputUsedSetting(value);
Per Åhgren552d3e32020-08-12 08:46:47 +02001281 break;
Alex Loiko73ec0192018-05-15 10:52:28 +02001282 }
Per Åhgren652ada52021-03-03 10:52:44 +00001283 ++num_settings_processed;
1284 }
1285
1286 if (num_settings_processed >= RuntimeSettingQueueSize()) {
1287 // Handle overrun of the runtime settings queue, which likely will has
1288 // caused settings to be discarded.
1289 HandleOverrunInCaptureRuntimeSettingsQueue();
1290 }
1291}
1292
1293void AudioProcessingImpl::HandleOverrunInCaptureRuntimeSettingsQueue() {
1294 // Fall back to a safe state for the case when a setting for capture output
1295 // usage setting has been missed.
Per Åhgren19775cb2021-03-12 23:08:09 +00001296 HandleCaptureOutputUsedSetting(/*capture_output_used=*/true);
Alex Loiko73ec0192018-05-15 10:52:28 +02001297}
1298
1299void AudioProcessingImpl::HandleRenderRuntimeSettings() {
1300 RuntimeSetting setting;
1301 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +02001302 if (aec_dump_) {
1303 aec_dump_->WriteRuntimeSetting(setting);
1304 }
Alex Loiko73ec0192018-05-15 10:52:28 +02001305 switch (setting.type()) {
Alessio Bazzica7c19a702019-11-07 13:22:00 +01001306 case RuntimeSetting::Type::kPlayoutAudioDeviceChange: // fall-through
Alessio Bazzica7587de42019-11-11 13:32:20 +01001307 case RuntimeSetting::Type::kPlayoutVolumeChange: // fall-through
Alex Loiko73ec0192018-05-15 10:52:28 +02001308 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
saza1d600522019-10-18 13:29:43 +02001309 if (submodules_.render_pre_processor) {
1310 submodules_.render_pre_processor->SetRuntimeSetting(setting);
Alex Loiko73ec0192018-05-15 10:52:28 +02001311 }
1312 break;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001313 case RuntimeSetting::Type::kCapturePreGain: // fall-through
Per Åhgrendb5d7282021-03-15 16:31:04 +00001314 case RuntimeSetting::Type::kCapturePostGain: // fall-through
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001315 case RuntimeSetting::Type::kCaptureCompressionGain: // fall-through
Per Åhgren6ee75fd2019-04-26 11:33:37 +02001316 case RuntimeSetting::Type::kCaptureFixedPostGain: // fall-through
Per Åhgren552d3e32020-08-12 08:46:47 +02001317 case RuntimeSetting::Type::kCaptureOutputUsed: // fall-through
Alessio Bazzica33444dc2018-04-20 13:16:55 +02001318 case RuntimeSetting::Type::kNotSpecified:
Artem Titovd3251962021-11-15 16:57:07 +01001319 RTC_DCHECK_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001320 break;
1321 }
1322 }
1323}
1324
peah9e6a2902017-05-15 07:19:21 -07001325void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
kwibergaf476c72016-11-28 15:21:39 -08001326 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -07001327
saza1d600522019-10-18 13:29:43 +02001328 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001329 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
1330 num_reverse_channels(),
1331 &aecm_render_queue_buffer_);
1332 RTC_DCHECK(aecm_render_signal_queue_);
1333 // Insert the samples into the queue.
1334 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
1335 // The data queue is full and needs to be emptied.
1336 EmptyQueuedRenderAudio();
peaha0624602016-10-25 04:45:24 -07001337
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001338 // Retry the insert (should always work).
1339 bool result =
1340 aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
1341 RTC_DCHECK(result);
1342 }
peah764e3642016-10-22 05:04:30 -07001343 }
peah701d6282016-10-25 05:42:20 -07001344
Per Åhgren0695df12020-01-13 14:43:13 +01001345 if (!submodules_.agc_manager && submodules_.gain_control) {
Per Åhgrene35b32c2019-11-22 18:22:04 +01001346 GainControlImpl::PackRenderAudioBuffer(*audio, &agc_render_queue_buffer_);
peah701d6282016-10-25 05:42:20 -07001347 // Insert the samples into the queue.
1348 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
1349 // The data queue is full and needs to be emptied.
1350 EmptyQueuedRenderAudio();
1351
1352 // Retry the insert (should always work).
1353 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
1354 RTC_DCHECK(result);
1355 }
1356 }
peah9e6a2902017-05-15 07:19:21 -07001357}
ivoc9f4a4a02016-10-28 05:39:16 -07001358
peah9e6a2902017-05-15 07:19:21 -07001359void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001360 if (submodules_.echo_detector) {
1361 PackRenderAudioBufferForEchoDetector(*audio, red_render_queue_buffer_);
1362 RTC_DCHECK(red_render_signal_queue_);
1363 // Insert the samples into the queue.
1364 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
1365 // The data queue is full and needs to be emptied.
1366 EmptyQueuedRenderAudio();
ivoc9f4a4a02016-10-28 05:39:16 -07001367
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001368 // Retry the insert (should always work).
1369 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
1370 RTC_DCHECK(result);
1371 }
ivoc9f4a4a02016-10-28 05:39:16 -07001372 }
peah764e3642016-10-22 05:04:30 -07001373}
1374
1375void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -07001376 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001377 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001378
ivoc9f4a4a02016-10-28 05:39:16 -07001379 const size_t new_red_render_queue_element_max_size =
1380 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1381
peaha0624602016-10-25 04:45:24 -07001382 // Reallocate the queues if the queue item sizes are too small to fit the
1383 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001384
1385 if (agc_render_queue_element_max_size_ <
1386 new_agc_render_queue_element_max_size) {
1387 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1388
1389 std::vector<int16_t> template_queue_element(
1390 agc_render_queue_element_max_size_);
1391
1392 agc_render_signal_queue_.reset(
1393 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1394 kMaxNumFramesToBuffer, template_queue_element,
1395 RenderQueueItemVerifier<int16_t>(
1396 agc_render_queue_element_max_size_)));
1397
1398 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1399 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1400 } else {
1401 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001402 }
ivoc9f4a4a02016-10-28 05:39:16 -07001403
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001404 if (submodules_.echo_detector) {
1405 if (red_render_queue_element_max_size_ <
1406 new_red_render_queue_element_max_size) {
1407 red_render_queue_element_max_size_ =
1408 new_red_render_queue_element_max_size;
ivoc9f4a4a02016-10-28 05:39:16 -07001409
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001410 std::vector<float> template_queue_element(
1411 red_render_queue_element_max_size_);
ivoc9f4a4a02016-10-28 05:39:16 -07001412
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001413 red_render_signal_queue_.reset(
1414 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1415 kMaxNumFramesToBuffer, template_queue_element,
1416 RenderQueueItemVerifier<float>(
1417 red_render_queue_element_max_size_)));
ivoc9f4a4a02016-10-28 05:39:16 -07001418
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001419 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1420 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1421 } else {
1422 red_render_signal_queue_->Clear();
1423 }
ivoc9f4a4a02016-10-28 05:39:16 -07001424 }
peah764e3642016-10-22 05:04:30 -07001425}
1426
1427void AudioProcessingImpl::EmptyQueuedRenderAudio() {
Markus Handell0df0fae2020-07-07 15:53:34 +02001428 MutexLock lock_capture(&mutex_capture_);
Markus Handell02ba1d22020-05-14 14:31:18 +02001429 EmptyQueuedRenderAudioLocked();
1430}
1431
1432void AudioProcessingImpl::EmptyQueuedRenderAudioLocked() {
saza1d600522019-10-18 13:29:43 +02001433 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001434 RTC_DCHECK(aecm_render_signal_queue_);
1435 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
saza1d600522019-10-18 13:29:43 +02001436 submodules_.echo_control_mobile->ProcessRenderAudio(
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001437 aecm_capture_queue_buffer_);
1438 }
peah701d6282016-10-25 05:42:20 -07001439 }
1440
Per Åhgren0695df12020-01-13 14:43:13 +01001441 if (submodules_.gain_control) {
1442 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1443 submodules_.gain_control->ProcessRenderAudio(agc_capture_queue_buffer_);
1444 }
peah764e3642016-10-22 05:04:30 -07001445 }
ivoc9f4a4a02016-10-28 05:39:16 -07001446
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001447 if (submodules_.echo_detector) {
1448 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1449 submodules_.echo_detector->AnalyzeRenderAudio(red_capture_queue_buffer_);
1450 }
ivoc9f4a4a02016-10-28 05:39:16 -07001451 }
peah764e3642016-10-22 05:04:30 -07001452}
1453
Per Åhgren645f24c2020-03-16 12:06:02 +01001454int AudioProcessingImpl::ProcessStream(const int16_t* const src,
1455 const StreamConfig& input_config,
1456 const StreamConfig& output_config,
Per Åhgrendc5522b2020-03-19 14:55:58 +01001457 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001458 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001459
1460 RETURN_ON_ERR(
1461 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1462 MaybeInitializeCapture(input_config, output_config);
Oskar Sundbom4b276482019-05-23 14:28:00 +02001463
Markus Handell0df0fae2020-07-07 15:53:34 +02001464 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001465 DenormalDisabler denormal_disabler;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466
aleloi868f32f2017-05-23 07:20:05 -07001467 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001468 RecordUnprocessedCaptureStream(src, input_config);
aleloi868f32f2017-05-23 07:20:05 -07001469 }
1470
Per Åhgren645f24c2020-03-16 12:06:02 +01001471 capture_.capture_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001472 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001473 capture_.capture_fullband_audio->CopyFrom(src, input_config);
Gustaf Ullberg3c918b12019-10-11 13:14:44 +02001474 }
peahde65ddc2016-09-16 15:02:15 -07001475 RETURN_ON_ERR(ProcessCaptureStreamLocked());
Gustaf Ullberg8675eee2019-10-09 13:34:36 +02001476 if (submodule_states_.CaptureMultiBandProcessingPresent() ||
Per Åhgrena1351272019-08-15 12:15:46 +02001477 submodule_states_.CaptureFullBandProcessingActive()) {
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001478 if (capture_.capture_fullband_audio) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001479 capture_.capture_fullband_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001480 } else {
Per Åhgren645f24c2020-03-16 12:06:02 +01001481 capture_.capture_audio->CopyTo(output_config, dest);
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001482 }
Per Åhgrena1351272019-08-15 12:15:46 +02001483 }
Per Åhgren645f24c2020-03-16 12:06:02 +01001484
aleloi868f32f2017-05-23 07:20:05 -07001485 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001486 RecordProcessedCaptureStream(dest, output_config);
aleloi868f32f2017-05-23 07:20:05 -07001487 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001488 return kNoError;
1489}
1490
peahde65ddc2016-09-16 15:02:15 -07001491int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Markus Handell02ba1d22020-05-14 14:31:18 +02001492 EmptyQueuedRenderAudioLocked();
Alex Loiko73ec0192018-05-15 10:52:28 +02001493 HandleCaptureRuntimeSettings();
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001494 DenormalDisabler denormal_disabler;
Alessio Bazzicac054e782018-04-16 12:10:09 +02001495
peahb58a1582016-03-15 09:34:24 -07001496 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001497 // TODO(peah): Simplify once the public API Enable functions for these
1498 // are moved to APM.
Sam Zackrisson308bc642019-12-23 10:22:08 +01001499 RTC_DCHECK_LE(
1500 !!submodules_.echo_controller + !!submodules_.echo_control_mobile, 1);
peahb58a1582016-03-15 09:34:24 -07001501
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001502 data_dumper_->DumpRaw(
1503 "applied_input_volume",
1504 capture_.applied_input_volume.value_or(kUnspecifiedDataDumpInputVolume));
1505
peahde65ddc2016-09-16 15:02:15 -07001506 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001507 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
ekmeyerson60d9b332015-08-14 10:35:55 -07001508
Per Åhgrenc0424252019-12-10 13:04:15 +01001509 if (submodules_.high_pass_filter &&
1510 config_.high_pass_filter.apply_in_full_band &&
1511 !constants_.enforce_split_band_hpf) {
1512 submodules_.high_pass_filter->Process(capture_buffer,
1513 /*use_split_band_data=*/false);
1514 }
1515
Per Åhgrendb5d7282021-03-15 16:31:04 +00001516 if (submodules_.capture_levels_adjuster) {
Per Åhgrendb5d7282021-03-15 16:31:04 +00001517 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001518 // When the input volume is emulated, retrieve the volume applied to the
1519 // input audio and notify that to APM so that the volume is passed to the
1520 // active AGC.
1521 set_stream_analog_level_locked(
1522 submodules_.capture_levels_adjuster->GetAnalogMicGainLevel());
Per Åhgrendb5d7282021-03-15 16:31:04 +00001523 }
Per Åhgrendb5d7282021-03-15 16:31:04 +00001524 submodules_.capture_levels_adjuster->ApplyPreLevelAdjustment(
1525 *capture_buffer);
Alex Loikob5c9a792018-04-16 16:31:22 +02001526 }
1527
Per Åhgren928146f2019-08-20 09:19:21 +02001528 capture_input_rms_.Analyze(rtc::ArrayView<const float>(
Per Åhgrend47941e2019-08-22 11:51:13 +02001529 capture_buffer->channels_const()[0],
henrik.lundin290d43a2016-11-29 08:09:09 -08001530 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001531 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1532 if (log_rms) {
1533 capture_rms_interval_counter_ = 0;
1534 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001535 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1536 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1537 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1538 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001539 }
1540
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001541 if (capture_.applied_input_volume.has_value()) {
Alessio Bazzicac34a8c12022-10-26 13:30:25 +00001542 applied_input_volume_stats_reporter_.UpdateStatistics(
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001543 *capture_.applied_input_volume);
1544 }
Hanna Silen5c7d5c92021-10-06 17:32:17 +02001545
saza1d600522019-10-18 13:29:43 +02001546 if (submodules_.echo_controller) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001547 // Determine if the echo path gain has changed by checking all the gains
1548 // applied before AEC.
1549 capture_.echo_path_gain_change = capture_.applied_input_volume_changed;
Per Åhgren88cf0502018-07-16 17:08:41 +02001550
Per Åhgrendb5d7282021-03-15 16:31:04 +00001551 // Detect and flag any change in the capture level adjustment pre-gain.
1552 if (submodules_.capture_levels_adjuster) {
1553 float pre_adjustment_gain =
1554 submodules_.capture_levels_adjuster->GetPreAdjustmentGain();
Per Åhgrend2650d12018-10-02 17:00:59 +02001555 capture_.echo_path_gain_change =
1556 capture_.echo_path_gain_change ||
Per Åhgrendb5d7282021-03-15 16:31:04 +00001557 (capture_.prev_pre_adjustment_gain != pre_adjustment_gain &&
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001558 capture_.prev_pre_adjustment_gain >= 0.0f);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001559 capture_.prev_pre_adjustment_gain = pre_adjustment_gain;
Per Åhgrend2650d12018-10-02 17:00:59 +02001560 }
Fredrik Hernqvistca362852019-05-10 15:50:02 +02001561
1562 // Detect volume change.
1563 capture_.echo_path_gain_change =
1564 capture_.echo_path_gain_change ||
1565 (capture_.prev_playout_volume != capture_.playout_volume &&
1566 capture_.prev_playout_volume >= 0);
1567 capture_.prev_playout_volume = capture_.playout_volume;
1568
saza1d600522019-10-18 13:29:43 +02001569 submodules_.echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001570 }
1571
Per Åhgren0695df12020-01-13 14:43:13 +01001572 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001573 submodules_.agc_manager->AnalyzePreProcess(*capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001574 }
1575
Hanna Silend4dbe452022-11-30 15:16:21 +01001576 if (submodules_.gain_controller2 &&
1577 config_.gain_controller2.input_volume_controller.enabled) {
1578 // Expect the volume to be available if the input controller is enabled.
1579 RTC_DCHECK(capture_.applied_input_volume.has_value());
1580 if (capture_.applied_input_volume.has_value()) {
1581 submodules_.gain_controller2->Analyze(*capture_.applied_input_volume,
1582 *capture_buffer);
1583 }
1584 }
1585
peah2ace3f92016-09-10 04:42:27 -07001586 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1587 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001588 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1589 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001590 }
1591
Per Åhgrene14cb992019-11-27 09:34:22 +01001592 const bool multi_channel_capture = config_.pipeline.multi_channel_capture &&
1593 constants_.multi_channel_capture_support;
1594 if (submodules_.echo_controller && !multi_channel_capture) {
peah522d71b2017-02-23 05:16:26 -08001595 // Force down-mixing of the number of channels after the detection of
1596 // capture signal saturation.
1597 // TODO(peah): Look into ensuring that this kind of tampering with the
1598 // AudioBuffer functionality should not be needed.
1599 capture_buffer->set_num_channels(1);
1600 }
1601
Per Åhgrenc0424252019-12-10 13:04:15 +01001602 if (submodules_.high_pass_filter &&
1603 (!config_.high_pass_filter.apply_in_full_band ||
1604 constants_.enforce_split_band_hpf)) {
1605 submodules_.high_pass_filter->Process(capture_buffer,
1606 /*use_split_band_data=*/true);
peah8271d042016-11-22 07:24:52 -08001607 }
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001608
Per Åhgren0695df12020-01-13 14:43:13 +01001609 if (submodules_.gain_control) {
1610 RETURN_ON_ERR(
1611 submodules_.gain_control->AnalyzeCaptureAudio(*capture_buffer));
1612 }
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001613
Per Åhgren8ad9e742020-01-30 07:40:58 +01001614 if ((!config_.noise_suppression.analyze_linear_aec_output_when_available ||
1615 !linear_aec_buffer || submodules_.echo_control_mobile) &&
1616 submodules_.noise_suppressor) {
1617 submodules_.noise_suppressor->Analyze(*capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001618 }
peahb58a1582016-03-15 09:34:24 -07001619
saza1d600522019-10-18 13:29:43 +02001620 if (submodules_.echo_control_mobile) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001621 // Ensure that the stream delay was set before the call to the
1622 // AECM ProcessCaptureAudio function.
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001623 if (!capture_.was_stream_delay_set) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001624 return AudioProcessing::kStreamParameterNotSetError;
Per Åhgrend0fa8202018-04-18 09:35:13 +02001625 }
1626
saza1d600522019-10-18 13:29:43 +02001627 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001628 submodules_.noise_suppressor->Process(capture_buffer);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001629 }
peahe0eae3c2016-12-14 01:16:23 -08001630
saza1d600522019-10-18 13:29:43 +02001631 RETURN_ON_ERR(submodules_.echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001632 capture_buffer, stream_delay_ms()));
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001633 } else {
saza1d600522019-10-18 13:29:43 +02001634 if (submodules_.echo_controller) {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001635 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1636
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01001637 if (capture_.was_stream_delay_set) {
saza1d600522019-10-18 13:29:43 +02001638 submodules_.echo_controller->SetAudioBufferDelay(stream_delay_ms());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001639 }
1640
saza1d600522019-10-18 13:29:43 +02001641 submodules_.echo_controller->ProcessCapture(
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001642 capture_buffer, linear_aec_buffer, capture_.echo_path_gain_change);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02001643 }
1644
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001645 if (config_.noise_suppression.analyze_linear_aec_output_when_available &&
Per Åhgren8ad9e742020-01-30 07:40:58 +01001646 linear_aec_buffer && submodules_.noise_suppressor) {
1647 submodules_.noise_suppressor->Analyze(*linear_aec_buffer);
Per Åhgren2e8e1c62019-12-20 00:42:22 +01001648 }
1649
saza1d600522019-10-18 13:29:43 +02001650 if (submodules_.noise_suppressor) {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01001651 submodules_.noise_suppressor->Process(capture_buffer);
saza0bad15f2019-10-16 11:46:11 +02001652 }
Per Åhgren46537a32017-06-07 10:08:10 +02001653 }
ivoc9f4a4a02016-10-28 05:39:16 -07001654
Per Åhgren0695df12020-01-13 14:43:13 +01001655 if (submodules_.agc_manager) {
Alessio Bazzicae56e3652022-09-06 17:36:26 +02001656 submodules_.agc_manager->Process(*capture_buffer);
Per Åhgren3daedb62019-11-22 12:11:40 +01001657
1658 absl::optional<int> new_digital_gain =
1659 submodules_.agc_manager->GetDigitalComressionGain();
Per Åhgren0695df12020-01-13 14:43:13 +01001660 if (new_digital_gain && submodules_.gain_control) {
Per Åhgren3daedb62019-11-22 12:11:40 +01001661 submodules_.gain_control->set_compression_gain_db(*new_digital_gain);
1662 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001663 }
Per Åhgren0695df12020-01-13 14:43:13 +01001664
1665 if (submodules_.gain_control) {
1666 // TODO(peah): Add reporting from AEC3 whether there is echo.
1667 RETURN_ON_ERR(submodules_.gain_control->ProcessCaptureAudio(
1668 capture_buffer, /*stream_has_echo*/ false));
1669 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001670
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001671 if (submodule_states_.CaptureMultiBandProcessingPresent() &&
1672 SampleRateSupportsMultiBand(
1673 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1674 capture_buffer->MergeFrequencyBands();
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02001675 }
1676
Per Åhgren19775cb2021-03-12 23:08:09 +00001677 if (capture_.capture_output_used) {
1678 if (capture_.capture_fullband_audio) {
1679 const auto& ec = submodules_.echo_controller;
1680 bool ec_active = ec ? ec->ActiveProcessing() : false;
1681 // Only update the fullband buffer if the multiband processing has changed
1682 // the signal. Keep the original signal otherwise.
1683 if (submodule_states_.CaptureMultiBandProcessingActive(ec_active)) {
1684 capture_buffer->CopyTo(capture_.capture_fullband_audio.get());
1685 }
1686 capture_buffer = capture_.capture_fullband_audio.get();
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001687 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001688
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001689 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001690 submodules_.echo_detector->AnalyzeCaptureAudio(
1691 rtc::ArrayView<const float>(capture_buffer->channels()[0],
1692 capture_buffer->num_frames()));
1693 }
1694
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001695 absl::optional<float> voice_probability;
1696 if (!!submodules_.voice_activity_detector) {
1697 voice_probability = submodules_.voice_activity_detector->Analyze(
1698 AudioFrameView<const float>(capture_buffer->channels(),
1699 capture_buffer->num_channels(),
1700 capture_buffer->num_frames()));
1701 }
1702
Per Åhgren19775cb2021-03-12 23:08:09 +00001703 if (submodules_.transient_suppressor) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001704 float transient_suppressor_voice_probability = 1.0f;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001705 switch (transient_suppressor_vad_mode_) {
1706 case TransientSuppressor::VadMode::kDefault:
1707 if (submodules_.agc_manager) {
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001708 transient_suppressor_voice_probability =
1709 submodules_.agc_manager->voice_probability();
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001710 }
1711 break;
1712 case TransientSuppressor::VadMode::kRnnVad:
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001713 RTC_DCHECK(voice_probability.has_value());
1714 transient_suppressor_voice_probability = *voice_probability;
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01001715 break;
1716 case TransientSuppressor::VadMode::kNoVad:
1717 // The transient suppressor will ignore `voice_probability`.
1718 break;
1719 }
Alessio Bazzicaac29b9c2022-06-20 17:52:43 +02001720 float delayed_voice_probability =
1721 submodules_.transient_suppressor->Suppress(
1722 capture_buffer->channels()[0], capture_buffer->num_frames(),
1723 capture_buffer->num_channels(),
1724 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1725 capture_buffer->num_frames_per_band(),
1726 /*reference_data=*/nullptr, /*reference_length=*/0,
1727 transient_suppressor_voice_probability, capture_.key_pressed);
1728 if (voice_probability.has_value()) {
1729 *voice_probability = delayed_voice_probability;
1730 }
Per Åhgren19775cb2021-03-12 23:08:09 +00001731 }
1732
Artem Titov0b489302021-07-28 20:50:03 +02001733 // Experimental APM sub-module that analyzes `capture_buffer`.
Per Åhgren19775cb2021-03-12 23:08:09 +00001734 if (submodules_.capture_analyzer) {
1735 submodules_.capture_analyzer->Analyze(capture_buffer);
1736 }
1737
1738 if (submodules_.gain_controller2) {
Hanna Silend4dbe452022-11-30 15:16:21 +01001739 // TODO(bugs.webrtc.org/7494): Let AGC2 detect applied input volume
1740 // changes.
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001741 submodules_.gain_controller2->Process(
1742 voice_probability, capture_.applied_input_volume_changed,
1743 capture_buffer);
Per Åhgren19775cb2021-03-12 23:08:09 +00001744 }
1745
1746 if (submodules_.capture_post_processor) {
1747 submodules_.capture_post_processor->Process(capture_buffer);
1748 }
1749
Per Åhgren19775cb2021-03-12 23:08:09 +00001750 capture_output_rms_.Analyze(rtc::ArrayView<const float>(
1751 capture_buffer->channels_const()[0],
1752 capture_nonlocked_.capture_processing_format.num_frames()));
1753 if (log_rms) {
1754 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1755 RTC_HISTOGRAM_COUNTS_LINEAR(
1756 "WebRTC.Audio.ApmCaptureOutputLevelAverageRms", levels.average, 1,
1757 RmsLevel::kMinLevelDb, 64);
1758 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1759 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1760 }
1761
Per Åhgren19775cb2021-03-12 23:08:09 +00001762 // Compute echo-detector stats.
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01001763 if (submodules_.echo_detector) {
Per Åhgren19775cb2021-03-12 23:08:09 +00001764 auto ed_metrics = submodules_.echo_detector->GetMetrics();
1765 capture_.stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1766 capture_.stats.residual_echo_likelihood_recent_max =
1767 ed_metrics.echo_likelihood_recent_max;
1768 }
Ilya Nikolaevskiy80979352021-03-11 11:40:46 +00001769 }
1770
Per Åhgren19775cb2021-03-12 23:08:09 +00001771 // Compute echo-controller stats.
Per Åhgrencf4c8722019-12-30 14:32:14 +01001772 if (submodules_.echo_controller) {
1773 auto ec_metrics = submodules_.echo_controller->GetMetrics();
1774 capture_.stats.echo_return_loss = ec_metrics.echo_return_loss;
1775 capture_.stats.echo_return_loss_enhancement =
1776 ec_metrics.echo_return_loss_enhancement;
1777 capture_.stats.delay_ms = ec_metrics.delay_ms;
1778 }
Per Åhgrencf4c8722019-12-30 14:32:14 +01001779
1780 // Pass stats for reporting.
1781 stats_reporter_.UpdateStatistics(capture_.stats);
1782
Alessio Bazzica533e4612022-09-07 16:58:33 +02001783 UpdateRecommendedInputVolumeLocked();
Alessio Bazzicafbe5d7c2022-10-27 00:05:32 +02001784 if (capture_.recommended_input_volume.has_value()) {
1785 recommended_input_volume_stats_reporter_.UpdateStatistics(
1786 *capture_.recommended_input_volume);
1787 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02001788
Per Åhgrendb5d7282021-03-15 16:31:04 +00001789 if (submodules_.capture_levels_adjuster) {
1790 submodules_.capture_levels_adjuster->ApplyPostLevelAdjustment(
1791 *capture_buffer);
1792
Per Åhgrendb5d7282021-03-15 16:31:04 +00001793 if (config_.capture_level_adjustment.analog_mic_gain_emulation.enabled) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001794 // If the input volume emulation is used, retrieve the recommended input
1795 // volume and set that to emulate the input volume on the next processed
1796 // audio frame.
Alessio Bazzica533e4612022-09-07 16:58:33 +02001797 RTC_DCHECK(capture_.recommended_input_volume.has_value());
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02001798 submodules_.capture_levels_adjuster->SetAnalogMicGainLevel(
Alessio Bazzica533e4612022-09-07 16:58:33 +02001799 *capture_.recommended_input_volume);
Per Åhgrendb5d7282021-03-15 16:31:04 +00001800 }
1801 }
1802
Per Åhgren55bc0772021-03-12 14:18:36 +00001803 // Temporarily set the output to zero after the stream has been unmuted
1804 // (capture output is again used). The purpose of this is to avoid clicks and
1805 // artefacts in the audio that results when the processing again is
1806 // reactivated after unmuting.
1807 if (!capture_.capture_output_used_last_frame &&
1808 capture_.capture_output_used) {
1809 for (size_t ch = 0; ch < capture_buffer->num_channels(); ++ch) {
1810 rtc::ArrayView<float> channel_view(capture_buffer->channels()[ch],
1811 capture_buffer->num_frames());
1812 std::fill(channel_view.begin(), channel_view.end(), 0.f);
1813 }
1814 }
1815 capture_.capture_output_used_last_frame = capture_.capture_output_used;
1816
peahdf3efa82015-11-28 12:35:15 -08001817 capture_.was_stream_delay_set = false;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001818
Alessio Bazzica533e4612022-09-07 16:58:33 +02001819 data_dumper_->DumpRaw("recommended_input_volume",
1820 capture_.recommended_input_volume.value_or(
1821 kUnspecifiedDataDumpInputVolume));
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02001822
niklase@google.com470e71d2011-07-07 08:21:25 +00001823 return kNoError;
1824}
1825
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001826int AudioProcessingImpl::AnalyzeReverseStream(
1827 const float* const* data,
1828 const StreamConfig& reverse_config) {
1829 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001830 MutexLock lock(&mutex_render_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001831 DenormalDisabler denormal_disabler;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001832 RTC_DCHECK(data);
1833 for (size_t i = 0; i < reverse_config.num_channels(); ++i) {
1834 RTC_DCHECK(data[i]);
1835 }
1836 RETURN_ON_ERR(
1837 AudioFormatValidityToErrorCode(ValidateAudioFormat(reverse_config)));
1838
1839 MaybeInitializeRender(reverse_config, reverse_config);
Gustaf Ullberg8c51f2e2019-10-22 15:21:31 +02001840 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
1841}
1842
peahde65ddc2016-09-16 15:02:15 -07001843int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1844 const StreamConfig& input_config,
1845 const StreamConfig& output_config,
1846 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001847 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
Markus Handell0df0fae2020-07-07 15:53:34 +02001848 MutexLock lock(&mutex_render_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001849 DenormalDisabler denormal_disabler;
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001850 RETURN_ON_ERR(
1851 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1852
1853 MaybeInitializeRender(input_config, output_config);
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001854
peahde65ddc2016-09-16 15:02:15 -07001855 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001856
Alex Loiko5825aa62017-12-18 16:02:40 +01001857 if (submodule_states_.RenderMultiBandProcessingActive() ||
1858 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001859 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1860 dest);
peah2ace3f92016-09-10 04:42:27 -07001861 } else if (formats_.api_format.reverse_input_stream() !=
1862 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001863 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1864 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001865 } else {
peahde65ddc2016-09-16 15:02:15 -07001866 CopyAudioIfNeeded(src, input_config.num_frames(),
1867 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001868 }
1869
1870 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001871}
1872
peahdf3efa82015-11-28 12:35:15 -08001873int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001874 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001875 const StreamConfig& input_config,
1876 const StreamConfig& output_config) {
aleloi868f32f2017-05-23 07:20:05 -07001877 if (aec_dump_) {
1878 const size_t channel_size =
1879 formats_.api_format.reverse_input_stream().num_frames();
1880 const size_t num_channels =
1881 formats_.api_format.reverse_input_stream().num_channels();
1882 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001883 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001884 }
peahdf3efa82015-11-28 12:35:15 -08001885 render_.render_audio->CopyFrom(src,
1886 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001887 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001888}
1889
Per Åhgren645f24c2020-03-16 12:06:02 +01001890int AudioProcessingImpl::ProcessReverseStream(const int16_t* const src,
1891 const StreamConfig& input_config,
1892 const StreamConfig& output_config,
1893 int16_t* const dest) {
Per Åhgren71652f42020-03-17 13:23:58 +01001894 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
Per Åhgren2507f8c2020-03-19 12:33:29 +01001895
Markus Handell0df0fae2020-07-07 15:53:34 +02001896 MutexLock lock(&mutex_render_);
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001897 DenormalDisabler denormal_disabler;
Alessio Bazzica0441bb62021-08-10 15:23:23 +02001898
Sam Zackrisson5dd54822022-11-17 11:26:58 +01001899 RETURN_ON_ERR(
1900 HandleUnsupportedAudioFormats(src, input_config, output_config, dest));
1901 MaybeInitializeRender(input_config, output_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001902
aleloi868f32f2017-05-23 07:20:05 -07001903 if (aec_dump_) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001904 aec_dump_->WriteRenderStreamMessage(src, input_config.num_frames(),
1905 input_config.num_channels());
aleloi868f32f2017-05-23 07:20:05 -07001906 }
1907
Per Åhgren645f24c2020-03-16 12:06:02 +01001908 render_.render_audio->CopyFrom(src, input_config);
peahde65ddc2016-09-16 15:02:15 -07001909 RETURN_ON_ERR(ProcessRenderStreamLocked());
Per Åhgrena1351272019-08-15 12:15:46 +02001910 if (submodule_states_.RenderMultiBandProcessingActive() ||
1911 submodule_states_.RenderFullBandProcessingActive()) {
Per Åhgren645f24c2020-03-16 12:06:02 +01001912 render_.render_audio->CopyTo(output_config, dest);
Per Åhgrena1351272019-08-15 12:15:46 +02001913 }
aluebsb0319552016-03-17 20:39:53 -07001914 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001915}
niklase@google.com470e71d2011-07-07 08:21:25 +00001916
peahde65ddc2016-09-16 15:02:15 -07001917int AudioProcessingImpl::ProcessRenderStreamLocked() {
1918 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001919
Alex Loiko73ec0192018-05-15 10:52:28 +02001920 HandleRenderRuntimeSettings();
Alessio Bazzica54cf7542022-12-20 16:22:44 +01001921 DenormalDisabler denormal_disabler;
Alex Loiko73ec0192018-05-15 10:52:28 +02001922
saza1d600522019-10-18 13:29:43 +02001923 if (submodules_.render_pre_processor) {
1924 submodules_.render_pre_processor->Process(render_buffer);
Alex Loiko5825aa62017-12-18 16:02:40 +01001925 }
1926
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001927 QueueNonbandedRenderAudio(render_buffer);
1928
peah2ace3f92016-09-10 04:42:27 -07001929 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001930 SampleRateSupportsMultiBand(
1931 formats_.render_processing_format.sample_rate_hz())) {
1932 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001933 }
1934
peahce4d9152017-05-19 01:28:05 -07001935 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1936 QueueBandedRenderAudio(render_buffer);
1937 }
1938
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001939 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
saza1d600522019-10-18 13:29:43 +02001940 if (submodules_.echo_controller) {
1941 submodules_.echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001942 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001943
peah2ace3f92016-09-10 04:42:27 -07001944 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001945 SampleRateSupportsMultiBand(
1946 formats_.render_processing_format.sample_rate_hz())) {
1947 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001948 }
1949
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001950 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001951}
1952
1953int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Markus Handell0df0fae2020-07-07 15:53:34 +02001954 MutexLock lock(&mutex_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001955 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001956 capture_.was_stream_delay_set = true;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001957
niklase@google.com470e71d2011-07-07 08:21:25 +00001958 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001959 delay = 0;
1960 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001961 }
1962
1963 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1964 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001965 delay = 500;
1966 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001967 }
1968
peahdf3efa82015-11-28 12:35:15 -08001969 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001970 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001971}
1972
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001973bool AudioProcessingImpl::GetLinearAecOutput(
1974 rtc::ArrayView<std::array<float, 160>> linear_output) const {
Markus Handell0df0fae2020-07-07 15:53:34 +02001975 MutexLock lock(&mutex_capture_);
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001976 AudioBuffer* linear_aec_buffer = capture_.linear_aec_output.get();
1977
1978 RTC_DCHECK(linear_aec_buffer);
1979 if (linear_aec_buffer) {
1980 RTC_DCHECK_EQ(1, linear_aec_buffer->num_bands());
1981 RTC_DCHECK_EQ(linear_output.size(), linear_aec_buffer->num_channels());
1982
1983 for (size_t ch = 0; ch < linear_aec_buffer->num_channels(); ++ch) {
1984 RTC_DCHECK_EQ(linear_output[ch].size(), linear_aec_buffer->num_frames());
1985 rtc::ArrayView<const float> channel_view =
1986 rtc::ArrayView<const float>(linear_aec_buffer->channels_const()[ch],
1987 linear_aec_buffer->num_frames());
Gustaf Ullberg45436972020-11-13 14:30:30 +01001988 FloatS16ToFloat(channel_view.data(), channel_view.size(),
1989 linear_output[ch].data());
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001990 }
1991 return true;
1992 }
1993 RTC_LOG(LS_ERROR) << "No linear AEC output available";
Artem Titovd3251962021-11-15 16:57:07 +01001994 RTC_DCHECK_NOTREACHED();
Per Åhgrenc20a19c2019-11-13 11:12:29 +01001995 return false;
1996}
1997
niklase@google.com470e71d2011-07-07 08:21:25 +00001998int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001999 // Used as callback from submodules, hence locking is not allowed.
2000 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00002001}
2002
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002003void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
Markus Handell0df0fae2020-07-07 15:53:34 +02002004 MutexLock lock(&mutex_capture_);
peahdf3efa82015-11-28 12:35:15 -08002005 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002006}
2007
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002008void AudioProcessingImpl::set_stream_analog_level(int level) {
Alessio Bazzica0c0c6022022-09-07 15:15:52 +02002009 MutexLock lock_capture(&mutex_capture_);
2010 set_stream_analog_level_locked(level);
2011}
2012
2013void AudioProcessingImpl::set_stream_analog_level_locked(int level) {
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002014 capture_.applied_input_volume_changed =
2015 capture_.applied_input_volume.has_value() &&
2016 *capture_.applied_input_volume != level;
2017 capture_.applied_input_volume = level;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002018
Alessio Bazzica533e4612022-09-07 16:58:33 +02002019 // Invalidate any previously recommended input volume which will be updated by
2020 // `ProcessStream()`.
2021 capture_.recommended_input_volume = absl::nullopt;
2022
Per Åhgren0e3198e2019-11-18 08:52:22 +01002023 if (submodules_.agc_manager) {
2024 submodules_.agc_manager->set_stream_analog_level(level);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002025 return;
2026 }
2027
2028 if (submodules_.gain_control) {
Per Åhgren0e3198e2019-11-18 08:52:22 +01002029 int error = submodules_.gain_control->set_stream_analog_level(level);
2030 RTC_DCHECK_EQ(kNoError, error);
Per Åhgrendb5d7282021-03-15 16:31:04 +00002031 return;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002032 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002033}
2034
2035int AudioProcessingImpl::recommended_stream_analog_level() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002036 MutexLock lock_capture(&mutex_capture_);
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002037 if (!capture_.applied_input_volume.has_value()) {
2038 RTC_LOG(LS_ERROR) << "set_stream_analog_level has not been called";
2039 }
Alessio Bazzica533e4612022-09-07 16:58:33 +02002040 // Input volume to recommend when `set_stream_analog_level()` is not called.
2041 constexpr int kFallBackInputVolume = 255;
2042 // When APM has no input volume to recommend, return the latest applied input
2043 // volume that has been observed in order to possibly produce no input volume
2044 // change. If no applied input volume has been observed, return a fall-back
2045 // value.
2046 return capture_.recommended_input_volume.value_or(
2047 capture_.applied_input_volume.value_or(kFallBackInputVolume));
2048}
2049
2050void AudioProcessingImpl::UpdateRecommendedInputVolumeLocked() {
2051 if (!capture_.applied_input_volume.has_value()) {
2052 // When `set_stream_analog_level()` is not called, no input level can be
2053 // recommended.
2054 capture_.recommended_input_volume = absl::nullopt;
2055 return;
2056 }
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002057
Per Åhgrendb5d7282021-03-15 16:31:04 +00002058 if (submodules_.agc_manager) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002059 capture_.recommended_input_volume =
2060 submodules_.agc_manager->recommended_analog_level();
2061 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002062 }
2063
2064 if (submodules_.gain_control) {
Alessio Bazzica533e4612022-09-07 16:58:33 +02002065 capture_.recommended_input_volume =
2066 submodules_.gain_control->stream_analog_level();
2067 return;
Per Åhgrendb5d7282021-03-15 16:31:04 +00002068 }
2069
Hanna Silend4dbe452022-11-30 15:16:21 +01002070 if (submodules_.gain_controller2 &&
2071 config_.gain_controller2.input_volume_controller.enabled) {
2072 capture_.recommended_input_volume =
Hanna Silen597a2ba2022-12-14 12:48:37 +01002073 submodules_.gain_controller2->recommended_input_volume();
Hanna Silend4dbe452022-11-30 15:16:21 +01002074 return;
2075 }
2076
Alessio Bazzica533e4612022-09-07 16:58:33 +02002077 capture_.recommended_input_volume = capture_.applied_input_volume;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01002078}
2079
Ali Tofigh1fa87c42022-07-25 22:07:08 +02002080bool AudioProcessingImpl::CreateAndAttachAecDump(absl::string_view file_name,
2081 int64_t max_log_size_bytes,
2082 rtc::TaskQueue* worker_queue) {
Ali Tofighf3592cb2022-08-16 14:44:38 +02002083 std::unique_ptr<AecDump> aec_dump =
2084 AecDumpFactory::Create(file_name, max_log_size_bytes, worker_queue);
Per Åhgren09e9a832020-05-11 11:03:47 +02002085 if (!aec_dump) {
2086 return false;
2087 }
2088
2089 AttachAecDump(std::move(aec_dump));
2090 return true;
2091}
2092
2093bool AudioProcessingImpl::CreateAndAttachAecDump(FILE* handle,
2094 int64_t max_log_size_bytes,
2095 rtc::TaskQueue* worker_queue) {
2096 std::unique_ptr<AecDump> aec_dump =
2097 AecDumpFactory::Create(handle, max_log_size_bytes, worker_queue);
2098 if (!aec_dump) {
2099 return false;
2100 }
2101
2102 AttachAecDump(std::move(aec_dump));
2103 return true;
2104}
2105
aleloi868f32f2017-05-23 07:20:05 -07002106void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
2107 RTC_DCHECK(aec_dump);
Markus Handell0df0fae2020-07-07 15:53:34 +02002108 MutexLock lock_render(&mutex_render_);
2109 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002110
2111 // The previously attached AecDump will be destroyed with the
2112 // 'aec_dump' parameter, which is after locks are released.
2113 aec_dump_.swap(aec_dump);
2114 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02002115 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07002116}
2117
2118void AudioProcessingImpl::DetachAecDump() {
2119 // The d-tor of a task-queue based AecDump blocks until all pending
2120 // tasks are done. This construction avoids blocking while holding
2121 // the render and capture locks.
2122 std::unique_ptr<AecDump> aec_dump = nullptr;
2123 {
Markus Handell0df0fae2020-07-07 15:53:34 +02002124 MutexLock lock_render(&mutex_render_);
2125 MutexLock lock_capture(&mutex_capture_);
aleloi868f32f2017-05-23 07:20:05 -07002126 aec_dump = std::move(aec_dump_);
2127 }
2128}
2129
peah8271d042016-11-22 07:24:52 -08002130AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
Markus Handell0df0fae2020-07-07 15:53:34 +02002131 MutexLock lock_render(&mutex_render_);
2132 MutexLock lock_capture(&mutex_capture_);
peah8271d042016-11-22 07:24:52 -08002133 return config_;
2134}
2135
peah2ace3f92016-09-10 04:42:27 -07002136bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
2137 return submodule_states_.Update(
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002138 config_.high_pass_filter.enabled, !!submodules_.echo_control_mobile,
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002139 !!submodules_.noise_suppressor, !!submodules_.gain_control,
Hanna Silen0c1ad292022-06-16 16:35:45 +02002140 !!submodules_.gain_controller2, !!submodules_.voice_activity_detector,
Per Åhgrendb5d7282021-03-15 16:31:04 +00002141 config_.pre_amplifier.enabled || config_.capture_level_adjustment.enabled,
2142 capture_nonlocked_.echo_controller_enabled,
Alessio Bazzica1db0a262022-02-15 14:18:09 +00002143 !!submodules_.transient_suppressor);
ekmeyerson60d9b332015-08-14 10:35:55 -07002144}
2145
Per Åhgrenc0734712020-01-02 15:15:36 +01002146void AudioProcessingImpl::InitializeTransientSuppressor() {
Gustaf Ullberga399c822021-05-18 12:17:56 +02002147 if (config_.transient_suppression.enabled &&
2148 !constants_.transient_suppressor_forced_off) {
sazaaa42ecd2020-04-01 15:24:40 +02002149 // Attempt to create a transient suppressor, if one is not already created.
Per Åhgrenc0734712020-01-02 15:15:36 +01002150 if (!submodules_.transient_suppressor) {
Alessio Bazzicaefbe3af2022-03-18 12:39:00 +01002151 submodules_.transient_suppressor = CreateTransientSuppressor(
Alessio Bazzica080006b2022-04-08 09:54:27 +02002152 submodule_creation_overrides_, transient_suppressor_vad_mode_,
2153 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2154 num_proc_channels());
2155 if (!submodules_.transient_suppressor) {
2156 RTC_LOG(LS_WARNING)
2157 << "No transient suppressor created (probably disabled)";
2158 }
2159 } else {
sazaaa42ecd2020-04-01 15:24:40 +02002160 submodules_.transient_suppressor->Initialize(
2161 proc_fullband_sample_rate_hz(), capture_nonlocked_.split_rate,
2162 num_proc_channels());
sazaaa42ecd2020-04-01 15:24:40 +02002163 }
Per Åhgrenc0734712020-01-02 15:15:36 +01002164 } else {
2165 submodules_.transient_suppressor.reset();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002166 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00002167}
2168
Per Åhgren0f14db22020-01-03 14:27:14 +01002169void AudioProcessingImpl::InitializeHighPassFilter(bool forced_reset) {
Per Åhgrenb8106462019-12-04 08:34:12 +01002170 bool high_pass_filter_needed_by_aec =
2171 config_.echo_canceller.enabled &&
2172 config_.echo_canceller.enforce_high_pass_filtering &&
2173 !config_.echo_canceller.mobile_mode;
2174 if (submodule_states_.HighPassFilteringRequired() ||
2175 high_pass_filter_needed_by_aec) {
Per Åhgrenc0424252019-12-10 13:04:15 +01002176 bool use_full_band = config_.high_pass_filter.apply_in_full_band &&
2177 !constants_.enforce_split_band_hpf;
2178 int rate = use_full_band ? proc_fullband_sample_rate_hz()
2179 : proc_split_sample_rate_hz();
2180 size_t num_channels =
2181 use_full_band ? num_output_channels() : num_proc_channels();
2182
Per Åhgren0f14db22020-01-03 14:27:14 +01002183 if (!submodules_.high_pass_filter ||
2184 rate != submodules_.high_pass_filter->sample_rate_hz() ||
2185 forced_reset ||
2186 num_channels != submodules_.high_pass_filter->num_channels()) {
2187 submodules_.high_pass_filter.reset(
2188 new HighPassFilter(rate, num_channels));
2189 }
peah8271d042016-11-22 07:24:52 -08002190 } else {
saza1d600522019-10-18 13:29:43 +02002191 submodules_.high_pass_filter.reset();
peah8271d042016-11-22 07:24:52 -08002192 }
2193}
alessiob3ec96df2017-05-22 06:57:06 -07002194
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02002195void AudioProcessingImpl::InitializeEchoController() {
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002196 bool use_echo_controller =
2197 echo_control_factory_ ||
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002198 (config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002199
2200 if (use_echo_controller) {
2201 // Create and activate the echo controller.
Per Åhgren200feba2019-03-06 04:16:46 +01002202 if (echo_control_factory_) {
Per Åhgren4e5c7092019-11-01 20:44:11 +01002203 submodules_.echo_controller = echo_control_factory_->Create(
2204 proc_sample_rate_hz(), num_reverse_channels(), num_proc_channels());
Gustaf Ullberg2c6f3732019-11-07 17:15:12 +01002205 RTC_DCHECK(submodules_.echo_controller);
Per Åhgren200feba2019-03-06 04:16:46 +01002206 } else {
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002207 EchoCanceller3Config config;
2208 absl::optional<EchoCanceller3Config> multichannel_config;
2209 if (use_setup_specific_default_aec3_config_) {
2210 multichannel_config = EchoCanceller3::CreateDefaultMultichannelConfig();
2211 }
saza1d600522019-10-18 13:29:43 +02002212 submodules_.echo_controller = std::make_unique<EchoCanceller3>(
Sam Zackrisson64cdcc02022-04-07 15:28:14 +02002213 config, multichannel_config, proc_sample_rate_hz(),
2214 num_reverse_channels(), num_proc_channels());
Per Åhgren200feba2019-03-06 04:16:46 +01002215 }
2216
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002217 // Setup the storage for returning the linear AEC output.
2218 if (config_.echo_canceller.export_linear_aec_output) {
2219 constexpr int kLinearOutputRateHz = 16000;
2220 capture_.linear_aec_output = std::make_unique<AudioBuffer>(
2221 kLinearOutputRateHz, num_proc_channels(), kLinearOutputRateHz,
2222 num_proc_channels(), kLinearOutputRateHz, num_proc_channels());
2223 } else {
2224 capture_.linear_aec_output.reset();
2225 }
2226
Per Åhgren200feba2019-03-06 04:16:46 +01002227 capture_nonlocked_.echo_controller_enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002228
saza1d600522019-10-18 13:29:43 +02002229 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002230 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002231 return;
peahe0eae3c2016-12-14 01:16:23 -08002232 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002233
saza1d600522019-10-18 13:29:43 +02002234 submodules_.echo_controller.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002235 capture_nonlocked_.echo_controller_enabled = false;
Per Åhgrenc20a19c2019-11-13 11:12:29 +01002236 capture_.linear_aec_output.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002237
2238 if (!config_.echo_canceller.enabled) {
saza1d600522019-10-18 13:29:43 +02002239 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002240 aecm_render_signal_queue_.reset();
Per Åhgrenf204faf2019-04-25 15:18:06 +02002241 return;
2242 }
2243
2244 if (config_.echo_canceller.mobile_mode) {
2245 // Create and activate AECM.
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002246 size_t max_element_size =
2247 std::max(static_cast<size_t>(1),
2248 kMaxAllowedValuesOfSamplesPerBand *
2249 EchoControlMobileImpl::NumCancellersRequired(
2250 num_output_channels(), num_reverse_channels()));
2251
2252 std::vector<int16_t> template_queue_element(max_element_size);
2253
2254 aecm_render_signal_queue_.reset(
2255 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
2256 kMaxNumFramesToBuffer, template_queue_element,
2257 RenderQueueItemVerifier<int16_t>(max_element_size)));
2258
2259 aecm_render_queue_buffer_.resize(max_element_size);
2260 aecm_capture_queue_buffer_.resize(max_element_size);
2261
saza1d600522019-10-18 13:29:43 +02002262 submodules_.echo_control_mobile.reset(new EchoControlMobileImpl());
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002263
saza1d600522019-10-18 13:29:43 +02002264 submodules_.echo_control_mobile->Initialize(proc_split_sample_rate_hz(),
2265 num_reverse_channels(),
2266 num_output_channels());
Per Åhgrenf204faf2019-04-25 15:18:06 +02002267 return;
2268 }
2269
saza1d600522019-10-18 13:29:43 +02002270 submodules_.echo_control_mobile.reset();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002271 aecm_render_signal_queue_.reset();
peahe0eae3c2016-12-14 01:16:23 -08002272}
peah8271d042016-11-22 07:24:52 -08002273
Per Åhgren0695df12020-01-13 14:43:13 +01002274void AudioProcessingImpl::InitializeGainController1() {
Hanna Silend4dbe452022-11-30 15:16:21 +01002275 if (config_.gain_controller2.enabled &&
2276 config_.gain_controller2.input_volume_controller.enabled &&
2277 config_.gain_controller1.enabled &&
2278 (config_.gain_controller1.mode ==
2279 AudioProcessing::Config::GainController1::kAdaptiveAnalog ||
2280 config_.gain_controller1.analog_gain_controller.enabled)) {
2281 RTC_LOG(LS_ERROR) << "APM configuration not valid: "
2282 << "Multiple input volume controllers enabled.";
2283 }
2284
Per Åhgren0695df12020-01-13 14:43:13 +01002285 if (!config_.gain_controller1.enabled) {
2286 submodules_.agc_manager.reset();
2287 submodules_.gain_control.reset();
2288 return;
2289 }
2290
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002291 RTC_HISTOGRAM_BOOLEAN(
2292 "WebRTC.Audio.GainController.Analog.Enabled",
2293 config_.gain_controller1.analog_gain_controller.enabled);
2294
Per Åhgren0695df12020-01-13 14:43:13 +01002295 if (!submodules_.gain_control) {
2296 submodules_.gain_control.reset(new GainControlImpl());
2297 }
2298
2299 submodules_.gain_control->Initialize(num_proc_channels(),
2300 proc_sample_rate_hz());
Per Åhgren0695df12020-01-13 14:43:13 +01002301 if (!config_.gain_controller1.analog_gain_controller.enabled) {
2302 int error = submodules_.gain_control->set_mode(
2303 Agc1ConfigModeToInterfaceMode(config_.gain_controller1.mode));
2304 RTC_DCHECK_EQ(kNoError, error);
2305 error = submodules_.gain_control->set_target_level_dbfs(
2306 config_.gain_controller1.target_level_dbfs);
2307 RTC_DCHECK_EQ(kNoError, error);
2308 error = submodules_.gain_control->set_compression_gain_db(
2309 config_.gain_controller1.compression_gain_db);
2310 RTC_DCHECK_EQ(kNoError, error);
2311 error = submodules_.gain_control->enable_limiter(
2312 config_.gain_controller1.enable_limiter);
2313 RTC_DCHECK_EQ(kNoError, error);
Hanna Silencd597042021-11-02 11:02:48 +01002314 constexpr int kAnalogLevelMinimum = 0;
2315 constexpr int kAnalogLevelMaximum = 255;
Per Åhgren0695df12020-01-13 14:43:13 +01002316 error = submodules_.gain_control->set_analog_level_limits(
Hanna Silencd597042021-11-02 11:02:48 +01002317 kAnalogLevelMinimum, kAnalogLevelMaximum);
Per Åhgren0695df12020-01-13 14:43:13 +01002318 RTC_DCHECK_EQ(kNoError, error);
2319
2320 submodules_.agc_manager.reset();
2321 return;
2322 }
2323
2324 if (!submodules_.agc_manager.get() ||
2325 submodules_.agc_manager->num_channels() !=
Alessio Bazzicabab12852022-02-03 16:30:25 +01002326 static_cast<int>(num_proc_channels())) {
Per Åhgren0695df12020-01-13 14:43:13 +01002327 int stream_analog_level = -1;
2328 const bool re_creation = !!submodules_.agc_manager;
2329 if (re_creation) {
Alessio Bazzicab190ca92022-09-05 16:04:31 +02002330 stream_analog_level = submodules_.agc_manager->recommended_analog_level();
Per Åhgren0695df12020-01-13 14:43:13 +01002331 }
2332 submodules_.agc_manager.reset(new AgcManagerDirect(
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002333 num_proc_channels(), config_.gain_controller1.analog_gain_controller));
Per Åhgren0695df12020-01-13 14:43:13 +01002334 if (re_creation) {
2335 submodules_.agc_manager->set_stream_analog_level(stream_analog_level);
2336 }
2337 }
2338 submodules_.agc_manager->Initialize();
Alessio Bazzica866caeb2022-07-19 12:18:38 +02002339 submodules_.agc_manager->SetupDigitalGainControl(*submodules_.gain_control);
Per Åhgren0a144a72021-02-09 08:47:51 +01002340 submodules_.agc_manager->HandleCaptureOutputUsedChange(
2341 capture_.capture_output_used);
Per Åhgren0695df12020-01-13 14:43:13 +01002342}
2343
Alessio Bazzica38901042021-10-14 12:14:21 +02002344void AudioProcessingImpl::InitializeGainController2(bool config_has_changed) {
2345 if (!config_has_changed) {
2346 return;
2347 }
2348 if (!config_.gain_controller2.enabled) {
Per Åhgren2bd85ab2020-01-03 10:36:34 +01002349 submodules_.gain_controller2.reset();
Alessio Bazzica38901042021-10-14 12:14:21 +02002350 return;
2351 }
2352 if (!submodules_.gain_controller2 || config_has_changed) {
Hanna Silen0c1ad292022-06-16 16:35:45 +02002353 const bool use_internal_vad =
2354 transient_suppressor_vad_mode_ != TransientSuppressor::VadMode::kRnnVad;
Alessio Bazzica3b51cd32022-12-14 16:36:10 +01002355 const bool input_volume_controller_config_overridden =
2356 gain_controller2_experiment_params_.has_value() &&
2357 gain_controller2_experiment_params_->agc2_config.has_value();
2358 const InputVolumeController::Config input_volume_controller_config =
2359 input_volume_controller_config_overridden
2360 ? gain_controller2_experiment_params_->agc2_config
2361 ->input_volume_controller
2362 : InputVolumeController::Config{};
Alessio Bazzica38901042021-10-14 12:14:21 +02002363 submodules_.gain_controller2 = std::make_unique<GainController2>(
Alessio Bazzica3b51cd32022-12-14 16:36:10 +01002364 config_.gain_controller2, input_volume_controller_config,
Alessio Bazzica2bfa7672022-12-09 14:16:30 +01002365 proc_fullband_sample_rate_hz(), num_proc_channels(), use_internal_vad);
Hanna Silend4dbe452022-11-30 15:16:21 +01002366 submodules_.gain_controller2->SetCaptureOutputUsed(
2367 capture_.capture_output_used);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002368 }
2369}
2370
2371void AudioProcessingImpl::InitializeVoiceActivityDetector(
2372 bool config_has_changed) {
2373 if (!config_has_changed) {
2374 return;
2375 }
2376 const bool use_vad =
2377 transient_suppressor_vad_mode_ == TransientSuppressor::VadMode::kRnnVad &&
2378 config_.gain_controller2.enabled &&
Alessio Bazzica17e14fd2022-12-07 17:08:45 +01002379 (config_.gain_controller2.adaptive_digital.enabled ||
2380 config_.gain_controller2.input_volume_controller.enabled);
Hanna Silen0c1ad292022-06-16 16:35:45 +02002381 if (!use_vad) {
2382 submodules_.voice_activity_detector.reset();
2383 return;
2384 }
2385 if (!submodules_.voice_activity_detector || config_has_changed) {
2386 RTC_DCHECK(!!submodules_.gain_controller2);
2387 // TODO(bugs.webrtc.org/13663): Cache CPU features in APM and use here.
2388 submodules_.voice_activity_detector =
2389 std::make_unique<VoiceActivityDetectorWrapper>(
Hanna Silen0c1ad292022-06-16 16:35:45 +02002390 submodules_.gain_controller2->GetCpuFeatures(),
2391 proc_fullband_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07002392 }
2393}
2394
saza0bad15f2019-10-16 11:46:11 +02002395void AudioProcessingImpl::InitializeNoiseSuppressor() {
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002396 submodules_.noise_suppressor.reset();
2397
saza0bad15f2019-10-16 11:46:11 +02002398 if (config_.noise_suppression.enabled) {
sazaaa42ecd2020-04-01 15:24:40 +02002399 auto map_level =
2400 [](AudioProcessing::Config::NoiseSuppression::Level level) {
2401 using NoiseSuppresionConfig =
2402 AudioProcessing::Config::NoiseSuppression;
2403 switch (level) {
2404 case NoiseSuppresionConfig::kLow:
2405 return NsConfig::SuppressionLevel::k6dB;
2406 case NoiseSuppresionConfig::kModerate:
2407 return NsConfig::SuppressionLevel::k12dB;
2408 case NoiseSuppresionConfig::kHigh:
2409 return NsConfig::SuppressionLevel::k18dB;
2410 case NoiseSuppresionConfig::kVeryHigh:
2411 return NsConfig::SuppressionLevel::k21dB;
sazaaa42ecd2020-04-01 15:24:40 +02002412 }
Karl Wibergc95b9392020-11-08 00:49:37 +01002413 RTC_CHECK_NOTREACHED();
sazaaa42ecd2020-04-01 15:24:40 +02002414 };
Per Åhgren0cbb58e2019-10-29 22:59:44 +01002415
sazaaa42ecd2020-04-01 15:24:40 +02002416 NsConfig cfg;
2417 cfg.target_level = map_level(config_.noise_suppression.level);
2418 submodules_.noise_suppressor = std::make_unique<NoiseSuppressor>(
2419 cfg, proc_sample_rate_hz(), num_proc_channels());
saza0bad15f2019-10-16 11:46:11 +02002420 }
2421}
2422
Per Åhgrendb5d7282021-03-15 16:31:04 +00002423void AudioProcessingImpl::InitializeCaptureLevelsAdjuster() {
2424 if (config_.pre_amplifier.enabled ||
2425 config_.capture_level_adjustment.enabled) {
2426 // Use both the pre-amplifier and the capture level adjustment gains as
2427 // pre-gains.
2428 float pre_gain = 1.f;
2429 if (config_.pre_amplifier.enabled) {
2430 pre_gain *= config_.pre_amplifier.fixed_gain_factor;
2431 }
2432 if (config_.capture_level_adjustment.enabled) {
2433 pre_gain *= config_.capture_level_adjustment.pre_gain_factor;
2434 }
2435
2436 submodules_.capture_levels_adjuster =
2437 std::make_unique<CaptureLevelsAdjuster>(
2438 config_.capture_level_adjustment.analog_mic_gain_emulation.enabled,
2439 config_.capture_level_adjustment.analog_mic_gain_emulation
2440 .initial_level,
2441 pre_gain, config_.capture_level_adjustment.post_gain_factor);
Alex Loikob5c9a792018-04-16 16:31:22 +02002442 } else {
Per Åhgrendb5d7282021-03-15 16:31:04 +00002443 submodules_.capture_levels_adjuster.reset();
Alex Loikob5c9a792018-04-16 16:31:22 +02002444 }
2445}
2446
ivoc9f4a4a02016-10-28 05:39:16 -07002447void AudioProcessingImpl::InitializeResidualEchoDetector() {
Sam Zackrisson03cb7e52021-12-06 15:40:04 +01002448 if (submodules_.echo_detector) {
2449 submodules_.echo_detector->Initialize(
2450 proc_fullband_sample_rate_hz(), 1,
2451 formats_.render_processing_format.sample_rate_hz(), 1);
2452 }
ivoc9f4a4a02016-10-28 05:39:16 -07002453}
2454
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002455void AudioProcessingImpl::InitializeAnalyzer() {
saza1d600522019-10-18 13:29:43 +02002456 if (submodules_.capture_analyzer) {
2457 submodules_.capture_analyzer->Initialize(proc_fullband_sample_rate_hz(),
2458 num_proc_channels());
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002459 }
2460}
2461
Sam Zackrisson0beac582017-09-25 12:04:02 +02002462void AudioProcessingImpl::InitializePostProcessor() {
saza1d600522019-10-18 13:29:43 +02002463 if (submodules_.capture_post_processor) {
2464 submodules_.capture_post_processor->Initialize(
Gustaf Ullberg422b9e02019-10-09 13:02:14 +02002465 proc_fullband_sample_rate_hz(), num_proc_channels());
Sam Zackrisson0beac582017-09-25 12:04:02 +02002466 }
2467}
2468
Alex Loiko5825aa62017-12-18 16:02:40 +01002469void AudioProcessingImpl::InitializePreProcessor() {
saza1d600522019-10-18 13:29:43 +02002470 if (submodules_.render_pre_processor) {
2471 submodules_.render_pre_processor->Initialize(
Alex Loiko5825aa62017-12-18 16:02:40 +01002472 formats_.render_processing_format.sample_rate_hz(),
2473 formats_.render_processing_format.num_channels());
2474 }
2475}
2476
aleloi868f32f2017-05-23 07:20:05 -07002477void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
2478 if (!aec_dump_) {
2479 return;
2480 }
Per Åhgrenf204faf2019-04-25 15:18:06 +02002481
2482 std::string experiments_description = "";
aleloi868f32f2017-05-23 07:20:05 -07002483 // TODO(peah): Add semicolon-separated concatenations of experiment
2484 // descriptions for other submodules.
Sam Zackrisson701bd172020-02-18 14:50:28 +01002485 if (!!submodules_.capture_post_processor) {
2486 experiments_description += "CapturePostProcessor;";
2487 }
2488 if (!!submodules_.render_pre_processor) {
2489 experiments_description += "RenderPreProcessor;";
2490 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02002491 if (capture_nonlocked_.echo_controller_enabled) {
2492 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07002493 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02002494 if (config_.gain_controller2.enabled) {
2495 experiments_description += "GainController2;";
2496 }
aleloi868f32f2017-05-23 07:20:05 -07002497
2498 InternalAPMConfig apm_config;
2499
Per Åhgren200feba2019-03-06 04:16:46 +01002500 apm_config.aec_enabled = config_.echo_canceller.enabled;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002501 apm_config.aec_delay_agnostic_enabled = false;
2502 apm_config.aec_extended_filter_enabled = false;
2503 apm_config.aec_suppression_level = 0;
aleloi868f32f2017-05-23 07:20:05 -07002504
saza1d600522019-10-18 13:29:43 +02002505 apm_config.aecm_enabled = !!submodules_.echo_control_mobile;
aleloi868f32f2017-05-23 07:20:05 -07002506 apm_config.aecm_comfort_noise_enabled =
saza1d600522019-10-18 13:29:43 +02002507 submodules_.echo_control_mobile &&
2508 submodules_.echo_control_mobile->is_comfort_noise_enabled();
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002509 apm_config.aecm_routing_mode =
saza1d600522019-10-18 13:29:43 +02002510 submodules_.echo_control_mobile
2511 ? static_cast<int>(submodules_.echo_control_mobile->routing_mode())
Per Åhgrenb6e24d72019-04-29 12:14:50 +02002512 : 0;
aleloi868f32f2017-05-23 07:20:05 -07002513
Per Åhgren0695df12020-01-13 14:43:13 +01002514 apm_config.agc_enabled = !!submodules_.gain_control;
2515
2516 apm_config.agc_mode = submodules_.gain_control
2517 ? static_cast<int>(submodules_.gain_control->mode())
2518 : GainControl::kAdaptiveAnalog;
aleloi868f32f2017-05-23 07:20:05 -07002519 apm_config.agc_limiter_enabled =
Per Åhgren0695df12020-01-13 14:43:13 +01002520 submodules_.gain_control ? submodules_.gain_control->is_limiter_enabled()
2521 : false;
Per Åhgren0e3198e2019-11-18 08:52:22 +01002522 apm_config.noise_robust_agc_enabled = !!submodules_.agc_manager;
aleloi868f32f2017-05-23 07:20:05 -07002523
2524 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2525
saza0bad15f2019-10-16 11:46:11 +02002526 apm_config.ns_enabled = config_.noise_suppression.enabled;
2527 apm_config.ns_level = static_cast<int>(config_.noise_suppression.level);
aleloi868f32f2017-05-23 07:20:05 -07002528
2529 apm_config.transient_suppression_enabled =
Per Åhgrenc0734712020-01-02 15:15:36 +01002530 config_.transient_suppression.enabled;
aleloi868f32f2017-05-23 07:20:05 -07002531 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02002532 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
2533 apm_config.pre_amplifier_fixed_gain_factor =
2534 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07002535
2536 if (!forced && apm_config == apm_config_for_aec_dump_) {
2537 return;
2538 }
2539 aec_dump_->WriteConfig(apm_config);
2540 apm_config_for_aec_dump_ = apm_config;
2541}
2542
2543void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2544 const float* const* src) {
2545 RTC_DCHECK(aec_dump_);
2546 WriteAecDumpConfigMessage(false);
2547
2548 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2549 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2550 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002551 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002552 RecordAudioProcessingState();
2553}
2554
2555void AudioProcessingImpl::RecordUnprocessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002556 const int16_t* const data,
2557 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002558 RTC_DCHECK(aec_dump_);
2559 WriteAecDumpConfigMessage(false);
2560
Per Åhgren645f24c2020-03-16 12:06:02 +01002561 aec_dump_->AddCaptureStreamInput(data, config.num_channels(),
2562 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002563 RecordAudioProcessingState();
2564}
2565
2566void AudioProcessingImpl::RecordProcessedCaptureStream(
2567 const float* const* processed_capture_stream) {
2568 RTC_DCHECK(aec_dump_);
2569
2570 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2571 const size_t num_channels =
2572 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002573 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2574 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002575 aec_dump_->WriteCaptureStreamMessage();
2576}
2577
2578void AudioProcessingImpl::RecordProcessedCaptureStream(
Per Åhgren645f24c2020-03-16 12:06:02 +01002579 const int16_t* const data,
2580 const StreamConfig& config) {
aleloi868f32f2017-05-23 07:20:05 -07002581 RTC_DCHECK(aec_dump_);
2582
Per Åhgren645f24c2020-03-16 12:06:02 +01002583 aec_dump_->AddCaptureStreamOutput(data, config.num_channels(),
Per Åhgren088329f2020-03-18 21:59:52 +01002584 config.num_frames());
aleloi868f32f2017-05-23 07:20:05 -07002585 aec_dump_->WriteCaptureStreamMessage();
2586}
2587
2588void AudioProcessingImpl::RecordAudioProcessingState() {
2589 RTC_DCHECK(aec_dump_);
2590 AecDump::AudioProcessingState audio_proc_state;
2591 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
Per Åhgren62ea0aa2019-12-09 10:18:44 +01002592 audio_proc_state.drift = 0;
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002593 audio_proc_state.applied_input_volume = capture_.applied_input_volume;
aleloi868f32f2017-05-23 07:20:05 -07002594 audio_proc_state.keypress = capture_.key_pressed;
2595 aec_dump_->AddAudioProcessingState(audio_proc_state);
2596}
2597
Per Åhgrenc0734712020-01-02 15:15:36 +01002598AudioProcessingImpl::ApmCaptureState::ApmCaptureState()
Sam Zackrisson2d31aea2020-01-17 10:55:09 +01002599 : was_stream_delay_set(false),
Per Åhgren0a144a72021-02-09 08:47:51 +01002600 capture_output_used(true),
Per Åhgren55bc0772021-03-12 14:18:36 +00002601 capture_output_used_last_frame(true),
kwiberg83ffe452016-08-29 14:46:07 -07002602 key_pressed(false),
peahde65ddc2016-09-16 15:02:15 -07002603 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002604 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002605 echo_path_gain_change(false),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002606 prev_pre_adjustment_gain(-1.0f),
Fredrik Hernqvistca362852019-05-10 15:50:02 +02002607 playout_volume(-1),
Alessio Bazzicafcf1af32022-09-07 17:14:26 +02002608 prev_playout_volume(-1),
2609 applied_input_volume_changed(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002610
2611AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2612
2613AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2614
2615AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2616
Per Åhgrencf4c8722019-12-30 14:32:14 +01002617AudioProcessingImpl::ApmStatsReporter::ApmStatsReporter()
2618 : stats_message_queue_(1) {}
2619
2620AudioProcessingImpl::ApmStatsReporter::~ApmStatsReporter() = default;
2621
2622AudioProcessingStats AudioProcessingImpl::ApmStatsReporter::GetStatistics() {
Markus Handell0df0fae2020-07-07 15:53:34 +02002623 MutexLock lock_stats(&mutex_stats_);
Per Åhgrencf4c8722019-12-30 14:32:14 +01002624 bool new_stats_available = stats_message_queue_.Remove(&cached_stats_);
2625 // If the message queue is full, return the cached stats.
2626 static_cast<void>(new_stats_available);
2627
2628 return cached_stats_;
2629}
2630
2631void AudioProcessingImpl::ApmStatsReporter::UpdateStatistics(
2632 const AudioProcessingStats& new_stats) {
2633 AudioProcessingStats stats_to_queue = new_stats;
2634 bool stats_message_passed = stats_message_queue_.Insert(&stats_to_queue);
2635 // If the message queue is full, discard the new stats.
2636 static_cast<void>(stats_message_passed);
2637}
2638
niklase@google.com470e71d2011-07-07 08:21:25 +00002639} // namespace webrtc