blob: 2937c0680bf5ac699b2c28ff968419688381f1eb [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <type_traits>
17#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000018
Yves Gerey988cc082018-10-23 12:03:01 +020019#include "absl/types/optional.h"
20#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "common_audio/audio_converter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/include/audio_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020024#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "modules/audio_processing/common.h"
27#include "modules/audio_processing/echo_cancellation_impl.h"
28#include "modules/audio_processing/echo_control_mobile_impl.h"
29#include "modules/audio_processing/gain_control_for_experimental_agc.h"
30#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010031#include "modules/audio_processing/gain_controller2.h"
Yves Gerey988cc082018-10-23 12:03:01 +020032#include "modules/audio_processing/include/audio_frame_view.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020033#include "modules/audio_processing/level_estimator_impl.h"
Per Åhgren13735822018-02-12 21:42:56 +010034#include "modules/audio_processing/logging/apm_data_dumper.h"
Per Åhgrend2650d12018-10-02 17:00:59 +020035#include "modules/audio_processing/low_cut_filter.h"
36#include "modules/audio_processing/noise_suppression_impl.h"
37#include "modules/audio_processing/residual_echo_detector.h"
38#include "modules/audio_processing/transient/transient_suppressor.h"
39#include "modules/audio_processing/voice_detection_impl.h"
40#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "rtc_base/checks.h"
Yves Gerey988cc082018-10-23 12:03:01 +020042#include "rtc_base/constructormagic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "rtc_base/logging.h"
Niels Möller84255bb2017-10-06 13:43:23 +020044#include "rtc_base/refcountedobject.h"
Minyue Li656d6092018-08-10 15:38:52 +020045#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/trace_event.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000048
Michael Graczyk86c6d332015-07-23 11:41:39 -070049#define RETURN_ON_ERR(expr) \
50 do { \
51 int err = (expr); \
52 if (err != kNoError) { \
53 return err; \
54 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000055 } while (0)
56
niklase@google.com470e71d2011-07-07 08:21:25 +000057namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070058
kwibergd59d3bb2016-09-13 07:49:33 -070059constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020060constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070061
Michael Graczyk86c6d332015-07-23 11:41:39 -070062namespace {
63
64static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
65 switch (layout) {
66 case AudioProcessing::kMono:
67 case AudioProcessing::kStereo:
68 return false;
69 case AudioProcessing::kMonoAndKeyboard:
70 case AudioProcessing::kStereoAndKeyboard:
71 return true;
72 }
73
kwiberg9e2be5f2016-09-14 05:23:22 -070074 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070075 return false;
76}
aluebsdf6416a2016-03-16 18:26:35 -070077
peah2ace3f92016-09-10 04:42:27 -070078bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070079 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
80 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
81}
82
peah2ace3f92016-09-10 04:42:27 -070083int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
84#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070085 constexpr int kMaxSplittingNativeProcessRate =
86 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070087#else
kwibergd59d3bb2016-09-13 07:49:33 -070088 constexpr int kMaxSplittingNativeProcessRate =
89 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070090#endif
kwibergd59d3bb2016-09-13 07:49:33 -070091 static_assert(
92 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
93 "");
peah2ace3f92016-09-10 04:42:27 -070094 const int uppermost_native_rate = band_splitting_required
95 ? kMaxSplittingNativeProcessRate
96 : AudioProcessing::kSampleRate48kHz;
97
98 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
99 if (rate >= uppermost_native_rate) {
100 return uppermost_native_rate;
101 }
102 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700103 return rate;
104 }
105 }
peah2ace3f92016-09-10 04:42:27 -0700106 RTC_NOTREACHED();
107 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700108}
109
peah9e6a2902017-05-15 07:19:21 -0700110// Maximum lengths that frame of samples being passed from the render side to
111// the capture side can have (does not apply to AEC3).
112static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
113static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
114
peah764e3642016-10-22 05:04:30 -0700115// Maximum number of frames to buffer in the render queue.
116// TODO(peah): Decrease this once we properly handle hugely unbalanced
117// reverse and forward call numbers.
118static const size_t kMaxNumFramesToBuffer = 100;
Michael Graczyk86c6d332015-07-23 11:41:39 -0700119} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000120
121// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000122static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000123
Sam Zackrisson0beac582017-09-25 12:04:02 +0200124AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100125 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200126 bool render_pre_processor_enabled,
127 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100128 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200129 render_pre_processor_enabled_(render_pre_processor_enabled),
130 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700131
132bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200133 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700134 bool echo_canceller_enabled,
135 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700136 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700137 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700138 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700139 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200140 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200141 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700142 bool voice_activity_detector_enabled,
143 bool level_estimator_enabled,
144 bool transient_suppressor_enabled) {
145 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200146 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700147 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
148 changed |=
149 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700150 changed |=
151 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700152 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
153 changed |=
peah2ace3f92016-09-10 04:42:27 -0700154 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700155 changed |=
156 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200157 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200158 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700159 changed |= (level_estimator_enabled != level_estimator_enabled_);
160 changed |=
161 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
162 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
163 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200164 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700165 echo_canceller_enabled_ = echo_canceller_enabled;
166 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700167 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700168 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700169 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700170 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200171 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200172 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700173 level_estimator_enabled_ = level_estimator_enabled;
174 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
175 transient_suppressor_enabled_ = transient_suppressor_enabled;
176 }
177
178 changed |= first_update_;
179 first_update_ = false;
180 return changed;
181}
182
183bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
184 const {
peah52775842017-05-16 06:14:09 -0700185 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700186}
187
188bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
189 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200190 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700191 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200192 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700193}
194
peah23ac8b42017-05-23 05:33:56 -0700195bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
196 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200197 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
198 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700199}
200
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200201bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
202 return capture_analyzer_enabled_;
203}
204
peah2ace3f92016-09-10 04:42:27 -0700205bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
206 const {
207 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800208 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200209 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700210}
211
Alex Loiko5825aa62017-12-18 16:02:40 +0100212bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
213 const {
214 return render_pre_processor_enabled_;
215}
216
peah2ace3f92016-09-10 04:42:27 -0700217bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
218 const {
peah2ace3f92016-09-10 04:42:27 -0700219 return false;
peah2ace3f92016-09-10 04:42:27 -0700220}
221
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200222bool AudioProcessingImpl::ApmSubmoduleStates::LowCutFilteringRequired() const {
223 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
224 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
225}
226
solenberg5e465c32015-12-08 13:22:33 -0800227struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800228 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800229 // Accessed externally of APM without any lock acquired.
peahbfa97112016-03-10 21:09:04 -0800230 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800231 std::unique_ptr<LevelEstimatorImpl> level_estimator;
232 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
233 std::unique_ptr<VoiceDetectionImpl> voice_detection;
234 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800235 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800236
237 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800238 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800239};
240
241struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200242 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100243 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200244 rtc::scoped_refptr<EchoDetector> echo_detector,
245 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200246 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100247 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200248 render_pre_processor(std::move(render_pre_processor)),
249 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800250 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800251 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700252 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800253 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200254 rtc::scoped_refptr<EchoDetector> echo_detector;
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100255 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100256 std::unique_ptr<EchoControl> echo_controller;
257 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Alex Loiko5825aa62017-12-18 16:02:40 +0100258 std::unique_ptr<CustomProcessing> capture_post_processor;
259 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200260 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200261 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100262 std::unique_ptr<LevelEstimatorImpl> output_level_estimator;
solenberg5e465c32015-12-08 13:22:33 -0800263};
264
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100265AudioProcessingBuilder::AudioProcessingBuilder() = default;
266AudioProcessingBuilder::~AudioProcessingBuilder() = default;
267
268AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
269 std::unique_ptr<CustomProcessing> capture_post_processing) {
270 capture_post_processing_ = std::move(capture_post_processing);
271 return *this;
272}
273
274AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
275 std::unique_ptr<CustomProcessing> render_pre_processing) {
276 render_pre_processing_ = std::move(render_pre_processing);
277 return *this;
278}
279
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200280AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
281 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
282 capture_analyzer_ = std::move(capture_analyzer);
283 return *this;
284}
285
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100286AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
287 std::unique_ptr<EchoControlFactory> echo_control_factory) {
288 echo_control_factory_ = std::move(echo_control_factory);
289 return *this;
290}
291
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100292AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200293 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100294 echo_detector_ = std::move(echo_detector);
295 return *this;
296}
297
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100298AudioProcessing* AudioProcessingBuilder::Create() {
299 webrtc::Config config;
300 return Create(config);
301}
302
303AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100304 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
305 config, std::move(capture_post_processing_),
306 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200307 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100308 if (apm->Initialize() != AudioProcessing::kNoError) {
309 delete apm;
310 apm = nullptr;
311 }
312 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100313}
314
peah88ac8532016-09-12 16:47:25 -0700315AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200316 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
317}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000318
Per Åhgren13735822018-02-12 21:42:56 +0100319int AudioProcessingImpl::instance_count_ = 0;
320
Sam Zackrisson0beac582017-09-25 12:04:02 +0200321AudioProcessingImpl::AudioProcessingImpl(
322 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100323 std::unique_ptr<CustomProcessing> capture_post_processor,
324 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200325 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200326 rtc::scoped_refptr<EchoDetector> echo_detector,
327 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100328 : data_dumper_(
329 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200330 capture_runtime_settings_(kRuntimeSettingQueueSize),
331 render_runtime_settings_(kRuntimeSettingQueueSize),
332 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
333 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200334 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200335 submodule_states_(!!capture_post_processor,
336 !!render_pre_processor,
337 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800338 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200339 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200340 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100341 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200342 std::move(echo_detector),
343 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800344 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800345 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000346#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200347 /* enabled= */ false,
348 /* enabled_agc2_level_estimator= */ false,
349 /* digital_adaptive_disabled= */ false,
350 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000351#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200352 config.Get<ExperimentalAgc>().enabled,
353 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200354 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
355 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000356#endif
andrew1c7075f2015-06-24 18:14:14 -0700357#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200358 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700359#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200360 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700361#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200362 capture_nonlocked_() {
peahdf3efa82015-11-28 12:35:15 -0800363 {
364 rtc::CritScope cs_render(&crit_render_);
365 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000366
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200367 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000368 capture_nonlocked_.echo_controller_enabled =
369 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200370
peahbfa97112016-03-10 21:09:04 -0800371 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200372 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800373 public_submodules_->level_estimator.reset(
374 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800375 public_submodules_->noise_suppression.reset(
376 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800377 public_submodules_->voice_detection.reset(
378 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800379 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800380 new GainControlForExperimentalAgc(
381 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100382
383 // If no echo detector is injected, use the ResidualEchoDetector.
384 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200385 private_submodules_->echo_detector =
386 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100387 }
peahca4cac72016-06-29 15:26:12 -0700388
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100389 private_submodules_->echo_cancellation.reset(new EchoCancellationImpl());
390 private_submodules_->echo_control_mobile.reset(new EchoControlMobileImpl());
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);
Sam Zackrissonc22f5512018-11-05 16:10:00 +0100518 private_submodules_->echo_control_mobile->Initialize(
peahde65ddc2016-09-16 15:02:15 -0700519 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 Zackrissonc22f5512018-11-05 16:10:00 +0100649 private_submodules_->echo_control_mobile->Enable(
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200650 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;
Sam Zackrissonb24c00f2018-11-26 16:18:25 +0100677
678 if (config_.level_estimation.enabled &&
679 !private_submodules_->output_level_estimator) {
680 private_submodules_->output_level_estimator.reset(
681 new LevelEstimatorImpl(&crit_capture_));
682 private_submodules_->output_level_estimator->Enable(true);
683 }
peah88ac8532016-09-12 16:47:25 -0700684}
685
686void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800687 // Run in a single-threaded manner when setting the extra options.
688 rtc::CritScope cs_render(&crit_render_);
689 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000690
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +0100691 private_submodules_->echo_cancellation->SetExtraOptions(config);
peahb624d8c2016-03-05 03:01:14 -0800692
peahdf3efa82015-11-28 12:35:15 -0800693 if (capture_.transient_suppressor_enabled !=
694 config.Get<ExperimentalNs>().enabled) {
695 capture_.transient_suppressor_enabled =
696 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000697 InitializeTransient();
698 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000699}
700
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000701int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800702 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700703 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000704}
705
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000706int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800707 // Used as callback from submodules, hence locking is not allowed.
708 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000709}
710
Peter Kasting69558702016-01-12 16:26:35 -0800711size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800712 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700713 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000714}
715
Peter Kasting69558702016-01-12 16:26:35 -0800716size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800717 // Used as callback from submodules, hence locking is not allowed.
718 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000719}
720
Peter Kasting69558702016-01-12 16:26:35 -0800721size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800722 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200723 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800724}
725
Peter Kasting69558702016-01-12 16:26:35 -0800726size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800727 // Used as callback from submodules, hence locking is not allowed.
728 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000729}
730
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000731void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800732 rtc::CritScope cs(&crit_capture_);
733 capture_.output_will_be_muted = muted;
734 if (private_submodules_->agc_manager.get()) {
735 private_submodules_->agc_manager->SetCaptureMuted(
736 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000737 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000738}
739
Alessio Bazzicac054e782018-04-16 12:10:09 +0200740void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200741 switch (setting.type()) {
742 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
743 render_runtime_settings_enqueuer_.Enqueue(setting);
744 return;
745 case RuntimeSetting::Type::kNotSpecified:
746 RTC_NOTREACHED();
747 return;
748 case RuntimeSetting::Type::kCapturePreGain:
749 capture_runtime_settings_enqueuer_.Enqueue(setting);
750 return;
751 }
752 // The language allows the enum to have a non-enumerator
753 // value. Check that this doesn't happen.
754 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200755}
756
757AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
758 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200759 : runtime_settings_(*runtime_settings) {
760 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200761}
762
763AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
764 default;
765
766void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
767 RuntimeSetting setting) {
768 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200769 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200770 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200771 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200772 RTC_LOG(LS_ERROR)
773 << "The runtime settings queue is full. Oldest setting discarded.";
774 }
775 if (remaining_attempts == 0)
776 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
777}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000778
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000779int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700780 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000781 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000782 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000783 int output_sample_rate_hz,
784 ChannelLayout output_layout,
785 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800786 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800787 StreamConfig input_stream;
788 StreamConfig output_stream;
789 {
790 // Access the formats_.api_format.input_stream beneath the capture lock.
791 // The lock must be released as it is later required in the call
792 // to ProcessStream(,,,);
793 rtc::CritScope cs(&crit_capture_);
794 input_stream = formats_.api_format.input_stream();
795 output_stream = formats_.api_format.output_stream();
796 }
797
Michael Graczyk86c6d332015-07-23 11:41:39 -0700798 input_stream.set_sample_rate_hz(input_sample_rate_hz);
799 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
800 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700801 output_stream.set_sample_rate_hz(output_sample_rate_hz);
802 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
803 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
804
805 if (samples_per_channel != input_stream.num_frames()) {
806 return kBadDataLengthError;
807 }
808 return ProcessStream(src, input_stream, output_stream, dest);
809}
810
811int AudioProcessingImpl::ProcessStream(const float* const* src,
812 const StreamConfig& input_config,
813 const StreamConfig& output_config,
814 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800815 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800816 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700817 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800818 {
819 // Acquire the capture lock in order to safely call the function
820 // that retrieves the render side data. This function accesses apm
821 // getters that need the capture lock held when being called.
822 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700823 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800824
825 if (!src || !dest) {
826 return kNullPointerError;
827 }
828
829 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700830 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000831 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000832
Michael Graczyk86c6d332015-07-23 11:41:39 -0700833 processing_config.input_stream() = input_config;
834 processing_config.output_stream() = output_config;
835
peahdf3efa82015-11-28 12:35:15 -0800836 {
837 // Do conditional reinitialization.
838 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700839 RETURN_ON_ERR(
840 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800841 }
842 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700843 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
844 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000845
aleloi868f32f2017-05-23 07:20:05 -0700846 if (aec_dump_) {
847 RecordUnprocessedCaptureStream(src);
848 }
849
peahdf3efa82015-11-28 12:35:15 -0800850 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700851 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800852 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000853
aleloi868f32f2017-05-23 07:20:05 -0700854 if (aec_dump_) {
855 RecordProcessedCaptureStream(dest);
856 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000857 return kNoError;
858}
859
Alex Loiko73ec0192018-05-15 10:52:28 +0200860void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200861 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200862 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200863 if (aec_dump_) {
864 aec_dump_->WriteRuntimeSetting(setting);
865 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200866 switch (setting.type()) {
867 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200868 if (config_.pre_amplifier.enabled) {
869 float value;
870 setting.GetFloat(&value);
871 private_submodules_->pre_amplifier->SetGainFactor(value);
872 }
873 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200874 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200875 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
876 RTC_NOTREACHED();
877 break;
878 case RuntimeSetting::Type::kNotSpecified:
879 RTC_NOTREACHED();
880 break;
881 }
882 }
883}
884
885void AudioProcessingImpl::HandleRenderRuntimeSettings() {
886 RuntimeSetting setting;
887 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200888 if (aec_dump_) {
889 aec_dump_->WriteRuntimeSetting(setting);
890 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200891 switch (setting.type()) {
892 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
893 if (private_submodules_->render_pre_processor) {
894 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
895 }
896 break;
897 case RuntimeSetting::Type::kCapturePreGain:
898 RTC_NOTREACHED();
899 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200900 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200901 RTC_NOTREACHED();
902 break;
903 }
904 }
905}
906
peah9e6a2902017-05-15 07:19:21 -0700907void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700908 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
909 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700910 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700911
kwibergaf476c72016-11-28 15:21:39 -0800912 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700913
914 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700915 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700916 // The data queue is full and needs to be emptied.
917 EmptyQueuedRenderAudio();
918
919 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700920 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700921 RTC_DCHECK(result);
922 }
923
924 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
925 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700926 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700927
928 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700929 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700930 // The data queue is full and needs to be emptied.
931 EmptyQueuedRenderAudio();
932
933 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700934 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700935 RTC_DCHECK(result);
936 }
peah701d6282016-10-25 05:42:20 -0700937
938 if (!constants_.use_experimental_agc) {
939 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
940 // Insert the samples into the queue.
941 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
942 // The data queue is full and needs to be emptied.
943 EmptyQueuedRenderAudio();
944
945 // Retry the insert (should always work).
946 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
947 RTC_DCHECK(result);
948 }
949 }
peah9e6a2902017-05-15 07:19:21 -0700950}
ivoc9f4a4a02016-10-28 05:39:16 -0700951
peah9e6a2902017-05-15 07:19:21 -0700952void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700953 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
954
955 // Insert the samples into the queue.
956 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
957 // The data queue is full and needs to be emptied.
958 EmptyQueuedRenderAudio();
959
960 // Retry the insert (should always work).
961 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
962 RTC_DCHECK(result);
963 }
peah764e3642016-10-22 05:04:30 -0700964}
965
966void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700967 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700968 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700969 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700970 EchoCancellationImpl::NumCancellersRequired(
971 num_output_channels(), num_reverse_channels()));
972
peah701d6282016-10-25 05:42:20 -0700973 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700974 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700975 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700976 EchoControlMobileImpl::NumCancellersRequired(
977 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700978
peah701d6282016-10-25 05:42:20 -0700979 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700980 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700981
ivoc9f4a4a02016-10-28 05:39:16 -0700982 const size_t new_red_render_queue_element_max_size =
983 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
984
peaha0624602016-10-25 04:45:24 -0700985 // Reallocate the queues if the queue item sizes are too small to fit the
986 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700987 if (aec_render_queue_element_max_size_ <
988 new_aec_render_queue_element_max_size) {
989 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700990
peaha0624602016-10-25 04:45:24 -0700991 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700992 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700993
peah701d6282016-10-25 05:42:20 -0700994 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700995 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
996 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700997 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700998 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700999
peah701d6282016-10-25 05:42:20 -07001000 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1001 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001002 } else {
peah701d6282016-10-25 05:42:20 -07001003 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001004 }
1005
peah701d6282016-10-25 05:42:20 -07001006 if (aecm_render_queue_element_max_size_ <
1007 new_aecm_render_queue_element_max_size) {
1008 aecm_render_queue_element_max_size_ =
1009 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001010
1011 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001012 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001013
peah701d6282016-10-25 05:42:20 -07001014 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001015 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1016 kMaxNumFramesToBuffer, template_queue_element,
1017 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001018 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001019
peah701d6282016-10-25 05:42:20 -07001020 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1021 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001022 } else {
peah701d6282016-10-25 05:42:20 -07001023 aecm_render_signal_queue_->Clear();
1024 }
1025
1026 if (agc_render_queue_element_max_size_ <
1027 new_agc_render_queue_element_max_size) {
1028 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1029
1030 std::vector<int16_t> template_queue_element(
1031 agc_render_queue_element_max_size_);
1032
1033 agc_render_signal_queue_.reset(
1034 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1035 kMaxNumFramesToBuffer, template_queue_element,
1036 RenderQueueItemVerifier<int16_t>(
1037 agc_render_queue_element_max_size_)));
1038
1039 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1040 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1041 } else {
1042 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001043 }
ivoc9f4a4a02016-10-28 05:39:16 -07001044
1045 if (red_render_queue_element_max_size_ <
1046 new_red_render_queue_element_max_size) {
1047 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1048
1049 std::vector<float> template_queue_element(
1050 red_render_queue_element_max_size_);
1051
1052 red_render_signal_queue_.reset(
1053 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1054 kMaxNumFramesToBuffer, template_queue_element,
1055 RenderQueueItemVerifier<float>(
1056 red_render_queue_element_max_size_)));
1057
1058 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1059 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1060 } else {
1061 red_render_signal_queue_->Clear();
1062 }
peah764e3642016-10-22 05:04:30 -07001063}
1064
1065void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1066 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001067 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001068 private_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001069 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001070 }
1071
peah701d6282016-10-25 05:42:20 -07001072 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001073 private_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001074 aecm_capture_queue_buffer_);
1075 }
1076
1077 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1078 public_submodules_->gain_control->ProcessRenderAudio(
1079 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001080 }
ivoc9f4a4a02016-10-28 05:39:16 -07001081
1082 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001083 RTC_DCHECK(private_submodules_->echo_detector);
1084 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001085 red_capture_queue_buffer_);
1086 }
peah764e3642016-10-22 05:04:30 -07001087}
1088
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001089int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001090 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001091 {
1092 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001093 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001094 // getters that need the capture lock held when being called.
peahdf3efa82015-11-28 12:35:15 -08001095 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001096 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001097 }
peahfa6228e2015-11-16 16:27:42 -08001098
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001099 if (!frame) {
1100 return kNullPointerError;
1101 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001102 // Must be a native rate.
1103 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1104 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001105 frame->sample_rate_hz_ != kSampleRate32kHz &&
1106 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001107 return kBadSampleRateError;
1108 }
peah192164e2015-11-17 02:16:45 -08001109
peahdf3efa82015-11-28 12:35:15 -08001110 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001111 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001112 {
1113 // Aquire lock for the access of api_format.
1114 // The lock is released immediately due to the conditional
1115 // reinitialization.
1116 rtc::CritScope cs_capture(&crit_capture_);
1117 // TODO(ajm): The input and output rates and channels are currently
1118 // constrained to be identical in the int16 interface.
1119 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001120
1121 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001122 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001123 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1124 processing_config.input_stream().set_num_channels(frame->num_channels_);
1125 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1126 processing_config.output_stream().set_num_channels(frame->num_channels_);
1127
peahdf3efa82015-11-28 12:35:15 -08001128 {
1129 // Do conditional reinitialization.
1130 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001131 RETURN_ON_ERR(
1132 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001133 }
1134 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001135 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001136 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001137 return kBadDataLengthError;
1138 }
1139
aleloi868f32f2017-05-23 07:20:05 -07001140 if (aec_dump_) {
1141 RecordUnprocessedCaptureStream(*frame);
1142 }
1143
peahdf3efa82015-11-28 12:35:15 -08001144 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001145 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001146 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001147 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1148 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001149
aleloi868f32f2017-05-23 07:20:05 -07001150 if (aec_dump_) {
1151 RecordProcessedCaptureStream(*frame);
1152 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001153
1154 return kNoError;
1155}
1156
peahde65ddc2016-09-16 15:02:15 -07001157int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001158 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001159
peahb58a1582016-03-15 09:34:24 -07001160 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001161 // TODO(peah): Simplify once the public API Enable functions for these
1162 // are moved to APM.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001163 RTC_DCHECK(!(private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001164 private_submodules_->echo_control_mobile->is_enabled()));
peahb58a1582016-03-15 09:34:24 -07001165
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001166 MaybeUpdateHistograms();
1167
peahde65ddc2016-09-16 15:02:15 -07001168 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001169
Alex Loikob5c9a792018-04-16 16:31:22 +02001170 if (private_submodules_->pre_amplifier) {
1171 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1172 capture_buffer->channels_f(), capture_buffer->num_channels(),
1173 capture_buffer->num_frames()));
1174 }
1175
peah1b08dc32016-12-20 13:45:58 -08001176 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001177 capture_buffer->channels_const()[0],
1178 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001179 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1180 if (log_rms) {
1181 capture_rms_interval_counter_ = 0;
1182 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001183 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1184 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1185 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1186 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001187 }
1188
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001189 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001190 // Detect and flag any change in the analog gain.
1191 int analog_mic_level = gain_control()->stream_analog_level();
1192 capture_.echo_path_gain_change =
1193 capture_.prev_analog_mic_level != analog_mic_level &&
1194 capture_.prev_analog_mic_level != -1;
1195 capture_.prev_analog_mic_level = analog_mic_level;
1196
Per Åhgrend2650d12018-10-02 17:00:59 +02001197 // Detect and flag any change in the pre-amplifier gain.
1198 if (private_submodules_->pre_amplifier) {
1199 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1200 capture_.echo_path_gain_change =
1201 capture_.echo_path_gain_change ||
1202 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001203 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001204 capture_.prev_pre_amp_gain = pre_amp_gain;
1205 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001206 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001207 }
1208
peahbe615622016-02-13 16:40:47 -08001209 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001210 public_submodules_->gain_control->is_enabled()) {
1211 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001212 capture_buffer->channels()[0], capture_buffer->num_channels(),
1213 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001214
1215 if (constants_.use_experimental_agc_process_before_aec) {
1216 private_submodules_->agc_manager->Process(
1217 capture_buffer->channels()[0],
1218 capture_nonlocked_.capture_processing_format.num_frames(),
1219 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1220 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001221 }
1222
peah2ace3f92016-09-10 04:42:27 -07001223 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1224 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001225 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1226 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001227 }
1228
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001229 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001230 // Force down-mixing of the number of channels after the detection of
1231 // capture signal saturation.
1232 // TODO(peah): Look into ensuring that this kind of tampering with the
1233 // AudioBuffer functionality should not be needed.
1234 capture_buffer->set_num_channels(1);
1235 }
1236
peahe0eae3c2016-12-14 01:16:23 -08001237 // TODO(peah): Move the AEC3 low-cut filter to this place.
1238 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001239 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001240 private_submodules_->low_cut_filter->Process(capture_buffer);
1241 }
peahde65ddc2016-09-16 15:02:15 -07001242 RETURN_ON_ERR(
1243 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1244 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001245
1246 // Ensure that the stream delay was set before the call to the
1247 // AEC ProcessCaptureAudio function.
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001248 if (private_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001249 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001250 return AudioProcessing::kStreamParameterNotSetError;
1251 }
1252
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001253 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001254 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1255
Per Åhgrend0fa8202018-04-18 09:35:13 +02001256 if (was_stream_delay_set()) {
1257 private_submodules_->echo_controller->SetAudioBufferDelay(
1258 stream_delay_ms());
1259 }
1260
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001261 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001262 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001263 } else {
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001264 RETURN_ON_ERR(private_submodules_->echo_cancellation->ProcessCaptureAudio(
peah61202ac2017-02-06 03:39:42 -08001265 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001266 }
1267
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001268 if (private_submodules_->echo_control_mobile->is_enabled() &&
peahdf3efa82015-11-28 12:35:15 -08001269 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001270 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001271 }
peahde65ddc2016-09-16 15:02:15 -07001272 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001273
1274 // Ensure that the stream delay was set before the call to the
1275 // AECM ProcessCaptureAudio function.
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001276 if (private_submodules_->echo_control_mobile->is_enabled() &&
peah253534d2016-03-15 04:32:28 -07001277 !was_stream_delay_set()) {
1278 return AudioProcessing::kStreamParameterNotSetError;
1279 }
1280
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001281 if (!(private_submodules_->echo_controller ||
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001282 private_submodules_->echo_cancellation->is_enabled())) {
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001283 RETURN_ON_ERR(private_submodules_->echo_control_mobile->ProcessCaptureAudio(
Per Åhgren46537a32017-06-07 10:08:10 +02001284 capture_buffer, stream_delay_ms()));
1285 }
ivoc9f4a4a02016-10-28 05:39:16 -07001286
peahde65ddc2016-09-16 15:02:15 -07001287 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001288
peahbe615622016-02-13 16:40:47 -08001289 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001290 public_submodules_->gain_control->is_enabled() &&
1291 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001292 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001293 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1294 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001295 }
peahb8fbb542016-03-15 02:28:08 -07001296 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001297 capture_buffer,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001298 private_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001299
peah2ace3f92016-09-10 04:42:27 -07001300 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1301 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001302 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1303 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001304 }
1305
peah9e6a2902017-05-15 07:19:21 -07001306 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001307 RTC_DCHECK(private_submodules_->echo_detector);
1308 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001309 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1310 capture_buffer->num_frames()));
1311 }
1312
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001313 // TODO(aluebs): Investigate if the transient suppression placement should be
1314 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001315 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001316 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001317 private_submodules_->agc_manager.get()
1318 ? private_submodules_->agc_manager->voice_probability()
1319 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001320
peahdf3efa82015-11-28 12:35:15 -08001321 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001322 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1323 capture_buffer->num_channels(),
1324 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1325 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1326 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001327 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001328 }
1329
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001330 // Experimental APM sub-module that analyzes |capture_buffer|.
1331 if (private_submodules_->capture_analyzer) {
1332 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1333 }
1334
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001335 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001336 private_submodules_->gain_controller2->NotifyAnalogLevel(
1337 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001338 private_submodules_->gain_controller2->Process(capture_buffer);
1339 }
1340
Sam Zackrisson0beac582017-09-25 12:04:02 +02001341 if (private_submodules_->capture_post_processor) {
1342 private_submodules_->capture_post_processor->Process(capture_buffer);
1343 }
1344
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001345 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001346 public_submodules_->level_estimator->ProcessStream(capture_buffer);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001347 if (config_.level_estimation.enabled) {
1348 private_submodules_->output_level_estimator->ProcessStream(capture_buffer);
1349 capture_.stats.output_rms_dbfs =
1350 private_submodules_->output_level_estimator->RMS();
1351 } else {
1352 capture_.stats.output_rms_dbfs = absl::nullopt;
1353 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001354
peah1b08dc32016-12-20 13:45:58 -08001355 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1356 capture_buffer->channels_const()[0],
1357 capture_nonlocked_.capture_processing_format.num_frames()));
1358 if (log_rms) {
1359 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1360 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1361 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1362 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1363 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1364 }
1365
peahdf3efa82015-11-28 12:35:15 -08001366 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001367 return kNoError;
1368}
1369
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001370int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001371 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001372 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001373 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001374 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001375 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001376 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001377 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001378 };
1379 if (samples_per_channel != reverse_config.num_frames()) {
1380 return kBadDataLengthError;
1381 }
peahdf3efa82015-11-28 12:35:15 -08001382 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001383}
1384
peahde65ddc2016-09-16 15:02:15 -07001385int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1386 const StreamConfig& input_config,
1387 const StreamConfig& output_config,
1388 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001389 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001390 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001391 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001392 if (submodule_states_.RenderMultiBandProcessingActive() ||
1393 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001394 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1395 dest);
peah2ace3f92016-09-10 04:42:27 -07001396 } else if (formats_.api_format.reverse_input_stream() !=
1397 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001398 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1399 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001400 } else {
peahde65ddc2016-09-16 15:02:15 -07001401 CopyAudioIfNeeded(src, input_config.num_frames(),
1402 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001403 }
1404
1405 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001406}
1407
peahdf3efa82015-11-28 12:35:15 -08001408int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001409 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001410 const StreamConfig& input_config,
1411 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001412 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001413 return kNullPointerError;
1414 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001415
peahde65ddc2016-09-16 15:02:15 -07001416 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001417 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001418 }
1419
peahdf3efa82015-11-28 12:35:15 -08001420 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001421 processing_config.reverse_input_stream() = input_config;
1422 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001423
peahdf3efa82015-11-28 12:35:15 -08001424 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001425 RTC_DCHECK_EQ(input_config.num_frames(),
1426 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001427
aleloi868f32f2017-05-23 07:20:05 -07001428 if (aec_dump_) {
1429 const size_t channel_size =
1430 formats_.api_format.reverse_input_stream().num_frames();
1431 const size_t num_channels =
1432 formats_.api_format.reverse_input_stream().num_channels();
1433 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001434 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001435 }
peahdf3efa82015-11-28 12:35:15 -08001436 render_.render_audio->CopyFrom(src,
1437 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001438 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001439}
1440
1441int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001442 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001443 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001444 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001445 return kNullPointerError;
1446 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001447 // Must be a native rate.
1448 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1449 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001450 frame->sample_rate_hz_ != kSampleRate32kHz &&
1451 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001452 return kBadSampleRateError;
1453 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001454
Michael Graczyk86c6d332015-07-23 11:41:39 -07001455 if (frame->num_channels_ <= 0) {
1456 return kBadNumberChannelsError;
1457 }
1458
peahdf3efa82015-11-28 12:35:15 -08001459 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001460 processing_config.reverse_input_stream().set_sample_rate_hz(
1461 frame->sample_rate_hz_);
1462 processing_config.reverse_input_stream().set_num_channels(
1463 frame->num_channels_);
1464 processing_config.reverse_output_stream().set_sample_rate_hz(
1465 frame->sample_rate_hz_);
1466 processing_config.reverse_output_stream().set_num_channels(
1467 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001468
peahdf3efa82015-11-28 12:35:15 -08001469 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001470 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001471 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001472 return kBadDataLengthError;
1473 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001474
aleloi868f32f2017-05-23 07:20:05 -07001475 if (aec_dump_) {
1476 aec_dump_->WriteRenderStreamMessage(*frame);
1477 }
1478
peahdf3efa82015-11-28 12:35:15 -08001479 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001480 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001481 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001482 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1483 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001484 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001485}
niklase@google.com470e71d2011-07-07 08:21:25 +00001486
peahde65ddc2016-09-16 15:02:15 -07001487int AudioProcessingImpl::ProcessRenderStreamLocked() {
1488 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001489
Alex Loiko73ec0192018-05-15 10:52:28 +02001490 HandleRenderRuntimeSettings();
1491
Alex Loiko5825aa62017-12-18 16:02:40 +01001492 if (private_submodules_->render_pre_processor) {
1493 private_submodules_->render_pre_processor->Process(render_buffer);
1494 }
1495
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001496 QueueNonbandedRenderAudio(render_buffer);
1497
peah2ace3f92016-09-10 04:42:27 -07001498 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001499 SampleRateSupportsMultiBand(
1500 formats_.render_processing_format.sample_rate_hz())) {
1501 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001502 }
1503
peahce4d9152017-05-19 01:28:05 -07001504 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1505 QueueBandedRenderAudio(render_buffer);
1506 }
1507
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001508 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001509 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001510 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001511 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001512
peah2ace3f92016-09-10 04:42:27 -07001513 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001514 SampleRateSupportsMultiBand(
1515 formats_.render_processing_format.sample_rate_hz())) {
1516 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001517 }
1518
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001519 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001520}
1521
1522int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001523 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001524 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001525 capture_.was_stream_delay_set = true;
1526 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001527
niklase@google.com470e71d2011-07-07 08:21:25 +00001528 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001529 delay = 0;
1530 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001531 }
1532
1533 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1534 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001535 delay = 500;
1536 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001537 }
1538
peahdf3efa82015-11-28 12:35:15 -08001539 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001540 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001541}
1542
1543int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001544 // Used as callback from submodules, hence locking is not allowed.
1545 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001546}
1547
1548bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001549 // Used as callback from submodules, hence locking is not allowed.
1550 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001551}
1552
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001553void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001554 rtc::CritScope cs(&crit_capture_);
1555 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001556}
1557
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001558void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001559 rtc::CritScope cs(&crit_capture_);
1560 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001561}
1562
1563int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001564 rtc::CritScope cs(&crit_capture_);
1565 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001566}
1567
aleloi868f32f2017-05-23 07:20:05 -07001568void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1569 RTC_DCHECK(aec_dump);
1570 rtc::CritScope cs_render(&crit_render_);
1571 rtc::CritScope cs_capture(&crit_capture_);
1572
1573 // The previously attached AecDump will be destroyed with the
1574 // 'aec_dump' parameter, which is after locks are released.
1575 aec_dump_.swap(aec_dump);
1576 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001577 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001578}
1579
1580void AudioProcessingImpl::DetachAecDump() {
1581 // The d-tor of a task-queue based AecDump blocks until all pending
1582 // tasks are done. This construction avoids blocking while holding
1583 // the render and capture locks.
1584 std::unique_ptr<AecDump> aec_dump = nullptr;
1585 {
1586 rtc::CritScope cs_render(&crit_render_);
1587 rtc::CritScope cs_capture(&crit_capture_);
1588 aec_dump = std::move(aec_dump_);
1589 }
1590}
1591
Sam Zackrisson4d364492018-03-02 16:03:21 +01001592void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1593 std::unique_ptr<AudioGenerator> audio_generator) {
1594 // TODO(bugs.webrtc.org/8882) Stub.
1595 // Reset internal audio generator with audio_generator.
1596}
1597
1598void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1599 // TODO(bugs.webrtc.org/8882) Stub.
1600 // Delete audio generator, if one is attached.
1601}
1602
Ivo Creusen56d46092017-11-24 17:29:59 +01001603AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001604 bool has_remote_tracks) const {
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001605 rtc::CritScope cs_capture(&crit_capture_);
1606 if (!has_remote_tracks) {
1607 return capture_.stats;
1608 }
1609 AudioProcessingStats stats = capture_.stats;
1610 EchoCancellationImpl::Metrics metrics;
1611 if (private_submodules_->echo_controller) {
1612 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1613 stats.echo_return_loss = ec_metrics.echo_return_loss;
1614 stats.echo_return_loss_enhancement =
1615 ec_metrics.echo_return_loss_enhancement;
1616 stats.delay_ms = ec_metrics.delay_ms;
1617 } else if (private_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1618 Error::kNoError) {
1619 if (metrics.divergent_filter_fraction != -1.0f) {
1620 stats.divergent_filter_fraction =
1621 absl::optional<double>(metrics.divergent_filter_fraction);
1622 }
1623 if (metrics.echo_return_loss.instant != -100) {
1624 stats.echo_return_loss =
1625 absl::optional<double>(metrics.echo_return_loss.instant);
1626 }
1627 if (metrics.echo_return_loss_enhancement.instant != -100) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001628 stats.echo_return_loss_enhancement =
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001629 absl::optional<double>(metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001630 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001631 }
1632 if (config_.residual_echo_detector.enabled) {
1633 RTC_DCHECK(private_submodules_->echo_detector);
1634 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1635 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1636 stats.residual_echo_likelihood_recent_max =
1637 ed_metrics.echo_likelihood_recent_max;
1638 }
1639 int delay_median, delay_std;
1640 float fraction_poor_delays;
1641 if (private_submodules_->echo_cancellation->GetDelayMetrics(
1642 &delay_median, &delay_std, &fraction_poor_delays) ==
1643 Error::kNoError) {
1644 if (delay_median >= 0) {
1645 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001646 }
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01001647 if (delay_std >= 0) {
1648 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001649 }
1650 }
1651 return stats;
1652}
1653
niklase@google.com470e71d2011-07-07 08:21:25 +00001654GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001655 if (constants_.use_experimental_agc) {
1656 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001657 }
peahbfa97112016-03-10 21:09:04 -08001658 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001659}
1660
niklase@google.com470e71d2011-07-07 08:21:25 +00001661LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001662 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001663}
1664
1665NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001666 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001667}
1668
1669VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001670 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001671}
1672
peah8271d042016-11-22 07:24:52 -08001673void AudioProcessingImpl::MutateConfig(
1674 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1675 rtc::CritScope cs_render(&crit_render_);
1676 rtc::CritScope cs_capture(&crit_capture_);
1677 mutator(&config_);
1678 ApplyConfig(config_);
1679}
1680
1681AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1682 rtc::CritScope cs_render(&crit_render_);
1683 rtc::CritScope cs_capture(&crit_capture_);
1684 return config_;
1685}
1686
peah2ace3f92016-09-10 04:42:27 -07001687bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1688 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001689 config_.high_pass_filter.enabled,
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001690 private_submodules_->echo_cancellation->is_enabled(),
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001691 private_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001692 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001693 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001694 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001695 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001696 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001697 public_submodules_->voice_detection->is_enabled(),
1698 public_submodules_->level_estimator->is_enabled(),
1699 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001700}
1701
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001702void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001703 if (capture_.transient_suppressor_enabled) {
1704 if (!public_submodules_->transient_suppressor.get()) {
1705 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001706 }
peahdf3efa82015-11-28 12:35:15 -08001707 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001708 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1709 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001710 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001711}
1712
peah8271d042016-11-22 07:24:52 -08001713void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001714 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001715 private_submodules_->low_cut_filter.reset(
1716 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1717 } else {
1718 private_submodules_->low_cut_filter.reset();
1719 }
1720}
alessiob3ec96df2017-05-22 06:57:06 -07001721
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001722void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001723 if (echo_control_factory_) {
1724 private_submodules_->echo_controller =
1725 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001726 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001727 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001728 }
1729}
peah8271d042016-11-22 07:24:52 -08001730
alessiob3ec96df2017-05-22 06:57:06 -07001731void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001732 if (config_.gain_controller2.enabled) {
1733 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001734 }
1735}
1736
Alex Loikob5c9a792018-04-16 16:31:22 +02001737void AudioProcessingImpl::InitializePreAmplifier() {
1738 if (config_.pre_amplifier.enabled) {
1739 private_submodules_->pre_amplifier.reset(
1740 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1741 } else {
1742 private_submodules_->pre_amplifier.reset();
1743 }
1744}
1745
ivoc9f4a4a02016-10-28 05:39:16 -07001746void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001747 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001748 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001749 proc_sample_rate_hz(), 1,
1750 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001751}
1752
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001753void AudioProcessingImpl::InitializeAnalyzer() {
1754 if (private_submodules_->capture_analyzer) {
1755 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1756 num_proc_channels());
1757 }
1758}
1759
Sam Zackrisson0beac582017-09-25 12:04:02 +02001760void AudioProcessingImpl::InitializePostProcessor() {
1761 if (private_submodules_->capture_post_processor) {
1762 private_submodules_->capture_post_processor->Initialize(
1763 proc_sample_rate_hz(), num_proc_channels());
1764 }
1765}
1766
Alex Loiko5825aa62017-12-18 16:02:40 +01001767void AudioProcessingImpl::InitializePreProcessor() {
1768 if (private_submodules_->render_pre_processor) {
1769 private_submodules_->render_pre_processor->Initialize(
1770 formats_.render_processing_format.sample_rate_hz(),
1771 formats_.render_processing_format.num_channels());
1772 }
1773}
1774
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001775void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001776 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001777
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001778 if (private_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001779 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1780 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001781 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001782 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001783 capture_.stream_delay_jumps = 0;
1784 }
1785 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001786 private_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001787 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001788 }
1789
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001790 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001791 const int diff_stream_delay_ms =
1792 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1793 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1794 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001795 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1796 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001797 if (capture_.stream_delay_jumps == -1) {
1798 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001799 }
peahdf3efa82015-11-28 12:35:15 -08001800 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001801 }
peahdf3efa82015-11-28 12:35:15 -08001802 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001803
1804 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001805 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001806 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001807 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001808 const int aec_system_delay_ms =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001809 private_submodules_->echo_cancellation->GetSystemDelayInSamples() /
peah20028c42016-03-04 11:50:54 -08001810 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001811 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001812 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001813 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001814 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001815 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1816 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1817 100);
peahdf3efa82015-11-28 12:35:15 -08001818 if (capture_.aec_system_delay_jumps == -1) {
1819 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001820 }
peahdf3efa82015-11-28 12:35:15 -08001821 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001822 }
peahdf3efa82015-11-28 12:35:15 -08001823 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001824 }
1825}
1826
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001827void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001828 // Run in a single-threaded manner.
1829 rtc::CritScope cs_render(&crit_render_);
1830 rtc::CritScope cs_capture(&crit_capture_);
1831
1832 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001833 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001834 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001835 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001836 }
peahdf3efa82015-11-28 12:35:15 -08001837 capture_.stream_delay_jumps = -1;
1838 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001839
peahdf3efa82015-11-28 12:35:15 -08001840 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001841 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1842 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001843 }
peahdf3efa82015-11-28 12:35:15 -08001844 capture_.aec_system_delay_jumps = -1;
1845 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001846}
1847
aleloi868f32f2017-05-23 07:20:05 -07001848void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1849 if (!aec_dump_) {
1850 return;
1851 }
1852 std::string experiments_description =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001853 private_submodules_->echo_cancellation->GetExperimentsDescription();
aleloi868f32f2017-05-23 07:20:05 -07001854 // TODO(peah): Add semicolon-separated concatenations of experiment
1855 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001856 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1857 experiments_description += "AgcClippingLevelExperiment;";
1858 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001859 if (capture_nonlocked_.echo_controller_enabled) {
1860 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001861 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001862 if (config_.gain_controller2.enabled) {
1863 experiments_description += "GainController2;";
1864 }
aleloi868f32f2017-05-23 07:20:05 -07001865
1866 InternalAPMConfig apm_config;
1867
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001868 apm_config.aec_enabled = private_submodules_->echo_cancellation->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001869 apm_config.aec_delay_agnostic_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001870 private_submodules_->echo_cancellation->is_delay_agnostic_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001871 apm_config.aec_drift_compensation_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001872 private_submodules_->echo_cancellation->is_drift_compensation_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001873 apm_config.aec_extended_filter_enabled =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001874 private_submodules_->echo_cancellation->is_extended_filter_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001875 apm_config.aec_suppression_level = static_cast<int>(
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001876 private_submodules_->echo_cancellation->suppression_level());
aleloi868f32f2017-05-23 07:20:05 -07001877
1878 apm_config.aecm_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001879 private_submodules_->echo_control_mobile->is_enabled();
aleloi868f32f2017-05-23 07:20:05 -07001880 apm_config.aecm_comfort_noise_enabled =
Sam Zackrissonc22f5512018-11-05 16:10:00 +01001881 private_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1882 apm_config.aecm_routing_mode = static_cast<int>(
1883 private_submodules_->echo_control_mobile->routing_mode());
aleloi868f32f2017-05-23 07:20:05 -07001884
1885 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1886 apm_config.agc_mode =
1887 static_cast<int>(public_submodules_->gain_control->mode());
1888 apm_config.agc_limiter_enabled =
1889 public_submodules_->gain_control->is_limiter_enabled();
1890 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1891
1892 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1893
1894 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1895 apm_config.ns_level =
1896 static_cast<int>(public_submodules_->noise_suppression->level());
1897
1898 apm_config.transient_suppression_enabled =
1899 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001900 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001901 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1902 apm_config.pre_amplifier_fixed_gain_factor =
1903 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001904
1905 if (!forced && apm_config == apm_config_for_aec_dump_) {
1906 return;
1907 }
1908 aec_dump_->WriteConfig(apm_config);
1909 apm_config_for_aec_dump_ = apm_config;
1910}
1911
1912void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1913 const float* const* src) {
1914 RTC_DCHECK(aec_dump_);
1915 WriteAecDumpConfigMessage(false);
1916
1917 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1918 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1919 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001920 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001921 RecordAudioProcessingState();
1922}
1923
1924void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1925 const AudioFrame& capture_frame) {
1926 RTC_DCHECK(aec_dump_);
1927 WriteAecDumpConfigMessage(false);
1928
1929 aec_dump_->AddCaptureStreamInput(capture_frame);
1930 RecordAudioProcessingState();
1931}
1932
1933void AudioProcessingImpl::RecordProcessedCaptureStream(
1934 const float* const* processed_capture_stream) {
1935 RTC_DCHECK(aec_dump_);
1936
1937 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1938 const size_t num_channels =
1939 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001940 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1941 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001942 aec_dump_->WriteCaptureStreamMessage();
1943}
1944
1945void AudioProcessingImpl::RecordProcessedCaptureStream(
1946 const AudioFrame& processed_capture_frame) {
1947 RTC_DCHECK(aec_dump_);
1948
1949 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1950 aec_dump_->WriteCaptureStreamMessage();
1951}
1952
1953void AudioProcessingImpl::RecordAudioProcessingState() {
1954 RTC_DCHECK(aec_dump_);
1955 AecDump::AudioProcessingState audio_proc_state;
1956 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
1957 audio_proc_state.drift =
Sam Zackrisson7f4dfa42018-11-01 08:59:29 +01001958 private_submodules_->echo_cancellation->stream_drift_samples();
aleloi868f32f2017-05-23 07:20:05 -07001959 audio_proc_state.level = gain_control()->stream_analog_level();
1960 audio_proc_state.keypress = capture_.key_pressed;
1961 aec_dump_->AddAudioProcessingState(audio_proc_state);
1962}
1963
kwiberg83ffe452016-08-29 14:46:07 -07001964AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02001965 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07001966 : aec_system_delay_jumps(-1),
1967 delay_offset_ms(0),
1968 was_stream_delay_set(false),
1969 last_stream_delay_ms(0),
1970 last_aec_system_delay_ms(0),
1971 stream_delay_jumps(-1),
1972 output_will_be_muted(false),
1973 key_pressed(false),
1974 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07001975 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001976 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02001977 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02001978 prev_analog_mic_level(-1),
1979 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07001980
1981AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1982
1983AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1984
1985AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1986
niklase@google.com470e71d2011-07-07 08:21:25 +00001987} // namespace webrtc