blob: 3207a59bfa425d42a15604eda07373498c4fd9f3 [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.
peahb624d8c2016-03-05 03:01:14 -0800230 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800231 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800232 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800233 std::unique_ptr<LevelEstimatorImpl> level_estimator;
234 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
235 std::unique_ptr<VoiceDetectionImpl> voice_detection;
236 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800237 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800238
239 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800240 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800241};
242
243struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200244 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100245 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200246 rtc::scoped_refptr<EchoDetector> echo_detector,
247 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200248 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100249 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200250 render_pre_processor(std::move(render_pre_processor)),
251 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800252 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800253 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700254 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800255 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200256 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200257 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100258 std::unique_ptr<CustomProcessing> capture_post_processor;
259 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200260 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200261 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
solenberg5e465c32015-12-08 13:22:33 -0800262};
263
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100264AudioProcessingBuilder::AudioProcessingBuilder() = default;
265AudioProcessingBuilder::~AudioProcessingBuilder() = default;
266
267AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
268 std::unique_ptr<CustomProcessing> capture_post_processing) {
269 capture_post_processing_ = std::move(capture_post_processing);
270 return *this;
271}
272
273AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
274 std::unique_ptr<CustomProcessing> render_pre_processing) {
275 render_pre_processing_ = std::move(render_pre_processing);
276 return *this;
277}
278
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200279AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
280 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
281 capture_analyzer_ = std::move(capture_analyzer);
282 return *this;
283}
284
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100285AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
286 std::unique_ptr<EchoControlFactory> echo_control_factory) {
287 echo_control_factory_ = std::move(echo_control_factory);
288 return *this;
289}
290
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100291AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200292 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100293 echo_detector_ = std::move(echo_detector);
294 return *this;
295}
296
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100297AudioProcessing* AudioProcessingBuilder::Create() {
298 webrtc::Config config;
299 return Create(config);
300}
301
302AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100303 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
304 config, std::move(capture_post_processing_),
305 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200306 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100307 if (apm->Initialize() != AudioProcessing::kNoError) {
308 delete apm;
309 apm = nullptr;
310 }
311 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100312}
313
peah88ac8532016-09-12 16:47:25 -0700314AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200315 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
316}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000317
Per Åhgren13735822018-02-12 21:42:56 +0100318int AudioProcessingImpl::instance_count_ = 0;
319
Sam Zackrisson0beac582017-09-25 12:04:02 +0200320AudioProcessingImpl::AudioProcessingImpl(
321 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100322 std::unique_ptr<CustomProcessing> capture_post_processor,
323 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200324 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200325 rtc::scoped_refptr<EchoDetector> echo_detector,
326 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100327 : data_dumper_(
328 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200329 capture_runtime_settings_(kRuntimeSettingQueueSize),
330 render_runtime_settings_(kRuntimeSettingQueueSize),
331 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
332 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200333 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200334 submodule_states_(!!capture_post_processor,
335 !!render_pre_processor,
336 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800337 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200338 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200339 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100340 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200341 std::move(echo_detector),
342 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800343 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800344 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000345#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200346 /* enabled= */ false,
347 /* enabled_agc2_level_estimator= */ false,
348 /* digital_adaptive_disabled= */ false,
349 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000350#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200351 config.Get<ExperimentalAgc>().enabled,
352 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200353 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
354 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000355#endif
andrew1c7075f2015-06-24 18:14:14 -0700356#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200357 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700358#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200359 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700360#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200361 capture_nonlocked_() {
peahdf3efa82015-11-28 12:35:15 -0800362 {
363 rtc::CritScope cs_render(&crit_render_);
364 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000365
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200366 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000367 capture_nonlocked_.echo_controller_enabled =
368 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200369
peahb624d8c2016-03-05 03:01:14 -0800370 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700371 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800372 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700373 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800374 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200375 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800376 public_submodules_->level_estimator.reset(
377 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800378 public_submodules_->noise_suppression.reset(
379 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800380 public_submodules_->voice_detection.reset(
381 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800382 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800383 new GainControlForExperimentalAgc(
384 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100385
386 // If no echo detector is injected, use the ResidualEchoDetector.
387 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200388 private_submodules_->echo_detector =
389 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100390 }
peahca4cac72016-06-29 15:26:12 -0700391
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200392 // TODO(alessiob): Move the injected gain controller once injection is
393 // implemented.
394 private_submodules_->gain_controller2.reset(new GainController2());
395
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200396 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
397 << !!private_submodules_->capture_analyzer
398 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100399 << !!private_submodules_->capture_post_processor
400 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100401 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800402 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000403
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000404 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000405}
406
407AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800408 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800409 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800410 private_submodules_->agc_manager.reset();
411 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800412 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000413}
414
niklase@google.com470e71d2011-07-07 08:21:25 +0000415int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800416 // Run in a single-threaded manner during initialization.
417 rtc::CritScope cs_render(&crit_render_);
418 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000419 return InitializeLocked();
420}
421
peahde65ddc2016-09-16 15:02:15 -0700422int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
423 int capture_output_sample_rate_hz,
424 int render_input_sample_rate_hz,
425 ChannelLayout capture_input_layout,
426 ChannelLayout capture_output_layout,
427 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700428 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700429 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
430 LayoutHasKeyboard(capture_input_layout)},
431 {capture_output_sample_rate_hz,
432 ChannelsFromLayout(capture_output_layout),
433 LayoutHasKeyboard(capture_output_layout)},
434 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
435 LayoutHasKeyboard(render_input_layout)},
436 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
437 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700438
439 return Initialize(processing_config);
440}
441
442int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800443 // Run in a single-threaded manner during initialization.
444 rtc::CritScope cs_render(&crit_render_);
445 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700446 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000447}
448
peahdf3efa82015-11-28 12:35:15 -0800449int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800450 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700451 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800452}
453
peahdf3efa82015-11-28 12:35:15 -0800454int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700455 const ProcessingConfig& processing_config,
456 bool force_initialization) {
457 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800458}
459
peah192164e2015-11-17 02:16:45 -0800460// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800461// their current values (needs to be called while holding the crit_render_lock).
462int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700463 const ProcessingConfig& processing_config,
464 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800465 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700466 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800467 return kNoError;
468 }
peahdf3efa82015-11-28 12:35:15 -0800469
470 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800471 return InitializeLocked(processing_config);
472}
473
niklase@google.com470e71d2011-07-07 08:21:25 +0000474int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200475 UpdateActiveSubmoduleStates();
476
peahde65ddc2016-09-16 15:02:15 -0700477 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800478 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700479 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800480 : formats_.api_format.reverse_output_stream().num_frames();
481 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
482 render_.render_audio.reset(new AudioBuffer(
483 formats_.api_format.reverse_input_stream().num_frames(),
484 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700485 formats_.render_processing_format.num_frames(),
486 formats_.render_processing_format.num_channels(),
487 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700488 if (formats_.api_format.reverse_input_stream() !=
489 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800490 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800491 formats_.api_format.reverse_input_stream().num_channels(),
492 formats_.api_format.reverse_input_stream().num_frames(),
493 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800494 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700495 } else {
peahdf3efa82015-11-28 12:35:15 -0800496 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700497 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700498 } else {
peahdf3efa82015-11-28 12:35:15 -0800499 render_.render_audio.reset(nullptr);
500 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700501 }
peahce4d9152017-05-19 01:28:05 -0700502
peahdf3efa82015-11-28 12:35:15 -0800503 capture_.capture_audio.reset(
504 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
505 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700506 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200507 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800508 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000509
peahde65ddc2016-09-16 15:02:15 -0700510 public_submodules_->echo_cancellation->Initialize(
511 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
512 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700513 AllocateRenderQueue();
514
ivoc3e9a5372016-10-28 07:55:33 -0700515 int success = public_submodules_->echo_cancellation->enable_metrics(true);
516 RTC_DCHECK_EQ(0, success);
517 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
518 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700519 public_submodules_->echo_control_mobile->Initialize(
520 proc_split_sample_rate_hz(), num_reverse_channels(),
521 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700522
523 public_submodules_->gain_control->Initialize(num_proc_channels(),
524 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700525 if (constants_.use_experimental_agc) {
526 if (!private_submodules_->agc_manager.get()) {
527 private_submodules_->agc_manager.reset(new AgcManagerDirect(
528 public_submodules_->gain_control.get(),
529 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200530 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
531 constants_.use_experimental_agc_agc2_level_estimation,
532 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700533 }
534 private_submodules_->agc_manager->Initialize();
535 private_submodules_->agc_manager->SetCaptureMuted(
536 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700537 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700538 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200539 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800540 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700541 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
542 proc_sample_rate_hz());
543 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
544 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700545 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200546 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700547 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200548 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200549 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100550 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800551
aleloi868f32f2017-05-23 07:20:05 -0700552 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200553 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700554 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000555 return kNoError;
556}
557
Michael Graczyk86c6d332015-07-23 11:41:39 -0700558int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200559 UpdateActiveSubmoduleStates();
560
Michael Graczyk86c6d332015-07-23 11:41:39 -0700561 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700562 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
563 return kBadSampleRateError;
564 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000565 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700566
Peter Kasting69558702016-01-12 16:26:35 -0800567 const size_t num_in_channels = config.input_stream().num_channels();
568 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700569
570 // Need at least one input channel.
571 // Need either one output channel or as many outputs as there are inputs.
572 if (num_in_channels == 0 ||
573 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700574 return kBadNumberChannelsError;
575 }
576
peahdf3efa82015-11-28 12:35:15 -0800577 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000578
peahde65ddc2016-09-16 15:02:15 -0700579 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700580 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700581 formats_.api_format.output_stream().sample_rate_hz()),
582 submodule_states_.CaptureMultiBandSubModulesActive() ||
583 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000584
peahde65ddc2016-09-16 15:02:15 -0700585 capture_nonlocked_.capture_processing_format =
586 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700587
peah2ce640f2017-04-07 03:57:48 -0700588 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200589 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700590 render_processing_rate = FindNativeProcessRateToUse(
591 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
592 formats_.api_format.reverse_output_stream().sample_rate_hz()),
593 submodule_states_.CaptureMultiBandSubModulesActive() ||
594 submodule_states_.RenderMultiBandSubModulesActive());
595 } else {
596 render_processing_rate = capture_processing_rate;
597 }
598
aluebseb3603b2016-04-20 15:27:58 -0700599 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
600 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700601 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200602 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700603 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
604 ? kSampleRate32kHz
605 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700606 }
peah2ce640f2017-04-07 03:57:48 -0700607
peahde65ddc2016-09-16 15:02:15 -0700608 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700609 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700610 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
611 kSampleRate8kHz) {
612 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000613 } else {
peahde65ddc2016-09-16 15:02:15 -0700614 render_processing_rate =
615 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000616 }
617
peahde65ddc2016-09-16 15:02:15 -0700618 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000619 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700620 if (submodule_states_.RenderMultiBandSubModulesActive()) {
621 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
622 } else {
623 formats_.render_processing_format = StreamConfig(
624 formats_.api_format.reverse_input_stream().sample_rate_hz(),
625 formats_.api_format.reverse_input_stream().num_channels());
626 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000627
peahde65ddc2016-09-16 15:02:15 -0700628 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
629 kSampleRate32kHz ||
630 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
631 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800632 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000633 } else {
peahdf3efa82015-11-28 12:35:15 -0800634 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700635 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000636 }
637
638 return InitializeLocked();
639}
640
peah88ac8532016-09-12 16:47:25 -0700641void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peah88ac8532016-09-12 16:47:25 -0700642 // Run in a single-threaded manner when applying the settings.
643 rtc::CritScope cs_render(&crit_render_);
644 rtc::CritScope cs_capture(&crit_capture_);
645
Yves Gerey499bc6c2018-10-10 18:29:07 +0200646 config_ = config;
647
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200648 public_submodules_->echo_cancellation->Enable(
649 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200650 public_submodules_->echo_control_mobile->Enable(
651 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200652
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200653 public_submodules_->echo_cancellation->set_suppression_level(
654 config.echo_canceller.legacy_moderate_suppression_level
sazabe490b22018-10-03 17:03:13 +0200655 ? EchoCancellationImpl::SuppressionLevel::kModerateSuppression
656 : EchoCancellationImpl::SuppressionLevel::kHighSuppression);
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200657
peah8271d042016-11-22 07:24:52 -0800658 InitializeLowCutFilter();
659
Mirko Bonadei675513b2017-11-09 11:09:25 +0100660 RTC_LOG(LS_INFO) << "Highpass filter activated: "
661 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800662
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100663 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700664 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100665 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
666 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100667 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100668 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700669 config_.gain_controller2 = AudioProcessing::Config::GainController2();
670 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200671 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200672 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200673 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100674 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
675 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200676 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
677 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700678}
679
680void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800681 // Run in a single-threaded manner when setting the extra options.
682 rtc::CritScope cs_render(&crit_render_);
683 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000684
peahb624d8c2016-03-05 03:01:14 -0800685 public_submodules_->echo_cancellation->SetExtraOptions(config);
686
peahdf3efa82015-11-28 12:35:15 -0800687 if (capture_.transient_suppressor_enabled !=
688 config.Get<ExperimentalNs>().enabled) {
689 capture_.transient_suppressor_enabled =
690 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000691 InitializeTransient();
692 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000693}
694
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000695int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800696 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700697 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000698}
699
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000700int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800701 // Used as callback from submodules, hence locking is not allowed.
702 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000703}
704
Peter Kasting69558702016-01-12 16:26:35 -0800705size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800706 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700707 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000708}
709
Peter Kasting69558702016-01-12 16:26:35 -0800710size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800711 // Used as callback from submodules, hence locking is not allowed.
712 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000713}
714
Peter Kasting69558702016-01-12 16:26:35 -0800715size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800716 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200717 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800718}
719
Peter Kasting69558702016-01-12 16:26:35 -0800720size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800721 // Used as callback from submodules, hence locking is not allowed.
722 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000723}
724
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000725void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800726 rtc::CritScope cs(&crit_capture_);
727 capture_.output_will_be_muted = muted;
728 if (private_submodules_->agc_manager.get()) {
729 private_submodules_->agc_manager->SetCaptureMuted(
730 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000731 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000732}
733
Alessio Bazzicac054e782018-04-16 12:10:09 +0200734void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200735 switch (setting.type()) {
736 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
737 render_runtime_settings_enqueuer_.Enqueue(setting);
738 return;
739 case RuntimeSetting::Type::kNotSpecified:
740 RTC_NOTREACHED();
741 return;
742 case RuntimeSetting::Type::kCapturePreGain:
743 capture_runtime_settings_enqueuer_.Enqueue(setting);
744 return;
745 }
746 // The language allows the enum to have a non-enumerator
747 // value. Check that this doesn't happen.
748 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200749}
750
751AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
752 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200753 : runtime_settings_(*runtime_settings) {
754 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200755}
756
757AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
758 default;
759
760void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
761 RuntimeSetting setting) {
762 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200763 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200764 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200765 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200766 RTC_LOG(LS_ERROR)
767 << "The runtime settings queue is full. Oldest setting discarded.";
768 }
769 if (remaining_attempts == 0)
770 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
771}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000772
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000773int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700774 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000775 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000776 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000777 int output_sample_rate_hz,
778 ChannelLayout output_layout,
779 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800780 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800781 StreamConfig input_stream;
782 StreamConfig output_stream;
783 {
784 // Access the formats_.api_format.input_stream beneath the capture lock.
785 // The lock must be released as it is later required in the call
786 // to ProcessStream(,,,);
787 rtc::CritScope cs(&crit_capture_);
788 input_stream = formats_.api_format.input_stream();
789 output_stream = formats_.api_format.output_stream();
790 }
791
Michael Graczyk86c6d332015-07-23 11:41:39 -0700792 input_stream.set_sample_rate_hz(input_sample_rate_hz);
793 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
794 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700795 output_stream.set_sample_rate_hz(output_sample_rate_hz);
796 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
797 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
798
799 if (samples_per_channel != input_stream.num_frames()) {
800 return kBadDataLengthError;
801 }
802 return ProcessStream(src, input_stream, output_stream, dest);
803}
804
805int AudioProcessingImpl::ProcessStream(const float* const* src,
806 const StreamConfig& input_config,
807 const StreamConfig& output_config,
808 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800809 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800810 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700811 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800812 {
813 // Acquire the capture lock in order to safely call the function
814 // that retrieves the render side data. This function accesses apm
815 // getters that need the capture lock held when being called.
816 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700817 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800818
819 if (!src || !dest) {
820 return kNullPointerError;
821 }
822
823 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700824 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000825 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000826
Michael Graczyk86c6d332015-07-23 11:41:39 -0700827 processing_config.input_stream() = input_config;
828 processing_config.output_stream() = output_config;
829
peahdf3efa82015-11-28 12:35:15 -0800830 {
831 // Do conditional reinitialization.
832 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700833 RETURN_ON_ERR(
834 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800835 }
836 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700837 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
838 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000839
aleloi868f32f2017-05-23 07:20:05 -0700840 if (aec_dump_) {
841 RecordUnprocessedCaptureStream(src);
842 }
843
peahdf3efa82015-11-28 12:35:15 -0800844 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700845 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800846 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000847
aleloi868f32f2017-05-23 07:20:05 -0700848 if (aec_dump_) {
849 RecordProcessedCaptureStream(dest);
850 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000851 return kNoError;
852}
853
Alex Loiko73ec0192018-05-15 10:52:28 +0200854void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200855 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200856 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200857 if (aec_dump_) {
858 aec_dump_->WriteRuntimeSetting(setting);
859 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200860 switch (setting.type()) {
861 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200862 if (config_.pre_amplifier.enabled) {
863 float value;
864 setting.GetFloat(&value);
865 private_submodules_->pre_amplifier->SetGainFactor(value);
866 }
867 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200868 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200869 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
870 RTC_NOTREACHED();
871 break;
872 case RuntimeSetting::Type::kNotSpecified:
873 RTC_NOTREACHED();
874 break;
875 }
876 }
877}
878
879void AudioProcessingImpl::HandleRenderRuntimeSettings() {
880 RuntimeSetting setting;
881 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200882 if (aec_dump_) {
883 aec_dump_->WriteRuntimeSetting(setting);
884 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200885 switch (setting.type()) {
886 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
887 if (private_submodules_->render_pre_processor) {
888 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
889 }
890 break;
891 case RuntimeSetting::Type::kCapturePreGain:
892 RTC_NOTREACHED();
893 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200894 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200895 RTC_NOTREACHED();
896 break;
897 }
898 }
899}
900
peah9e6a2902017-05-15 07:19:21 -0700901void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700902 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
903 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700904 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700905
kwibergaf476c72016-11-28 15:21:39 -0800906 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700907
908 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700909 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700910 // The data queue is full and needs to be emptied.
911 EmptyQueuedRenderAudio();
912
913 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700914 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700915 RTC_DCHECK(result);
916 }
917
918 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
919 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700920 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700921
922 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700923 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700924 // The data queue is full and needs to be emptied.
925 EmptyQueuedRenderAudio();
926
927 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700928 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700929 RTC_DCHECK(result);
930 }
peah701d6282016-10-25 05:42:20 -0700931
932 if (!constants_.use_experimental_agc) {
933 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
934 // Insert the samples into the queue.
935 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
936 // The data queue is full and needs to be emptied.
937 EmptyQueuedRenderAudio();
938
939 // Retry the insert (should always work).
940 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
941 RTC_DCHECK(result);
942 }
943 }
peah9e6a2902017-05-15 07:19:21 -0700944}
ivoc9f4a4a02016-10-28 05:39:16 -0700945
peah9e6a2902017-05-15 07:19:21 -0700946void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700947 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
948
949 // Insert the samples into the queue.
950 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
951 // The data queue is full and needs to be emptied.
952 EmptyQueuedRenderAudio();
953
954 // Retry the insert (should always work).
955 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
956 RTC_DCHECK(result);
957 }
peah764e3642016-10-22 05:04:30 -0700958}
959
960void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700961 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700962 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700963 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700964 EchoCancellationImpl::NumCancellersRequired(
965 num_output_channels(), num_reverse_channels()));
966
peah701d6282016-10-25 05:42:20 -0700967 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700968 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700969 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700970 EchoControlMobileImpl::NumCancellersRequired(
971 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700972
peah701d6282016-10-25 05:42:20 -0700973 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700974 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700975
ivoc9f4a4a02016-10-28 05:39:16 -0700976 const size_t new_red_render_queue_element_max_size =
977 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
978
peaha0624602016-10-25 04:45:24 -0700979 // Reallocate the queues if the queue item sizes are too small to fit the
980 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700981 if (aec_render_queue_element_max_size_ <
982 new_aec_render_queue_element_max_size) {
983 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700984
peaha0624602016-10-25 04:45:24 -0700985 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700986 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700987
peah701d6282016-10-25 05:42:20 -0700988 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700989 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
990 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700991 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700992 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700993
peah701d6282016-10-25 05:42:20 -0700994 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
995 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700996 } else {
peah701d6282016-10-25 05:42:20 -0700997 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700998 }
999
peah701d6282016-10-25 05:42:20 -07001000 if (aecm_render_queue_element_max_size_ <
1001 new_aecm_render_queue_element_max_size) {
1002 aecm_render_queue_element_max_size_ =
1003 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001004
1005 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001006 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001007
peah701d6282016-10-25 05:42:20 -07001008 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001009 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1010 kMaxNumFramesToBuffer, template_queue_element,
1011 RenderQueueItemVerifier<int16_t>(
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_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1015 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001016 } else {
peah701d6282016-10-25 05:42:20 -07001017 aecm_render_signal_queue_->Clear();
1018 }
1019
1020 if (agc_render_queue_element_max_size_ <
1021 new_agc_render_queue_element_max_size) {
1022 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1023
1024 std::vector<int16_t> template_queue_element(
1025 agc_render_queue_element_max_size_);
1026
1027 agc_render_signal_queue_.reset(
1028 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1029 kMaxNumFramesToBuffer, template_queue_element,
1030 RenderQueueItemVerifier<int16_t>(
1031 agc_render_queue_element_max_size_)));
1032
1033 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1034 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1035 } else {
1036 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001037 }
ivoc9f4a4a02016-10-28 05:39:16 -07001038
1039 if (red_render_queue_element_max_size_ <
1040 new_red_render_queue_element_max_size) {
1041 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1042
1043 std::vector<float> template_queue_element(
1044 red_render_queue_element_max_size_);
1045
1046 red_render_signal_queue_.reset(
1047 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1048 kMaxNumFramesToBuffer, template_queue_element,
1049 RenderQueueItemVerifier<float>(
1050 red_render_queue_element_max_size_)));
1051
1052 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1053 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1054 } else {
1055 red_render_signal_queue_->Clear();
1056 }
peah764e3642016-10-22 05:04:30 -07001057}
1058
1059void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1060 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001061 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001062 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001063 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001064 }
1065
peah701d6282016-10-25 05:42:20 -07001066 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001067 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001068 aecm_capture_queue_buffer_);
1069 }
1070
1071 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1072 public_submodules_->gain_control->ProcessRenderAudio(
1073 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001074 }
ivoc9f4a4a02016-10-28 05:39:16 -07001075
1076 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001077 RTC_DCHECK(private_submodules_->echo_detector);
1078 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001079 red_capture_queue_buffer_);
1080 }
peah764e3642016-10-22 05:04:30 -07001081}
1082
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001083int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001084 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001085 {
1086 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001087 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001088 // getters that need the capture lock held when being called.
1089 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001090 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001091 // as well.
1092 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001093 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001094 }
peahfa6228e2015-11-16 16:27:42 -08001095
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001096 if (!frame) {
1097 return kNullPointerError;
1098 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001099 // Must be a native rate.
1100 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1101 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001102 frame->sample_rate_hz_ != kSampleRate32kHz &&
1103 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001104 return kBadSampleRateError;
1105 }
peah192164e2015-11-17 02:16:45 -08001106
peahdf3efa82015-11-28 12:35:15 -08001107 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001108 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001109 {
1110 // Aquire lock for the access of api_format.
1111 // The lock is released immediately due to the conditional
1112 // reinitialization.
1113 rtc::CritScope cs_capture(&crit_capture_);
1114 // TODO(ajm): The input and output rates and channels are currently
1115 // constrained to be identical in the int16 interface.
1116 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001117
1118 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001119 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001120 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1121 processing_config.input_stream().set_num_channels(frame->num_channels_);
1122 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1123 processing_config.output_stream().set_num_channels(frame->num_channels_);
1124
peahdf3efa82015-11-28 12:35:15 -08001125 {
1126 // Do conditional reinitialization.
1127 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001128 RETURN_ON_ERR(
1129 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001130 }
1131 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001132 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001133 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001134 return kBadDataLengthError;
1135 }
1136
aleloi868f32f2017-05-23 07:20:05 -07001137 if (aec_dump_) {
1138 RecordUnprocessedCaptureStream(*frame);
1139 }
1140
peahdf3efa82015-11-28 12:35:15 -08001141 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001142 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001143 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001144 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1145 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001146
aleloi868f32f2017-05-23 07:20:05 -07001147 if (aec_dump_) {
1148 RecordProcessedCaptureStream(*frame);
1149 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001150
1151 return kNoError;
1152}
1153
peahde65ddc2016-09-16 15:02:15 -07001154int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001155 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001156
peahb58a1582016-03-15 09:34:24 -07001157 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001158 // TODO(peah): Simplify once the public API Enable functions for these
1159 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001160 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1161 public_submodules_->echo_control_mobile->is_enabled()));
1162
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001163 MaybeUpdateHistograms();
1164
peahde65ddc2016-09-16 15:02:15 -07001165 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001166
Alex Loikob5c9a792018-04-16 16:31:22 +02001167 if (private_submodules_->pre_amplifier) {
1168 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1169 capture_buffer->channels_f(), capture_buffer->num_channels(),
1170 capture_buffer->num_frames()));
1171 }
1172
peah1b08dc32016-12-20 13:45:58 -08001173 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001174 capture_buffer->channels_const()[0],
1175 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001176 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1177 if (log_rms) {
1178 capture_rms_interval_counter_ = 0;
1179 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001180 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1181 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1182 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1183 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001184 }
1185
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001186 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001187 // Detect and flag any change in the analog gain.
1188 int analog_mic_level = gain_control()->stream_analog_level();
1189 capture_.echo_path_gain_change =
1190 capture_.prev_analog_mic_level != analog_mic_level &&
1191 capture_.prev_analog_mic_level != -1;
1192 capture_.prev_analog_mic_level = analog_mic_level;
1193
Per Åhgrend2650d12018-10-02 17:00:59 +02001194 // Detect and flag any change in the pre-amplifier gain.
1195 if (private_submodules_->pre_amplifier) {
1196 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1197 capture_.echo_path_gain_change =
1198 capture_.echo_path_gain_change ||
1199 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001200 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001201 capture_.prev_pre_amp_gain = pre_amp_gain;
1202 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001203 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001204 }
1205
peahbe615622016-02-13 16:40:47 -08001206 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001207 public_submodules_->gain_control->is_enabled()) {
1208 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001209 capture_buffer->channels()[0], capture_buffer->num_channels(),
1210 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001211
1212 if (constants_.use_experimental_agc_process_before_aec) {
1213 private_submodules_->agc_manager->Process(
1214 capture_buffer->channels()[0],
1215 capture_nonlocked_.capture_processing_format.num_frames(),
1216 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1217 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001218 }
1219
peah2ace3f92016-09-10 04:42:27 -07001220 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1221 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001222 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1223 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001224 }
1225
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001226 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001227 // Force down-mixing of the number of channels after the detection of
1228 // capture signal saturation.
1229 // TODO(peah): Look into ensuring that this kind of tampering with the
1230 // AudioBuffer functionality should not be needed.
1231 capture_buffer->set_num_channels(1);
1232 }
1233
peahe0eae3c2016-12-14 01:16:23 -08001234 // TODO(peah): Move the AEC3 low-cut filter to this place.
1235 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001236 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001237 private_submodules_->low_cut_filter->Process(capture_buffer);
1238 }
peahde65ddc2016-09-16 15:02:15 -07001239 RETURN_ON_ERR(
1240 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1241 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001242
1243 // Ensure that the stream delay was set before the call to the
1244 // AEC ProcessCaptureAudio function.
1245 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001246 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001247 return AudioProcessing::kStreamParameterNotSetError;
1248 }
1249
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001250 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001251 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1252
Per Åhgrend0fa8202018-04-18 09:35:13 +02001253 if (was_stream_delay_set()) {
1254 private_submodules_->echo_controller->SetAudioBufferDelay(
1255 stream_delay_ms());
1256 }
1257
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001258 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001259 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001260 } else {
1261 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1262 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001263 }
1264
peahdf3efa82015-11-28 12:35:15 -08001265 if (public_submodules_->echo_control_mobile->is_enabled() &&
1266 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001267 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001268 }
peahde65ddc2016-09-16 15:02:15 -07001269 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001270
1271 // Ensure that the stream delay was set before the call to the
1272 // AECM ProcessCaptureAudio function.
1273 if (public_submodules_->echo_control_mobile->is_enabled() &&
1274 !was_stream_delay_set()) {
1275 return AudioProcessing::kStreamParameterNotSetError;
1276 }
1277
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001278 if (!(private_submodules_->echo_controller ||
1279 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001280 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1281 capture_buffer, stream_delay_ms()));
1282 }
ivoc9f4a4a02016-10-28 05:39:16 -07001283
peahde65ddc2016-09-16 15:02:15 -07001284 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001285
peahbe615622016-02-13 16:40:47 -08001286 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001287 public_submodules_->gain_control->is_enabled() &&
1288 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001289 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001290 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1291 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001292 }
peahb8fbb542016-03-15 02:28:08 -07001293 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001294 capture_buffer,
1295 public_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001296
peah2ace3f92016-09-10 04:42:27 -07001297 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1298 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001299 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1300 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001301 }
1302
peah9e6a2902017-05-15 07:19:21 -07001303 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001304 RTC_DCHECK(private_submodules_->echo_detector);
1305 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001306 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1307 capture_buffer->num_frames()));
1308 }
1309
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001310 // TODO(aluebs): Investigate if the transient suppression placement should be
1311 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001312 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001313 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001314 private_submodules_->agc_manager.get()
1315 ? private_submodules_->agc_manager->voice_probability()
1316 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001317
peahdf3efa82015-11-28 12:35:15 -08001318 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001319 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1320 capture_buffer->num_channels(),
1321 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1322 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1323 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001324 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001325 }
1326
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001327 // Experimental APM sub-module that analyzes |capture_buffer|.
1328 if (private_submodules_->capture_analyzer) {
1329 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1330 }
1331
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001332 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001333 private_submodules_->gain_controller2->NotifyAnalogLevel(
1334 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001335 private_submodules_->gain_controller2->Process(capture_buffer);
1336 }
1337
Sam Zackrisson0beac582017-09-25 12:04:02 +02001338 if (private_submodules_->capture_post_processor) {
1339 private_submodules_->capture_post_processor->Process(capture_buffer);
1340 }
1341
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001342 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001343 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001344
peah1b08dc32016-12-20 13:45:58 -08001345 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1346 capture_buffer->channels_const()[0],
1347 capture_nonlocked_.capture_processing_format.num_frames()));
1348 if (log_rms) {
1349 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1350 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1351 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1352 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1353 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1354 }
1355
peahdf3efa82015-11-28 12:35:15 -08001356 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001357 return kNoError;
1358}
1359
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001360int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001361 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001362 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001363 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001364 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001365 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001366 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001367 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001368 };
1369 if (samples_per_channel != reverse_config.num_frames()) {
1370 return kBadDataLengthError;
1371 }
peahdf3efa82015-11-28 12:35:15 -08001372 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001373}
1374
peahde65ddc2016-09-16 15:02:15 -07001375int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1376 const StreamConfig& input_config,
1377 const StreamConfig& output_config,
1378 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001379 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001380 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001381 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001382 if (submodule_states_.RenderMultiBandProcessingActive() ||
1383 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001384 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1385 dest);
peah2ace3f92016-09-10 04:42:27 -07001386 } else if (formats_.api_format.reverse_input_stream() !=
1387 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001388 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1389 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001390 } else {
peahde65ddc2016-09-16 15:02:15 -07001391 CopyAudioIfNeeded(src, input_config.num_frames(),
1392 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001393 }
1394
1395 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001396}
1397
peahdf3efa82015-11-28 12:35:15 -08001398int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001399 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001400 const StreamConfig& input_config,
1401 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001402 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001403 return kNullPointerError;
1404 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001405
peahde65ddc2016-09-16 15:02:15 -07001406 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001407 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001408 }
1409
peahdf3efa82015-11-28 12:35:15 -08001410 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001411 processing_config.reverse_input_stream() = input_config;
1412 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001413
peahdf3efa82015-11-28 12:35:15 -08001414 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001415 RTC_DCHECK_EQ(input_config.num_frames(),
1416 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001417
aleloi868f32f2017-05-23 07:20:05 -07001418 if (aec_dump_) {
1419 const size_t channel_size =
1420 formats_.api_format.reverse_input_stream().num_frames();
1421 const size_t num_channels =
1422 formats_.api_format.reverse_input_stream().num_channels();
1423 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001424 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001425 }
peahdf3efa82015-11-28 12:35:15 -08001426 render_.render_audio->CopyFrom(src,
1427 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001428 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001429}
1430
1431int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001432 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001433 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001434 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001435 return kNullPointerError;
1436 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001437 // Must be a native rate.
1438 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1439 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001440 frame->sample_rate_hz_ != kSampleRate32kHz &&
1441 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001442 return kBadSampleRateError;
1443 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001444
Michael Graczyk86c6d332015-07-23 11:41:39 -07001445 if (frame->num_channels_ <= 0) {
1446 return kBadNumberChannelsError;
1447 }
1448
peahdf3efa82015-11-28 12:35:15 -08001449 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001450 processing_config.reverse_input_stream().set_sample_rate_hz(
1451 frame->sample_rate_hz_);
1452 processing_config.reverse_input_stream().set_num_channels(
1453 frame->num_channels_);
1454 processing_config.reverse_output_stream().set_sample_rate_hz(
1455 frame->sample_rate_hz_);
1456 processing_config.reverse_output_stream().set_num_channels(
1457 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001458
peahdf3efa82015-11-28 12:35:15 -08001459 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001460 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001461 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001462 return kBadDataLengthError;
1463 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001464
aleloi868f32f2017-05-23 07:20:05 -07001465 if (aec_dump_) {
1466 aec_dump_->WriteRenderStreamMessage(*frame);
1467 }
1468
peahdf3efa82015-11-28 12:35:15 -08001469 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001470 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001471 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001472 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1473 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001474 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001475}
niklase@google.com470e71d2011-07-07 08:21:25 +00001476
peahde65ddc2016-09-16 15:02:15 -07001477int AudioProcessingImpl::ProcessRenderStreamLocked() {
1478 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001479
Alex Loiko73ec0192018-05-15 10:52:28 +02001480 HandleRenderRuntimeSettings();
1481
Alex Loiko5825aa62017-12-18 16:02:40 +01001482 if (private_submodules_->render_pre_processor) {
1483 private_submodules_->render_pre_processor->Process(render_buffer);
1484 }
1485
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001486 QueueNonbandedRenderAudio(render_buffer);
1487
peah2ace3f92016-09-10 04:42:27 -07001488 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001489 SampleRateSupportsMultiBand(
1490 formats_.render_processing_format.sample_rate_hz())) {
1491 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001492 }
1493
peahce4d9152017-05-19 01:28:05 -07001494 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1495 QueueBandedRenderAudio(render_buffer);
1496 }
1497
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001498 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001499 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001500 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001501 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001502
peah2ace3f92016-09-10 04:42:27 -07001503 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001504 SampleRateSupportsMultiBand(
1505 formats_.render_processing_format.sample_rate_hz())) {
1506 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001507 }
1508
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001509 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001510}
1511
1512int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001513 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001514 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001515 capture_.was_stream_delay_set = true;
1516 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001517
niklase@google.com470e71d2011-07-07 08:21:25 +00001518 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001519 delay = 0;
1520 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001521 }
1522
1523 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1524 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001525 delay = 500;
1526 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001527 }
1528
peahdf3efa82015-11-28 12:35:15 -08001529 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001530 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001531}
1532
1533int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001534 // Used as callback from submodules, hence locking is not allowed.
1535 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001536}
1537
1538bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001539 // Used as callback from submodules, hence locking is not allowed.
1540 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001541}
1542
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001543void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001544 rtc::CritScope cs(&crit_capture_);
1545 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001546}
1547
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001548void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001549 rtc::CritScope cs(&crit_capture_);
1550 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001551}
1552
1553int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001554 rtc::CritScope cs(&crit_capture_);
1555 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001556}
1557
aleloi868f32f2017-05-23 07:20:05 -07001558void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1559 RTC_DCHECK(aec_dump);
1560 rtc::CritScope cs_render(&crit_render_);
1561 rtc::CritScope cs_capture(&crit_capture_);
1562
1563 // The previously attached AecDump will be destroyed with the
1564 // 'aec_dump' parameter, which is after locks are released.
1565 aec_dump_.swap(aec_dump);
1566 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001567 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001568}
1569
1570void AudioProcessingImpl::DetachAecDump() {
1571 // The d-tor of a task-queue based AecDump blocks until all pending
1572 // tasks are done. This construction avoids blocking while holding
1573 // the render and capture locks.
1574 std::unique_ptr<AecDump> aec_dump = nullptr;
1575 {
1576 rtc::CritScope cs_render(&crit_render_);
1577 rtc::CritScope cs_capture(&crit_capture_);
1578 aec_dump = std::move(aec_dump_);
1579 }
1580}
1581
Sam Zackrisson4d364492018-03-02 16:03:21 +01001582void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1583 std::unique_ptr<AudioGenerator> audio_generator) {
1584 // TODO(bugs.webrtc.org/8882) Stub.
1585 // Reset internal audio generator with audio_generator.
1586}
1587
1588void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1589 // TODO(bugs.webrtc.org/8882) Stub.
1590 // Delete audio generator, if one is attached.
1591}
1592
ivoc4e477a12017-01-15 08:29:46 -08001593AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1594 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1595 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1596 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1597 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1598}
1599
1600AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1601 const AudioProcessingStatistics& other) = default;
1602
1603AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1604 default;
1605
ivoc3e9a5372016-10-28 07:55:33 -07001606// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1607AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1608 const {
1609 return AudioProcessingStatistics();
1610}
1611
Ivo Creusenae026092017-11-20 13:07:16 +01001612// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001613AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001614 bool has_remote_tracks) const {
1615 return AudioProcessingStats();
1616}
1617
ivoc3e9a5372016-10-28 07:55:33 -07001618AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1619 const {
1620 AudioProcessingStatistics stats;
sazabe490b22018-10-03 17:03:13 +02001621 EchoCancellationImpl::Metrics metrics;
Yves Gerey499bc6c2018-10-10 18:29:07 +02001622 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001623 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001624 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1625 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1626 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1627 // Instant value will also be used for min, max and average.
1628 stats.echo_return_loss.Set(erl, erl, erl, erl);
1629 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1630 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1631 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001632 stats.a_nlp.Set(metrics.a_nlp);
1633 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1634 stats.echo_return_loss.Set(metrics.echo_return_loss);
1635 stats.echo_return_loss_enhancement.Set(
1636 metrics.echo_return_loss_enhancement);
1637 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1638 }
Yves Gerey499bc6c2018-10-10 18:29:07 +02001639 RTC_DCHECK(private_submodules_->echo_detector);
1640 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1641 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
1642 stats.residual_echo_likelihood_recent_max =
1643 ed_metrics.echo_likelihood_recent_max;
ivoc3e9a5372016-10-28 07:55:33 -07001644 public_submodules_->echo_cancellation->GetDelayMetrics(
1645 &stats.delay_median, &stats.delay_standard_deviation,
1646 &stats.fraction_poor_delays);
1647 return stats;
1648}
1649
Ivo Creusen56d46092017-11-24 17:29:59 +01001650AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001651 bool has_remote_tracks) const {
1652 AudioProcessingStats stats;
1653 if (has_remote_tracks) {
sazabe490b22018-10-03 17:03:13 +02001654 EchoCancellationImpl::Metrics metrics;
Yves Gerey499bc6c2018-10-10 18:29:07 +02001655 rtc::CritScope cs_capture(&crit_capture_);
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001656 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001657 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1658 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001659 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001660 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001661 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001662 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1663 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001664 if (metrics.divergent_filter_fraction != -1.0f) {
1665 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001666 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001667 }
1668 if (metrics.echo_return_loss.instant != -100) {
1669 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001670 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001671 }
1672 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001673 stats.echo_return_loss_enhancement = absl::optional<double>(
1674 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001675 }
1676 }
1677 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001678 RTC_DCHECK(private_submodules_->echo_detector);
1679 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1680 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001681 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001682 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001683 }
1684 int delay_median, delay_std;
1685 float fraction_poor_delays;
1686 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1687 &delay_median, &delay_std, &fraction_poor_delays) ==
1688 Error::kNoError) {
1689 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001690 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001691 }
1692 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001693 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001694 }
1695 }
1696 }
1697 return stats;
1698}
1699
niklase@google.com470e71d2011-07-07 08:21:25 +00001700GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001701 if (constants_.use_experimental_agc) {
1702 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001703 }
peahbfa97112016-03-10 21:09:04 -08001704 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001705}
1706
niklase@google.com470e71d2011-07-07 08:21:25 +00001707LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001708 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001709}
1710
1711NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001712 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001713}
1714
1715VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001716 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001717}
1718
peah8271d042016-11-22 07:24:52 -08001719void AudioProcessingImpl::MutateConfig(
1720 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1721 rtc::CritScope cs_render(&crit_render_);
1722 rtc::CritScope cs_capture(&crit_capture_);
1723 mutator(&config_);
1724 ApplyConfig(config_);
1725}
1726
1727AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1728 rtc::CritScope cs_render(&crit_render_);
1729 rtc::CritScope cs_capture(&crit_capture_);
1730 return config_;
1731}
1732
peah2ace3f92016-09-10 04:42:27 -07001733bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1734 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001735 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001736 public_submodules_->echo_cancellation->is_enabled(),
1737 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001738 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001739 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001740 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001741 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001742 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001743 public_submodules_->voice_detection->is_enabled(),
1744 public_submodules_->level_estimator->is_enabled(),
1745 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001746}
1747
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001748void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001749 if (capture_.transient_suppressor_enabled) {
1750 if (!public_submodules_->transient_suppressor.get()) {
1751 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001752 }
peahdf3efa82015-11-28 12:35:15 -08001753 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001754 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1755 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001756 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001757}
1758
peah8271d042016-11-22 07:24:52 -08001759void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001760 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001761 private_submodules_->low_cut_filter.reset(
1762 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1763 } else {
1764 private_submodules_->low_cut_filter.reset();
1765 }
1766}
alessiob3ec96df2017-05-22 06:57:06 -07001767
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001768void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001769 if (echo_control_factory_) {
1770 private_submodules_->echo_controller =
1771 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001772 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001773 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001774 }
1775}
peah8271d042016-11-22 07:24:52 -08001776
alessiob3ec96df2017-05-22 06:57:06 -07001777void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001778 if (config_.gain_controller2.enabled) {
1779 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001780 }
1781}
1782
Alex Loikob5c9a792018-04-16 16:31:22 +02001783void AudioProcessingImpl::InitializePreAmplifier() {
1784 if (config_.pre_amplifier.enabled) {
1785 private_submodules_->pre_amplifier.reset(
1786 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1787 } else {
1788 private_submodules_->pre_amplifier.reset();
1789 }
1790}
1791
ivoc9f4a4a02016-10-28 05:39:16 -07001792void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001793 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001794 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001795 proc_sample_rate_hz(), 1,
1796 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001797}
1798
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001799void AudioProcessingImpl::InitializeAnalyzer() {
1800 if (private_submodules_->capture_analyzer) {
1801 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1802 num_proc_channels());
1803 }
1804}
1805
Sam Zackrisson0beac582017-09-25 12:04:02 +02001806void AudioProcessingImpl::InitializePostProcessor() {
1807 if (private_submodules_->capture_post_processor) {
1808 private_submodules_->capture_post_processor->Initialize(
1809 proc_sample_rate_hz(), num_proc_channels());
1810 }
1811}
1812
Alex Loiko5825aa62017-12-18 16:02:40 +01001813void AudioProcessingImpl::InitializePreProcessor() {
1814 if (private_submodules_->render_pre_processor) {
1815 private_submodules_->render_pre_processor->Initialize(
1816 formats_.render_processing_format.sample_rate_hz(),
1817 formats_.render_processing_format.num_channels());
1818 }
1819}
1820
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001821void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001822 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001823
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001824 if (public_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001825 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1826 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001827 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001828 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001829 capture_.stream_delay_jumps = 0;
1830 }
1831 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001832 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001833 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001834 }
1835
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001836 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001837 const int diff_stream_delay_ms =
1838 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1839 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1840 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001841 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1842 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001843 if (capture_.stream_delay_jumps == -1) {
1844 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001845 }
peahdf3efa82015-11-28 12:35:15 -08001846 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001847 }
peahdf3efa82015-11-28 12:35:15 -08001848 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001849
1850 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001851 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001852 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001853 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001854 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001855 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1856 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001857 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001858 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001859 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001860 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001861 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1862 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1863 100);
peahdf3efa82015-11-28 12:35:15 -08001864 if (capture_.aec_system_delay_jumps == -1) {
1865 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001866 }
peahdf3efa82015-11-28 12:35:15 -08001867 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001868 }
peahdf3efa82015-11-28 12:35:15 -08001869 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001870 }
1871}
1872
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001873void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001874 // Run in a single-threaded manner.
1875 rtc::CritScope cs_render(&crit_render_);
1876 rtc::CritScope cs_capture(&crit_capture_);
1877
1878 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001879 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001880 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001881 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001882 }
peahdf3efa82015-11-28 12:35:15 -08001883 capture_.stream_delay_jumps = -1;
1884 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001885
peahdf3efa82015-11-28 12:35:15 -08001886 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001887 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1888 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001889 }
peahdf3efa82015-11-28 12:35:15 -08001890 capture_.aec_system_delay_jumps = -1;
1891 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001892}
1893
aleloi868f32f2017-05-23 07:20:05 -07001894void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1895 if (!aec_dump_) {
1896 return;
1897 }
1898 std::string experiments_description =
1899 public_submodules_->echo_cancellation->GetExperimentsDescription();
1900 // TODO(peah): Add semicolon-separated concatenations of experiment
1901 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001902 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1903 experiments_description += "AgcClippingLevelExperiment;";
1904 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001905 if (capture_nonlocked_.echo_controller_enabled) {
1906 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001907 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001908 if (config_.gain_controller2.enabled) {
1909 experiments_description += "GainController2;";
1910 }
aleloi868f32f2017-05-23 07:20:05 -07001911
1912 InternalAPMConfig apm_config;
1913
1914 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1915 apm_config.aec_delay_agnostic_enabled =
1916 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1917 apm_config.aec_drift_compensation_enabled =
1918 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1919 apm_config.aec_extended_filter_enabled =
1920 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1921 apm_config.aec_suppression_level = static_cast<int>(
1922 public_submodules_->echo_cancellation->suppression_level());
1923
1924 apm_config.aecm_enabled =
1925 public_submodules_->echo_control_mobile->is_enabled();
1926 apm_config.aecm_comfort_noise_enabled =
1927 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1928 apm_config.aecm_routing_mode =
1929 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1930
1931 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1932 apm_config.agc_mode =
1933 static_cast<int>(public_submodules_->gain_control->mode());
1934 apm_config.agc_limiter_enabled =
1935 public_submodules_->gain_control->is_limiter_enabled();
1936 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1937
1938 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1939
1940 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1941 apm_config.ns_level =
1942 static_cast<int>(public_submodules_->noise_suppression->level());
1943
1944 apm_config.transient_suppression_enabled =
1945 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001946 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001947 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1948 apm_config.pre_amplifier_fixed_gain_factor =
1949 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001950
1951 if (!forced && apm_config == apm_config_for_aec_dump_) {
1952 return;
1953 }
1954 aec_dump_->WriteConfig(apm_config);
1955 apm_config_for_aec_dump_ = apm_config;
1956}
1957
1958void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1959 const float* const* src) {
1960 RTC_DCHECK(aec_dump_);
1961 WriteAecDumpConfigMessage(false);
1962
1963 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1964 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1965 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001966 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001967 RecordAudioProcessingState();
1968}
1969
1970void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1971 const AudioFrame& capture_frame) {
1972 RTC_DCHECK(aec_dump_);
1973 WriteAecDumpConfigMessage(false);
1974
1975 aec_dump_->AddCaptureStreamInput(capture_frame);
1976 RecordAudioProcessingState();
1977}
1978
1979void AudioProcessingImpl::RecordProcessedCaptureStream(
1980 const float* const* processed_capture_stream) {
1981 RTC_DCHECK(aec_dump_);
1982
1983 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1984 const size_t num_channels =
1985 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001986 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
1987 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001988 aec_dump_->WriteCaptureStreamMessage();
1989}
1990
1991void AudioProcessingImpl::RecordProcessedCaptureStream(
1992 const AudioFrame& processed_capture_frame) {
1993 RTC_DCHECK(aec_dump_);
1994
1995 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1996 aec_dump_->WriteCaptureStreamMessage();
1997}
1998
1999void AudioProcessingImpl::RecordAudioProcessingState() {
2000 RTC_DCHECK(aec_dump_);
2001 AecDump::AudioProcessingState audio_proc_state;
2002 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2003 audio_proc_state.drift =
2004 public_submodules_->echo_cancellation->stream_drift_samples();
2005 audio_proc_state.level = gain_control()->stream_analog_level();
2006 audio_proc_state.keypress = capture_.key_pressed;
2007 aec_dump_->AddAudioProcessingState(audio_proc_state);
2008}
2009
kwiberg83ffe452016-08-29 14:46:07 -07002010AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002011 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002012 : aec_system_delay_jumps(-1),
2013 delay_offset_ms(0),
2014 was_stream_delay_set(false),
2015 last_stream_delay_ms(0),
2016 last_aec_system_delay_ms(0),
2017 stream_delay_jumps(-1),
2018 output_will_be_muted(false),
2019 key_pressed(false),
2020 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002021 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002022 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002023 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002024 prev_analog_mic_level(-1),
2025 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002026
2027AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2028
2029AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2030
2031AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2032
niklase@google.com470e71d2011-07-07 08:21:25 +00002033} // namespace webrtc