blob: 9712d42d22d43cfc3161cf59d01a7133f160c51b [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.
peahbb9edbd2016-03-10 12:54:25 -0800230 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800231 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800232 std::unique_ptr<LevelEstimatorImpl> level_estimator;
233 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
234 std::unique_ptr<VoiceDetectionImpl> voice_detection;
235 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800236 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800237
238 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800239 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800240};
241
242struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200243 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100244 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200245 rtc::scoped_refptr<EchoDetector> echo_detector,
246 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200247 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100248 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200249 render_pre_processor(std::move(render_pre_processor)),
250 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800251 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800252 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700253 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800254 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200255 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200256 std::unique_ptr<EchoControl> echo_controller;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100257 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
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
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100370 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
peahbb9edbd2016-03-10 12:54:25 -0800371 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700372 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800373 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200374 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800375 public_submodules_->level_estimator.reset(
376 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800377 public_submodules_->noise_suppression.reset(
378 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800379 public_submodules_->voice_detection.reset(
380 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800381 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800382 new GainControlForExperimentalAgc(
383 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100384
385 // If no echo detector is injected, use the ResidualEchoDetector.
386 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200387 private_submodules_->echo_detector =
388 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100389 }
peahca4cac72016-06-29 15:26:12 -0700390
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200391 // TODO(alessiob): Move the injected gain controller once injection is
392 // implemented.
393 private_submodules_->gain_controller2.reset(new GainController2());
394
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200395 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
396 << !!private_submodules_->capture_analyzer
397 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100398 << !!private_submodules_->capture_post_processor
399 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100400 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800401 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000402
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000403 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000404}
405
406AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800407 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800408 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800409 private_submodules_->agc_manager.reset();
410 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800411 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000412}
413
niklase@google.com470e71d2011-07-07 08:21:25 +0000414int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800415 // Run in a single-threaded manner during initialization.
416 rtc::CritScope cs_render(&crit_render_);
417 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000418 return InitializeLocked();
419}
420
peahde65ddc2016-09-16 15:02:15 -0700421int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
422 int capture_output_sample_rate_hz,
423 int render_input_sample_rate_hz,
424 ChannelLayout capture_input_layout,
425 ChannelLayout capture_output_layout,
426 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700427 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700428 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
429 LayoutHasKeyboard(capture_input_layout)},
430 {capture_output_sample_rate_hz,
431 ChannelsFromLayout(capture_output_layout),
432 LayoutHasKeyboard(capture_output_layout)},
433 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
434 LayoutHasKeyboard(render_input_layout)},
435 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
436 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700437
438 return Initialize(processing_config);
439}
440
441int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800442 // Run in a single-threaded manner during initialization.
443 rtc::CritScope cs_render(&crit_render_);
444 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700445 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000446}
447
peahdf3efa82015-11-28 12:35:15 -0800448int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800449 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700450 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800451}
452
peahdf3efa82015-11-28 12:35:15 -0800453int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700454 const ProcessingConfig& processing_config,
455 bool force_initialization) {
456 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800457}
458
peah192164e2015-11-17 02:16:45 -0800459// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800460// their current values (needs to be called while holding the crit_render_lock).
461int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700462 const ProcessingConfig& processing_config,
463 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800464 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700465 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800466 return kNoError;
467 }
peahdf3efa82015-11-28 12:35:15 -0800468
469 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800470 return InitializeLocked(processing_config);
471}
472
niklase@google.com470e71d2011-07-07 08:21:25 +0000473int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200474 UpdateActiveSubmoduleStates();
475
peahde65ddc2016-09-16 15:02:15 -0700476 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800477 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700478 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800479 : formats_.api_format.reverse_output_stream().num_frames();
480 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
481 render_.render_audio.reset(new AudioBuffer(
482 formats_.api_format.reverse_input_stream().num_frames(),
483 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700484 formats_.render_processing_format.num_frames(),
485 formats_.render_processing_format.num_channels(),
486 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700487 if (formats_.api_format.reverse_input_stream() !=
488 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800489 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800490 formats_.api_format.reverse_input_stream().num_channels(),
491 formats_.api_format.reverse_input_stream().num_frames(),
492 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800493 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700494 } else {
peahdf3efa82015-11-28 12:35:15 -0800495 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700496 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700497 } else {
peahdf3efa82015-11-28 12:35:15 -0800498 render_.render_audio.reset(nullptr);
499 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700500 }
peahce4d9152017-05-19 01:28:05 -0700501
peahdf3efa82015-11-28 12:35:15 -0800502 capture_.capture_audio.reset(
503 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
504 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700505 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200506 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800507 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000508
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100509 private_submodules_->echo_cancellation->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700510 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
511 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700512 AllocateRenderQueue();
513
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100514 int success = private_submodules_->echo_cancellation->enable_metrics(true);
ivoc3e9a5372016-10-28 07:55:33 -0700515 RTC_DCHECK_EQ(0, success);
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100516 success = private_submodules_->echo_cancellation->enable_delay_logging(true);
ivoc3e9a5372016-10-28 07:55:33 -0700517 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700518 public_submodules_->echo_control_mobile->Initialize(
519 proc_split_sample_rate_hz(), num_reverse_channels(),
520 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700521
522 public_submodules_->gain_control->Initialize(num_proc_channels(),
523 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700524 if (constants_.use_experimental_agc) {
525 if (!private_submodules_->agc_manager.get()) {
526 private_submodules_->agc_manager.reset(new AgcManagerDirect(
527 public_submodules_->gain_control.get(),
528 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200529 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
530 constants_.use_experimental_agc_agc2_level_estimation,
531 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700532 }
533 private_submodules_->agc_manager->Initialize();
534 private_submodules_->agc_manager->SetCaptureMuted(
535 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700536 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700537 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200538 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800539 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700540 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
541 proc_sample_rate_hz());
542 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
543 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700544 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200545 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700546 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200547 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200548 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100549 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800550
aleloi868f32f2017-05-23 07:20:05 -0700551 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200552 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700553 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000554 return kNoError;
555}
556
Michael Graczyk86c6d332015-07-23 11:41:39 -0700557int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200558 UpdateActiveSubmoduleStates();
559
Michael Graczyk86c6d332015-07-23 11:41:39 -0700560 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700561 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
562 return kBadSampleRateError;
563 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000564 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700565
Peter Kasting69558702016-01-12 16:26:35 -0800566 const size_t num_in_channels = config.input_stream().num_channels();
567 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700568
569 // Need at least one input channel.
570 // Need either one output channel or as many outputs as there are inputs.
571 if (num_in_channels == 0 ||
572 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700573 return kBadNumberChannelsError;
574 }
575
peahdf3efa82015-11-28 12:35:15 -0800576 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000577
peahde65ddc2016-09-16 15:02:15 -0700578 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700579 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700580 formats_.api_format.output_stream().sample_rate_hz()),
581 submodule_states_.CaptureMultiBandSubModulesActive() ||
582 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000583
peahde65ddc2016-09-16 15:02:15 -0700584 capture_nonlocked_.capture_processing_format =
585 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700586
peah2ce640f2017-04-07 03:57:48 -0700587 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200588 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700589 render_processing_rate = FindNativeProcessRateToUse(
590 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
591 formats_.api_format.reverse_output_stream().sample_rate_hz()),
592 submodule_states_.CaptureMultiBandSubModulesActive() ||
593 submodule_states_.RenderMultiBandSubModulesActive());
594 } else {
595 render_processing_rate = capture_processing_rate;
596 }
597
aluebseb3603b2016-04-20 15:27:58 -0700598 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
599 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700600 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200601 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700602 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
603 ? kSampleRate32kHz
604 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700605 }
peah2ce640f2017-04-07 03:57:48 -0700606
peahde65ddc2016-09-16 15:02:15 -0700607 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700608 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700609 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
610 kSampleRate8kHz) {
611 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000612 } else {
peahde65ddc2016-09-16 15:02:15 -0700613 render_processing_rate =
614 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000615 }
616
peahde65ddc2016-09-16 15:02:15 -0700617 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000618 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700619 if (submodule_states_.RenderMultiBandSubModulesActive()) {
620 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
621 } else {
622 formats_.render_processing_format = StreamConfig(
623 formats_.api_format.reverse_input_stream().sample_rate_hz(),
624 formats_.api_format.reverse_input_stream().num_channels());
625 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000626
peahde65ddc2016-09-16 15:02:15 -0700627 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
628 kSampleRate32kHz ||
629 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
630 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800631 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000632 } else {
peahdf3efa82015-11-28 12:35:15 -0800633 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700634 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000635 }
636
637 return InitializeLocked();
638}
639
peah88ac8532016-09-12 16:47:25 -0700640void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700641 // Run in a single-threaded manner when applying the settings.
642 rtc::CritScope cs_render(&crit_render_);
643 rtc::CritScope cs_capture(&crit_capture_);
644
Yves Gerey499bc6c2018-10-10 18:29:07 +0200645 config_ = config;
646
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100647 private_submodules_->echo_cancellation->Enable(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200648 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200649 public_submodules_->echo_control_mobile->Enable(
650 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200651
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100652 private_submodules_->echo_cancellation->set_suppression_level(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200653 config.echo_canceller.legacy_moderate_suppression_level
sazabe490b22018-10-03 17:03:13 +0200654 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
655 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200656
peah8271d042016-11-22 07:24:52 -0800657 InitializeLowCutFilter();
658
Mirko Bonadei675513b2017-11-09 11:09:25 +0100659 RTC_LOG(LS_INFO) << "Highpass filter activated: "
660 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800661
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100662 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700663 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100664 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
665 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100666 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100667 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700668 config_.gain_controller2 = AudioProcessing::Config::GainController2();
669 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200670 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200671 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200672 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100673 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
674 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200675 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
676 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700677}
678
679void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800680 // Run in a single-threaded manner when setting the extra options.
681 rtc::CritScope cs_render(&crit_render_);
682 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000683
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100684 private_submodules_->echo_cancellation->SetExtraOptions(config);
peahb624d8c2016-03-05 03:01:14 -0800685
peahdf3efa82015-11-28 12:35:15 -0800686 if (capture_.transient_suppressor_enabled !=
687 config.Get<ExperimentalNs>().enabled) {
688 capture_.transient_suppressor_enabled =
689 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000690 InitializeTransient();
691 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000692}
693
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000694int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800695 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700696 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000697}
698
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000699int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800700 // Used as callback from submodules, hence locking is not allowed.
701 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000702}
703
Peter Kasting69558702016-01-12 16:26:35 -0800704size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800705 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700706 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000707}
708
Peter Kasting69558702016-01-12 16:26:35 -0800709size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800710 // Used as callback from submodules, hence locking is not allowed.
711 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000712}
713
Peter Kasting69558702016-01-12 16:26:35 -0800714size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800715 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200716 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800717}
718
Peter Kasting69558702016-01-12 16:26:35 -0800719size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800720 // Used as callback from submodules, hence locking is not allowed.
721 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000722}
723
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000724void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800725 rtc::CritScope cs(&crit_capture_);
726 capture_.output_will_be_muted = muted;
727 if (private_submodules_->agc_manager.get()) {
728 private_submodules_->agc_manager->SetCaptureMuted(
729 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000730 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000731}
732
Alessio Bazzicac054e782018-04-16 12:10:09 +0200733void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200734 switch (setting.type()) {
735 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
736 render_runtime_settings_enqueuer_.Enqueue(setting);
737 return;
738 case RuntimeSetting::Type::kNotSpecified:
739 RTC_NOTREACHED();
740 return;
741 case RuntimeSetting::Type::kCapturePreGain:
742 capture_runtime_settings_enqueuer_.Enqueue(setting);
743 return;
744 }
745 // The language allows the enum to have a non-enumerator
746 // value. Check that this doesn't happen.
747 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200748}
749
750AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
751 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200752 : runtime_settings_(*runtime_settings) {
753 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200754}
755
756AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
757 default;
758
759void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
760 RuntimeSetting setting) {
761 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200762 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200763 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200764 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200765 RTC_LOG(LS_ERROR)
766 << "The runtime settings queue is full. Oldest setting discarded.";
767 }
768 if (remaining_attempts == 0)
769 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
770}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000771
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000772int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700773 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000774 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000775 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000776 int output_sample_rate_hz,
777 ChannelLayout output_layout,
778 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800779 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800780 StreamConfig input_stream;
781 StreamConfig output_stream;
782 {
783 // Access the formats_.api_format.input_stream beneath the capture lock.
784 // The lock must be released as it is later required in the call
785 // to ProcessStream(,,,);
786 rtc::CritScope cs(&crit_capture_);
787 input_stream = formats_.api_format.input_stream();
788 output_stream = formats_.api_format.output_stream();
789 }
790
Michael Graczyk86c6d332015-07-23 11:41:39 -0700791 input_stream.set_sample_rate_hz(input_sample_rate_hz);
792 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
793 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700794 output_stream.set_sample_rate_hz(output_sample_rate_hz);
795 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
796 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
797
798 if (samples_per_channel != input_stream.num_frames()) {
799 return kBadDataLengthError;
800 }
801 return ProcessStream(src, input_stream, output_stream, dest);
802}
803
804int AudioProcessingImpl::ProcessStream(const float* const* src,
805 const StreamConfig& input_config,
806 const StreamConfig& output_config,
807 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800808 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800809 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700810 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800811 {
812 // Acquire the capture lock in order to safely call the function
813 // that retrieves the render side data. This function accesses apm
814 // getters that need the capture lock held when being called.
815 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700816 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800817
818 if (!src || !dest) {
819 return kNullPointerError;
820 }
821
822 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700823 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000824 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000825
Michael Graczyk86c6d332015-07-23 11:41:39 -0700826 processing_config.input_stream() = input_config;
827 processing_config.output_stream() = output_config;
828
peahdf3efa82015-11-28 12:35:15 -0800829 {
830 // Do conditional reinitialization.
831 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700832 RETURN_ON_ERR(
833 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800834 }
835 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700836 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
837 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000838
aleloi868f32f2017-05-23 07:20:05 -0700839 if (aec_dump_) {
840 RecordUnprocessedCaptureStream(src);
841 }
842
peahdf3efa82015-11-28 12:35:15 -0800843 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700844 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800845 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000846
aleloi868f32f2017-05-23 07:20:05 -0700847 if (aec_dump_) {
848 RecordProcessedCaptureStream(dest);
849 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000850 return kNoError;
851}
852
Alex Loiko73ec0192018-05-15 10:52:28 +0200853void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200854 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200855 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200856 if (aec_dump_) {
857 aec_dump_->WriteRuntimeSetting(setting);
858 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200859 switch (setting.type()) {
860 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200861 if (config_.pre_amplifier.enabled) {
862 float value;
863 setting.GetFloat(&value);
864 private_submodules_->pre_amplifier->SetGainFactor(value);
865 }
866 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200867 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200868 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
869 RTC_NOTREACHED();
870 break;
871 case RuntimeSetting::Type::kNotSpecified:
872 RTC_NOTREACHED();
873 break;
874 }
875 }
876}
877
878void AudioProcessingImpl::HandleRenderRuntimeSettings() {
879 RuntimeSetting setting;
880 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200881 if (aec_dump_) {
882 aec_dump_->WriteRuntimeSetting(setting);
883 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200884 switch (setting.type()) {
885 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
886 if (private_submodules_->render_pre_processor) {
887 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
888 }
889 break;
890 case RuntimeSetting::Type::kCapturePreGain:
891 RTC_NOTREACHED();
892 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200893 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200894 RTC_NOTREACHED();
895 break;
896 }
897 }
898}
899
peah9e6a2902017-05-15 07:19:21 -0700900void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700901 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
902 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700903 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700904
kwibergaf476c72016-11-28 15:21:39 -0800905 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700906
907 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700908 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700909 // The data queue is full and needs to be emptied.
910 EmptyQueuedRenderAudio();
911
912 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700913 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700914 RTC_DCHECK(result);
915 }
916
917 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
918 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700919 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700920
921 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700922 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700923 // The data queue is full and needs to be emptied.
924 EmptyQueuedRenderAudio();
925
926 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700927 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700928 RTC_DCHECK(result);
929 }
peah701d6282016-10-25 05:42:20 -0700930
931 if (!constants_.use_experimental_agc) {
932 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
933 // Insert the samples into the queue.
934 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
935 // The data queue is full and needs to be emptied.
936 EmptyQueuedRenderAudio();
937
938 // Retry the insert (should always work).
939 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
940 RTC_DCHECK(result);
941 }
942 }
peah9e6a2902017-05-15 07:19:21 -0700943}
ivoc9f4a4a02016-10-28 05:39:16 -0700944
peah9e6a2902017-05-15 07:19:21 -0700945void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700946 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
947
948 // Insert the samples into the queue.
949 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
950 // The data queue is full and needs to be emptied.
951 EmptyQueuedRenderAudio();
952
953 // Retry the insert (should always work).
954 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
955 RTC_DCHECK(result);
956 }
peah764e3642016-10-22 05:04:30 -0700957}
958
959void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700960 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700961 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700962 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700963 EchoCancellationImpl::NumCancellersRequired(
964 num_output_channels(), num_reverse_channels()));
965
peah701d6282016-10-25 05:42:20 -0700966 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700967 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700968 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700969 EchoControlMobileImpl::NumCancellersRequired(
970 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700971
peah701d6282016-10-25 05:42:20 -0700972 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700973 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700974
ivoc9f4a4a02016-10-28 05:39:16 -0700975 const size_t new_red_render_queue_element_max_size =
976 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
977
peaha0624602016-10-25 04:45:24 -0700978 // Reallocate the queues if the queue item sizes are too small to fit the
979 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700980 if (aec_render_queue_element_max_size_ <
981 new_aec_render_queue_element_max_size) {
982 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700983
peaha0624602016-10-25 04:45:24 -0700984 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700985 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700986
peah701d6282016-10-25 05:42:20 -0700987 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700988 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
989 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700990 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700991 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700992
peah701d6282016-10-25 05:42:20 -0700993 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
994 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700995 } else {
peah701d6282016-10-25 05:42:20 -0700996 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700997 }
998
peah701d6282016-10-25 05:42:20 -0700999 if (aecm_render_queue_element_max_size_ <
1000 new_aecm_render_queue_element_max_size) {
1001 aecm_render_queue_element_max_size_ =
1002 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001003
1004 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001005 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001006
peah701d6282016-10-25 05:42:20 -07001007 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001008 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1009 kMaxNumFramesToBuffer, template_queue_element,
1010 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001011 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001012
peah701d6282016-10-25 05:42:20 -07001013 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1014 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001015 } else {
peah701d6282016-10-25 05:42:20 -07001016 aecm_render_signal_queue_->Clear();
1017 }
1018
1019 if (agc_render_queue_element_max_size_ <
1020 new_agc_render_queue_element_max_size) {
1021 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1022
1023 std::vector<int16_t> template_queue_element(
1024 agc_render_queue_element_max_size_);
1025
1026 agc_render_signal_queue_.reset(
1027 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1028 kMaxNumFramesToBuffer, template_queue_element,
1029 RenderQueueItemVerifier<int16_t>(
1030 agc_render_queue_element_max_size_)));
1031
1032 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1033 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1034 } else {
1035 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001036 }
ivoc9f4a4a02016-10-28 05:39:16 -07001037
1038 if (red_render_queue_element_max_size_ <
1039 new_red_render_queue_element_max_size) {
1040 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1041
1042 std::vector<float> template_queue_element(
1043 red_render_queue_element_max_size_);
1044
1045 red_render_signal_queue_.reset(
1046 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1047 kMaxNumFramesToBuffer, template_queue_element,
1048 RenderQueueItemVerifier<float>(
1049 red_render_queue_element_max_size_)));
1050
1051 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1052 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1053 } else {
1054 red_render_signal_queue_->Clear();
1055 }
peah764e3642016-10-22 05:04:30 -07001056}
1057
1058void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1059 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001060 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001061 private_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001062 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001063 }
1064
peah701d6282016-10-25 05:42:20 -07001065 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001066 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001067 aecm_capture_queue_buffer_);
1068 }
1069
1070 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1071 public_submodules_->gain_control->ProcessRenderAudio(
1072 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001073 }
ivoc9f4a4a02016-10-28 05:39:16 -07001074
1075 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001076 RTC_DCHECK(private_submodules_->echo_detector);
1077 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001078 red_capture_queue_buffer_);
1079 }
peah764e3642016-10-22 05:04:30 -07001080}
1081
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001082int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001083 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001084 {
1085 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001086 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001087 // getters that need the capture lock held when being called.
1088 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001089 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001090 // as well.
1091 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001092 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001093 }
peahfa6228e2015-11-16 16:27:42 -08001094
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001095 if (!frame) {
1096 return kNullPointerError;
1097 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001098 // Must be a native rate.
1099 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1100 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001101 frame->sample_rate_hz_ != kSampleRate32kHz &&
1102 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001103 return kBadSampleRateError;
1104 }
peah192164e2015-11-17 02:16:45 -08001105
peahdf3efa82015-11-28 12:35:15 -08001106 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001107 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001108 {
1109 // Aquire lock for the access of api_format.
1110 // The lock is released immediately due to the conditional
1111 // reinitialization.
1112 rtc::CritScope cs_capture(&crit_capture_);
1113 // TODO(ajm): The input and output rates and channels are currently
1114 // constrained to be identical in the int16 interface.
1115 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001116
1117 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001118 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001119 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1120 processing_config.input_stream().set_num_channels(frame->num_channels_);
1121 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1122 processing_config.output_stream().set_num_channels(frame->num_channels_);
1123
peahdf3efa82015-11-28 12:35:15 -08001124 {
1125 // Do conditional reinitialization.
1126 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001127 RETURN_ON_ERR(
1128 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001129 }
1130 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001131 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001132 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001133 return kBadDataLengthError;
1134 }
1135
aleloi868f32f2017-05-23 07:20:05 -07001136 if (aec_dump_) {
1137 RecordUnprocessedCaptureStream(*frame);
1138 }
1139
peahdf3efa82015-11-28 12:35:15 -08001140 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001141 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001142 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001143 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1144 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001145
aleloi868f32f2017-05-23 07:20:05 -07001146 if (aec_dump_) {
1147 RecordProcessedCaptureStream(*frame);
1148 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001149
1150 return kNoError;
1151}
1152
peahde65ddc2016-09-16 15:02:15 -07001153int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001154 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001155
peahb58a1582016-03-15 09:34:24 -07001156 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001157 // TODO(peah): Simplify once the public API Enable functions for these
1158 // are moved to APM.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001159 RTC_DCHECK(!(private_submodules_->echo_cancellation->is_enabled() &&
peahb58a1582016-03-15 09:34:24 -07001160 public_submodules_->echo_control_mobile->is_enabled()));
1161
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001162 MaybeUpdateHistograms();
1163
peahde65ddc2016-09-16 15:02:15 -07001164 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001165
Alex Loikob5c9a792018-04-16 16:31:22 +02001166 if (private_submodules_->pre_amplifier) {
1167 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1168 capture_buffer->channels_f(), capture_buffer->num_channels(),
1169 capture_buffer->num_frames()));
1170 }
1171
peah1b08dc32016-12-20 13:45:58 -08001172 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001173 capture_buffer->channels_const()[0],
1174 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001175 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1176 if (log_rms) {
1177 capture_rms_interval_counter_ = 0;
1178 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001179 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1180 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1181 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1182 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001183 }
1184
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001185 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001186 // Detect and flag any change in the analog gain.
1187 int analog_mic_level = gain_control()->stream_analog_level();
1188 capture_.echo_path_gain_change =
1189 capture_.prev_analog_mic_level != analog_mic_level &&
1190 capture_.prev_analog_mic_level != -1;
1191 capture_.prev_analog_mic_level = analog_mic_level;
1192
Per Åhgrend2650d12018-10-02 17:00:59 +02001193 // Detect and flag any change in the pre-amplifier gain.
1194 if (private_submodules_->pre_amplifier) {
1195 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1196 capture_.echo_path_gain_change =
1197 capture_.echo_path_gain_change ||
1198 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001199 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001200 capture_.prev_pre_amp_gain = pre_amp_gain;
1201 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001202 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001203 }
1204
peahbe615622016-02-13 16:40:47 -08001205 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001206 public_submodules_->gain_control->is_enabled()) {
1207 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001208 capture_buffer->channels()[0], capture_buffer->num_channels(),
1209 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001210
1211 if (constants_.use_experimental_agc_process_before_aec) {
1212 private_submodules_->agc_manager->Process(
1213 capture_buffer->channels()[0],
1214 capture_nonlocked_.capture_processing_format.num_frames(),
1215 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1216 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001217 }
1218
peah2ace3f92016-09-10 04:42:27 -07001219 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1220 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001221 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1222 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001223 }
1224
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001225 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001226 // Force down-mixing of the number of channels after the detection of
1227 // capture signal saturation.
1228 // TODO(peah): Look into ensuring that this kind of tampering with the
1229 // AudioBuffer functionality should not be needed.
1230 capture_buffer->set_num_channels(1);
1231 }
1232
peahe0eae3c2016-12-14 01:16:23 -08001233 // TODO(peah): Move the AEC3 low-cut filter to this place.
1234 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001235 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001236 private_submodules_->low_cut_filter->Process(capture_buffer);
1237 }
peahde65ddc2016-09-16 15:02:15 -07001238 RETURN_ON_ERR(
1239 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1240 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001241
1242 // Ensure that the stream delay was set before the call to the
1243 // AEC ProcessCaptureAudio function.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001244 if (private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001245 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001246 return AudioProcessing::kStreamParameterNotSetError;
1247 }
1248
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001249 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001250 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1251
Per Åhgrend0fa8202018-04-18 09:35:13 +02001252 if (was_stream_delay_set()) {
1253 private_submodules_->echo_controller->SetAudioBufferDelay(
1254 stream_delay_ms());
1255 }
1256
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001257 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001258 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001259 } else {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001260 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
peah61202ac2017-02-06 03:39:42 -08001261 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001262 }
1263
peahdf3efa82015-11-28 12:35:15 -08001264 if (public_submodules_->echo_control_mobile->is_enabled() &&
1265 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001266 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001267 }
peahde65ddc2016-09-16 15:02:15 -07001268 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001269
1270 // Ensure that the stream delay was set before the call to the
1271 // AECM ProcessCaptureAudio function.
1272 if (public_submodules_->echo_control_mobile->is_enabled() &&
1273 !was_stream_delay_set()) {
1274 return AudioProcessing::kStreamParameterNotSetError;
1275 }
1276
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001277 if (!(private_submodules_->echo_controller ||
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001278 private_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001279 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1280 capture_buffer, stream_delay_ms()));
1281 }
ivoc9f4a4a02016-10-28 05:39:16 -07001282
peahde65ddc2016-09-16 15:02:15 -07001283 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001284
peahbe615622016-02-13 16:40:47 -08001285 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001286 public_submodules_->gain_control->is_enabled() &&
1287 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001288 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001289 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1290 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001291 }
peahb8fbb542016-03-15 02:28:08 -07001292 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001293 capture_buffer,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001294 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001295
peah2ace3f92016-09-10 04:42:27 -07001296 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1297 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001298 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1299 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001300 }
1301
peah9e6a2902017-05-15 07:19:21 -07001302 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001303 RTC_DCHECK(private_submodules_->echo_detector);
1304 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001305 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1306 capture_buffer->num_frames()));
1307 }
1308
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001309 // TODO(aluebs): Investigate if the transient suppression placement should be
1310 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001311 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001312 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001313 private_submodules_->agc_manager.get()
1314 ? private_submodules_->agc_manager->voice_probability()
1315 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001316
peahdf3efa82015-11-28 12:35:15 -08001317 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001318 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1319 capture_buffer->num_channels(),
1320 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1321 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1322 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001323 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001324 }
1325
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001326 // Experimental APM sub-module that analyzes |capture_buffer|.
1327 if (private_submodules_->capture_analyzer) {
1328 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1329 }
1330
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001331 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001332 private_submodules_->gain_controller2->NotifyAnalogLevel(
1333 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001334 private_submodules_->gain_controller2->Process(capture_buffer);
1335 }
1336
Sam Zackrisson0beac582017-09-25 12:04:02 +02001337 if (private_submodules_->capture_post_processor) {
1338 private_submodules_->capture_post_processor->Process(capture_buffer);
1339 }
1340
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001341 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001342 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001343
peah1b08dc32016-12-20 13:45:58 -08001344 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1345 capture_buffer->channels_const()[0],
1346 capture_nonlocked_.capture_processing_format.num_frames()));
1347 if (log_rms) {
1348 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1349 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1350 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1351 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1352 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1353 }
1354
peahdf3efa82015-11-28 12:35:15 -08001355 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001356 return kNoError;
1357}
1358
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001359int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001360 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001361 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001362 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001363 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001364 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001365 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001366 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001367 };
1368 if (samples_per_channel != reverse_config.num_frames()) {
1369 return kBadDataLengthError;
1370 }
peahdf3efa82015-11-28 12:35:15 -08001371 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001372}
1373
peahde65ddc2016-09-16 15:02:15 -07001374int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1375 const StreamConfig& input_config,
1376 const StreamConfig& output_config,
1377 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001378 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001379 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001380 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001381 if (submodule_states_.RenderMultiBandProcessingActive() ||
1382 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001383 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1384 dest);
peah2ace3f92016-09-10 04:42:27 -07001385 } else if (formats_.api_format.reverse_input_stream() !=
1386 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001387 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1388 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001389 } else {
peahde65ddc2016-09-16 15:02:15 -07001390 CopyAudioIfNeeded(src, input_config.num_frames(),
1391 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001392 }
1393
1394 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001395}
1396
peahdf3efa82015-11-28 12:35:15 -08001397int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001398 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001399 const StreamConfig& input_config,
1400 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001401 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001402 return kNullPointerError;
1403 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001404
peahde65ddc2016-09-16 15:02:15 -07001405 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001406 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001407 }
1408
peahdf3efa82015-11-28 12:35:15 -08001409 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001410 processing_config.reverse_input_stream() = input_config;
1411 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001412
peahdf3efa82015-11-28 12:35:15 -08001413 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001414 RTC_DCHECK_EQ(input_config.num_frames(),
1415 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001416
aleloi868f32f2017-05-23 07:20:05 -07001417 if (aec_dump_) {
1418 const size_t channel_size =
1419 formats_.api_format.reverse_input_stream().num_frames();
1420 const size_t num_channels =
1421 formats_.api_format.reverse_input_stream().num_channels();
1422 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001423 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001424 }
peahdf3efa82015-11-28 12:35:15 -08001425 render_.render_audio->CopyFrom(src,
1426 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001427 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001428}
1429
1430int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001431 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001432 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001433 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001434 return kNullPointerError;
1435 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001436 // Must be a native rate.
1437 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1438 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001439 frame->sample_rate_hz_ != kSampleRate32kHz &&
1440 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001441 return kBadSampleRateError;
1442 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001443
Michael Graczyk86c6d332015-07-23 11:41:39 -07001444 if (frame->num_channels_ <= 0) {
1445 return kBadNumberChannelsError;
1446 }
1447
peahdf3efa82015-11-28 12:35:15 -08001448 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001449 processing_config.reverse_input_stream().set_sample_rate_hz(
1450 frame->sample_rate_hz_);
1451 processing_config.reverse_input_stream().set_num_channels(
1452 frame->num_channels_);
1453 processing_config.reverse_output_stream().set_sample_rate_hz(
1454 frame->sample_rate_hz_);
1455 processing_config.reverse_output_stream().set_num_channels(
1456 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001457
peahdf3efa82015-11-28 12:35:15 -08001458 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001459 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001460 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001461 return kBadDataLengthError;
1462 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001463
aleloi868f32f2017-05-23 07:20:05 -07001464 if (aec_dump_) {
1465 aec_dump_->WriteRenderStreamMessage(*frame);
1466 }
1467
peahdf3efa82015-11-28 12:35:15 -08001468 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001469 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001470 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001471 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1472 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001473 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001474}
niklase@google.com470e71d2011-07-07 08:21:25 +00001475
peahde65ddc2016-09-16 15:02:15 -07001476int AudioProcessingImpl::ProcessRenderStreamLocked() {
1477 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001478
Alex Loiko73ec0192018-05-15 10:52:28 +02001479 HandleRenderRuntimeSettings();
1480
Alex Loiko5825aa62017-12-18 16:02:40 +01001481 if (private_submodules_->render_pre_processor) {
1482 private_submodules_->render_pre_processor->Process(render_buffer);
1483 }
1484
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001485 QueueNonbandedRenderAudio(render_buffer);
1486
peah2ace3f92016-09-10 04:42:27 -07001487 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001488 SampleRateSupportsMultiBand(
1489 formats_.render_processing_format.sample_rate_hz())) {
1490 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001491 }
1492
peahce4d9152017-05-19 01:28:05 -07001493 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1494 QueueBandedRenderAudio(render_buffer);
1495 }
1496
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001497 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001498 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001499 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001500 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001501
peah2ace3f92016-09-10 04:42:27 -07001502 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001503 SampleRateSupportsMultiBand(
1504 formats_.render_processing_format.sample_rate_hz())) {
1505 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001506 }
1507
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001508 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001509}
1510
1511int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001512 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001513 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001514 capture_.was_stream_delay_set = true;
1515 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001516
niklase@google.com470e71d2011-07-07 08:21:25 +00001517 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001518 delay = 0;
1519 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001520 }
1521
1522 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1523 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001524 delay = 500;
1525 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001526 }
1527
peahdf3efa82015-11-28 12:35:15 -08001528 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001529 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001530}
1531
1532int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001533 // Used as callback from submodules, hence locking is not allowed.
1534 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001535}
1536
1537bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001538 // Used as callback from submodules, hence locking is not allowed.
1539 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001540}
1541
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001542void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001543 rtc::CritScope cs(&crit_capture_);
1544 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001545}
1546
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001547void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001548 rtc::CritScope cs(&crit_capture_);
1549 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001550}
1551
1552int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001553 rtc::CritScope cs(&crit_capture_);
1554 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001555}
1556
aleloi868f32f2017-05-23 07:20:05 -07001557void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1558 RTC_DCHECK(aec_dump);
1559 rtc::CritScope cs_render(&crit_render_);
1560 rtc::CritScope cs_capture(&crit_capture_);
1561
1562 // The previously attached AecDump will be destroyed with the
1563 // 'aec_dump' parameter, which is after locks are released.
1564 aec_dump_.swap(aec_dump);
1565 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001566 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001567}
1568
1569void AudioProcessingImpl::DetachAecDump() {
1570 // The d-tor of a task-queue based AecDump blocks until all pending
1571 // tasks are done. This construction avoids blocking while holding
1572 // the render and capture locks.
1573 std::unique_ptr<AecDump> aec_dump = nullptr;
1574 {
1575 rtc::CritScope cs_render(&crit_render_);
1576 rtc::CritScope cs_capture(&crit_capture_);
1577 aec_dump = std::move(aec_dump_);
1578 }
1579}
1580
Sam Zackrisson4d364492018-03-02 16:03:21 +01001581void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1582 std::unique_ptr<AudioGenerator> audio_generator) {
1583 // TODO(bugs.webrtc.org/8882) Stub.
1584 // Reset internal audio generator with audio_generator.
1585}
1586
1587void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1588 // TODO(bugs.webrtc.org/8882) Stub.
1589 // Delete audio generator, if one is attached.
1590}
1591
Ivo Creusen56d46092017-11-24 17:29:59 +01001592AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001593 bool has_remote_tracks) const {
1594 AudioProcessingStats stats;
1595 if (has_remote_tracks) {
sazabe490b22018-10-03 17:03:13 +02001596 EchoCancellationImpl::Metrics metrics;
Yves Gerey499bc6c2018-10-10 18:29:07 +02001597 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001598 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001599 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1600 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001601 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001602 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001603 stats.delay_ms = ec_metrics.delay_ms;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001604 } else if (private_submodules_->echo_cancellation->GetMetrics(&metrics) ==
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001605 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001606 if (metrics.divergent_filter_fraction != -1.0f) {
1607 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001608 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001609 }
1610 if (metrics.echo_return_loss.instant != -100) {
1611 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001612 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001613 }
1614 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001615 stats.echo_return_loss_enhancement = absl::optional<double>(
1616 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001617 }
1618 }
1619 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001620 RTC_DCHECK(private_submodules_->echo_detector);
1621 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1622 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001623 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001624 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001625 }
1626 int delay_median, delay_std;
1627 float fraction_poor_delays;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001628 if (private_submodules_->echo_cancellation->GetDelayMetrics(
Ivo Creusenae026092017-11-20 13:07:16 +01001629 &delay_median, &delay_std, &fraction_poor_delays) ==
1630 Error::kNoError) {
1631 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001632 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001633 }
1634 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001635 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001636 }
1637 }
1638 }
1639 return stats;
1640}
1641
niklase@google.com470e71d2011-07-07 08:21:25 +00001642GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001643 if (constants_.use_experimental_agc) {
1644 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001645 }
peahbfa97112016-03-10 21:09:04 -08001646 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001647}
1648
niklase@google.com470e71d2011-07-07 08:21:25 +00001649LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001650 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001651}
1652
1653NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001654 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001655}
1656
1657VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001658 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001659}
1660
peah8271d042016-11-22 07:24:52 -08001661void AudioProcessingImpl::MutateConfig(
1662 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1663 rtc::CritScope cs_render(&crit_render_);
1664 rtc::CritScope cs_capture(&crit_capture_);
1665 mutator(&config_);
1666 ApplyConfig(config_);
1667}
1668
1669AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1670 rtc::CritScope cs_render(&crit_render_);
1671 rtc::CritScope cs_capture(&crit_capture_);
1672 return config_;
1673}
1674
peah2ace3f92016-09-10 04:42:27 -07001675bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1676 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001677 config_.high_pass_filter.enabled,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001678 private_submodules_->echo_cancellation->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001679 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001680 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001681 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001682 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001683 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001684 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001685 public_submodules_->voice_detection->is_enabled(),
1686 public_submodules_->level_estimator->is_enabled(),
1687 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001688}
1689
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001690void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001691 if (capture_.transient_suppressor_enabled) {
1692 if (!public_submodules_->transient_suppressor.get()) {
1693 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001694 }
peahdf3efa82015-11-28 12:35:15 -08001695 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001696 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1697 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001698 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001699}
1700
peah8271d042016-11-22 07:24:52 -08001701void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001702 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001703 private_submodules_->low_cut_filter.reset(
1704 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1705 } else {
1706 private_submodules_->low_cut_filter.reset();
1707 }
1708}
alessiob3ec96df2017-05-22 06:57:06 -07001709
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001710void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001711 if (echo_control_factory_) {
1712 private_submodules_->echo_controller =
1713 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001714 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001715 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001716 }
1717}
peah8271d042016-11-22 07:24:52 -08001718
alessiob3ec96df2017-05-22 06:57:06 -07001719void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001720 if (config_.gain_controller2.enabled) {
1721 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001722 }
1723}
1724
Alex Loikob5c9a792018-04-16 16:31:22 +02001725void AudioProcessingImpl::InitializePreAmplifier() {
1726 if (config_.pre_amplifier.enabled) {
1727 private_submodules_->pre_amplifier.reset(
1728 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1729 } else {
1730 private_submodules_->pre_amplifier.reset();
1731 }
1732}
1733
ivoc9f4a4a02016-10-28 05:39:16 -07001734void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001735 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001736 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001737 proc_sample_rate_hz(), 1,
1738 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001739}
1740
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001741void AudioProcessingImpl::InitializeAnalyzer() {
1742 if (private_submodules_->capture_analyzer) {
1743 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1744 num_proc_channels());
1745 }
1746}
1747
Sam Zackrisson0beac582017-09-25 12:04:02 +02001748void AudioProcessingImpl::InitializePostProcessor() {
1749 if (private_submodules_->capture_post_processor) {
1750 private_submodules_->capture_post_processor->Initialize(
1751 proc_sample_rate_hz(), num_proc_channels());
1752 }
1753}
1754
Alex Loiko5825aa62017-12-18 16:02:40 +01001755void AudioProcessingImpl::InitializePreProcessor() {
1756 if (private_submodules_->render_pre_processor) {
1757 private_submodules_->render_pre_processor->Initialize(
1758 formats_.render_processing_format.sample_rate_hz(),
1759 formats_.render_processing_format.num_channels());
1760 }
1761}
1762
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001763void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001764 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001765
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001766 if (private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001767 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1768 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001769 if (capture_.stream_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_.stream_delay_jumps = 0;
1772 }
1773 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001774 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001775 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001776 }
1777
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001778 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001779 const int diff_stream_delay_ms =
1780 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1781 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1782 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001783 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1784 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001785 if (capture_.stream_delay_jumps == -1) {
1786 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001787 }
peahdf3efa82015-11-28 12:35:15 -08001788 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001789 }
peahdf3efa82015-11-28 12:35:15 -08001790 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001791
1792 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001793 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001794 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001795 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001796 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001797 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001798 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001799 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001800 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001801 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001802 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001803 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1804 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1805 100);
peahdf3efa82015-11-28 12:35:15 -08001806 if (capture_.aec_system_delay_jumps == -1) {
1807 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001808 }
peahdf3efa82015-11-28 12:35:15 -08001809 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001810 }
peahdf3efa82015-11-28 12:35:15 -08001811 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001812 }
1813}
1814
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001815void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001816 // Run in a single-threaded manner.
1817 rtc::CritScope cs_render(&crit_render_);
1818 rtc::CritScope cs_capture(&crit_capture_);
1819
1820 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001821 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001822 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001823 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001824 }
peahdf3efa82015-11-28 12:35:15 -08001825 capture_.stream_delay_jumps = -1;
1826 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001827
peahdf3efa82015-11-28 12:35:15 -08001828 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001829 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1830 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001831 }
peahdf3efa82015-11-28 12:35:15 -08001832 capture_.aec_system_delay_jumps = -1;
1833 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001834}
1835
aleloi868f32f2017-05-23 07:20:05 -07001836void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1837 if (!aec_dump_) {
1838 return;
1839 }
1840 std::string experiments_description =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001841 private_submodules_->echo_cancellation->GetExperimentsDescription();
aleloi868f32f2017-05-23 07:20:05 -07001842 // TODO(peah): Add semicolon-separated concatenations of experiment
1843 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001844 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1845 experiments_description += "AgcClippingLevelExperiment;";
1846 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001847 if (capture_nonlocked_.echo_controller_enabled) {
1848 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001849 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001850 if (config_.gain_controller2.enabled) {
1851 experiments_description += "GainController2;";
1852 }
aleloi868f32f2017-05-23 07:20:05 -07001853
1854 InternalAPMConfig apm_config;
1855
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001856 apm_config.aec_enabled = private_submodules_->echo_cancellation->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001857 apm_config.aec_delay_agnostic_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001858 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001859 apm_config.aec_drift_compensation_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001860 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001861 apm_config.aec_extended_filter_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001862 private_submodules_->echo_cancellation->is_extended_filter_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001863 apm_config.aec_suppression_level = static_cast<int>(
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001864 private_submodules_->echo_cancellation->suppression_level());
aleloi868f32f2017-05-23 07:20:05 -07001865
1866 apm_config.aecm_enabled =
1867 public_submodules_->echo_control_mobile->is_enabled();
1868 apm_config.aecm_comfort_noise_enabled =
1869 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1870 apm_config.aecm_routing_mode =
1871 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1872
1873 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1874 apm_config.agc_mode =
1875 static_cast<int>(public_submodules_->gain_control->mode());
1876 apm_config.agc_limiter_enabled =
1877 public_submodules_->gain_control->is_limiter_enabled();
1878 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1879
1880 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1881
1882 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1883 apm_config.ns_level =
1884 static_cast<int>(public_submodules_->noise_suppression->level());
1885
1886 apm_config.transient_suppression_enabled =
1887 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001888 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001889 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1890 apm_config.pre_amplifier_fixed_gain_factor =
1891 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001892
1893 if (!forced && apm_config == apm_config_for_aec_dump_) {
1894 return;
1895 }
1896 aec_dump_->WriteConfig(apm_config);
1897 apm_config_for_aec_dump_ = apm_config;
1898}
1899
1900void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1901 const float* const* src) {
1902 RTC_DCHECK(aec_dump_);
1903 WriteAecDumpConfigMessage(false);
1904
1905 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1906 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1907 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001908 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001909 RecordAudioProcessingState();
1910}
1911
1912void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1913 const AudioFrame& capture_frame) {
1914 RTC_DCHECK(aec_dump_);
1915 WriteAecDumpConfigMessage(false);
1916
1917 aec_dump_->AddCaptureStreamInput(capture_frame);
1918 RecordAudioProcessingState();
1919}
1920
1921void AudioProcessingImpl::RecordProcessedCaptureStream(
1922 const float* const* processed_capture_stream) {
1923 RTC_DCHECK(aec_dump_);
1924
1925 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1926 const size_t num_channels =
1927 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001928 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1929 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001930 aec_dump_->WriteCaptureStreamMessage();
1931}
1932
1933void AudioProcessingImpl::RecordProcessedCaptureStream(
1934 const AudioFrame& processed_capture_frame) {
1935 RTC_DCHECK(aec_dump_);
1936
1937 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1938 aec_dump_->WriteCaptureStreamMessage();
1939}
1940
1941void AudioProcessingImpl::RecordAudioProcessingState() {
1942 RTC_DCHECK(aec_dump_);
1943 AecDump::AudioProcessingState audio_proc_state;
1944 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
1945 audio_proc_state.drift =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001946 private_submodules_->echo_cancellation->stream_drift_samples();
aleloi868f32f2017-05-23 07:20:05 -07001947 audio_proc_state.level = gain_control()->stream_analog_level();
1948 audio_proc_state.keypress = capture_.key_pressed;
1949 aec_dump_->AddAudioProcessingState(audio_proc_state);
1950}
1951
kwiberg83ffe452016-08-29 14:46:07 -07001952AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001953 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07001954 : aec_system_delay_jumps(-1),
1955 delay_offset_ms(0),
1956 was_stream_delay_set(false),
1957 last_stream_delay_ms(0),
1958 last_aec_system_delay_ms(0),
1959 stream_delay_jumps(-1),
1960 output_will_be_muted(false),
1961 key_pressed(false),
1962 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07001963 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001964 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02001965 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02001966 prev_analog_mic_level(-1),
1967 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07001968
1969AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1970
1971AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1972
1973AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1974
niklase@google.com470e71d2011-07-07 08:21:25 +00001975} // namespace webrtc