blob: 376464793c3056bff52a89b6a20d8973c609bb09 [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>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <type_traits>
17#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000018
Yves Gerey988cc082018-10-23 12:03:01 +020019#include "absl/types/optional.h"
20#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/include/audio_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020024#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/common.h"
27#include "modules/audio_processing/echo_cancellation_impl.h"
28#include "modules/audio_processing/echo_control_mobile_impl.h"
29#include "modules/audio_processing/gain_control_for_experimental_agc.h"
30#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010031#include "modules/audio_processing/gain_controller2.h"
Yves Gerey988cc082018-10-23 12:03:01 +020032#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020033#include "modules/audio_processing/level_estimator_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010034#include "modules/audio_processing/logging/apm_data_dumper.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020035#include "modules/audio_processing/low_cut_filter.h"
36#include "modules/audio_processing/noise_suppression_impl.h"
37#include "modules/audio_processing/residual_echo_detector.h"
38#include "modules/audio_processing/transient/transient_suppressor.h"
39#include "modules/audio_processing/voice_detection_impl.h"
40#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "rtc_base/checks.h"
Yves Gerey988cc082018-10-23 12:03:01 +020042#include "rtc_base/constructormagic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "rtc_base/logging.h"
Niels Möller84255bb2017-10-06 13:43:23 +020044#include "rtc_base/refcountedobject.h"
Minyue Li656d6092018-08-10 15:38:52 +020045#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/trace_event.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000048
Michael Graczyk86c6d332015-07-23 11:41:39 -070049#define RETURN_ON_ERR(expr) \
50 do { \
51 int err = (expr); \
52 if (err != kNoError) { \
53 return err; \
54 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000055 } while (0)
56
niklase@google.com470e71d2011-07-07 08:21:25 +000057namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070058
kwibergd59d3bb2016-09-13 07:49:33 -070059constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020060constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070061
Michael Graczyk86c6d332015-07-23 11:41:39 -070062namespace {
63
64static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
65 switch (layout) {
66 case AudioProcessing::kMono:
67 case AudioProcessing::kStereo:
68 return false;
69 case AudioProcessing::kMonoAndKeyboard:
70 case AudioProcessing::kStereoAndKeyboard:
71 return true;
72 }
73
kwiberg9e2be5f2016-09-14 05:23:22 -070074 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070075 return false;
76}
aluebsdf6416a2016-03-16 18:26:35 -070077
peah2ace3f92016-09-10 04:42:27 -070078bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070079 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
80 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
81}
82
peah2ace3f92016-09-10 04:42:27 -070083int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
84#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070085 constexpr int kMaxSplittingNativeProcessRate =
86 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070087#else
kwibergd59d3bb2016-09-13 07:49:33 -070088 constexpr int kMaxSplittingNativeProcessRate =
89 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070090#endif
kwibergd59d3bb2016-09-13 07:49:33 -070091 static_assert(
92 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
93 "");
peah2ace3f92016-09-10 04:42:27 -070094 const int uppermost_native_rate = band_splitting_required
95 ? kMaxSplittingNativeProcessRate
96 : AudioProcessing::kSampleRate48kHz;
97
98 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
99 if (rate >= uppermost_native_rate) {
100 return uppermost_native_rate;
101 }
102 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700103 return rate;
104 }
105 }
peah2ace3f92016-09-10 04:42:27 -0700106 RTC_NOTREACHED();
107 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700108}
109
peah9e6a2902017-05-15 07:19:21 -0700110// Maximum lengths that frame of samples being passed from the render side to
111// the capture side can have (does not apply to AEC3).
112static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
113static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
114
peah764e3642016-10-22 05:04:30 -0700115// Maximum number of frames to buffer in the render queue.
116// TODO(peah): Decrease this once we properly handle hugely unbalanced
117// reverse and forward call numbers.
118static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700119} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000120
121// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000122static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000123
Sam Zackrisson0beac582017-09-25 12:04:02 +0200124AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100125 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200126 bool render_pre_processor_enabled,
127 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100128 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200129 render_pre_processor_enabled_(render_pre_processor_enabled),
130 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700131
132bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200133 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700134 bool echo_canceller_enabled,
135 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700136 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700137 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700138 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700139 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200140 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200141 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700142 bool voice_activity_detector_enabled,
143 bool level_estimator_enabled,
144 bool transient_suppressor_enabled) {
145 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200146 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700147 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
148 changed |=
149 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700150 changed |=
151 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700152 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
153 changed |=
peah2ace3f92016-09-10 04:42:27 -0700154 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700155 changed |=
156 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200157 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200158 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700159 changed |= (level_estimator_enabled != level_estimator_enabled_);
160 changed |=
161 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
162 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
163 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200164 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700165 echo_canceller_enabled_ = echo_canceller_enabled;
166 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700167 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700168 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700169 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700170 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200171 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200172 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700173 level_estimator_enabled_ = level_estimator_enabled;
174 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
175 transient_suppressor_enabled_ = transient_suppressor_enabled;
176 }
177
178 changed |= first_update_;
179 first_update_ = false;
180 return changed;
181}
182
183bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
184 const {
peah52775842017-05-16 06:14:09 -0700185 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700186}
187
188bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
189 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200190 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700191 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200192 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700193}
194
peah23ac8b42017-05-23 05:33:56 -0700195bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
196 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200197 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
198 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700199}
200
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200201bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
202 return capture_analyzer_enabled_;
203}
204
peah2ace3f92016-09-10 04:42:27 -0700205bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
206 const {
207 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800208 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200209 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700210}
211
Alex Loiko5825aa62017-12-18 16:02:40 +0100212bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
213 const {
214 return render_pre_processor_enabled_;
215}
216
peah2ace3f92016-09-10 04:42:27 -0700217bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
218 const {
peah2ace3f92016-09-10 04:42:27 -0700219 return false;
peah2ace3f92016-09-10 04:42:27 -0700220}
221
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200222bool AudioProcessingImpl::ApmSubmoduleStates::LowCutFilteringRequired() const {
223 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
224 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
225}
226
solenberg5e465c32015-12-08 13:22:33 -0800227struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800228 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800229 // Accessed externally of APM without any lock acquired.
peahbfa97112016-03-10 21:09:04 -0800230 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800231 std::unique_ptr<LevelEstimatorImpl> level_estimator;
232 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
233 std::unique_ptr<VoiceDetectionImpl> voice_detection;
234 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800235 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800236
237 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800238 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800239};
240
241struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200242 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100243 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200244 rtc::scoped_refptr<EchoDetector> echo_detector,
245 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200246 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100247 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200248 render_pre_processor(std::move(render_pre_processor)),
249 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800250 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800251 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700252 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800253 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200254 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100255 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100256 std::unique_ptr<EchoControl> echo_controller;
257 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100258 std::unique_ptr<CustomProcessing> capture_post_processor;
259 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200260 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200261 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
solenberg5e465c32015-12-08 13:22:33 -0800262};
263
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100264AudioProcessingBuilder::AudioProcessingBuilder() = default;
265AudioProcessingBuilder::~AudioProcessingBuilder() = default;
266
267AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
268 std::unique_ptr<CustomProcessing> capture_post_processing) {
269 capture_post_processing_ = std::move(capture_post_processing);
270 return *this;
271}
272
273AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
274 std::unique_ptr<CustomProcessing> render_pre_processing) {
275 render_pre_processing_ = std::move(render_pre_processing);
276 return *this;
277}
278
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200279AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
280 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
281 capture_analyzer_ = std::move(capture_analyzer);
282 return *this;
283}
284
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100285AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
286 std::unique_ptr<EchoControlFactory> echo_control_factory) {
287 echo_control_factory_ = std::move(echo_control_factory);
288 return *this;
289}
290
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100291AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200292 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100293 echo_detector_ = std::move(echo_detector);
294 return *this;
295}
296
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100297AudioProcessing* AudioProcessingBuilder::Create() {
298 webrtc::Config config;
299 return Create(config);
300}
301
302AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100303 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
304 config, std::move(capture_post_processing_),
305 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200306 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100307 if (apm->Initialize() != AudioProcessing::kNoError) {
308 delete apm;
309 apm = nullptr;
310 }
311 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100312}
313
peah88ac8532016-09-12 16:47:25 -0700314AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200315 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
316}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000317
Per Åhgren13735822018-02-12 21:42:56 +0100318int AudioProcessingImpl::instance_count_ = 0;
319
Sam Zackrisson0beac582017-09-25 12:04:02 +0200320AudioProcessingImpl::AudioProcessingImpl(
321 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100322 std::unique_ptr<CustomProcessing> capture_post_processor,
323 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200324 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200325 rtc::scoped_refptr<EchoDetector> echo_detector,
326 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100327 : data_dumper_(
328 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200329 capture_runtime_settings_(kRuntimeSettingQueueSize),
330 render_runtime_settings_(kRuntimeSettingQueueSize),
331 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
332 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200333 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200334 submodule_states_(!!capture_post_processor,
335 !!render_pre_processor,
336 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800337 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200338 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200339 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100340 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200341 std::move(echo_detector),
342 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800343 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800344 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000345#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200346 /* enabled= */ false,
347 /* enabled_agc2_level_estimator= */ false,
348 /* digital_adaptive_disabled= */ false,
349 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000350#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200351 config.Get<ExperimentalAgc>().enabled,
352 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200353 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
354 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000355#endif
andrew1c7075f2015-06-24 18:14:14 -0700356#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200357 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700358#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200359 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700360#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200361 capture_nonlocked_() {
peahdf3efa82015-11-28 12:35:15 -0800362 {
363 rtc::CritScope cs_render(&crit_render_);
364 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000365
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200366 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000367 capture_nonlocked_.echo_controller_enabled =
368 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200369
peahbfa97112016-03-10 21:09:04 -0800370 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200371 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800372 public_submodules_->level_estimator.reset(
373 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800374 public_submodules_->noise_suppression.reset(
375 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800376 public_submodules_->voice_detection.reset(
377 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800378 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800379 new GainControlForExperimentalAgc(
380 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100381
382 // If no echo detector is injected, use the ResidualEchoDetector.
383 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200384 private_submodules_->echo_detector =
385 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100386 }
peahca4cac72016-06-29 15:26:12 -0700387
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100388 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
389 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200390 // TODO(alessiob): Move the injected gain controller once injection is
391 // implemented.
392 private_submodules_->gain_controller2.reset(new GainController2());
393
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200394 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
395 << !!private_submodules_->capture_analyzer
396 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100397 << !!private_submodules_->capture_post_processor
398 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100399 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800400 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000401
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000402 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000403}
404
405AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800406 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800407 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800408 private_submodules_->agc_manager.reset();
409 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800410 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000411}
412
niklase@google.com470e71d2011-07-07 08:21:25 +0000413int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800414 // Run in a single-threaded manner during initialization.
415 rtc::CritScope cs_render(&crit_render_);
416 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000417 return InitializeLocked();
418}
419
peahde65ddc2016-09-16 15:02:15 -0700420int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
421 int capture_output_sample_rate_hz,
422 int render_input_sample_rate_hz,
423 ChannelLayout capture_input_layout,
424 ChannelLayout capture_output_layout,
425 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700426 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700427 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
428 LayoutHasKeyboard(capture_input_layout)},
429 {capture_output_sample_rate_hz,
430 ChannelsFromLayout(capture_output_layout),
431 LayoutHasKeyboard(capture_output_layout)},
432 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
433 LayoutHasKeyboard(render_input_layout)},
434 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
435 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700436
437 return Initialize(processing_config);
438}
439
440int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800441 // Run in a single-threaded manner during initialization.
442 rtc::CritScope cs_render(&crit_render_);
443 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700444 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000445}
446
peahdf3efa82015-11-28 12:35:15 -0800447int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800448 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700449 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800450}
451
peahdf3efa82015-11-28 12:35:15 -0800452int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700453 const ProcessingConfig& processing_config,
454 bool force_initialization) {
455 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800456}
457
peah192164e2015-11-17 02:16:45 -0800458// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800459// their current values (needs to be called while holding the crit_render_lock).
460int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700461 const ProcessingConfig& processing_config,
462 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800463 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700464 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800465 return kNoError;
466 }
peahdf3efa82015-11-28 12:35:15 -0800467
468 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800469 return InitializeLocked(processing_config);
470}
471
niklase@google.com470e71d2011-07-07 08:21:25 +0000472int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200473 UpdateActiveSubmoduleStates();
474
peahde65ddc2016-09-16 15:02:15 -0700475 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800476 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700477 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800478 : formats_.api_format.reverse_output_stream().num_frames();
479 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
480 render_.render_audio.reset(new AudioBuffer(
481 formats_.api_format.reverse_input_stream().num_frames(),
482 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700483 formats_.render_processing_format.num_frames(),
484 formats_.render_processing_format.num_channels(),
485 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700486 if (formats_.api_format.reverse_input_stream() !=
487 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800488 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800489 formats_.api_format.reverse_input_stream().num_channels(),
490 formats_.api_format.reverse_input_stream().num_frames(),
491 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800492 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700493 } else {
peahdf3efa82015-11-28 12:35:15 -0800494 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700495 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700496 } else {
peahdf3efa82015-11-28 12:35:15 -0800497 render_.render_audio.reset(nullptr);
498 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700499 }
peahce4d9152017-05-19 01:28:05 -0700500
peahdf3efa82015-11-28 12:35:15 -0800501 capture_.capture_audio.reset(
502 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
503 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700504 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200505 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800506 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000507
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100508 private_submodules_->echo_cancellation->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700509 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
510 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700511 AllocateRenderQueue();
512
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100513 int success = private_submodules_->echo_cancellation->enable_metrics(true);
ivoc3e9a5372016-10-28 07:55:33 -0700514 RTC_DCHECK_EQ(0, success);
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100515 success = private_submodules_->echo_cancellation->enable_delay_logging(true);
ivoc3e9a5372016-10-28 07:55:33 -0700516 RTC_DCHECK_EQ(0, success);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100517 private_submodules_->echo_control_mobile->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700518 proc_split_sample_rate_hz(), num_reverse_channels(),
519 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700520
521 public_submodules_->gain_control->Initialize(num_proc_channels(),
522 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700523 if (constants_.use_experimental_agc) {
524 if (!private_submodules_->agc_manager.get()) {
525 private_submodules_->agc_manager.reset(new AgcManagerDirect(
526 public_submodules_->gain_control.get(),
527 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200528 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
529 constants_.use_experimental_agc_agc2_level_estimation,
530 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700531 }
532 private_submodules_->agc_manager->Initialize();
533 private_submodules_->agc_manager->SetCaptureMuted(
534 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700535 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700536 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200537 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800538 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700539 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
540 proc_sample_rate_hz());
541 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
542 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700543 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200544 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700545 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200546 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200547 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100548 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800549
aleloi868f32f2017-05-23 07:20:05 -0700550 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200551 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700552 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000553 return kNoError;
554}
555
Michael Graczyk86c6d332015-07-23 11:41:39 -0700556int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200557 UpdateActiveSubmoduleStates();
558
Michael Graczyk86c6d332015-07-23 11:41:39 -0700559 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700560 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
561 return kBadSampleRateError;
562 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000563 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700564
Peter Kasting69558702016-01-12 16:26:35 -0800565 const size_t num_in_channels = config.input_stream().num_channels();
566 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700567
568 // Need at least one input channel.
569 // Need either one output channel or as many outputs as there are inputs.
570 if (num_in_channels == 0 ||
571 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700572 return kBadNumberChannelsError;
573 }
574
peahdf3efa82015-11-28 12:35:15 -0800575 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000576
peahde65ddc2016-09-16 15:02:15 -0700577 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700578 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700579 formats_.api_format.output_stream().sample_rate_hz()),
580 submodule_states_.CaptureMultiBandSubModulesActive() ||
581 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000582
peahde65ddc2016-09-16 15:02:15 -0700583 capture_nonlocked_.capture_processing_format =
584 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700585
peah2ce640f2017-04-07 03:57:48 -0700586 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200587 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700588 render_processing_rate = FindNativeProcessRateToUse(
589 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
590 formats_.api_format.reverse_output_stream().sample_rate_hz()),
591 submodule_states_.CaptureMultiBandSubModulesActive() ||
592 submodule_states_.RenderMultiBandSubModulesActive());
593 } else {
594 render_processing_rate = capture_processing_rate;
595 }
596
aluebseb3603b2016-04-20 15:27:58 -0700597 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
598 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700599 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200600 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700601 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
602 ? kSampleRate32kHz
603 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700604 }
peah2ce640f2017-04-07 03:57:48 -0700605
peahde65ddc2016-09-16 15:02:15 -0700606 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700607 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700608 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
609 kSampleRate8kHz) {
610 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000611 } else {
peahde65ddc2016-09-16 15:02:15 -0700612 render_processing_rate =
613 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000614 }
615
peahde65ddc2016-09-16 15:02:15 -0700616 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000617 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700618 if (submodule_states_.RenderMultiBandSubModulesActive()) {
619 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
620 } else {
621 formats_.render_processing_format = StreamConfig(
622 formats_.api_format.reverse_input_stream().sample_rate_hz(),
623 formats_.api_format.reverse_input_stream().num_channels());
624 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000625
peahde65ddc2016-09-16 15:02:15 -0700626 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
627 kSampleRate32kHz ||
628 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
629 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800630 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000631 } else {
peahdf3efa82015-11-28 12:35:15 -0800632 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700633 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000634 }
635
636 return InitializeLocked();
637}
638
peah88ac8532016-09-12 16:47:25 -0700639void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700640 // Run in a single-threaded manner when applying the settings.
641 rtc::CritScope cs_render(&crit_render_);
642 rtc::CritScope cs_capture(&crit_capture_);
643
Yves Gerey499bc6c2018-10-10 18:29:07 +0200644 config_ = config;
645
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100646 private_submodules_->echo_cancellation->Enable(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200647 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100648 private_submodules_->echo_control_mobile->Enable(
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200649 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200650
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100651 private_submodules_->echo_cancellation->set_suppression_level(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200652 config.echo_canceller.legacy_moderate_suppression_level
sazabe490b22018-10-03 17:03:13 +0200653 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
654 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200655
peah8271d042016-11-22 07:24:52 -0800656 InitializeLowCutFilter();
657
Mirko Bonadei675513b2017-11-09 11:09:25 +0100658 RTC_LOG(LS_INFO) << "Highpass filter activated: "
659 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800660
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100661 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700662 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100663 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
664 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100665 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100666 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700667 config_.gain_controller2 = AudioProcessing::Config::GainController2();
668 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200669 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200670 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200671 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100672 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
673 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200674 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
675 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700676}
677
678void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800679 // Run in a single-threaded manner when setting the extra options.
680 rtc::CritScope cs_render(&crit_render_);
681 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000682
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100683 private_submodules_->echo_cancellation->SetExtraOptions(config);
peahb624d8c2016-03-05 03:01:14 -0800684
peahdf3efa82015-11-28 12:35:15 -0800685 if (capture_.transient_suppressor_enabled !=
686 config.Get<ExperimentalNs>().enabled) {
687 capture_.transient_suppressor_enabled =
688 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000689 InitializeTransient();
690 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000691}
692
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000693int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800694 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700695 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000696}
697
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000698int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800699 // Used as callback from submodules, hence locking is not allowed.
700 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000701}
702
Peter Kasting69558702016-01-12 16:26:35 -0800703size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800704 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700705 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000706}
707
Peter Kasting69558702016-01-12 16:26:35 -0800708size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800709 // Used as callback from submodules, hence locking is not allowed.
710 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000711}
712
Peter Kasting69558702016-01-12 16:26:35 -0800713size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800714 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200715 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800716}
717
Peter Kasting69558702016-01-12 16:26:35 -0800718size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800719 // Used as callback from submodules, hence locking is not allowed.
720 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000721}
722
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000723void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800724 rtc::CritScope cs(&crit_capture_);
725 capture_.output_will_be_muted = muted;
726 if (private_submodules_->agc_manager.get()) {
727 private_submodules_->agc_manager->SetCaptureMuted(
728 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000729 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000730}
731
Alessio Bazzicac054e782018-04-16 12:10:09 +0200732void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200733 switch (setting.type()) {
734 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
735 render_runtime_settings_enqueuer_.Enqueue(setting);
736 return;
737 case RuntimeSetting::Type::kNotSpecified:
738 RTC_NOTREACHED();
739 return;
740 case RuntimeSetting::Type::kCapturePreGain:
741 capture_runtime_settings_enqueuer_.Enqueue(setting);
742 return;
743 }
744 // The language allows the enum to have a non-enumerator
745 // value. Check that this doesn't happen.
746 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200747}
748
749AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
750 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200751 : runtime_settings_(*runtime_settings) {
752 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200753}
754
755AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
756 default;
757
758void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
759 RuntimeSetting setting) {
760 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200761 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200762 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200763 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200764 RTC_LOG(LS_ERROR)
765 << "The runtime settings queue is full. Oldest setting discarded.";
766 }
767 if (remaining_attempts == 0)
768 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
769}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000770
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000771int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700772 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000773 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000774 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000775 int output_sample_rate_hz,
776 ChannelLayout output_layout,
777 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800778 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800779 StreamConfig input_stream;
780 StreamConfig output_stream;
781 {
782 // Access the formats_.api_format.input_stream beneath the capture lock.
783 // The lock must be released as it is later required in the call
784 // to ProcessStream(,,,);
785 rtc::CritScope cs(&crit_capture_);
786 input_stream = formats_.api_format.input_stream();
787 output_stream = formats_.api_format.output_stream();
788 }
789
Michael Graczyk86c6d332015-07-23 11:41:39 -0700790 input_stream.set_sample_rate_hz(input_sample_rate_hz);
791 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
792 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700793 output_stream.set_sample_rate_hz(output_sample_rate_hz);
794 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
795 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
796
797 if (samples_per_channel != input_stream.num_frames()) {
798 return kBadDataLengthError;
799 }
800 return ProcessStream(src, input_stream, output_stream, dest);
801}
802
803int AudioProcessingImpl::ProcessStream(const float* const* src,
804 const StreamConfig& input_config,
805 const StreamConfig& output_config,
806 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800807 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800808 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700809 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800810 {
811 // Acquire the capture lock in order to safely call the function
812 // that retrieves the render side data. This function accesses apm
813 // getters that need the capture lock held when being called.
814 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700815 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800816
817 if (!src || !dest) {
818 return kNullPointerError;
819 }
820
821 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700822 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000823 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000824
Michael Graczyk86c6d332015-07-23 11:41:39 -0700825 processing_config.input_stream() = input_config;
826 processing_config.output_stream() = output_config;
827
peahdf3efa82015-11-28 12:35:15 -0800828 {
829 // Do conditional reinitialization.
830 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700831 RETURN_ON_ERR(
832 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800833 }
834 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700835 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
836 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000837
aleloi868f32f2017-05-23 07:20:05 -0700838 if (aec_dump_) {
839 RecordUnprocessedCaptureStream(src);
840 }
841
peahdf3efa82015-11-28 12:35:15 -0800842 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700843 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800844 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000845
aleloi868f32f2017-05-23 07:20:05 -0700846 if (aec_dump_) {
847 RecordProcessedCaptureStream(dest);
848 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000849 return kNoError;
850}
851
Alex Loiko73ec0192018-05-15 10:52:28 +0200852void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200853 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200854 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200855 if (aec_dump_) {
856 aec_dump_->WriteRuntimeSetting(setting);
857 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200858 switch (setting.type()) {
859 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200860 if (config_.pre_amplifier.enabled) {
861 float value;
862 setting.GetFloat(&value);
863 private_submodules_->pre_amplifier->SetGainFactor(value);
864 }
865 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200866 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200867 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
868 RTC_NOTREACHED();
869 break;
870 case RuntimeSetting::Type::kNotSpecified:
871 RTC_NOTREACHED();
872 break;
873 }
874 }
875}
876
877void AudioProcessingImpl::HandleRenderRuntimeSettings() {
878 RuntimeSetting setting;
879 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200880 if (aec_dump_) {
881 aec_dump_->WriteRuntimeSetting(setting);
882 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200883 switch (setting.type()) {
884 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
885 if (private_submodules_->render_pre_processor) {
886 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
887 }
888 break;
889 case RuntimeSetting::Type::kCapturePreGain:
890 RTC_NOTREACHED();
891 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200892 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200893 RTC_NOTREACHED();
894 break;
895 }
896 }
897}
898
peah9e6a2902017-05-15 07:19:21 -0700899void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700900 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
901 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700902 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700903
kwibergaf476c72016-11-28 15:21:39 -0800904 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700905
906 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700907 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700908 // The data queue is full and needs to be emptied.
909 EmptyQueuedRenderAudio();
910
911 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700912 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700913 RTC_DCHECK(result);
914 }
915
916 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
917 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700918 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700919
920 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700921 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700922 // The data queue is full and needs to be emptied.
923 EmptyQueuedRenderAudio();
924
925 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700926 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700927 RTC_DCHECK(result);
928 }
peah701d6282016-10-25 05:42:20 -0700929
930 if (!constants_.use_experimental_agc) {
931 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
932 // Insert the samples into the queue.
933 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
934 // The data queue is full and needs to be emptied.
935 EmptyQueuedRenderAudio();
936
937 // Retry the insert (should always work).
938 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
939 RTC_DCHECK(result);
940 }
941 }
peah9e6a2902017-05-15 07:19:21 -0700942}
ivoc9f4a4a02016-10-28 05:39:16 -0700943
peah9e6a2902017-05-15 07:19:21 -0700944void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700945 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
946
947 // Insert the samples into the queue.
948 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
949 // The data queue is full and needs to be emptied.
950 EmptyQueuedRenderAudio();
951
952 // Retry the insert (should always work).
953 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
954 RTC_DCHECK(result);
955 }
peah764e3642016-10-22 05:04:30 -0700956}
957
958void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700959 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700960 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700961 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700962 EchoCancellationImpl::NumCancellersRequired(
963 num_output_channels(), num_reverse_channels()));
964
peah701d6282016-10-25 05:42:20 -0700965 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700966 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700967 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700968 EchoControlMobileImpl::NumCancellersRequired(
969 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700970
peah701d6282016-10-25 05:42:20 -0700971 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700972 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700973
ivoc9f4a4a02016-10-28 05:39:16 -0700974 const size_t new_red_render_queue_element_max_size =
975 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
976
peaha0624602016-10-25 04:45:24 -0700977 // Reallocate the queues if the queue item sizes are too small to fit the
978 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700979 if (aec_render_queue_element_max_size_ <
980 new_aec_render_queue_element_max_size) {
981 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700982
peaha0624602016-10-25 04:45:24 -0700983 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700984 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700985
peah701d6282016-10-25 05:42:20 -0700986 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700987 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
988 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700989 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700990 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700991
peah701d6282016-10-25 05:42:20 -0700992 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
993 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700994 } else {
peah701d6282016-10-25 05:42:20 -0700995 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700996 }
997
peah701d6282016-10-25 05:42:20 -0700998 if (aecm_render_queue_element_max_size_ <
999 new_aecm_render_queue_element_max_size) {
1000 aecm_render_queue_element_max_size_ =
1001 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001002
1003 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001004 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001005
peah701d6282016-10-25 05:42:20 -07001006 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001007 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1008 kMaxNumFramesToBuffer, template_queue_element,
1009 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001010 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001011
peah701d6282016-10-25 05:42:20 -07001012 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1013 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001014 } else {
peah701d6282016-10-25 05:42:20 -07001015 aecm_render_signal_queue_->Clear();
1016 }
1017
1018 if (agc_render_queue_element_max_size_ <
1019 new_agc_render_queue_element_max_size) {
1020 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1021
1022 std::vector<int16_t> template_queue_element(
1023 agc_render_queue_element_max_size_);
1024
1025 agc_render_signal_queue_.reset(
1026 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1027 kMaxNumFramesToBuffer, template_queue_element,
1028 RenderQueueItemVerifier<int16_t>(
1029 agc_render_queue_element_max_size_)));
1030
1031 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1032 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1033 } else {
1034 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001035 }
ivoc9f4a4a02016-10-28 05:39:16 -07001036
1037 if (red_render_queue_element_max_size_ <
1038 new_red_render_queue_element_max_size) {
1039 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1040
1041 std::vector<float> template_queue_element(
1042 red_render_queue_element_max_size_);
1043
1044 red_render_signal_queue_.reset(
1045 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1046 kMaxNumFramesToBuffer, template_queue_element,
1047 RenderQueueItemVerifier<float>(
1048 red_render_queue_element_max_size_)));
1049
1050 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1051 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1052 } else {
1053 red_render_signal_queue_->Clear();
1054 }
peah764e3642016-10-22 05:04:30 -07001055}
1056
1057void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1058 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001059 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001060 private_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001061 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001062 }
1063
peah701d6282016-10-25 05:42:20 -07001064 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001065 private_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001066 aecm_capture_queue_buffer_);
1067 }
1068
1069 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1070 public_submodules_->gain_control->ProcessRenderAudio(
1071 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001072 }
ivoc9f4a4a02016-10-28 05:39:16 -07001073
1074 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001075 RTC_DCHECK(private_submodules_->echo_detector);
1076 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001077 red_capture_queue_buffer_);
1078 }
peah764e3642016-10-22 05:04:30 -07001079}
1080
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001081int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001082 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001083 {
1084 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001085 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001086 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001087 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001088 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001089 }
peahfa6228e2015-11-16 16:27:42 -08001090
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001091 if (!frame) {
1092 return kNullPointerError;
1093 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001094 // Must be a native rate.
1095 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1096 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001097 frame->sample_rate_hz_ != kSampleRate32kHz &&
1098 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001099 return kBadSampleRateError;
1100 }
peah192164e2015-11-17 02:16:45 -08001101
peahdf3efa82015-11-28 12:35:15 -08001102 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001103 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001104 {
1105 // Aquire lock for the access of api_format.
1106 // The lock is released immediately due to the conditional
1107 // reinitialization.
1108 rtc::CritScope cs_capture(&crit_capture_);
1109 // TODO(ajm): The input and output rates and channels are currently
1110 // constrained to be identical in the int16 interface.
1111 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001112
1113 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001114 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001115 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1116 processing_config.input_stream().set_num_channels(frame->num_channels_);
1117 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1118 processing_config.output_stream().set_num_channels(frame->num_channels_);
1119
peahdf3efa82015-11-28 12:35:15 -08001120 {
1121 // Do conditional reinitialization.
1122 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001123 RETURN_ON_ERR(
1124 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001125 }
1126 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001127 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001128 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001129 return kBadDataLengthError;
1130 }
1131
aleloi868f32f2017-05-23 07:20:05 -07001132 if (aec_dump_) {
1133 RecordUnprocessedCaptureStream(*frame);
1134 }
1135
peahdf3efa82015-11-28 12:35:15 -08001136 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001137 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001138 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001139 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1140 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001141
aleloi868f32f2017-05-23 07:20:05 -07001142 if (aec_dump_) {
1143 RecordProcessedCaptureStream(*frame);
1144 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001145
1146 return kNoError;
1147}
1148
peahde65ddc2016-09-16 15:02:15 -07001149int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001150 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001151
peahb58a1582016-03-15 09:34:24 -07001152 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001153 // TODO(peah): Simplify once the public API Enable functions for these
1154 // are moved to APM.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001155 RTC_DCHECK(!(private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001156 private_submodules_->echo_control_mobile->is_enabled()));
peahb58a1582016-03-15 09:34:24 -07001157
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001158 MaybeUpdateHistograms();
1159
peahde65ddc2016-09-16 15:02:15 -07001160 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001161
Alex Loikob5c9a792018-04-16 16:31:22 +02001162 if (private_submodules_->pre_amplifier) {
1163 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1164 capture_buffer->channels_f(), capture_buffer->num_channels(),
1165 capture_buffer->num_frames()));
1166 }
1167
peah1b08dc32016-12-20 13:45:58 -08001168 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001169 capture_buffer->channels_const()[0],
1170 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001171 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1172 if (log_rms) {
1173 capture_rms_interval_counter_ = 0;
1174 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001175 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1176 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1177 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1178 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001179 }
1180
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001181 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001182 // Detect and flag any change in the analog gain.
1183 int analog_mic_level = gain_control()->stream_analog_level();
1184 capture_.echo_path_gain_change =
1185 capture_.prev_analog_mic_level != analog_mic_level &&
1186 capture_.prev_analog_mic_level != -1;
1187 capture_.prev_analog_mic_level = analog_mic_level;
1188
Per Åhgrend2650d12018-10-02 17:00:59 +02001189 // Detect and flag any change in the pre-amplifier gain.
1190 if (private_submodules_->pre_amplifier) {
1191 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1192 capture_.echo_path_gain_change =
1193 capture_.echo_path_gain_change ||
1194 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001195 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001196 capture_.prev_pre_amp_gain = pre_amp_gain;
1197 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001198 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001199 }
1200
peahbe615622016-02-13 16:40:47 -08001201 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001202 public_submodules_->gain_control->is_enabled()) {
1203 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001204 capture_buffer->channels()[0], capture_buffer->num_channels(),
1205 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001206
1207 if (constants_.use_experimental_agc_process_before_aec) {
1208 private_submodules_->agc_manager->Process(
1209 capture_buffer->channels()[0],
1210 capture_nonlocked_.capture_processing_format.num_frames(),
1211 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1212 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001213 }
1214
peah2ace3f92016-09-10 04:42:27 -07001215 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1216 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001217 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1218 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001219 }
1220
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001221 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001222 // Force down-mixing of the number of channels after the detection of
1223 // capture signal saturation.
1224 // TODO(peah): Look into ensuring that this kind of tampering with the
1225 // AudioBuffer functionality should not be needed.
1226 capture_buffer->set_num_channels(1);
1227 }
1228
peahe0eae3c2016-12-14 01:16:23 -08001229 // TODO(peah): Move the AEC3 low-cut filter to this place.
1230 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001231 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001232 private_submodules_->low_cut_filter->Process(capture_buffer);
1233 }
peahde65ddc2016-09-16 15:02:15 -07001234 RETURN_ON_ERR(
1235 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1236 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001237
1238 // Ensure that the stream delay was set before the call to the
1239 // AEC ProcessCaptureAudio function.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001240 if (private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001241 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001242 return AudioProcessing::kStreamParameterNotSetError;
1243 }
1244
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001245 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001246 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1247
Per Åhgrend0fa8202018-04-18 09:35:13 +02001248 if (was_stream_delay_set()) {
1249 private_submodules_->echo_controller->SetAudioBufferDelay(
1250 stream_delay_ms());
1251 }
1252
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001253 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001254 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001255 } else {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001256 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
peah61202ac2017-02-06 03:39:42 -08001257 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001258 }
1259
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001260 if (private_submodules_->echo_control_mobile->is_enabled() &&
peahdf3efa82015-11-28 12:35:15 -08001261 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001262 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001263 }
peahde65ddc2016-09-16 15:02:15 -07001264 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001265
1266 // Ensure that the stream delay was set before the call to the
1267 // AECM ProcessCaptureAudio function.
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001268 if (private_submodules_->echo_control_mobile->is_enabled() &&
peah253534d2016-03-15 04:32:28 -07001269 !was_stream_delay_set()) {
1270 return AudioProcessing::kStreamParameterNotSetError;
1271 }
1272
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001273 if (!(private_submodules_->echo_controller ||
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001274 private_submodules_->echo_cancellation->is_enabled())) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001275 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001276 capture_buffer, stream_delay_ms()));
1277 }
ivoc9f4a4a02016-10-28 05:39:16 -07001278
peahde65ddc2016-09-16 15:02:15 -07001279 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001280
peahbe615622016-02-13 16:40:47 -08001281 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001282 public_submodules_->gain_control->is_enabled() &&
1283 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001284 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001285 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1286 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001287 }
peahb8fbb542016-03-15 02:28:08 -07001288 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001289 capture_buffer,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001290 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001291
peah2ace3f92016-09-10 04:42:27 -07001292 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1293 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001294 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1295 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001296 }
1297
peah9e6a2902017-05-15 07:19:21 -07001298 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001299 RTC_DCHECK(private_submodules_->echo_detector);
1300 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001301 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1302 capture_buffer->num_frames()));
1303 }
1304
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001305 // TODO(aluebs): Investigate if the transient suppression placement should be
1306 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001307 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001308 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001309 private_submodules_->agc_manager.get()
1310 ? private_submodules_->agc_manager->voice_probability()
1311 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001312
peahdf3efa82015-11-28 12:35:15 -08001313 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001314 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1315 capture_buffer->num_channels(),
1316 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1317 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1318 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001319 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001320 }
1321
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001322 // Experimental APM sub-module that analyzes |capture_buffer|.
1323 if (private_submodules_->capture_analyzer) {
1324 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1325 }
1326
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001327 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001328 private_submodules_->gain_controller2->NotifyAnalogLevel(
1329 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001330 private_submodules_->gain_controller2->Process(capture_buffer);
1331 }
1332
Sam Zackrisson0beac582017-09-25 12:04:02 +02001333 if (private_submodules_->capture_post_processor) {
1334 private_submodules_->capture_post_processor->Process(capture_buffer);
1335 }
1336
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001337 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001338 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001339
peah1b08dc32016-12-20 13:45:58 -08001340 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1341 capture_buffer->channels_const()[0],
1342 capture_nonlocked_.capture_processing_format.num_frames()));
1343 if (log_rms) {
1344 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1345 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1346 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1347 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1348 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1349 }
1350
peahdf3efa82015-11-28 12:35:15 -08001351 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001352 return kNoError;
1353}
1354
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001355int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001356 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001357 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001358 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001359 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001360 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001361 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001362 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001363 };
1364 if (samples_per_channel != reverse_config.num_frames()) {
1365 return kBadDataLengthError;
1366 }
peahdf3efa82015-11-28 12:35:15 -08001367 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001368}
1369
peahde65ddc2016-09-16 15:02:15 -07001370int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1371 const StreamConfig& input_config,
1372 const StreamConfig& output_config,
1373 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001374 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001375 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001376 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001377 if (submodule_states_.RenderMultiBandProcessingActive() ||
1378 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001379 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1380 dest);
peah2ace3f92016-09-10 04:42:27 -07001381 } else if (formats_.api_format.reverse_input_stream() !=
1382 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001383 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1384 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001385 } else {
peahde65ddc2016-09-16 15:02:15 -07001386 CopyAudioIfNeeded(src, input_config.num_frames(),
1387 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001388 }
1389
1390 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001391}
1392
peahdf3efa82015-11-28 12:35:15 -08001393int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001394 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001395 const StreamConfig& input_config,
1396 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001397 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001398 return kNullPointerError;
1399 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001400
peahde65ddc2016-09-16 15:02:15 -07001401 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001402 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001403 }
1404
peahdf3efa82015-11-28 12:35:15 -08001405 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001406 processing_config.reverse_input_stream() = input_config;
1407 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001408
peahdf3efa82015-11-28 12:35:15 -08001409 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001410 RTC_DCHECK_EQ(input_config.num_frames(),
1411 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001412
aleloi868f32f2017-05-23 07:20:05 -07001413 if (aec_dump_) {
1414 const size_t channel_size =
1415 formats_.api_format.reverse_input_stream().num_frames();
1416 const size_t num_channels =
1417 formats_.api_format.reverse_input_stream().num_channels();
1418 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001419 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001420 }
peahdf3efa82015-11-28 12:35:15 -08001421 render_.render_audio->CopyFrom(src,
1422 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001423 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001424}
1425
1426int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001427 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001428 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001429 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001430 return kNullPointerError;
1431 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001432 // Must be a native rate.
1433 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1434 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001435 frame->sample_rate_hz_ != kSampleRate32kHz &&
1436 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001437 return kBadSampleRateError;
1438 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001439
Michael Graczyk86c6d332015-07-23 11:41:39 -07001440 if (frame->num_channels_ <= 0) {
1441 return kBadNumberChannelsError;
1442 }
1443
peahdf3efa82015-11-28 12:35:15 -08001444 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001445 processing_config.reverse_input_stream().set_sample_rate_hz(
1446 frame->sample_rate_hz_);
1447 processing_config.reverse_input_stream().set_num_channels(
1448 frame->num_channels_);
1449 processing_config.reverse_output_stream().set_sample_rate_hz(
1450 frame->sample_rate_hz_);
1451 processing_config.reverse_output_stream().set_num_channels(
1452 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001453
peahdf3efa82015-11-28 12:35:15 -08001454 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001455 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001456 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001457 return kBadDataLengthError;
1458 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001459
aleloi868f32f2017-05-23 07:20:05 -07001460 if (aec_dump_) {
1461 aec_dump_->WriteRenderStreamMessage(*frame);
1462 }
1463
peahdf3efa82015-11-28 12:35:15 -08001464 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001465 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001466 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001467 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1468 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001469 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001470}
niklase@google.com470e71d2011-07-07 08:21:25 +00001471
peahde65ddc2016-09-16 15:02:15 -07001472int AudioProcessingImpl::ProcessRenderStreamLocked() {
1473 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001474
Alex Loiko73ec0192018-05-15 10:52:28 +02001475 HandleRenderRuntimeSettings();
1476
Alex Loiko5825aa62017-12-18 16:02:40 +01001477 if (private_submodules_->render_pre_processor) {
1478 private_submodules_->render_pre_processor->Process(render_buffer);
1479 }
1480
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001481 QueueNonbandedRenderAudio(render_buffer);
1482
peah2ace3f92016-09-10 04:42:27 -07001483 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001484 SampleRateSupportsMultiBand(
1485 formats_.render_processing_format.sample_rate_hz())) {
1486 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001487 }
1488
peahce4d9152017-05-19 01:28:05 -07001489 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1490 QueueBandedRenderAudio(render_buffer);
1491 }
1492
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001493 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001494 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001495 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001496 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001497
peah2ace3f92016-09-10 04:42:27 -07001498 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001499 SampleRateSupportsMultiBand(
1500 formats_.render_processing_format.sample_rate_hz())) {
1501 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001502 }
1503
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001504 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001505}
1506
1507int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001508 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001509 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001510 capture_.was_stream_delay_set = true;
1511 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001512
niklase@google.com470e71d2011-07-07 08:21:25 +00001513 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001514 delay = 0;
1515 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001516 }
1517
1518 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1519 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001520 delay = 500;
1521 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001522 }
1523
peahdf3efa82015-11-28 12:35:15 -08001524 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001525 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001526}
1527
1528int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001529 // Used as callback from submodules, hence locking is not allowed.
1530 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001531}
1532
1533bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001534 // Used as callback from submodules, hence locking is not allowed.
1535 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001536}
1537
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001538void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001539 rtc::CritScope cs(&crit_capture_);
1540 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001541}
1542
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001543void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001544 rtc::CritScope cs(&crit_capture_);
1545 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001546}
1547
1548int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001549 rtc::CritScope cs(&crit_capture_);
1550 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001551}
1552
aleloi868f32f2017-05-23 07:20:05 -07001553void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1554 RTC_DCHECK(aec_dump);
1555 rtc::CritScope cs_render(&crit_render_);
1556 rtc::CritScope cs_capture(&crit_capture_);
1557
1558 // The previously attached AecDump will be destroyed with the
1559 // 'aec_dump' parameter, which is after locks are released.
1560 aec_dump_.swap(aec_dump);
1561 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001562 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001563}
1564
1565void AudioProcessingImpl::DetachAecDump() {
1566 // The d-tor of a task-queue based AecDump blocks until all pending
1567 // tasks are done. This construction avoids blocking while holding
1568 // the render and capture locks.
1569 std::unique_ptr<AecDump> aec_dump = nullptr;
1570 {
1571 rtc::CritScope cs_render(&crit_render_);
1572 rtc::CritScope cs_capture(&crit_capture_);
1573 aec_dump = std::move(aec_dump_);
1574 }
1575}
1576
Sam Zackrisson4d364492018-03-02 16:03:21 +01001577void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1578 std::unique_ptr<AudioGenerator> audio_generator) {
1579 // TODO(bugs.webrtc.org/8882) Stub.
1580 // Reset internal audio generator with audio_generator.
1581}
1582
1583void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1584 // TODO(bugs.webrtc.org/8882) Stub.
1585 // Delete audio generator, if one is attached.
1586}
1587
Ivo Creusen56d46092017-11-24 17:29:59 +01001588AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001589 bool has_remote_tracks) const {
1590 AudioProcessingStats stats;
1591 if (has_remote_tracks) {
sazabe490b22018-10-03 17:03:13 +02001592 EchoCancellationImpl::Metrics metrics;
Yves Gerey499bc6c2018-10-10 18:29:07 +02001593 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001594 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001595 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1596 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001597 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001598 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001599 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001600 } else if (private_submodules_->echo_cancellation->GetMetrics(&metrics) ==
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001601 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001602 if (metrics.divergent_filter_fraction != -1.0f) {
1603 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001604 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001605 }
1606 if (metrics.echo_return_loss.instant != -100) {
1607 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001608 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001609 }
1610 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001611 stats.echo_return_loss_enhancement = absl::optional<double>(
1612 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001613 }
1614 }
1615 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001616 RTC_DCHECK(private_submodules_->echo_detector);
1617 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1618 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001619 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001620 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001621 }
1622 int delay_median, delay_std;
1623 float fraction_poor_delays;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001624 if (private_submodules_->echo_cancellation->GetDelayMetrics(
Ivo Creusenae026092017-11-20 13:07:16 +01001625 &delay_median, &delay_std, &fraction_poor_delays) ==
1626 Error::kNoError) {
1627 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001628 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001629 }
1630 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001631 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001632 }
1633 }
1634 }
1635 return stats;
1636}
1637
niklase@google.com470e71d2011-07-07 08:21:25 +00001638GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001639 if (constants_.use_experimental_agc) {
1640 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001641 }
peahbfa97112016-03-10 21:09:04 -08001642 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001643}
1644
niklase@google.com470e71d2011-07-07 08:21:25 +00001645LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001646 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001647}
1648
1649NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001650 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001651}
1652
1653VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001654 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001655}
1656
peah8271d042016-11-22 07:24:52 -08001657void AudioProcessingImpl::MutateConfig(
1658 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1659 rtc::CritScope cs_render(&crit_render_);
1660 rtc::CritScope cs_capture(&crit_capture_);
1661 mutator(&config_);
1662 ApplyConfig(config_);
1663}
1664
1665AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1666 rtc::CritScope cs_render(&crit_render_);
1667 rtc::CritScope cs_capture(&crit_capture_);
1668 return config_;
1669}
1670
peah2ace3f92016-09-10 04:42:27 -07001671bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1672 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001673 config_.high_pass_filter.enabled,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001674 private_submodules_->echo_cancellation->is_enabled(),
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001675 private_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001676 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001677 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001678 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001679 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001680 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001681 public_submodules_->voice_detection->is_enabled(),
1682 public_submodules_->level_estimator->is_enabled(),
1683 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001684}
1685
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001686void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001687 if (capture_.transient_suppressor_enabled) {
1688 if (!public_submodules_->transient_suppressor.get()) {
1689 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001690 }
peahdf3efa82015-11-28 12:35:15 -08001691 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001692 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1693 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001694 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001695}
1696
peah8271d042016-11-22 07:24:52 -08001697void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001698 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001699 private_submodules_->low_cut_filter.reset(
1700 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1701 } else {
1702 private_submodules_->low_cut_filter.reset();
1703 }
1704}
alessiob3ec96df2017-05-22 06:57:06 -07001705
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001706void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001707 if (echo_control_factory_) {
1708 private_submodules_->echo_controller =
1709 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001710 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001711 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001712 }
1713}
peah8271d042016-11-22 07:24:52 -08001714
alessiob3ec96df2017-05-22 06:57:06 -07001715void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001716 if (config_.gain_controller2.enabled) {
1717 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001718 }
1719}
1720
Alex Loikob5c9a792018-04-16 16:31:22 +02001721void AudioProcessingImpl::InitializePreAmplifier() {
1722 if (config_.pre_amplifier.enabled) {
1723 private_submodules_->pre_amplifier.reset(
1724 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1725 } else {
1726 private_submodules_->pre_amplifier.reset();
1727 }
1728}
1729
ivoc9f4a4a02016-10-28 05:39:16 -07001730void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001731 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001732 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001733 proc_sample_rate_hz(), 1,
1734 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001735}
1736
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001737void AudioProcessingImpl::InitializeAnalyzer() {
1738 if (private_submodules_->capture_analyzer) {
1739 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1740 num_proc_channels());
1741 }
1742}
1743
Sam Zackrisson0beac582017-09-25 12:04:02 +02001744void AudioProcessingImpl::InitializePostProcessor() {
1745 if (private_submodules_->capture_post_processor) {
1746 private_submodules_->capture_post_processor->Initialize(
1747 proc_sample_rate_hz(), num_proc_channels());
1748 }
1749}
1750
Alex Loiko5825aa62017-12-18 16:02:40 +01001751void AudioProcessingImpl::InitializePreProcessor() {
1752 if (private_submodules_->render_pre_processor) {
1753 private_submodules_->render_pre_processor->Initialize(
1754 formats_.render_processing_format.sample_rate_hz(),
1755 formats_.render_processing_format.num_channels());
1756 }
1757}
1758
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001759void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001760 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001761
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001762 if (private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001763 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1764 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001765 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001766 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001767 capture_.stream_delay_jumps = 0;
1768 }
1769 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001770 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001771 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001772 }
1773
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001774 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001775 const int diff_stream_delay_ms =
1776 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1777 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1778 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001779 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1780 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001781 if (capture_.stream_delay_jumps == -1) {
1782 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001783 }
peahdf3efa82015-11-28 12:35:15 -08001784 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001785 }
peahdf3efa82015-11-28 12:35:15 -08001786 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001787
1788 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001789 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001790 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001791 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001792 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001793 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001794 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001795 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001796 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001797 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001798 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001799 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1800 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1801 100);
peahdf3efa82015-11-28 12:35:15 -08001802 if (capture_.aec_system_delay_jumps == -1) {
1803 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001804 }
peahdf3efa82015-11-28 12:35:15 -08001805 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001806 }
peahdf3efa82015-11-28 12:35:15 -08001807 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001808 }
1809}
1810
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001811void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001812 // Run in a single-threaded manner.
1813 rtc::CritScope cs_render(&crit_render_);
1814 rtc::CritScope cs_capture(&crit_capture_);
1815
1816 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001817 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001818 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001819 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001820 }
peahdf3efa82015-11-28 12:35:15 -08001821 capture_.stream_delay_jumps = -1;
1822 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001823
peahdf3efa82015-11-28 12:35:15 -08001824 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001825 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1826 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001827 }
peahdf3efa82015-11-28 12:35:15 -08001828 capture_.aec_system_delay_jumps = -1;
1829 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001830}
1831
aleloi868f32f2017-05-23 07:20:05 -07001832void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1833 if (!aec_dump_) {
1834 return;
1835 }
1836 std::string experiments_description =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001837 private_submodules_->echo_cancellation->GetExperimentsDescription();
aleloi868f32f2017-05-23 07:20:05 -07001838 // TODO(peah): Add semicolon-separated concatenations of experiment
1839 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001840 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1841 experiments_description += "AgcClippingLevelExperiment;";
1842 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001843 if (capture_nonlocked_.echo_controller_enabled) {
1844 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001845 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001846 if (config_.gain_controller2.enabled) {
1847 experiments_description += "GainController2;";
1848 }
aleloi868f32f2017-05-23 07:20:05 -07001849
1850 InternalAPMConfig apm_config;
1851
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001852 apm_config.aec_enabled = private_submodules_->echo_cancellation->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001853 apm_config.aec_delay_agnostic_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001854 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001855 apm_config.aec_drift_compensation_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001856 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001857 apm_config.aec_extended_filter_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001858 private_submodules_->echo_cancellation->is_extended_filter_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001859 apm_config.aec_suppression_level = static_cast<int>(
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001860 private_submodules_->echo_cancellation->suppression_level());
aleloi868f32f2017-05-23 07:20:05 -07001861
1862 apm_config.aecm_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001863 private_submodules_->echo_control_mobile->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001864 apm_config.aecm_comfort_noise_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001865 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1866 apm_config.aecm_routing_mode = static_cast<int>(
1867 private_submodules_->echo_control_mobile->routing_mode());
aleloi868f32f2017-05-23 07:20:05 -07001868
1869 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1870 apm_config.agc_mode =
1871 static_cast<int>(public_submodules_->gain_control->mode());
1872 apm_config.agc_limiter_enabled =
1873 public_submodules_->gain_control->is_limiter_enabled();
1874 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1875
1876 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1877
1878 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1879 apm_config.ns_level =
1880 static_cast<int>(public_submodules_->noise_suppression->level());
1881
1882 apm_config.transient_suppression_enabled =
1883 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001884 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001885 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1886 apm_config.pre_amplifier_fixed_gain_factor =
1887 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001888
1889 if (!forced && apm_config == apm_config_for_aec_dump_) {
1890 return;
1891 }
1892 aec_dump_->WriteConfig(apm_config);
1893 apm_config_for_aec_dump_ = apm_config;
1894}
1895
1896void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1897 const float* const* src) {
1898 RTC_DCHECK(aec_dump_);
1899 WriteAecDumpConfigMessage(false);
1900
1901 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1902 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1903 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001904 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001905 RecordAudioProcessingState();
1906}
1907
1908void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1909 const AudioFrame& capture_frame) {
1910 RTC_DCHECK(aec_dump_);
1911 WriteAecDumpConfigMessage(false);
1912
1913 aec_dump_->AddCaptureStreamInput(capture_frame);
1914 RecordAudioProcessingState();
1915}
1916
1917void AudioProcessingImpl::RecordProcessedCaptureStream(
1918 const float* const* processed_capture_stream) {
1919 RTC_DCHECK(aec_dump_);
1920
1921 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1922 const size_t num_channels =
1923 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001924 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1925 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001926 aec_dump_->WriteCaptureStreamMessage();
1927}
1928
1929void AudioProcessingImpl::RecordProcessedCaptureStream(
1930 const AudioFrame& processed_capture_frame) {
1931 RTC_DCHECK(aec_dump_);
1932
1933 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1934 aec_dump_->WriteCaptureStreamMessage();
1935}
1936
1937void AudioProcessingImpl::RecordAudioProcessingState() {
1938 RTC_DCHECK(aec_dump_);
1939 AecDump::AudioProcessingState audio_proc_state;
1940 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
1941 audio_proc_state.drift =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001942 private_submodules_->echo_cancellation->stream_drift_samples();
aleloi868f32f2017-05-23 07:20:05 -07001943 audio_proc_state.level = gain_control()->stream_analog_level();
1944 audio_proc_state.keypress = capture_.key_pressed;
1945 aec_dump_->AddAudioProcessingState(audio_proc_state);
1946}
1947
kwiberg83ffe452016-08-29 14:46:07 -07001948AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001949 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07001950 : aec_system_delay_jumps(-1),
1951 delay_offset_ms(0),
1952 was_stream_delay_set(false),
1953 last_stream_delay_ms(0),
1954 last_aec_system_delay_ms(0),
1955 stream_delay_jumps(-1),
1956 output_will_be_muted(false),
1957 key_pressed(false),
1958 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07001959 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001960 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02001961 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02001962 prev_analog_mic_level(-1),
1963 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07001964
1965AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1966
1967AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1968
1969AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1970
niklase@google.com470e71d2011-07-07 08:21:25 +00001971} // namespace webrtc