blob: 95d36b8654fe341e7bb8dc467c69a48caecaabfb [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
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "common_audio/audio_converter.h"
18#include "common_audio/channel_buffer.h"
19#include "common_audio/include/audio_util.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_processing/aec/aec_core.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_processing/agc/agc_manager_direct.h"
Alex Loikob5c9a792018-04-16 16:31:22 +020023#include "modules/audio_processing/agc2/gain_applier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/audio_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/audio_processing/common.h"
26#include "modules/audio_processing/echo_cancellation_impl.h"
Sam Zackrisson74ed7342018-08-16 10:54:07 +020027#include "modules/audio_processing/echo_cancellation_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/echo_control_mobile_impl.h"
Sam Zackrisson74ed7342018-08-16 10:54:07 +020029#include "modules/audio_processing/echo_control_mobile_proxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "modules/audio_processing/gain_control_for_experimental_agc.h"
31#include "modules/audio_processing/gain_control_impl.h"
Alex Loikoe36e8bb2018-02-16 11:54:07 +010032#include "modules/audio_processing/gain_controller2.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"
42#include "rtc_base/logging.h"
43#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020044#include "rtc_base/refcountedobject.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020045#include "rtc_base/system/arch.h"
Minyue Li656d6092018-08-10 15:38:52 +020046#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/trace_event.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000049
Michael Graczyk86c6d332015-07-23 11:41:39 -070050#define RETURN_ON_ERR(expr) \
51 do { \
52 int err = (expr); \
53 if (err != kNoError) { \
54 return err; \
55 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000056 } while (0)
57
niklase@google.com470e71d2011-07-07 08:21:25 +000058namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070059
kwibergd59d3bb2016-09-13 07:49:33 -070060constexpr int AudioProcessing::kNativeSampleRatesHz[];
Alex Loiko73ec0192018-05-15 10:52:28 +020061constexpr int kRuntimeSettingQueueSize = 100;
aluebsdf6416a2016-03-16 18:26:35 -070062
Michael Graczyk86c6d332015-07-23 11:41:39 -070063namespace {
64
65static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
66 switch (layout) {
67 case AudioProcessing::kMono:
68 case AudioProcessing::kStereo:
69 return false;
70 case AudioProcessing::kMonoAndKeyboard:
71 case AudioProcessing::kStereoAndKeyboard:
72 return true;
73 }
74
kwiberg9e2be5f2016-09-14 05:23:22 -070075 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070076 return false;
77}
aluebsdf6416a2016-03-16 18:26:35 -070078
peah2ace3f92016-09-10 04:42:27 -070079bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070080 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
81 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
82}
83
peah2ace3f92016-09-10 04:42:27 -070084int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
85#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070086 constexpr int kMaxSplittingNativeProcessRate =
87 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070088#else
kwibergd59d3bb2016-09-13 07:49:33 -070089 constexpr int kMaxSplittingNativeProcessRate =
90 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070091#endif
kwibergd59d3bb2016-09-13 07:49:33 -070092 static_assert(
93 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
94 "");
peah2ace3f92016-09-10 04:42:27 -070095 const int uppermost_native_rate = band_splitting_required
96 ? kMaxSplittingNativeProcessRate
97 : AudioProcessing::kSampleRate48kHz;
98
99 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
100 if (rate >= uppermost_native_rate) {
101 return uppermost_native_rate;
102 }
103 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700104 return rate;
105 }
106 }
peah2ace3f92016-09-10 04:42:27 -0700107 RTC_NOTREACHED();
108 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700109}
110
peah9e6a2902017-05-15 07:19:21 -0700111// Maximum lengths that frame of samples being passed from the render side to
112// the capture side can have (does not apply to AEC3).
113static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
114static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
115
peah764e3642016-10-22 05:04:30 -0700116// Maximum number of frames to buffer in the render queue.
117// TODO(peah): Decrease this once we properly handle hugely unbalanced
118// reverse and forward call numbers.
119static const size_t kMaxNumFramesToBuffer = 100;
120
peah8271d042016-11-22 07:24:52 -0800121class HighPassFilterImpl : public HighPassFilter {
122 public:
123 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
124 ~HighPassFilterImpl() override = default;
125
126 // HighPassFilter implementation.
127 int Enable(bool enable) override {
128 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
129 config->high_pass_filter.enabled = enable;
130 });
131
132 return AudioProcessing::kNoError;
133 }
134
135 bool is_enabled() const override {
136 return apm_->GetConfig().high_pass_filter.enabled;
137 }
138
139 private:
140 AudioProcessingImpl* apm_;
141 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
142};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700143} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000144
145// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000146static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000147
Sam Zackrisson0beac582017-09-25 12:04:02 +0200148AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
Alex Loiko5825aa62017-12-18 16:02:40 +0100149 bool capture_post_processor_enabled,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200150 bool render_pre_processor_enabled,
151 bool capture_analyzer_enabled)
Alex Loiko5825aa62017-12-18 16:02:40 +0100152 : capture_post_processor_enabled_(capture_post_processor_enabled),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200153 render_pre_processor_enabled_(render_pre_processor_enabled),
154 capture_analyzer_enabled_(capture_analyzer_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700155
156bool AudioProcessingImpl::ApmSubmoduleStates::Update(
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200157 bool high_pass_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700158 bool echo_canceller_enabled,
159 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700160 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700161 bool noise_suppressor_enabled,
peah2ace3f92016-09-10 04:42:27 -0700162 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700163 bool gain_controller2_enabled,
Alex Loikob5c9a792018-04-16 16:31:22 +0200164 bool pre_amplifier_enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200165 bool echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool voice_activity_detector_enabled,
167 bool level_estimator_enabled,
168 bool transient_suppressor_enabled) {
169 bool changed = false;
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200170 changed |= (high_pass_filter_enabled != high_pass_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700171 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
172 changed |=
173 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700174 changed |=
175 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700176 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
177 changed |=
peah2ace3f92016-09-10 04:42:27 -0700178 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700179 changed |=
180 (gain_controller2_enabled != gain_controller2_enabled_);
Alex Loikob5c9a792018-04-16 16:31:22 +0200181 changed |= (pre_amplifier_enabled_ != pre_amplifier_enabled);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200182 changed |= (echo_controller_enabled != echo_controller_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700183 changed |= (level_estimator_enabled != level_estimator_enabled_);
184 changed |=
185 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
186 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
187 if (changed) {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200188 high_pass_filter_enabled_ = high_pass_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700189 echo_canceller_enabled_ = echo_canceller_enabled;
190 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700191 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700192 noise_suppressor_enabled_ = noise_suppressor_enabled;
peah2ace3f92016-09-10 04:42:27 -0700193 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700194 gain_controller2_enabled_ = gain_controller2_enabled;
Alex Loikob5c9a792018-04-16 16:31:22 +0200195 pre_amplifier_enabled_ = pre_amplifier_enabled;
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200196 echo_controller_enabled_ = echo_controller_enabled;
peah2ace3f92016-09-10 04:42:27 -0700197 level_estimator_enabled_ = level_estimator_enabled;
198 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
199 transient_suppressor_enabled_ = transient_suppressor_enabled;
200 }
201
202 changed |= first_update_;
203 first_update_ = false;
204 return changed;
205}
206
207bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
208 const {
peah52775842017-05-16 06:14:09 -0700209 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700210}
211
212bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
213 const {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200214 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700215 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200216 adaptive_gain_controller_enabled_ || echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700217}
218
peah23ac8b42017-05-23 05:33:56 -0700219bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
220 const {
Alex Loikob5c9a792018-04-16 16:31:22 +0200221 return gain_controller2_enabled_ || capture_post_processor_enabled_ ||
222 pre_amplifier_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700223}
224
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200225bool AudioProcessingImpl::ApmSubmoduleStates::CaptureAnalyzerActive() const {
226 return capture_analyzer_enabled_;
227}
228
peah2ace3f92016-09-10 04:42:27 -0700229bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
230 const {
231 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800232 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200233 echo_controller_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700234}
235
Alex Loiko5825aa62017-12-18 16:02:40 +0100236bool AudioProcessingImpl::ApmSubmoduleStates::RenderFullBandProcessingActive()
237 const {
238 return render_pre_processor_enabled_;
239}
240
peah2ace3f92016-09-10 04:42:27 -0700241bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
242 const {
peah2ace3f92016-09-10 04:42:27 -0700243 return false;
peah2ace3f92016-09-10 04:42:27 -0700244}
245
Sam Zackrissoncb1b5562018-09-28 14:15:09 +0200246bool AudioProcessingImpl::ApmSubmoduleStates::LowCutFilteringRequired() const {
247 return high_pass_filter_enabled_ || echo_canceller_enabled_ ||
248 mobile_echo_controller_enabled_ || noise_suppressor_enabled_;
249}
250
solenberg5e465c32015-12-08 13:22:33 -0800251struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800252 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800253 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800254 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800255 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
Sam Zackrisson74ed7342018-08-16 10:54:07 +0200256 std::unique_ptr<EchoCancellationProxy> echo_cancellation_proxy;
257 std::unique_ptr<EchoControlMobileProxy> echo_control_mobile_proxy;
peahbfa97112016-03-10 21:09:04 -0800258 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800259 std::unique_ptr<LevelEstimatorImpl> level_estimator;
260 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
261 std::unique_ptr<VoiceDetectionImpl> voice_detection;
262 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800263 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800264
265 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800266 std::unique_ptr<TransientSuppressor> transient_suppressor;
solenberg5e465c32015-12-08 13:22:33 -0800267};
268
269struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrissondb389722018-06-21 10:12:24 +0200270 ApmPrivateSubmodules(std::unique_ptr<CustomProcessing> capture_post_processor,
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100271 std::unique_ptr<CustomProcessing> render_pre_processor,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200272 rtc::scoped_refptr<EchoDetector> echo_detector,
273 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Sam Zackrissondb389722018-06-21 10:12:24 +0200274 : echo_detector(std::move(echo_detector)),
Alex Loiko5825aa62017-12-18 16:02:40 +0100275 capture_post_processor(std::move(capture_post_processor)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200276 render_pre_processor(std::move(render_pre_processor)),
277 capture_analyzer(std::move(capture_analyzer)) {}
solenberg5e465c32015-12-08 13:22:33 -0800278 // Accessed internally from capture or during initialization
kwiberg88788ad2016-02-19 07:04:49 -0800279 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700280 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800281 std::unique_ptr<LowCutFilter> low_cut_filter;
Ivo Creusend1f970d2018-06-14 11:02:03 +0200282 rtc::scoped_refptr<EchoDetector> echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200283 std::unique_ptr<EchoControl> echo_controller;
Alex Loiko5825aa62017-12-18 16:02:40 +0100284 std::unique_ptr<CustomProcessing> capture_post_processor;
285 std::unique_ptr<CustomProcessing> render_pre_processor;
Alex Loikob5c9a792018-04-16 16:31:22 +0200286 std::unique_ptr<GainApplier> pre_amplifier;
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200287 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer;
solenberg5e465c32015-12-08 13:22:33 -0800288};
289
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100290AudioProcessingBuilder::AudioProcessingBuilder() = default;
291AudioProcessingBuilder::~AudioProcessingBuilder() = default;
292
293AudioProcessingBuilder& AudioProcessingBuilder::SetCapturePostProcessing(
294 std::unique_ptr<CustomProcessing> capture_post_processing) {
295 capture_post_processing_ = std::move(capture_post_processing);
296 return *this;
297}
298
299AudioProcessingBuilder& AudioProcessingBuilder::SetRenderPreProcessing(
300 std::unique_ptr<CustomProcessing> render_pre_processing) {
301 render_pre_processing_ = std::move(render_pre_processing);
302 return *this;
303}
304
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200305AudioProcessingBuilder& AudioProcessingBuilder::SetCaptureAnalyzer(
306 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer) {
307 capture_analyzer_ = std::move(capture_analyzer);
308 return *this;
309}
310
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100311AudioProcessingBuilder& AudioProcessingBuilder::SetEchoControlFactory(
312 std::unique_ptr<EchoControlFactory> echo_control_factory) {
313 echo_control_factory_ = std::move(echo_control_factory);
314 return *this;
315}
316
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100317AudioProcessingBuilder& AudioProcessingBuilder::SetEchoDetector(
Ivo Creusend1f970d2018-06-14 11:02:03 +0200318 rtc::scoped_refptr<EchoDetector> echo_detector) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100319 echo_detector_ = std::move(echo_detector);
320 return *this;
321}
322
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100323AudioProcessing* AudioProcessingBuilder::Create() {
324 webrtc::Config config;
325 return Create(config);
326}
327
328AudioProcessing* AudioProcessingBuilder::Create(const webrtc::Config& config) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100329 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
330 config, std::move(capture_post_processing_),
331 std::move(render_pre_processing_), std::move(echo_control_factory_),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200332 std::move(echo_detector_), std::move(capture_analyzer_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100333 if (apm->Initialize() != AudioProcessing::kNoError) {
334 delete apm;
335 apm = nullptr;
336 }
337 return apm;
Ivo Creusen5ec7e122017-12-22 11:35:59 +0100338}
339
peah88ac8532016-09-12 16:47:25 -0700340AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200341 : AudioProcessingImpl(config, nullptr, nullptr, nullptr, nullptr, nullptr) {
342}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000343
Per Åhgren13735822018-02-12 21:42:56 +0100344int AudioProcessingImpl::instance_count_ = 0;
345
Sam Zackrisson0beac582017-09-25 12:04:02 +0200346AudioProcessingImpl::AudioProcessingImpl(
347 const webrtc::Config& config,
Alex Loiko5825aa62017-12-18 16:02:40 +0100348 std::unique_ptr<CustomProcessing> capture_post_processor,
349 std::unique_ptr<CustomProcessing> render_pre_processor,
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200350 std::unique_ptr<EchoControlFactory> echo_control_factory,
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200351 rtc::scoped_refptr<EchoDetector> echo_detector,
352 std::unique_ptr<CustomAudioAnalyzer> capture_analyzer)
Per Åhgren13735822018-02-12 21:42:56 +0100353 : data_dumper_(
354 new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
Alex Loiko73ec0192018-05-15 10:52:28 +0200355 capture_runtime_settings_(kRuntimeSettingQueueSize),
356 render_runtime_settings_(kRuntimeSettingQueueSize),
357 capture_runtime_settings_enqueuer_(&capture_runtime_settings_),
358 render_runtime_settings_enqueuer_(&render_runtime_settings_),
Per Åhgren13735822018-02-12 21:42:56 +0100359 high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullberg002ef282017-10-12 15:13:17 +0200360 echo_control_factory_(std::move(echo_control_factory)),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200361 submodule_states_(!!capture_post_processor,
362 !!render_pre_processor,
363 !!capture_analyzer),
peah8271d042016-11-22 07:24:52 -0800364 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200365 private_submodules_(
Sam Zackrissondb389722018-06-21 10:12:24 +0200366 new ApmPrivateSubmodules(std::move(capture_post_processor),
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100367 std::move(render_pre_processor),
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200368 std::move(echo_detector),
369 std::move(capture_analyzer))),
peahdf3efa82015-11-28 12:35:15 -0800370 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800371 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000372#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alex Loikod9342442018-09-10 13:59:41 +0200373 /* enabled= */ false,
374 /* enabled_agc2_level_estimator= */ false,
375 /* digital_adaptive_disabled= */ false,
376 /* analyze_before_aec= */ false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000377#else
Alex Loiko64cb83b2018-07-02 13:38:19 +0200378 config.Get<ExperimentalAgc>().enabled,
379 config.Get<ExperimentalAgc>().enabled_agc2_level_estimator,
Alex Loikod9342442018-09-10 13:59:41 +0200380 config.Get<ExperimentalAgc>().digital_adaptive_disabled,
381 config.Get<ExperimentalAgc>().analyze_before_aec),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000382#endif
andrew1c7075f2015-06-24 18:14:14 -0700383#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200384 capture_(false),
andrew1c7075f2015-06-24 18:14:14 -0700385#else
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200386 capture_(config.Get<ExperimentalNs>().enabled),
andrew1c7075f2015-06-24 18:14:14 -0700387#endif
Alessio Bazzicacc22f512018-08-30 13:01:34 +0200388 capture_nonlocked_() {
peahdf3efa82015-11-28 12:35:15 -0800389 {
390 rtc::CritScope cs_render(&crit_render_);
391 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000392
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200393 // Mark Echo Controller enabled if a factory is injected.
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000394 capture_nonlocked_.echo_controller_enabled =
395 static_cast<bool>(echo_control_factory_);
Gustaf Ullbergce045ac2017-10-16 13:49:04 +0200396
peahb624d8c2016-03-05 03:01:14 -0800397 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700398 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800399 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700400 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
Sam Zackrisson74ed7342018-08-16 10:54:07 +0200401 public_submodules_->echo_cancellation_proxy.reset(new EchoCancellationProxy(
402 this, public_submodules_->echo_cancellation.get()));
403 public_submodules_->echo_control_mobile_proxy.reset(
404 new EchoControlMobileProxy(
405 this, public_submodules_->echo_control_mobile.get()));
peahbfa97112016-03-10 21:09:04 -0800406 public_submodules_->gain_control.reset(
Alex Loiko80c0f062018-06-19 17:09:43 +0200407 new GainControlImpl(&crit_render_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800408 public_submodules_->level_estimator.reset(
409 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800410 public_submodules_->noise_suppression.reset(
411 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800412 public_submodules_->voice_detection.reset(
413 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800414 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800415 new GainControlForExperimentalAgc(
416 public_submodules_->gain_control.get(), &crit_capture_));
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100417
418 // If no echo detector is injected, use the ResidualEchoDetector.
419 if (!private_submodules_->echo_detector) {
Ivo Creusend1f970d2018-06-14 11:02:03 +0200420 private_submodules_->echo_detector =
421 new rtc::RefCountedObject<ResidualEchoDetector>();
Ivo Creusen09fa4b02018-01-11 16:08:54 +0100422 }
peahca4cac72016-06-29 15:26:12 -0700423
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200424 // TODO(alessiob): Move the injected gain controller once injection is
425 // implemented.
426 private_submodules_->gain_controller2.reset(new GainController2());
427
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200428 RTC_LOG(LS_INFO) << "Capture analyzer activated: "
429 << !!private_submodules_->capture_analyzer
430 << "\nCapture post processor activated: "
Jonas Olsson645b0272018-02-15 15:16:27 +0100431 << !!private_submodules_->capture_post_processor
432 << "\nRender pre processor activated: "
Alex Loiko5825aa62017-12-18 16:02:40 +0100433 << !!private_submodules_->render_pre_processor;
peahdf3efa82015-11-28 12:35:15 -0800434 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000435
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000436 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000437}
438
439AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800440 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800441 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800442 private_submodules_->agc_manager.reset();
443 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800444 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000445}
446
niklase@google.com470e71d2011-07-07 08:21:25 +0000447int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800448 // Run in a single-threaded manner during initialization.
449 rtc::CritScope cs_render(&crit_render_);
450 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000451 return InitializeLocked();
452}
453
peahde65ddc2016-09-16 15:02:15 -0700454int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
455 int capture_output_sample_rate_hz,
456 int render_input_sample_rate_hz,
457 ChannelLayout capture_input_layout,
458 ChannelLayout capture_output_layout,
459 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700460 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700461 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
462 LayoutHasKeyboard(capture_input_layout)},
463 {capture_output_sample_rate_hz,
464 ChannelsFromLayout(capture_output_layout),
465 LayoutHasKeyboard(capture_output_layout)},
466 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
467 LayoutHasKeyboard(render_input_layout)},
468 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
469 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700470
471 return Initialize(processing_config);
472}
473
474int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800475 // Run in a single-threaded manner during initialization.
476 rtc::CritScope cs_render(&crit_render_);
477 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700478 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000479}
480
peahdf3efa82015-11-28 12:35:15 -0800481int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800482 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700483 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800484}
485
peahdf3efa82015-11-28 12:35:15 -0800486int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700487 const ProcessingConfig& processing_config,
488 bool force_initialization) {
489 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800490}
491
peah192164e2015-11-17 02:16:45 -0800492// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800493// their current values (needs to be called while holding the crit_render_lock).
494int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700495 const ProcessingConfig& processing_config,
496 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800497 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700498 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800499 return kNoError;
500 }
peahdf3efa82015-11-28 12:35:15 -0800501
502 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800503 return InitializeLocked(processing_config);
504}
505
niklase@google.com470e71d2011-07-07 08:21:25 +0000506int AudioProcessingImpl::InitializeLocked() {
Per Åhgren4bdced52017-06-27 16:00:38 +0200507 UpdateActiveSubmoduleStates();
508
peahde65ddc2016-09-16 15:02:15 -0700509 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800510 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700511 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800512 : formats_.api_format.reverse_output_stream().num_frames();
513 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
514 render_.render_audio.reset(new AudioBuffer(
515 formats_.api_format.reverse_input_stream().num_frames(),
516 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700517 formats_.render_processing_format.num_frames(),
518 formats_.render_processing_format.num_channels(),
519 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700520 if (formats_.api_format.reverse_input_stream() !=
521 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800522 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800523 formats_.api_format.reverse_input_stream().num_channels(),
524 formats_.api_format.reverse_input_stream().num_frames(),
525 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800526 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700527 } else {
peahdf3efa82015-11-28 12:35:15 -0800528 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700529 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700530 } else {
peahdf3efa82015-11-28 12:35:15 -0800531 render_.render_audio.reset(nullptr);
532 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700533 }
peahce4d9152017-05-19 01:28:05 -0700534
peahdf3efa82015-11-28 12:35:15 -0800535 capture_.capture_audio.reset(
536 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
537 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700538 capture_nonlocked_.capture_processing_format.num_frames(),
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200539 formats_.api_format.output_stream().num_channels(),
peahdf3efa82015-11-28 12:35:15 -0800540 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000541
peahde65ddc2016-09-16 15:02:15 -0700542 public_submodules_->echo_cancellation->Initialize(
543 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
544 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700545 AllocateRenderQueue();
546
ivoc3e9a5372016-10-28 07:55:33 -0700547 int success = public_submodules_->echo_cancellation->enable_metrics(true);
548 RTC_DCHECK_EQ(0, success);
549 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
550 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700551 public_submodules_->echo_control_mobile->Initialize(
552 proc_split_sample_rate_hz(), num_reverse_channels(),
553 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700554
555 public_submodules_->gain_control->Initialize(num_proc_channels(),
556 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700557 if (constants_.use_experimental_agc) {
558 if (!private_submodules_->agc_manager.get()) {
559 private_submodules_->agc_manager.reset(new AgcManagerDirect(
560 public_submodules_->gain_control.get(),
561 public_submodules_->gain_control_for_experimental_agc.get(),
Alex Loiko64cb83b2018-07-02 13:38:19 +0200562 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min,
563 constants_.use_experimental_agc_agc2_level_estimation,
564 constants_.use_experimental_agc_agc2_digital_adaptive));
peahde65ddc2016-09-16 15:02:15 -0700565 }
566 private_submodules_->agc_manager->Initialize();
567 private_submodules_->agc_manager->SetCaptureMuted(
568 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700569 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700570 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200571 InitializeTransient();
peah8271d042016-11-22 07:24:52 -0800572 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700573 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
574 proc_sample_rate_hz());
575 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
576 public_submodules_->level_estimator->Initialize();
ivoc9f4a4a02016-10-28 05:39:16 -0700577 InitializeResidualEchoDetector();
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +0200578 InitializeEchoController();
alessiob3ec96df2017-05-22 06:57:06 -0700579 InitializeGainController2();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +0200580 InitializeAnalyzer();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200581 InitializePostProcessor();
Alex Loiko5825aa62017-12-18 16:02:40 +0100582 InitializePreProcessor();
solenberg70f99032015-12-08 11:07:32 -0800583
aleloi868f32f2017-05-23 07:20:05 -0700584 if (aec_dump_) {
Minyue Li656d6092018-08-10 15:38:52 +0200585 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -0700586 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000587 return kNoError;
588}
589
Michael Graczyk86c6d332015-07-23 11:41:39 -0700590int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Åhgren4bdced52017-06-27 16:00:38 +0200591 UpdateActiveSubmoduleStates();
592
Michael Graczyk86c6d332015-07-23 11:41:39 -0700593 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700594 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
595 return kBadSampleRateError;
596 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000597 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700598
Peter Kasting69558702016-01-12 16:26:35 -0800599 const size_t num_in_channels = config.input_stream().num_channels();
600 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700601
602 // Need at least one input channel.
603 // Need either one output channel or as many outputs as there are inputs.
604 if (num_in_channels == 0 ||
605 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700606 return kBadNumberChannelsError;
607 }
608
peahdf3efa82015-11-28 12:35:15 -0800609 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000610
peahde65ddc2016-09-16 15:02:15 -0700611 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700612 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700613 formats_.api_format.output_stream().sample_rate_hz()),
614 submodule_states_.CaptureMultiBandSubModulesActive() ||
615 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000616
peahde65ddc2016-09-16 15:02:15 -0700617 capture_nonlocked_.capture_processing_format =
618 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700619
peah2ce640f2017-04-07 03:57:48 -0700620 int render_processing_rate;
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200621 if (!capture_nonlocked_.echo_controller_enabled) {
peah2ce640f2017-04-07 03:57:48 -0700622 render_processing_rate = FindNativeProcessRateToUse(
623 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
624 formats_.api_format.reverse_output_stream().sample_rate_hz()),
625 submodule_states_.CaptureMultiBandSubModulesActive() ||
626 submodule_states_.RenderMultiBandSubModulesActive());
627 } else {
628 render_processing_rate = capture_processing_rate;
629 }
630
aluebseb3603b2016-04-20 15:27:58 -0700631 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
632 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700633 if (render_processing_rate > kSampleRate32kHz &&
Gustaf Ullbergbd83b912017-10-18 12:32:42 +0200634 !capture_nonlocked_.echo_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700635 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
636 ? kSampleRate32kHz
637 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700638 }
peah2ce640f2017-04-07 03:57:48 -0700639
peahde65ddc2016-09-16 15:02:15 -0700640 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700641 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700642 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
643 kSampleRate8kHz) {
644 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000645 } else {
peahde65ddc2016-09-16 15:02:15 -0700646 render_processing_rate =
647 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000648 }
649
peahde65ddc2016-09-16 15:02:15 -0700650 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000651 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700652 if (submodule_states_.RenderMultiBandSubModulesActive()) {
653 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
654 } else {
655 formats_.render_processing_format = StreamConfig(
656 formats_.api_format.reverse_input_stream().sample_rate_hz(),
657 formats_.api_format.reverse_input_stream().num_channels());
658 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000659
peahde65ddc2016-09-16 15:02:15 -0700660 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
661 kSampleRate32kHz ||
662 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
663 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800664 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000665 } else {
peahdf3efa82015-11-28 12:35:15 -0800666 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700667 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000668 }
669
670 return InitializeLocked();
671}
672
peah88ac8532016-09-12 16:47:25 -0700673void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700674 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700675
peah88ac8532016-09-12 16:47:25 -0700676 // Run in a single-threaded manner when applying the settings.
677 rtc::CritScope cs_render(&crit_render_);
678 rtc::CritScope cs_capture(&crit_capture_);
679
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200680 public_submodules_->echo_cancellation->Enable(
681 config_.echo_canceller.enabled && !config_.echo_canceller.mobile_mode);
Sam Zackrisson8c147b62018-09-28 12:40:47 +0200682 public_submodules_->echo_control_mobile->Enable(
683 config_.echo_canceller.enabled && config_.echo_canceller.mobile_mode);
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200684
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200685 public_submodules_->echo_cancellation->set_suppression_level(
686 config.echo_canceller.legacy_moderate_suppression_level
687 ? EchoCancellation::SuppressionLevel::kModerateSuppression
688 : EchoCancellation::SuppressionLevel::kHighSuppression);
689
peah8271d042016-11-22 07:24:52 -0800690 InitializeLowCutFilter();
691
Mirko Bonadei675513b2017-11-09 11:09:25 +0100692 RTC_LOG(LS_INFO) << "Highpass filter activated: "
693 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800694
Sam Zackrissonab1aee02018-03-05 15:59:06 +0100695 const bool config_ok = GainController2::Validate(config_.gain_controller2);
alessiob3ec96df2017-05-22 06:57:06 -0700696 if (!config_ok) {
Jonas Olsson645b0272018-02-15 15:16:27 +0100697 RTC_LOG(LS_ERROR) << "AudioProcessing module config error\n"
698 "Gain Controller 2: "
Mirko Bonadei675513b2017-11-09 11:09:25 +0100699 << GainController2::ToString(config_.gain_controller2)
Jonas Olsson645b0272018-02-15 15:16:27 +0100700 << "\nReverting to default parameter set";
alessiob3ec96df2017-05-22 06:57:06 -0700701 config_.gain_controller2 = AudioProcessing::Config::GainController2();
702 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200703 InitializeGainController2();
Alex Loikob5c9a792018-04-16 16:31:22 +0200704 InitializePreAmplifier();
Alessio Bazzica270f7b52017-10-13 11:05:17 +0200705 private_submodules_->gain_controller2->ApplyConfig(config_.gain_controller2);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100706 RTC_LOG(LS_INFO) << "Gain Controller 2 activated: "
707 << config_.gain_controller2.enabled;
Alex Loiko5feb30e2018-04-16 13:52:32 +0200708 RTC_LOG(LS_INFO) << "Pre-amplifier activated: "
709 << config_.pre_amplifier.enabled;
peah88ac8532016-09-12 16:47:25 -0700710}
711
712void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800713 // Run in a single-threaded manner when setting the extra options.
714 rtc::CritScope cs_render(&crit_render_);
715 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000716
peahb624d8c2016-03-05 03:01:14 -0800717 public_submodules_->echo_cancellation->SetExtraOptions(config);
718
peahdf3efa82015-11-28 12:35:15 -0800719 if (capture_.transient_suppressor_enabled !=
720 config.Get<ExperimentalNs>().enabled) {
721 capture_.transient_suppressor_enabled =
722 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000723 InitializeTransient();
724 }
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000725}
726
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000727int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800728 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700729 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000730}
731
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000732int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800733 // Used as callback from submodules, hence locking is not allowed.
734 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000735}
736
Peter Kasting69558702016-01-12 16:26:35 -0800737size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800738 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700739 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000740}
741
Peter Kasting69558702016-01-12 16:26:35 -0800742size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800743 // Used as callback from submodules, hence locking is not allowed.
744 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000745}
746
Peter Kasting69558702016-01-12 16:26:35 -0800747size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800748 // Used as callback from submodules, hence locking is not allowed.
Sam Zackrisson9394f6f2018-06-14 10:11:35 +0200749 return capture_nonlocked_.echo_controller_enabled ? 1 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800750}
751
Peter Kasting69558702016-01-12 16:26:35 -0800752size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800753 // Used as callback from submodules, hence locking is not allowed.
754 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000755}
756
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000757void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800758 rtc::CritScope cs(&crit_capture_);
759 capture_.output_will_be_muted = muted;
760 if (private_submodules_->agc_manager.get()) {
761 private_submodules_->agc_manager->SetCaptureMuted(
762 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000763 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000764}
765
Alessio Bazzicac054e782018-04-16 12:10:09 +0200766void AudioProcessingImpl::SetRuntimeSetting(RuntimeSetting setting) {
Alex Loiko73ec0192018-05-15 10:52:28 +0200767 switch (setting.type()) {
768 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
769 render_runtime_settings_enqueuer_.Enqueue(setting);
770 return;
771 case RuntimeSetting::Type::kNotSpecified:
772 RTC_NOTREACHED();
773 return;
774 case RuntimeSetting::Type::kCapturePreGain:
775 capture_runtime_settings_enqueuer_.Enqueue(setting);
776 return;
777 }
778 // The language allows the enum to have a non-enumerator
779 // value. Check that this doesn't happen.
780 RTC_NOTREACHED();
Alessio Bazzicac054e782018-04-16 12:10:09 +0200781}
782
783AudioProcessingImpl::RuntimeSettingEnqueuer::RuntimeSettingEnqueuer(
784 SwapQueue<RuntimeSetting>* runtime_settings)
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200785 : runtime_settings_(*runtime_settings) {
786 RTC_DCHECK(runtime_settings);
Alessio Bazzicac054e782018-04-16 12:10:09 +0200787}
788
789AudioProcessingImpl::RuntimeSettingEnqueuer::~RuntimeSettingEnqueuer() =
790 default;
791
792void AudioProcessingImpl::RuntimeSettingEnqueuer::Enqueue(
793 RuntimeSetting setting) {
794 size_t remaining_attempts = 10;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200795 while (!runtime_settings_.Insert(&setting) && remaining_attempts-- > 0) {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200796 RuntimeSetting setting_to_discard;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200797 if (runtime_settings_.Remove(&setting_to_discard))
Alessio Bazzicac054e782018-04-16 12:10:09 +0200798 RTC_LOG(LS_ERROR)
799 << "The runtime settings queue is full. Oldest setting discarded.";
800 }
801 if (remaining_attempts == 0)
802 RTC_LOG(LS_ERROR) << "Cannot enqueue a new runtime setting.";
803}
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000804
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000805int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700806 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000807 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000808 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000809 int output_sample_rate_hz,
810 ChannelLayout output_layout,
811 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800812 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800813 StreamConfig input_stream;
814 StreamConfig output_stream;
815 {
816 // Access the formats_.api_format.input_stream beneath the capture lock.
817 // The lock must be released as it is later required in the call
818 // to ProcessStream(,,,);
819 rtc::CritScope cs(&crit_capture_);
820 input_stream = formats_.api_format.input_stream();
821 output_stream = formats_.api_format.output_stream();
822 }
823
Michael Graczyk86c6d332015-07-23 11:41:39 -0700824 input_stream.set_sample_rate_hz(input_sample_rate_hz);
825 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
826 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700827 output_stream.set_sample_rate_hz(output_sample_rate_hz);
828 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
829 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
830
831 if (samples_per_channel != input_stream.num_frames()) {
832 return kBadDataLengthError;
833 }
834 return ProcessStream(src, input_stream, output_stream, dest);
835}
836
837int AudioProcessingImpl::ProcessStream(const float* const* src,
838 const StreamConfig& input_config,
839 const StreamConfig& output_config,
840 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800841 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800842 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700843 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800844 {
845 // Acquire the capture lock in order to safely call the function
846 // that retrieves the render side data. This function accesses apm
847 // getters that need the capture lock held when being called.
848 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700849 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800850
851 if (!src || !dest) {
852 return kNullPointerError;
853 }
854
855 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700856 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000857 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000858
Michael Graczyk86c6d332015-07-23 11:41:39 -0700859 processing_config.input_stream() = input_config;
860 processing_config.output_stream() = output_config;
861
peahdf3efa82015-11-28 12:35:15 -0800862 {
863 // Do conditional reinitialization.
864 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700865 RETURN_ON_ERR(
866 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800867 }
868 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700869 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
870 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000871
aleloi868f32f2017-05-23 07:20:05 -0700872 if (aec_dump_) {
873 RecordUnprocessedCaptureStream(src);
874 }
875
peahdf3efa82015-11-28 12:35:15 -0800876 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700877 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800878 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000879
aleloi868f32f2017-05-23 07:20:05 -0700880 if (aec_dump_) {
881 RecordProcessedCaptureStream(dest);
882 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000883 return kNoError;
884}
885
Alex Loiko73ec0192018-05-15 10:52:28 +0200886void AudioProcessingImpl::HandleCaptureRuntimeSettings() {
Alessio Bazzicac054e782018-04-16 12:10:09 +0200887 RuntimeSetting setting;
Alex Loiko73ec0192018-05-15 10:52:28 +0200888 while (capture_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200889 if (aec_dump_) {
890 aec_dump_->WriteRuntimeSetting(setting);
891 }
Alessio Bazzicac054e782018-04-16 12:10:09 +0200892 switch (setting.type()) {
893 case RuntimeSetting::Type::kCapturePreGain:
Alex Loikob5c9a792018-04-16 16:31:22 +0200894 if (config_.pre_amplifier.enabled) {
895 float value;
896 setting.GetFloat(&value);
897 private_submodules_->pre_amplifier->SetGainFactor(value);
898 }
899 // TODO(bugs.chromium.org/9138): Log setting handling by Aec Dump.
Alessio Bazzicac054e782018-04-16 12:10:09 +0200900 break;
Alex Loiko73ec0192018-05-15 10:52:28 +0200901 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
902 RTC_NOTREACHED();
903 break;
904 case RuntimeSetting::Type::kNotSpecified:
905 RTC_NOTREACHED();
906 break;
907 }
908 }
909}
910
911void AudioProcessingImpl::HandleRenderRuntimeSettings() {
912 RuntimeSetting setting;
913 while (render_runtime_settings_.Remove(&setting)) {
Alex Loiko62347222018-09-10 10:18:07 +0200914 if (aec_dump_) {
915 aec_dump_->WriteRuntimeSetting(setting);
916 }
Alex Loiko73ec0192018-05-15 10:52:28 +0200917 switch (setting.type()) {
918 case RuntimeSetting::Type::kCustomRenderProcessingRuntimeSetting:
919 if (private_submodules_->render_pre_processor) {
920 private_submodules_->render_pre_processor->SetRuntimeSetting(setting);
921 }
922 break;
923 case RuntimeSetting::Type::kCapturePreGain:
924 RTC_NOTREACHED();
925 break;
Alessio Bazzica33444dc2018-04-20 13:16:55 +0200926 case RuntimeSetting::Type::kNotSpecified:
Alessio Bazzicac054e782018-04-16 12:10:09 +0200927 RTC_NOTREACHED();
928 break;
929 }
930 }
931}
932
peah9e6a2902017-05-15 07:19:21 -0700933void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700934 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
935 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700936 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700937
kwibergaf476c72016-11-28 15:21:39 -0800938 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700939
940 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700941 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700942 // The data queue is full and needs to be emptied.
943 EmptyQueuedRenderAudio();
944
945 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700946 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700947 RTC_DCHECK(result);
948 }
949
950 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
951 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700952 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700953
954 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700955 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700956 // The data queue is full and needs to be emptied.
957 EmptyQueuedRenderAudio();
958
959 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700960 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700961 RTC_DCHECK(result);
962 }
peah701d6282016-10-25 05:42:20 -0700963
964 if (!constants_.use_experimental_agc) {
965 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
966 // Insert the samples into the queue.
967 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
968 // The data queue is full and needs to be emptied.
969 EmptyQueuedRenderAudio();
970
971 // Retry the insert (should always work).
972 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
973 RTC_DCHECK(result);
974 }
975 }
peah9e6a2902017-05-15 07:19:21 -0700976}
ivoc9f4a4a02016-10-28 05:39:16 -0700977
peah9e6a2902017-05-15 07:19:21 -0700978void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700979 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
980
981 // Insert the samples into the queue.
982 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
983 // The data queue is full and needs to be emptied.
984 EmptyQueuedRenderAudio();
985
986 // Retry the insert (should always work).
987 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
988 RTC_DCHECK(result);
989 }
peah764e3642016-10-22 05:04:30 -0700990}
991
992void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700993 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700994 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700995 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700996 EchoCancellationImpl::NumCancellersRequired(
997 num_output_channels(), num_reverse_channels()));
998
peah701d6282016-10-25 05:42:20 -0700999 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -07001000 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -07001001 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -07001002 EchoControlMobileImpl::NumCancellersRequired(
1003 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -07001004
peah701d6282016-10-25 05:42:20 -07001005 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -07001006 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -07001007
ivoc9f4a4a02016-10-28 05:39:16 -07001008 const size_t new_red_render_queue_element_max_size =
1009 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
1010
peaha0624602016-10-25 04:45:24 -07001011 // Reallocate the queues if the queue item sizes are too small to fit the
1012 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -07001013 if (aec_render_queue_element_max_size_ <
1014 new_aec_render_queue_element_max_size) {
1015 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -07001016
peaha0624602016-10-25 04:45:24 -07001017 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001018 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001019
peah701d6282016-10-25 05:42:20 -07001020 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001021 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1022 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001023 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001024 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001025
peah701d6282016-10-25 05:42:20 -07001026 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1027 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001028 } else {
peah701d6282016-10-25 05:42:20 -07001029 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001030 }
1031
peah701d6282016-10-25 05:42:20 -07001032 if (aecm_render_queue_element_max_size_ <
1033 new_aecm_render_queue_element_max_size) {
1034 aecm_render_queue_element_max_size_ =
1035 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001036
1037 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001038 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001039
peah701d6282016-10-25 05:42:20 -07001040 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001041 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1042 kMaxNumFramesToBuffer, template_queue_element,
1043 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001044 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001045
peah701d6282016-10-25 05:42:20 -07001046 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1047 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001048 } else {
peah701d6282016-10-25 05:42:20 -07001049 aecm_render_signal_queue_->Clear();
1050 }
1051
1052 if (agc_render_queue_element_max_size_ <
1053 new_agc_render_queue_element_max_size) {
1054 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1055
1056 std::vector<int16_t> template_queue_element(
1057 agc_render_queue_element_max_size_);
1058
1059 agc_render_signal_queue_.reset(
1060 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1061 kMaxNumFramesToBuffer, template_queue_element,
1062 RenderQueueItemVerifier<int16_t>(
1063 agc_render_queue_element_max_size_)));
1064
1065 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1066 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1067 } else {
1068 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001069 }
ivoc9f4a4a02016-10-28 05:39:16 -07001070
1071 if (red_render_queue_element_max_size_ <
1072 new_red_render_queue_element_max_size) {
1073 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1074
1075 std::vector<float> template_queue_element(
1076 red_render_queue_element_max_size_);
1077
1078 red_render_signal_queue_.reset(
1079 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1080 kMaxNumFramesToBuffer, template_queue_element,
1081 RenderQueueItemVerifier<float>(
1082 red_render_queue_element_max_size_)));
1083
1084 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1085 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1086 } else {
1087 red_render_signal_queue_->Clear();
1088 }
peah764e3642016-10-22 05:04:30 -07001089}
1090
1091void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1092 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001093 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001094 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001095 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001096 }
1097
peah701d6282016-10-25 05:42:20 -07001098 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001099 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001100 aecm_capture_queue_buffer_);
1101 }
1102
1103 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1104 public_submodules_->gain_control->ProcessRenderAudio(
1105 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001106 }
ivoc9f4a4a02016-10-28 05:39:16 -07001107
1108 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001109 RTC_DCHECK(private_submodules_->echo_detector);
1110 private_submodules_->echo_detector->AnalyzeRenderAudio(
ivoc9f4a4a02016-10-28 05:39:16 -07001111 red_capture_queue_buffer_);
1112 }
peah764e3642016-10-22 05:04:30 -07001113}
1114
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001115int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001116 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001117 {
1118 // Acquire the capture lock in order to safely call the function
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001119 // that retrieves the render side data. This function accesses APM
peahdf3efa82015-11-28 12:35:15 -08001120 // getters that need the capture lock held when being called.
1121 // The lock needs to be released as
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001122 // public_submodules_->echo_control_mobile->is_enabled() acquires this lock
peahdf3efa82015-11-28 12:35:15 -08001123 // as well.
1124 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001125 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001126 }
peahfa6228e2015-11-16 16:27:42 -08001127
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001128 if (!frame) {
1129 return kNullPointerError;
1130 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001131 // Must be a native rate.
1132 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1133 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001134 frame->sample_rate_hz_ != kSampleRate32kHz &&
1135 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001136 return kBadSampleRateError;
1137 }
peah192164e2015-11-17 02:16:45 -08001138
peahdf3efa82015-11-28 12:35:15 -08001139 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001140 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001141 {
1142 // Aquire lock for the access of api_format.
1143 // The lock is released immediately due to the conditional
1144 // reinitialization.
1145 rtc::CritScope cs_capture(&crit_capture_);
1146 // TODO(ajm): The input and output rates and channels are currently
1147 // constrained to be identical in the int16 interface.
1148 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001149
1150 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001151 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001152 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1153 processing_config.input_stream().set_num_channels(frame->num_channels_);
1154 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1155 processing_config.output_stream().set_num_channels(frame->num_channels_);
1156
peahdf3efa82015-11-28 12:35:15 -08001157 {
1158 // Do conditional reinitialization.
1159 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001160 RETURN_ON_ERR(
1161 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001162 }
1163 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001164 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001165 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001166 return kBadDataLengthError;
1167 }
1168
aleloi868f32f2017-05-23 07:20:05 -07001169 if (aec_dump_) {
1170 RecordUnprocessedCaptureStream(*frame);
1171 }
1172
peahdf3efa82015-11-28 12:35:15 -08001173 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001174 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001175 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001176 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1177 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001178
aleloi868f32f2017-05-23 07:20:05 -07001179 if (aec_dump_) {
1180 RecordProcessedCaptureStream(*frame);
1181 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001182
1183 return kNoError;
1184}
1185
peahde65ddc2016-09-16 15:02:15 -07001186int AudioProcessingImpl::ProcessCaptureStreamLocked() {
Alex Loiko73ec0192018-05-15 10:52:28 +02001187 HandleCaptureRuntimeSettings();
Alessio Bazzicac054e782018-04-16 12:10:09 +02001188
peahb58a1582016-03-15 09:34:24 -07001189 // Ensure that not both the AEC and AECM are active at the same time.
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001190 // TODO(peah): Simplify once the public API Enable functions for these
1191 // are moved to APM.
peahb58a1582016-03-15 09:34:24 -07001192 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1193 public_submodules_->echo_control_mobile->is_enabled()));
1194
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001195 MaybeUpdateHistograms();
1196
peahde65ddc2016-09-16 15:02:15 -07001197 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001198
Alex Loikob5c9a792018-04-16 16:31:22 +02001199 if (private_submodules_->pre_amplifier) {
1200 private_submodules_->pre_amplifier->ApplyGain(AudioFrameView<float>(
1201 capture_buffer->channels_f(), capture_buffer->num_channels(),
1202 capture_buffer->num_frames()));
1203 }
1204
peah1b08dc32016-12-20 13:45:58 -08001205 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001206 capture_buffer->channels_const()[0],
1207 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001208 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1209 if (log_rms) {
1210 capture_rms_interval_counter_ = 0;
1211 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001212 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1213 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1214 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1215 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001216 }
1217
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001218 if (private_submodules_->echo_controller) {
Per Åhgren88cf0502018-07-16 17:08:41 +02001219 // Detect and flag any change in the analog gain.
1220 int analog_mic_level = gain_control()->stream_analog_level();
1221 capture_.echo_path_gain_change =
1222 capture_.prev_analog_mic_level != analog_mic_level &&
1223 capture_.prev_analog_mic_level != -1;
1224 capture_.prev_analog_mic_level = analog_mic_level;
1225
Per Åhgrend2650d12018-10-02 17:00:59 +02001226 // Detect and flag any change in the pre-amplifier gain.
1227 if (private_submodules_->pre_amplifier) {
1228 float pre_amp_gain = private_submodules_->pre_amplifier->GetGainFactor();
1229 capture_.echo_path_gain_change =
1230 capture_.echo_path_gain_change ||
1231 (capture_.prev_pre_amp_gain != pre_amp_gain &&
Per Åhgrene8a55692018-10-02 23:10:38 +02001232 capture_.prev_pre_amp_gain >= 0.f);
Per Åhgrend2650d12018-10-02 17:00:59 +02001233 capture_.prev_pre_amp_gain = pre_amp_gain;
1234 }
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001235 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001236 }
1237
peahbe615622016-02-13 16:40:47 -08001238 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001239 public_submodules_->gain_control->is_enabled()) {
1240 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001241 capture_buffer->channels()[0], capture_buffer->num_channels(),
1242 capture_nonlocked_.capture_processing_format.num_frames());
Alex Loikod9342442018-09-10 13:59:41 +02001243
1244 if (constants_.use_experimental_agc_process_before_aec) {
1245 private_submodules_->agc_manager->Process(
1246 capture_buffer->channels()[0],
1247 capture_nonlocked_.capture_processing_format.num_frames(),
1248 capture_nonlocked_.capture_processing_format.sample_rate_hz());
1249 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001250 }
1251
peah2ace3f92016-09-10 04:42:27 -07001252 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1253 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001254 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1255 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001256 }
1257
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001258 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001259 // Force down-mixing of the number of channels after the detection of
1260 // capture signal saturation.
1261 // TODO(peah): Look into ensuring that this kind of tampering with the
1262 // AudioBuffer functionality should not be needed.
1263 capture_buffer->set_num_channels(1);
1264 }
1265
peahe0eae3c2016-12-14 01:16:23 -08001266 // TODO(peah): Move the AEC3 low-cut filter to this place.
1267 if (private_submodules_->low_cut_filter &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001268 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001269 private_submodules_->low_cut_filter->Process(capture_buffer);
1270 }
peahde65ddc2016-09-16 15:02:15 -07001271 RETURN_ON_ERR(
1272 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1273 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001274
1275 // Ensure that the stream delay was set before the call to the
1276 // AEC ProcessCaptureAudio function.
1277 if (public_submodules_->echo_cancellation->is_enabled() &&
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001278 !private_submodules_->echo_controller && !was_stream_delay_set()) {
peahb58a1582016-03-15 09:34:24 -07001279 return AudioProcessing::kStreamParameterNotSetError;
1280 }
1281
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001282 if (private_submodules_->echo_controller) {
Per Åhgren13735822018-02-12 21:42:56 +01001283 data_dumper_->DumpRaw("stream_delay", stream_delay_ms());
1284
Per Åhgrend0fa8202018-04-18 09:35:13 +02001285 if (was_stream_delay_set()) {
1286 private_submodules_->echo_controller->SetAudioBufferDelay(
1287 stream_delay_ms());
1288 }
1289
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001290 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001291 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001292 } else {
1293 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1294 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001295 }
1296
peahdf3efa82015-11-28 12:35:15 -08001297 if (public_submodules_->echo_control_mobile->is_enabled() &&
1298 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001299 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001300 }
peahde65ddc2016-09-16 15:02:15 -07001301 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah253534d2016-03-15 04:32:28 -07001302
1303 // Ensure that the stream delay was set before the call to the
1304 // AECM ProcessCaptureAudio function.
1305 if (public_submodules_->echo_control_mobile->is_enabled() &&
1306 !was_stream_delay_set()) {
1307 return AudioProcessing::kStreamParameterNotSetError;
1308 }
1309
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001310 if (!(private_submodules_->echo_controller ||
1311 public_submodules_->echo_cancellation->is_enabled())) {
Per Åhgren46537a32017-06-07 10:08:10 +02001312 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1313 capture_buffer, stream_delay_ms()));
1314 }
ivoc9f4a4a02016-10-28 05:39:16 -07001315
peahde65ddc2016-09-16 15:02:15 -07001316 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001317
peahbe615622016-02-13 16:40:47 -08001318 if (constants_.use_experimental_agc &&
Alex Loikod9342442018-09-10 13:59:41 +02001319 public_submodules_->gain_control->is_enabled() &&
1320 !constants_.use_experimental_agc_process_before_aec) {
peahdf3efa82015-11-28 12:35:15 -08001321 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001322 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1323 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001324 }
peahb8fbb542016-03-15 02:28:08 -07001325 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001326 capture_buffer,
1327 public_submodules_->echo_cancellation->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001328
peah2ace3f92016-09-10 04:42:27 -07001329 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1330 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001331 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1332 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001333 }
1334
peah9e6a2902017-05-15 07:19:21 -07001335 if (config_.residual_echo_detector.enabled) {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001336 RTC_DCHECK(private_submodules_->echo_detector);
1337 private_submodules_->echo_detector->AnalyzeCaptureAudio(
peah9e6a2902017-05-15 07:19:21 -07001338 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1339 capture_buffer->num_frames()));
1340 }
1341
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001342 // TODO(aluebs): Investigate if the transient suppression placement should be
1343 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001344 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001345 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001346 private_submodules_->agc_manager.get()
1347 ? private_submodules_->agc_manager->voice_probability()
1348 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001349
peahdf3efa82015-11-28 12:35:15 -08001350 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001351 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1352 capture_buffer->num_channels(),
1353 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1354 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1355 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001356 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001357 }
1358
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001359 // Experimental APM sub-module that analyzes |capture_buffer|.
1360 if (private_submodules_->capture_analyzer) {
1361 private_submodules_->capture_analyzer->Analyze(capture_buffer);
1362 }
1363
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001364 if (config_.gain_controller2.enabled) {
Alex Loikoa837dd72018-08-06 16:32:12 +02001365 private_submodules_->gain_controller2->NotifyAnalogLevel(
1366 gain_control()->stream_analog_level());
alessiob3ec96df2017-05-22 06:57:06 -07001367 private_submodules_->gain_controller2->Process(capture_buffer);
1368 }
1369
Sam Zackrisson0beac582017-09-25 12:04:02 +02001370 if (private_submodules_->capture_post_processor) {
1371 private_submodules_->capture_post_processor->Process(capture_buffer);
1372 }
1373
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001374 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001375 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001376
peah1b08dc32016-12-20 13:45:58 -08001377 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1378 capture_buffer->channels_const()[0],
1379 capture_nonlocked_.capture_processing_format.num_frames()));
1380 if (log_rms) {
1381 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1382 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1383 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1384 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1385 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1386 }
1387
peahdf3efa82015-11-28 12:35:15 -08001388 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001389 return kNoError;
1390}
1391
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001392int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001393 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001394 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001395 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001396 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001397 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001398 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001399 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001400 };
1401 if (samples_per_channel != reverse_config.num_frames()) {
1402 return kBadDataLengthError;
1403 }
peahdf3efa82015-11-28 12:35:15 -08001404 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001405}
1406
peahde65ddc2016-09-16 15:02:15 -07001407int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1408 const StreamConfig& input_config,
1409 const StreamConfig& output_config,
1410 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001411 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001412 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001413 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
Alex Loiko5825aa62017-12-18 16:02:40 +01001414 if (submodule_states_.RenderMultiBandProcessingActive() ||
1415 submodule_states_.RenderFullBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001416 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1417 dest);
peah2ace3f92016-09-10 04:42:27 -07001418 } else if (formats_.api_format.reverse_input_stream() !=
1419 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001420 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1421 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001422 } else {
peahde65ddc2016-09-16 15:02:15 -07001423 CopyAudioIfNeeded(src, input_config.num_frames(),
1424 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001425 }
1426
1427 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001428}
1429
peahdf3efa82015-11-28 12:35:15 -08001430int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001431 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001432 const StreamConfig& input_config,
1433 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001434 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001435 return kNullPointerError;
1436 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001437
peahde65ddc2016-09-16 15:02:15 -07001438 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001439 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001440 }
1441
peahdf3efa82015-11-28 12:35:15 -08001442 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001443 processing_config.reverse_input_stream() = input_config;
1444 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001445
peahdf3efa82015-11-28 12:35:15 -08001446 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +02001447 RTC_DCHECK_EQ(input_config.num_frames(),
1448 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001449
aleloi868f32f2017-05-23 07:20:05 -07001450 if (aec_dump_) {
1451 const size_t channel_size =
1452 formats_.api_format.reverse_input_stream().num_frames();
1453 const size_t num_channels =
1454 formats_.api_format.reverse_input_stream().num_channels();
1455 aec_dump_->WriteRenderStreamMessage(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01001456 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07001457 }
peahdf3efa82015-11-28 12:35:15 -08001458 render_.render_audio->CopyFrom(src,
1459 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001460 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001461}
1462
1463int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001464 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001465 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001466 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001467 return kNullPointerError;
1468 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001469 // Must be a native rate.
1470 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1471 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001472 frame->sample_rate_hz_ != kSampleRate32kHz &&
1473 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001474 return kBadSampleRateError;
1475 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001476
Michael Graczyk86c6d332015-07-23 11:41:39 -07001477 if (frame->num_channels_ <= 0) {
1478 return kBadNumberChannelsError;
1479 }
1480
peahdf3efa82015-11-28 12:35:15 -08001481 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001482 processing_config.reverse_input_stream().set_sample_rate_hz(
1483 frame->sample_rate_hz_);
1484 processing_config.reverse_input_stream().set_num_channels(
1485 frame->num_channels_);
1486 processing_config.reverse_output_stream().set_sample_rate_hz(
1487 frame->sample_rate_hz_);
1488 processing_config.reverse_output_stream().set_num_channels(
1489 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001490
peahdf3efa82015-11-28 12:35:15 -08001491 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001492 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001493 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001494 return kBadDataLengthError;
1495 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001496
aleloi868f32f2017-05-23 07:20:05 -07001497 if (aec_dump_) {
1498 aec_dump_->WriteRenderStreamMessage(*frame);
1499 }
1500
peahdf3efa82015-11-28 12:35:15 -08001501 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001502 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001503 render_.render_audio->InterleaveTo(
Alex Loiko5825aa62017-12-18 16:02:40 +01001504 frame, submodule_states_.RenderMultiBandProcessingActive() ||
1505 submodule_states_.RenderFullBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001506 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001507}
niklase@google.com470e71d2011-07-07 08:21:25 +00001508
peahde65ddc2016-09-16 15:02:15 -07001509int AudioProcessingImpl::ProcessRenderStreamLocked() {
1510 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001511
Alex Loiko73ec0192018-05-15 10:52:28 +02001512 HandleRenderRuntimeSettings();
1513
Alex Loiko5825aa62017-12-18 16:02:40 +01001514 if (private_submodules_->render_pre_processor) {
1515 private_submodules_->render_pre_processor->Process(render_buffer);
1516 }
1517
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001518 QueueNonbandedRenderAudio(render_buffer);
1519
peah2ace3f92016-09-10 04:42:27 -07001520 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001521 SampleRateSupportsMultiBand(
1522 formats_.render_processing_format.sample_rate_hz())) {
1523 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001524 }
1525
peahce4d9152017-05-19 01:28:05 -07001526 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1527 QueueBandedRenderAudio(render_buffer);
1528 }
1529
Alessio Bazzicad2b97402018-08-09 14:23:11 +02001530 // TODO(peah): Perform the queuing inside QueueRenderAudiuo().
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001531 if (private_submodules_->echo_controller) {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001532 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001533 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001534
peah2ace3f92016-09-10 04:42:27 -07001535 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001536 SampleRateSupportsMultiBand(
1537 formats_.render_processing_format.sample_rate_hz())) {
1538 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001539 }
1540
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001541 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001542}
1543
1544int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001545 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001546 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001547 capture_.was_stream_delay_set = true;
1548 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001549
niklase@google.com470e71d2011-07-07 08:21:25 +00001550 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001551 delay = 0;
1552 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001553 }
1554
1555 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1556 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001557 delay = 500;
1558 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001559 }
1560
peahdf3efa82015-11-28 12:35:15 -08001561 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001562 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001563}
1564
1565int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001566 // Used as callback from submodules, hence locking is not allowed.
1567 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001568}
1569
1570bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001571 // Used as callback from submodules, hence locking is not allowed.
1572 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001573}
1574
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001575void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001576 rtc::CritScope cs(&crit_capture_);
1577 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001578}
1579
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001580void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001581 rtc::CritScope cs(&crit_capture_);
1582 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001583}
1584
1585int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001586 rtc::CritScope cs(&crit_capture_);
1587 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001588}
1589
aleloi868f32f2017-05-23 07:20:05 -07001590void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1591 RTC_DCHECK(aec_dump);
1592 rtc::CritScope cs_render(&crit_render_);
1593 rtc::CritScope cs_capture(&crit_capture_);
1594
1595 // The previously attached AecDump will be destroyed with the
1596 // 'aec_dump' parameter, which is after locks are released.
1597 aec_dump_.swap(aec_dump);
1598 WriteAecDumpConfigMessage(true);
Minyue Li656d6092018-08-10 15:38:52 +02001599 aec_dump_->WriteInitMessage(formats_.api_format, rtc::TimeUTCMillis());
aleloi868f32f2017-05-23 07:20:05 -07001600}
1601
1602void AudioProcessingImpl::DetachAecDump() {
1603 // The d-tor of a task-queue based AecDump blocks until all pending
1604 // tasks are done. This construction avoids blocking while holding
1605 // the render and capture locks.
1606 std::unique_ptr<AecDump> aec_dump = nullptr;
1607 {
1608 rtc::CritScope cs_render(&crit_render_);
1609 rtc::CritScope cs_capture(&crit_capture_);
1610 aec_dump = std::move(aec_dump_);
1611 }
1612}
1613
Sam Zackrisson4d364492018-03-02 16:03:21 +01001614void AudioProcessingImpl::AttachPlayoutAudioGenerator(
1615 std::unique_ptr<AudioGenerator> audio_generator) {
1616 // TODO(bugs.webrtc.org/8882) Stub.
1617 // Reset internal audio generator with audio_generator.
1618}
1619
1620void AudioProcessingImpl::DetachPlayoutAudioGenerator() {
1621 // TODO(bugs.webrtc.org/8882) Stub.
1622 // Delete audio generator, if one is attached.
1623}
1624
ivoc4e477a12017-01-15 08:29:46 -08001625AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1626 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1627 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1628 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1629 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1630}
1631
1632AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1633 const AudioProcessingStatistics& other) = default;
1634
1635AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1636 default;
1637
ivoc3e9a5372016-10-28 07:55:33 -07001638// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1639AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1640 const {
1641 return AudioProcessingStatistics();
1642}
1643
Ivo Creusenae026092017-11-20 13:07:16 +01001644// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
Ivo Creusen56d46092017-11-24 17:29:59 +01001645AudioProcessingStats AudioProcessing::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001646 bool has_remote_tracks) const {
1647 return AudioProcessingStats();
1648}
1649
ivoc3e9a5372016-10-28 07:55:33 -07001650AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1651 const {
1652 AudioProcessingStatistics stats;
1653 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001654 if (private_submodules_->echo_controller) {
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001655 rtc::CritScope cs_capture(&crit_capture_);
1656 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1657 float erl = static_cast<float>(ec_metrics.echo_return_loss);
1658 float erle = static_cast<float>(ec_metrics.echo_return_loss_enhancement);
1659 // Instant value will also be used for min, max and average.
1660 stats.echo_return_loss.Set(erl, erl, erl, erl);
1661 stats.echo_return_loss_enhancement.Set(erle, erle, erle, erle);
1662 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1663 Error::kNoError) {
ivocd0a151c2016-11-02 09:14:37 -07001664 stats.a_nlp.Set(metrics.a_nlp);
1665 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1666 stats.echo_return_loss.Set(metrics.echo_return_loss);
1667 stats.echo_return_loss_enhancement.Set(
1668 metrics.echo_return_loss_enhancement);
1669 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1670 }
ivoc9c192b22017-03-16 04:22:14 -07001671 {
1672 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001673 RTC_DCHECK(private_submodules_->echo_detector);
1674 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1675 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
ivoc9c192b22017-03-16 04:22:14 -07001676 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001677 ed_metrics.echo_likelihood_recent_max;
ivoc9c192b22017-03-16 04:22:14 -07001678 }
ivoc3e9a5372016-10-28 07:55:33 -07001679 public_submodules_->echo_cancellation->GetDelayMetrics(
1680 &stats.delay_median, &stats.delay_standard_deviation,
1681 &stats.fraction_poor_delays);
1682 return stats;
1683}
1684
Ivo Creusen56d46092017-11-24 17:29:59 +01001685AudioProcessingStats AudioProcessingImpl::GetStatistics(
Ivo Creusenae026092017-11-20 13:07:16 +01001686 bool has_remote_tracks) const {
1687 AudioProcessingStats stats;
1688 if (has_remote_tracks) {
1689 EchoCancellation::Metrics metrics;
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001690 if (private_submodules_->echo_controller) {
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001691 rtc::CritScope cs_capture(&crit_capture_);
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001692 auto ec_metrics = private_submodules_->echo_controller->GetMetrics();
1693 stats.echo_return_loss = ec_metrics.echo_return_loss;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001694 stats.echo_return_loss_enhancement =
Gustaf Ullberg09b9fae2017-11-24 13:42:29 +01001695 ec_metrics.echo_return_loss_enhancement;
Per Åhgren83c4a022017-11-27 12:07:09 +01001696 stats.delay_ms = ec_metrics.delay_ms;
Gustaf Ullberg332150d2017-11-22 14:17:39 +01001697 } else if (public_submodules_->echo_cancellation->GetMetrics(&metrics) ==
1698 Error::kNoError) {
Ivo Creusenae026092017-11-20 13:07:16 +01001699 if (metrics.divergent_filter_fraction != -1.0f) {
1700 stats.divergent_filter_fraction =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001701 absl::optional<double>(metrics.divergent_filter_fraction);
Ivo Creusenae026092017-11-20 13:07:16 +01001702 }
1703 if (metrics.echo_return_loss.instant != -100) {
1704 stats.echo_return_loss =
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001705 absl::optional<double>(metrics.echo_return_loss.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001706 }
1707 if (metrics.echo_return_loss_enhancement.instant != -100) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001708 stats.echo_return_loss_enhancement = absl::optional<double>(
1709 metrics.echo_return_loss_enhancement.instant);
Ivo Creusenae026092017-11-20 13:07:16 +01001710 }
1711 }
1712 if (config_.residual_echo_detector.enabled) {
1713 rtc::CritScope cs_capture(&crit_capture_);
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001714 RTC_DCHECK(private_submodules_->echo_detector);
1715 auto ed_metrics = private_submodules_->echo_detector->GetMetrics();
1716 stats.residual_echo_likelihood = ed_metrics.echo_likelihood;
Ivo Creusenae026092017-11-20 13:07:16 +01001717 stats.residual_echo_likelihood_recent_max =
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001718 ed_metrics.echo_likelihood_recent_max;
Ivo Creusenae026092017-11-20 13:07:16 +01001719 }
1720 int delay_median, delay_std;
1721 float fraction_poor_delays;
1722 if (public_submodules_->echo_cancellation->GetDelayMetrics(
1723 &delay_median, &delay_std, &fraction_poor_delays) ==
1724 Error::kNoError) {
1725 if (delay_median >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001726 stats.delay_median_ms = absl::optional<int32_t>(delay_median);
Ivo Creusenae026092017-11-20 13:07:16 +01001727 }
1728 if (delay_std >= 0) {
Danil Chapovalovdb9f7ab2018-06-19 10:50:11 +02001729 stats.delay_standard_deviation_ms = absl::optional<int32_t>(delay_std);
Ivo Creusenae026092017-11-20 13:07:16 +01001730 }
1731 }
1732 }
1733 return stats;
1734}
1735
niklase@google.com470e71d2011-07-07 08:21:25 +00001736EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001737 return public_submodules_->echo_cancellation_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001738}
1739
1740EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
Sam Zackrisson74ed7342018-08-16 10:54:07 +02001741 return public_submodules_->echo_control_mobile_proxy.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001742}
1743
1744GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001745 if (constants_.use_experimental_agc) {
1746 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001747 }
peahbfa97112016-03-10 21:09:04 -08001748 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001749}
1750
1751HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001752 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001753}
1754
1755LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001756 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001757}
1758
1759NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001760 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001761}
1762
1763VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001764 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001765}
1766
peah8271d042016-11-22 07:24:52 -08001767void AudioProcessingImpl::MutateConfig(
1768 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1769 rtc::CritScope cs_render(&crit_render_);
1770 rtc::CritScope cs_capture(&crit_capture_);
1771 mutator(&config_);
1772 ApplyConfig(config_);
1773}
1774
1775AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1776 rtc::CritScope cs_render(&crit_render_);
1777 rtc::CritScope cs_capture(&crit_capture_);
1778 return config_;
1779}
1780
peah2ace3f92016-09-10 04:42:27 -07001781bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1782 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001783 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001784 public_submodules_->echo_cancellation->is_enabled(),
1785 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001786 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001787 public_submodules_->noise_suppression->is_enabled(),
peah2ace3f92016-09-10 04:42:27 -07001788 public_submodules_->gain_control->is_enabled(),
Alex Loikob5c9a792018-04-16 16:31:22 +02001789 config_.gain_controller2.enabled, config_.pre_amplifier.enabled,
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001790 capture_nonlocked_.echo_controller_enabled,
peah2ace3f92016-09-10 04:42:27 -07001791 public_submodules_->voice_detection->is_enabled(),
1792 public_submodules_->level_estimator->is_enabled(),
1793 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001794}
1795
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001796void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001797 if (capture_.transient_suppressor_enabled) {
1798 if (!public_submodules_->transient_suppressor.get()) {
1799 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001800 }
peahdf3efa82015-11-28 12:35:15 -08001801 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001802 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1803 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001804 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001805}
1806
peah8271d042016-11-22 07:24:52 -08001807void AudioProcessingImpl::InitializeLowCutFilter() {
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001808 if (submodule_states_.LowCutFilteringRequired()) {
peah8271d042016-11-22 07:24:52 -08001809 private_submodules_->low_cut_filter.reset(
1810 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1811 } else {
1812 private_submodules_->low_cut_filter.reset();
1813 }
1814}
alessiob3ec96df2017-05-22 06:57:06 -07001815
Gustaf Ullberg8eb9c7d2017-10-14 08:28:46 +02001816void AudioProcessingImpl::InitializeEchoController() {
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001817 if (echo_control_factory_) {
1818 private_submodules_->echo_controller =
1819 echo_control_factory_->Create(proc_sample_rate_hz());
peahe0eae3c2016-12-14 01:16:23 -08001820 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001821 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001822 }
1823}
peah8271d042016-11-22 07:24:52 -08001824
alessiob3ec96df2017-05-22 06:57:06 -07001825void AudioProcessingImpl::InitializeGainController2() {
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001826 if (config_.gain_controller2.enabled) {
1827 private_submodules_->gain_controller2->Initialize(proc_sample_rate_hz());
alessiob3ec96df2017-05-22 06:57:06 -07001828 }
1829}
1830
Alex Loikob5c9a792018-04-16 16:31:22 +02001831void AudioProcessingImpl::InitializePreAmplifier() {
1832 if (config_.pre_amplifier.enabled) {
1833 private_submodules_->pre_amplifier.reset(
1834 new GainApplier(true, config_.pre_amplifier.fixed_gain_factor));
1835 } else {
1836 private_submodules_->pre_amplifier.reset();
1837 }
1838}
1839
ivoc9f4a4a02016-10-28 05:39:16 -07001840void AudioProcessingImpl::InitializeResidualEchoDetector() {
Ivo Creusen09fa4b02018-01-11 16:08:54 +01001841 RTC_DCHECK(private_submodules_->echo_detector);
Ivo Creusen647ef092018-03-14 17:13:48 +01001842 private_submodules_->echo_detector->Initialize(
Ivo Creusenb1facc12018-04-12 16:15:58 +02001843 proc_sample_rate_hz(), 1,
1844 formats_.render_processing_format.sample_rate_hz(), 1);
ivoc9f4a4a02016-10-28 05:39:16 -07001845}
1846
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02001847void AudioProcessingImpl::InitializeAnalyzer() {
1848 if (private_submodules_->capture_analyzer) {
1849 private_submodules_->capture_analyzer->Initialize(proc_sample_rate_hz(),
1850 num_proc_channels());
1851 }
1852}
1853
Sam Zackrisson0beac582017-09-25 12:04:02 +02001854void AudioProcessingImpl::InitializePostProcessor() {
1855 if (private_submodules_->capture_post_processor) {
1856 private_submodules_->capture_post_processor->Initialize(
1857 proc_sample_rate_hz(), num_proc_channels());
1858 }
1859}
1860
Alex Loiko5825aa62017-12-18 16:02:40 +01001861void AudioProcessingImpl::InitializePreProcessor() {
1862 if (private_submodules_->render_pre_processor) {
1863 private_submodules_->render_pre_processor->Initialize(
1864 formats_.render_processing_format.sample_rate_hz(),
1865 formats_.render_processing_format.num_channels());
1866 }
1867}
1868
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001869void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001870 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001871
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001872 if (public_submodules_->echo_cancellation->is_enabled()) {
Sam Zackrisson2a959d92018-07-23 14:48:07 +00001873 // Activate delay_jumps_ counters if we know echo_cancellation is running.
1874 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001875 if (capture_.stream_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001876 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001877 capture_.stream_delay_jumps = 0;
1878 }
1879 if (capture_.aec_system_delay_jumps == -1 &&
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001880 public_submodules_->echo_cancellation->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001881 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001882 }
1883
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001884 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001885 const int diff_stream_delay_ms =
1886 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1887 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1888 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001889 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1890 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001891 if (capture_.stream_delay_jumps == -1) {
1892 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001893 }
peahdf3efa82015-11-28 12:35:15 -08001894 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001895 }
peahdf3efa82015-11-28 12:35:15 -08001896 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001897
1898 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001899 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001900 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001901 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001902 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001903 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1904 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001905 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001906 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001907 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001908 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001909 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1910 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1911 100);
peahdf3efa82015-11-28 12:35:15 -08001912 if (capture_.aec_system_delay_jumps == -1) {
1913 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001914 }
peahdf3efa82015-11-28 12:35:15 -08001915 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001916 }
peahdf3efa82015-11-28 12:35:15 -08001917 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001918 }
1919}
1920
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001921void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001922 // Run in a single-threaded manner.
1923 rtc::CritScope cs_render(&crit_render_);
1924 rtc::CritScope cs_capture(&crit_capture_);
1925
1926 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001927 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001928 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001929 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001930 }
peahdf3efa82015-11-28 12:35:15 -08001931 capture_.stream_delay_jumps = -1;
1932 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001933
peahdf3efa82015-11-28 12:35:15 -08001934 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001935 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1936 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001937 }
peahdf3efa82015-11-28 12:35:15 -08001938 capture_.aec_system_delay_jumps = -1;
1939 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001940}
1941
aleloi868f32f2017-05-23 07:20:05 -07001942void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1943 if (!aec_dump_) {
1944 return;
1945 }
1946 std::string experiments_description =
1947 public_submodules_->echo_cancellation->GetExperimentsDescription();
1948 // TODO(peah): Add semicolon-separated concatenations of experiment
1949 // descriptions for other submodules.
aleloi868f32f2017-05-23 07:20:05 -07001950 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1951 experiments_description += "AgcClippingLevelExperiment;";
1952 }
Gustaf Ullbergce045ac2017-10-16 13:49:04 +02001953 if (capture_nonlocked_.echo_controller_enabled) {
1954 experiments_description += "EchoController;";
aleloi868f32f2017-05-23 07:20:05 -07001955 }
Alessio Bazzica270f7b52017-10-13 11:05:17 +02001956 if (config_.gain_controller2.enabled) {
1957 experiments_description += "GainController2;";
1958 }
aleloi868f32f2017-05-23 07:20:05 -07001959
1960 InternalAPMConfig apm_config;
1961
1962 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1963 apm_config.aec_delay_agnostic_enabled =
1964 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1965 apm_config.aec_drift_compensation_enabled =
1966 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1967 apm_config.aec_extended_filter_enabled =
1968 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1969 apm_config.aec_suppression_level = static_cast<int>(
1970 public_submodules_->echo_cancellation->suppression_level());
1971
1972 apm_config.aecm_enabled =
1973 public_submodules_->echo_control_mobile->is_enabled();
1974 apm_config.aecm_comfort_noise_enabled =
1975 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1976 apm_config.aecm_routing_mode =
1977 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1978
1979 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1980 apm_config.agc_mode =
1981 static_cast<int>(public_submodules_->gain_control->mode());
1982 apm_config.agc_limiter_enabled =
1983 public_submodules_->gain_control->is_limiter_enabled();
1984 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1985
1986 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1987
1988 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1989 apm_config.ns_level =
1990 static_cast<int>(public_submodules_->noise_suppression->level());
1991
1992 apm_config.transient_suppression_enabled =
1993 capture_.transient_suppressor_enabled;
aleloi868f32f2017-05-23 07:20:05 -07001994 apm_config.experiments_description = experiments_description;
Alex Loiko5feb30e2018-04-16 13:52:32 +02001995 apm_config.pre_amplifier_enabled = config_.pre_amplifier.enabled;
1996 apm_config.pre_amplifier_fixed_gain_factor =
1997 config_.pre_amplifier.fixed_gain_factor;
aleloi868f32f2017-05-23 07:20:05 -07001998
1999 if (!forced && apm_config == apm_config_for_aec_dump_) {
2000 return;
2001 }
2002 aec_dump_->WriteConfig(apm_config);
2003 apm_config_for_aec_dump_ = apm_config;
2004}
2005
2006void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2007 const float* const* src) {
2008 RTC_DCHECK(aec_dump_);
2009 WriteAecDumpConfigMessage(false);
2010
2011 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2012 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2013 aec_dump_->AddCaptureStreamInput(
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002014 AudioFrameView<const float>(src, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002015 RecordAudioProcessingState();
2016}
2017
2018void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2019 const AudioFrame& capture_frame) {
2020 RTC_DCHECK(aec_dump_);
2021 WriteAecDumpConfigMessage(false);
2022
2023 aec_dump_->AddCaptureStreamInput(capture_frame);
2024 RecordAudioProcessingState();
2025}
2026
2027void AudioProcessingImpl::RecordProcessedCaptureStream(
2028 const float* const* processed_capture_stream) {
2029 RTC_DCHECK(aec_dump_);
2030
2031 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2032 const size_t num_channels =
2033 formats_.api_format.output_stream().num_channels();
Alex Loikoe36e8bb2018-02-16 11:54:07 +01002034 aec_dump_->AddCaptureStreamOutput(AudioFrameView<const float>(
2035 processed_capture_stream, num_channels, channel_size));
aleloi868f32f2017-05-23 07:20:05 -07002036 aec_dump_->WriteCaptureStreamMessage();
2037}
2038
2039void AudioProcessingImpl::RecordProcessedCaptureStream(
2040 const AudioFrame& processed_capture_frame) {
2041 RTC_DCHECK(aec_dump_);
2042
2043 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2044 aec_dump_->WriteCaptureStreamMessage();
2045}
2046
2047void AudioProcessingImpl::RecordAudioProcessingState() {
2048 RTC_DCHECK(aec_dump_);
2049 AecDump::AudioProcessingState audio_proc_state;
2050 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2051 audio_proc_state.drift =
2052 public_submodules_->echo_cancellation->stream_drift_samples();
2053 audio_proc_state.level = gain_control()->stream_analog_level();
2054 audio_proc_state.keypress = capture_.key_pressed;
2055 aec_dump_->AddAudioProcessingState(audio_proc_state);
2056}
2057
kwiberg83ffe452016-08-29 14:46:07 -07002058AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
Sam Zackrisson9394f6f2018-06-14 10:11:35 +02002059 bool transient_suppressor_enabled)
kwiberg83ffe452016-08-29 14:46:07 -07002060 : aec_system_delay_jumps(-1),
2061 delay_offset_ms(0),
2062 was_stream_delay_set(false),
2063 last_stream_delay_ms(0),
2064 last_aec_system_delay_ms(0),
2065 stream_delay_jumps(-1),
2066 output_will_be_muted(false),
2067 key_pressed(false),
2068 transient_suppressor_enabled(transient_suppressor_enabled),
peahde65ddc2016-09-16 15:02:15 -07002069 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002070 split_rate(kSampleRate16kHz),
Per Åhgren88cf0502018-07-16 17:08:41 +02002071 echo_path_gain_change(false),
Per Åhgrend2650d12018-10-02 17:00:59 +02002072 prev_analog_mic_level(-1),
2073 prev_pre_amp_gain(-1.f) {}
kwiberg83ffe452016-08-29 14:46:07 -07002074
2075AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2076
2077AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2078
2079AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2080
niklase@google.com470e71d2011-07-07 08:21:25 +00002081} // namespace webrtc