blob: c1010669b06c8f0d67a2eab44866cb94aa593c08 [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"
22#include "modules/audio_processing/aec3/echo_canceller3.h"
23#include "modules/audio_processing/agc/agc_manager_direct.h"
24#include "modules/audio_processing/agc2/gain_controller2.h"
25#include "modules/audio_processing/audio_buffer.h"
26#include "modules/audio_processing/beamformer/nonlinear_beamformer.h"
27#include "modules/audio_processing/common.h"
28#include "modules/audio_processing/echo_cancellation_impl.h"
29#include "modules/audio_processing/echo_control_mobile_impl.h"
30#include "modules/audio_processing/gain_control_for_experimental_agc.h"
31#include "modules/audio_processing/gain_control_impl.h"
32#include "rtc_base/checks.h"
33#include "rtc_base/logging.h"
34#include "rtc_base/platform_file.h"
Niels Möller84255bb2017-10-06 13:43:23 +020035#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/trace_event.h"
peah1bcfce52016-08-26 07:16:04 -070037#if WEBRTC_INTELLIGIBILITY_ENHANCER
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070039#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "modules/audio_processing/level_controller/level_controller.h"
41#include "modules/audio_processing/level_estimator_impl.h"
42#include "modules/audio_processing/low_cut_filter.h"
43#include "modules/audio_processing/noise_suppression_impl.h"
44#include "modules/audio_processing/residual_echo_detector.h"
45#include "modules/audio_processing/transient/transient_suppressor.h"
46#include "modules/audio_processing/voice_detection_impl.h"
47#include "modules/include/module_common_types.h"
48#include "system_wrappers/include/file_wrapper.h"
49#include "system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000050
peah1bcfce52016-08-26 07:16:04 -070051// Check to verify that the define for the intelligibility enhancer is properly
52// set.
53#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
54 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
55 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
56#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
57#endif
58
Michael Graczyk86c6d332015-07-23 11:41:39 -070059#define RETURN_ON_ERR(expr) \
60 do { \
61 int err = (expr); \
62 if (err != kNoError) { \
63 return err; \
64 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000065 } while (0)
66
niklase@google.com470e71d2011-07-07 08:21:25 +000067namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070068
kwibergd59d3bb2016-09-13 07:49:33 -070069constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070070
Michael Graczyk86c6d332015-07-23 11:41:39 -070071namespace {
72
73static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
74 switch (layout) {
75 case AudioProcessing::kMono:
76 case AudioProcessing::kStereo:
77 return false;
78 case AudioProcessing::kMonoAndKeyboard:
79 case AudioProcessing::kStereoAndKeyboard:
80 return true;
81 }
82
kwiberg9e2be5f2016-09-14 05:23:22 -070083 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070084 return false;
85}
aluebsdf6416a2016-03-16 18:26:35 -070086
peah2ace3f92016-09-10 04:42:27 -070087bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070088 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
89 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
90}
91
peah2ace3f92016-09-10 04:42:27 -070092int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
93#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070094 constexpr int kMaxSplittingNativeProcessRate =
95 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -070096#else
kwibergd59d3bb2016-09-13 07:49:33 -070097 constexpr int kMaxSplittingNativeProcessRate =
98 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -070099#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700100 static_assert(
101 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
102 "");
peah2ace3f92016-09-10 04:42:27 -0700103 const int uppermost_native_rate = band_splitting_required
104 ? kMaxSplittingNativeProcessRate
105 : AudioProcessing::kSampleRate48kHz;
106
107 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
108 if (rate >= uppermost_native_rate) {
109 return uppermost_native_rate;
110 }
111 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700112 return rate;
113 }
114 }
peah2ace3f92016-09-10 04:42:27 -0700115 RTC_NOTREACHED();
116 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700117}
118
peah9e6a2902017-05-15 07:19:21 -0700119// Maximum lengths that frame of samples being passed from the render side to
120// the capture side can have (does not apply to AEC3).
121static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
122static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum number of frames to buffer in the render queue.
125// TODO(peah): Decrease this once we properly handle hugely unbalanced
126// reverse and forward call numbers.
127static const size_t kMaxNumFramesToBuffer = 100;
128
peah8271d042016-11-22 07:24:52 -0800129class HighPassFilterImpl : public HighPassFilter {
130 public:
131 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
132 ~HighPassFilterImpl() override = default;
133
134 // HighPassFilter implementation.
135 int Enable(bool enable) override {
136 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
137 config->high_pass_filter.enabled = enable;
138 });
139
140 return AudioProcessing::kNoError;
141 }
142
143 bool is_enabled() const override {
144 return apm_->GetConfig().high_pass_filter.enabled;
145 }
146
147 private:
148 AudioProcessingImpl* apm_;
149 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
150};
151
aleloi868f32f2017-05-23 07:20:05 -0700152webrtc::InternalAPMStreamsConfig ToStreamsConfig(
153 const ProcessingConfig& api_format) {
154 webrtc::InternalAPMStreamsConfig result;
155 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
156 result.input_num_channels = api_format.input_stream().num_channels();
157 result.output_num_channels = api_format.output_stream().num_channels();
158 result.render_input_num_channels =
159 api_format.reverse_input_stream().num_channels();
160 result.render_input_sample_rate =
161 api_format.reverse_input_stream().sample_rate_hz();
162 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
163 result.render_output_sample_rate =
164 api_format.reverse_output_stream().sample_rate_hz();
165 result.render_output_num_channels =
166 api_format.reverse_output_stream().num_channels();
167 return result;
168}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700169} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000170
171// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000172static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000173
Sam Zackrisson0beac582017-09-25 12:04:02 +0200174AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates(
175 bool capture_post_processor_enabled)
176 : capture_post_processor_enabled_(capture_post_processor_enabled) {}
peah2ace3f92016-09-10 04:42:27 -0700177
178bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800179 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700180 bool echo_canceller_enabled,
181 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700182 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700183 bool noise_suppressor_enabled,
184 bool intelligibility_enhancer_enabled,
185 bool beamformer_enabled,
186 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700187 bool gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -0700188 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800189 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700190 bool voice_activity_detector_enabled,
191 bool level_estimator_enabled,
192 bool transient_suppressor_enabled) {
193 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800194 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700195 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
196 changed |=
197 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700198 changed |=
199 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700200 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
201 changed |=
202 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
203 changed |= (beamformer_enabled != beamformer_enabled_);
204 changed |=
205 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700206 changed |=
207 (gain_controller2_enabled != gain_controller2_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700208 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800209 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700210 changed |= (level_estimator_enabled != level_estimator_enabled_);
211 changed |=
212 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
213 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
214 if (changed) {
peah8271d042016-11-22 07:24:52 -0800215 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700216 echo_canceller_enabled_ = echo_canceller_enabled;
217 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700218 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700219 noise_suppressor_enabled_ = noise_suppressor_enabled;
220 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
221 beamformer_enabled_ = beamformer_enabled;
222 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700223 gain_controller2_enabled_ = gain_controller2_enabled;
peah2ace3f92016-09-10 04:42:27 -0700224 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800225 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700226 level_estimator_enabled_ = level_estimator_enabled;
227 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
228 transient_suppressor_enabled_ = transient_suppressor_enabled;
229 }
230
231 changed |= first_update_;
232 first_update_ = false;
233 return changed;
234}
235
236bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
237 const {
238#if WEBRTC_INTELLIGIBILITY_ENHANCER
239 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700240 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700241#else
peah52775842017-05-16 06:14:09 -0700242 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700243#endif
244}
245
246bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
247 const {
peah8271d042016-11-22 07:24:52 -0800248 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700249 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800250 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
251 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700252}
253
peah23ac8b42017-05-23 05:33:56 -0700254bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
255 const {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200256 return level_controller_enabled_ || capture_post_processor_enabled_;
peah23ac8b42017-05-23 05:33:56 -0700257}
258
peah2ace3f92016-09-10 04:42:27 -0700259bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
260 const {
261 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800262 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peah52775842017-05-16 06:14:09 -0700263 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700264}
265
266bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
267 const {
268#if WEBRTC_INTELLIGIBILITY_ENHANCER
269 return intelligibility_enhancer_enabled_;
270#else
271 return false;
272#endif
273}
274
solenberg5e465c32015-12-08 13:22:33 -0800275struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800276 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800277 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800278 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800279 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800280 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800281 std::unique_ptr<LevelEstimatorImpl> level_estimator;
282 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
283 std::unique_ptr<VoiceDetectionImpl> voice_detection;
284 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800285 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800286
287 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800288 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700289#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800290 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700291#endif
solenberg5e465c32015-12-08 13:22:33 -0800292};
293
294struct AudioProcessingImpl::ApmPrivateSubmodules {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200295 ApmPrivateSubmodules(NonlinearBeamformer* beamformer,
296 std::unique_ptr<PostProcessing> capture_post_processor)
297 : beamformer(beamformer),
298 capture_post_processor(std::move(capture_post_processor)) {}
solenberg5e465c32015-12-08 13:22:33 -0800299 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700300 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800301 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700302 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800303 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700304 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700305 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +0200306 std::unique_ptr<EchoControl> echo_controller;
Sam Zackrisson0beac582017-09-25 12:04:02 +0200307 std::unique_ptr<PostProcessing> capture_post_processor;
solenberg5e465c32015-12-08 13:22:33 -0800308};
309
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000310AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700311 webrtc::Config config;
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200312 return Create(config, nullptr, rtc::Callback1<EchoControl*, int>(), nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000313}
314
peah88ac8532016-09-12 16:47:25 -0700315AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200316 return Create(config, nullptr, rtc::Callback1<EchoControl*, int>(), nullptr);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000317}
318
peah88ac8532016-09-12 16:47:25 -0700319AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700320 NonlinearBeamformer* beamformer) {
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200321 return Create(config, nullptr, rtc::Callback1<EchoControl*, int>(),
322 beamformer);
Sam Zackrisson0beac582017-09-25 12:04:02 +0200323}
324
325AudioProcessing* AudioProcessing::Create(
326 const webrtc::Config& config,
327 std::unique_ptr<PostProcessing> capture_post_processor,
328 NonlinearBeamformer* beamformer) {
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200329 return Create(config, std::move(capture_post_processor),
330 rtc::Callback1<EchoControl*, int>(), beamformer);
331}
332
333AudioProcessing* AudioProcessing::Create(
334 const webrtc::Config& config,
335 std::unique_ptr<PostProcessing> capture_post_processor,
336 rtc::Callback1<EchoControl*, int> echo_control_factory,
337 NonlinearBeamformer* beamformer) {
Sam Zackrisson0beac582017-09-25 12:04:02 +0200338 AudioProcessingImpl* apm = new rtc::RefCountedObject<AudioProcessingImpl>(
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200339 config, std::move(capture_post_processor), echo_control_factory,
340 beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000341 if (apm->Initialize() != kNoError) {
342 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800343 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000344 }
345
346 return apm;
347}
348
peah88ac8532016-09-12 16:47:25 -0700349AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200350 : AudioProcessingImpl(config,
351 nullptr,
352 rtc::Callback1<EchoControl*, int>(),
353 nullptr) {}
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000354
Sam Zackrisson0beac582017-09-25 12:04:02 +0200355AudioProcessingImpl::AudioProcessingImpl(
356 const webrtc::Config& config,
357 std::unique_ptr<PostProcessing> capture_post_processor,
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200358 rtc::Callback1<EchoControl*, int> echo_control_factory,
Sam Zackrisson0beac582017-09-25 12:04:02 +0200359 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800360 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200361 echo_control_factory_(echo_control_factory),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200362 submodule_states_(!!capture_post_processor),
peah8271d042016-11-22 07:24:52 -0800363 public_submodules_(new ApmPublicSubmodules()),
Sam Zackrisson0beac582017-09-25 12:04:02 +0200364 private_submodules_(
365 new ApmPrivateSubmodules(beamformer,
366 std::move(capture_post_processor))),
peahdf3efa82015-11-28 12:35:15 -0800367 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800368 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000369#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700370 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000371#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700372 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000373#endif
andrew1c7075f2015-06-24 18:14:14 -0700374#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800375 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700376#else
aluebs2a346882016-01-11 18:04:30 -0800377 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700378#endif
aluebs2a346882016-01-11 18:04:30 -0800379 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800380 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700381 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700382 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800383 {
384 rtc::CritScope cs_render(&crit_render_);
385 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000386
peahb624d8c2016-03-05 03:01:14 -0800387 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700388 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800389 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700390 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800391 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700392 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800393 public_submodules_->level_estimator.reset(
394 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800395 public_submodules_->noise_suppression.reset(
396 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800397 public_submodules_->voice_detection.reset(
398 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800399 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800400 new GainControlForExperimentalAgc(
401 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700402 private_submodules_->residual_echo_detector.reset(
403 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700404
peahc19f3122016-10-07 14:54:10 -0700405 // TODO(peah): Move this creation to happen only when the level controller
406 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700407 private_submodules_->level_controller.reset(new LevelController());
Sam Zackrisson0beac582017-09-25 12:04:02 +0200408
409 LOG(LS_INFO) << "Capture post processor activated: "
410 << !!private_submodules_->capture_post_processor;
peahdf3efa82015-11-28 12:35:15 -0800411 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000412
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000413 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000414}
415
416AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800417 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800418 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800419 private_submodules_->agc_manager.reset();
420 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800421 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000422}
423
niklase@google.com470e71d2011-07-07 08:21:25 +0000424int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800425 // Run in a single-threaded manner during initialization.
426 rtc::CritScope cs_render(&crit_render_);
427 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000428 return InitializeLocked();
429}
430
peahde65ddc2016-09-16 15:02:15 -0700431int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
432 int capture_output_sample_rate_hz,
433 int render_input_sample_rate_hz,
434 ChannelLayout capture_input_layout,
435 ChannelLayout capture_output_layout,
436 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700437 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700438 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
439 LayoutHasKeyboard(capture_input_layout)},
440 {capture_output_sample_rate_hz,
441 ChannelsFromLayout(capture_output_layout),
442 LayoutHasKeyboard(capture_output_layout)},
443 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
444 LayoutHasKeyboard(render_input_layout)},
445 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
446 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700447
448 return Initialize(processing_config);
449}
450
451int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800452 // Run in a single-threaded manner during initialization.
453 rtc::CritScope cs_render(&crit_render_);
454 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700455 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000456}
457
peahdf3efa82015-11-28 12:35:15 -0800458int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800459 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700460 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800461}
462
peahdf3efa82015-11-28 12:35:15 -0800463int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700464 const ProcessingConfig& processing_config,
465 bool force_initialization) {
466 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800467}
468
peah192164e2015-11-17 02:16:45 -0800469// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800470// their current values (needs to be called while holding the crit_render_lock).
471int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700472 const ProcessingConfig& processing_config,
473 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800474 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700475 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800476 return kNoError;
477 }
peahdf3efa82015-11-28 12:35:15 -0800478
479 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800480 return InitializeLocked(processing_config);
481}
482
niklase@google.com470e71d2011-07-07 08:21:25 +0000483int AudioProcessingImpl::InitializeLocked() {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200484 UpdateActiveSubmoduleStates();
485
peah522d71b2017-02-23 05:16:26 -0800486 const int capture_audiobuffer_num_channels =
487 capture_nonlocked_.beamformer_enabled
488 ? formats_.api_format.input_stream().num_channels()
489 : formats_.api_format.output_stream().num_channels();
490
peahde65ddc2016-09-16 15:02:15 -0700491 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800492 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700493 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800494 : formats_.api_format.reverse_output_stream().num_frames();
495 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
496 render_.render_audio.reset(new AudioBuffer(
497 formats_.api_format.reverse_input_stream().num_frames(),
498 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700499 formats_.render_processing_format.num_frames(),
500 formats_.render_processing_format.num_channels(),
501 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700502 if (formats_.api_format.reverse_input_stream() !=
503 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800504 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800505 formats_.api_format.reverse_input_stream().num_channels(),
506 formats_.api_format.reverse_input_stream().num_frames(),
507 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800508 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700509 } else {
peahdf3efa82015-11-28 12:35:15 -0800510 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700511 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700512 } else {
peahdf3efa82015-11-28 12:35:15 -0800513 render_.render_audio.reset(nullptr);
514 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700515 }
peahce4d9152017-05-19 01:28:05 -0700516
peahdf3efa82015-11-28 12:35:15 -0800517 capture_.capture_audio.reset(
518 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
519 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700520 capture_nonlocked_.capture_processing_format.num_frames(),
521 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800522 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000523
peahde65ddc2016-09-16 15:02:15 -0700524 public_submodules_->echo_cancellation->Initialize(
525 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
526 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700527 AllocateRenderQueue();
528
ivoc3e9a5372016-10-28 07:55:33 -0700529 int success = public_submodules_->echo_cancellation->enable_metrics(true);
530 RTC_DCHECK_EQ(0, success);
531 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
532 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700533 public_submodules_->echo_control_mobile->Initialize(
534 proc_split_sample_rate_hz(), num_reverse_channels(),
535 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700536
537 public_submodules_->gain_control->Initialize(num_proc_channels(),
538 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700539 if (constants_.use_experimental_agc) {
540 if (!private_submodules_->agc_manager.get()) {
541 private_submodules_->agc_manager.reset(new AgcManagerDirect(
542 public_submodules_->gain_control.get(),
543 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800544 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700545 }
546 private_submodules_->agc_manager->Initialize();
547 private_submodules_->agc_manager->SetCaptureMuted(
548 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700549 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700550 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200551 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000552 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700553#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700554 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700555#endif
peah8271d042016-11-22 07:24:52 -0800556 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700557 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
558 proc_sample_rate_hz());
559 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
560 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700561 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700562 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800563 InitializeEchoCanceller3();
alessiob3ec96df2017-05-22 06:57:06 -0700564 InitializeGainController2();
Sam Zackrisson0beac582017-09-25 12:04:02 +0200565 InitializePostProcessor();
solenberg70f99032015-12-08 11:07:32 -0800566
aleloi868f32f2017-05-23 07:20:05 -0700567 if (aec_dump_) {
568 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
569 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000570 return kNoError;
571}
572
Michael Graczyk86c6d332015-07-23 11:41:39 -0700573int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
Per Ã…hgren4bdced52017-06-27 16:00:38 +0200574 UpdateActiveSubmoduleStates();
575
Michael Graczyk86c6d332015-07-23 11:41:39 -0700576 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700577 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
578 return kBadSampleRateError;
579 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000580 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700581
Peter Kasting69558702016-01-12 16:26:35 -0800582 const size_t num_in_channels = config.input_stream().num_channels();
583 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700584
585 // Need at least one input channel.
586 // Need either one output channel or as many outputs as there are inputs.
587 if (num_in_channels == 0 ||
588 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700589 return kBadNumberChannelsError;
590 }
591
aluebsb2328d12016-01-11 20:32:29 -0800592 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800593 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700594 return kBadNumberChannelsError;
595 }
596
peahdf3efa82015-11-28 12:35:15 -0800597 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000598
peahde65ddc2016-09-16 15:02:15 -0700599 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700600 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700601 formats_.api_format.output_stream().sample_rate_hz()),
602 submodule_states_.CaptureMultiBandSubModulesActive() ||
603 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000604
peahde65ddc2016-09-16 15:02:15 -0700605 capture_nonlocked_.capture_processing_format =
606 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700607
peah2ce640f2017-04-07 03:57:48 -0700608 int render_processing_rate;
609 if (!config_.echo_canceller3.enabled) {
610 render_processing_rate = FindNativeProcessRateToUse(
611 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
612 formats_.api_format.reverse_output_stream().sample_rate_hz()),
613 submodule_states_.CaptureMultiBandSubModulesActive() ||
614 submodule_states_.RenderMultiBandSubModulesActive());
615 } else {
616 render_processing_rate = capture_processing_rate;
617 }
618
aluebseb3603b2016-04-20 15:27:58 -0700619 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
620 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700621 if (render_processing_rate > kSampleRate32kHz &&
622 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700623 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
624 ? kSampleRate32kHz
625 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700626 }
peah2ce640f2017-04-07 03:57:48 -0700627
peahde65ddc2016-09-16 15:02:15 -0700628 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700629 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700630 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
631 kSampleRate8kHz) {
632 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000633 } else {
peahde65ddc2016-09-16 15:02:15 -0700634 render_processing_rate =
635 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000636 }
637
peahde65ddc2016-09-16 15:02:15 -0700638 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000639 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700640 if (submodule_states_.RenderMultiBandSubModulesActive()) {
641 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
642 } else {
643 formats_.render_processing_format = StreamConfig(
644 formats_.api_format.reverse_input_stream().sample_rate_hz(),
645 formats_.api_format.reverse_input_stream().num_channels());
646 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000647
peahde65ddc2016-09-16 15:02:15 -0700648 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
649 kSampleRate32kHz ||
650 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
651 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800652 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000653 } else {
peahdf3efa82015-11-28 12:35:15 -0800654 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700655 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000656 }
657
658 return InitializeLocked();
659}
660
peah88ac8532016-09-12 16:47:25 -0700661void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700662 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700663
peahc19f3122016-10-07 14:54:10 -0700664 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700665 if (!config_ok) {
666 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
667 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700668 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700669 << std::endl
670 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700671 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700672 }
673
674 // Run in a single-threaded manner when applying the settings.
675 rtc::CritScope cs_render(&crit_render_);
676 rtc::CritScope cs_capture(&crit_capture_);
677
peahc19f3122016-10-07 14:54:10 -0700678 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
679 // with the value in config_ everywhere in the code.
680 if (capture_nonlocked_.level_controller_enabled !=
681 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700682 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700683 config_.level_controller.enabled;
684 // TODO(peah): Remove the conditional initialization to always initialize
685 // the level controller regardless of whether it is enabled or not.
686 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700687 }
peahc19f3122016-10-07 14:54:10 -0700688 LOG(LS_INFO) << "Level controller activated: "
689 << capture_nonlocked_.level_controller_enabled;
690
691 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800692
693 InitializeLowCutFilter();
694
695 LOG(LS_INFO) << "Highpass filter activated: "
696 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800697
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200698 // TODO(gustaf): Do this outside of APM.
peahe0eae3c2016-12-14 01:16:23 -0800699 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
700 if (!config_ok) {
701 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
702 << "echo canceller 3: "
703 << EchoCanceller3::ToString(config_.echo_canceller3)
704 << std::endl
705 << "Reverting to default parameter set";
706 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
707 }
708
Gustaf Ullbergd8579e02017-10-11 16:29:02 +0200709 // TODO(gustaf): Enable EchoCanceller3 by injection, not configuration.
peahe0eae3c2016-12-14 01:16:23 -0800710 if (config.echo_canceller3.enabled !=
711 capture_nonlocked_.echo_canceller3_enabled) {
712 capture_nonlocked_.echo_canceller3_enabled =
713 config_.echo_canceller3.enabled;
714 InitializeEchoCanceller3();
715 LOG(LS_INFO) << "Echo canceller 3 activated: "
716 << capture_nonlocked_.echo_canceller3_enabled;
717 }
alessiob3ec96df2017-05-22 06:57:06 -0700718
719 config_ok = GainController2::Validate(config_.gain_controller2);
720 if (!config_ok) {
721 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
722 << "gain_controller2: "
723 << GainController2::ToString(config_.gain_controller2)
724 << std::endl
725 << "Reverting to default parameter set";
726 config_.gain_controller2 = AudioProcessing::Config::GainController2();
727 }
728
729 if (config.gain_controller2.enabled !=
730 capture_nonlocked_.gain_controller2_enabled) {
731 capture_nonlocked_.gain_controller2_enabled =
732 config_.gain_controller2.enabled;
733 InitializeGainController2();
734 LOG(LS_INFO) << "Gain controller 2 activated: "
735 << capture_nonlocked_.gain_controller2_enabled;
736 }
peah88ac8532016-09-12 16:47:25 -0700737}
738
739void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800740 // Run in a single-threaded manner when setting the extra options.
741 rtc::CritScope cs_render(&crit_render_);
742 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000743
peahb624d8c2016-03-05 03:01:14 -0800744 public_submodules_->echo_cancellation->SetExtraOptions(config);
745
peahdf3efa82015-11-28 12:35:15 -0800746 if (capture_.transient_suppressor_enabled !=
747 config.Get<ExperimentalNs>().enabled) {
748 capture_.transient_suppressor_enabled =
749 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000750 InitializeTransient();
751 }
aluebs2a346882016-01-11 18:04:30 -0800752
peah1bcfce52016-08-26 07:16:04 -0700753#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700754 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700755 config.Get<Intelligibility>().enabled) {
756 capture_nonlocked_.intelligibility_enabled =
757 config.Get<Intelligibility>().enabled;
758 InitializeIntelligibility();
759 }
peah1bcfce52016-08-26 07:16:04 -0700760#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700761
aluebs2a346882016-01-11 18:04:30 -0800762#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800763 if (capture_nonlocked_.beamformer_enabled !=
764 config.Get<Beamforming>().enabled) {
765 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800766 if (config.Get<Beamforming>().array_geometry.size() > 1) {
767 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
768 }
769 capture_.target_direction = config.Get<Beamforming>().target_direction;
770 InitializeBeamformer();
771 }
772#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000773}
774
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000775int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800776 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700777 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000778}
779
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000780int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800781 // Used as callback from submodules, hence locking is not allowed.
782 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000783}
784
Peter Kasting69558702016-01-12 16:26:35 -0800785size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800786 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700787 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000788}
789
Peter Kasting69558702016-01-12 16:26:35 -0800790size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800791 // Used as callback from submodules, hence locking is not allowed.
792 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000793}
794
Peter Kasting69558702016-01-12 16:26:35 -0800795size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800796 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700797 return (capture_nonlocked_.beamformer_enabled ||
798 capture_nonlocked_.echo_canceller3_enabled)
799 ? 1
800 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800801}
802
Peter Kasting69558702016-01-12 16:26:35 -0800803size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800804 // Used as callback from submodules, hence locking is not allowed.
805 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000806}
807
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000808void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800809 rtc::CritScope cs(&crit_capture_);
810 capture_.output_will_be_muted = muted;
811 if (private_submodules_->agc_manager.get()) {
812 private_submodules_->agc_manager->SetCaptureMuted(
813 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000814 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000815}
816
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000817
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000818int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700819 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000820 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000821 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000822 int output_sample_rate_hz,
823 ChannelLayout output_layout,
824 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800825 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800826 StreamConfig input_stream;
827 StreamConfig output_stream;
828 {
829 // Access the formats_.api_format.input_stream beneath the capture lock.
830 // The lock must be released as it is later required in the call
831 // to ProcessStream(,,,);
832 rtc::CritScope cs(&crit_capture_);
833 input_stream = formats_.api_format.input_stream();
834 output_stream = formats_.api_format.output_stream();
835 }
836
Michael Graczyk86c6d332015-07-23 11:41:39 -0700837 input_stream.set_sample_rate_hz(input_sample_rate_hz);
838 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
839 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700840 output_stream.set_sample_rate_hz(output_sample_rate_hz);
841 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
842 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
843
844 if (samples_per_channel != input_stream.num_frames()) {
845 return kBadDataLengthError;
846 }
847 return ProcessStream(src, input_stream, output_stream, dest);
848}
849
850int AudioProcessingImpl::ProcessStream(const float* const* src,
851 const StreamConfig& input_config,
852 const StreamConfig& output_config,
853 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800854 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800855 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700856 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800857 {
858 // Acquire the capture lock in order to safely call the function
859 // that retrieves the render side data. This function accesses apm
860 // getters that need the capture lock held when being called.
861 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700862 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800863
864 if (!src || !dest) {
865 return kNullPointerError;
866 }
867
868 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700869 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000870 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000871
Michael Graczyk86c6d332015-07-23 11:41:39 -0700872 processing_config.input_stream() = input_config;
873 processing_config.output_stream() = output_config;
874
peahdf3efa82015-11-28 12:35:15 -0800875 {
876 // Do conditional reinitialization.
877 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700878 RETURN_ON_ERR(
879 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800880 }
881 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700882 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
883 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000884
aleloi868f32f2017-05-23 07:20:05 -0700885 if (aec_dump_) {
886 RecordUnprocessedCaptureStream(src);
887 }
888
peahdf3efa82015-11-28 12:35:15 -0800889 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700890 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800891 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000892
aleloi868f32f2017-05-23 07:20:05 -0700893 if (aec_dump_) {
894 RecordProcessedCaptureStream(dest);
895 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000896 return kNoError;
897}
898
peah9e6a2902017-05-15 07:19:21 -0700899void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700900 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
901 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700902 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700903
kwibergaf476c72016-11-28 15:21:39 -0800904 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700905
906 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700907 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700908 // The data queue is full and needs to be emptied.
909 EmptyQueuedRenderAudio();
910
911 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700912 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700913 RTC_DCHECK(result);
914 }
915
916 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
917 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700918 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700919
920 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700921 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700922 // The data queue is full and needs to be emptied.
923 EmptyQueuedRenderAudio();
924
925 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700926 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700927 RTC_DCHECK(result);
928 }
peah701d6282016-10-25 05:42:20 -0700929
930 if (!constants_.use_experimental_agc) {
931 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
932 // Insert the samples into the queue.
933 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
934 // The data queue is full and needs to be emptied.
935 EmptyQueuedRenderAudio();
936
937 // Retry the insert (should always work).
938 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
939 RTC_DCHECK(result);
940 }
941 }
peah9e6a2902017-05-15 07:19:21 -0700942}
ivoc9f4a4a02016-10-28 05:39:16 -0700943
peah9e6a2902017-05-15 07:19:21 -0700944void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700945 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
946
947 // Insert the samples into the queue.
948 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
949 // The data queue is full and needs to be emptied.
950 EmptyQueuedRenderAudio();
951
952 // Retry the insert (should always work).
953 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
954 RTC_DCHECK(result);
955 }
peah764e3642016-10-22 05:04:30 -0700956}
957
958void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700959 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700960 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700961 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700962 EchoCancellationImpl::NumCancellersRequired(
963 num_output_channels(), num_reverse_channels()));
964
peah701d6282016-10-25 05:42:20 -0700965 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700966 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700967 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700968 EchoControlMobileImpl::NumCancellersRequired(
969 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700970
peah701d6282016-10-25 05:42:20 -0700971 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700972 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700973
ivoc9f4a4a02016-10-28 05:39:16 -0700974 const size_t new_red_render_queue_element_max_size =
975 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
976
peaha0624602016-10-25 04:45:24 -0700977 // Reallocate the queues if the queue item sizes are too small to fit the
978 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700979 if (aec_render_queue_element_max_size_ <
980 new_aec_render_queue_element_max_size) {
981 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700982
peaha0624602016-10-25 04:45:24 -0700983 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700984 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700985
peah701d6282016-10-25 05:42:20 -0700986 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700987 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
988 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700989 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700990 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700991
peah701d6282016-10-25 05:42:20 -0700992 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
993 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700994 } else {
peah701d6282016-10-25 05:42:20 -0700995 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700996 }
997
peah701d6282016-10-25 05:42:20 -0700998 if (aecm_render_queue_element_max_size_ <
999 new_aecm_render_queue_element_max_size) {
1000 aecm_render_queue_element_max_size_ =
1001 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001002
1003 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001004 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001005
peah701d6282016-10-25 05:42:20 -07001006 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001007 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1008 kMaxNumFramesToBuffer, template_queue_element,
1009 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001010 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001011
peah701d6282016-10-25 05:42:20 -07001012 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1013 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001014 } else {
peah701d6282016-10-25 05:42:20 -07001015 aecm_render_signal_queue_->Clear();
1016 }
1017
1018 if (agc_render_queue_element_max_size_ <
1019 new_agc_render_queue_element_max_size) {
1020 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1021
1022 std::vector<int16_t> template_queue_element(
1023 agc_render_queue_element_max_size_);
1024
1025 agc_render_signal_queue_.reset(
1026 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1027 kMaxNumFramesToBuffer, template_queue_element,
1028 RenderQueueItemVerifier<int16_t>(
1029 agc_render_queue_element_max_size_)));
1030
1031 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1032 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1033 } else {
1034 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001035 }
ivoc9f4a4a02016-10-28 05:39:16 -07001036
1037 if (red_render_queue_element_max_size_ <
1038 new_red_render_queue_element_max_size) {
1039 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1040
1041 std::vector<float> template_queue_element(
1042 red_render_queue_element_max_size_);
1043
1044 red_render_signal_queue_.reset(
1045 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1046 kMaxNumFramesToBuffer, template_queue_element,
1047 RenderQueueItemVerifier<float>(
1048 red_render_queue_element_max_size_)));
1049
1050 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1051 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1052 } else {
1053 red_render_signal_queue_->Clear();
1054 }
peah764e3642016-10-22 05:04:30 -07001055}
1056
1057void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1058 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001059 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001060 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001061 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001062 }
1063
peah701d6282016-10-25 05:42:20 -07001064 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001065 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001066 aecm_capture_queue_buffer_);
1067 }
1068
1069 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1070 public_submodules_->gain_control->ProcessRenderAudio(
1071 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001072 }
ivoc9f4a4a02016-10-28 05:39:16 -07001073
1074 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1075 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1076 red_capture_queue_buffer_);
1077 }
peah764e3642016-10-22 05:04:30 -07001078}
1079
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001080int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001081 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001082 {
1083 // Acquire the capture lock in order to safely call the function
1084 // that retrieves the render side data. This function accesses apm
1085 // getters that need the capture lock held when being called.
1086 // The lock needs to be released as
1087 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1088 // as well.
1089 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001090 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001091 }
peahfa6228e2015-11-16 16:27:42 -08001092
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001093 if (!frame) {
1094 return kNullPointerError;
1095 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001096 // Must be a native rate.
1097 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1098 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001099 frame->sample_rate_hz_ != kSampleRate32kHz &&
1100 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001101 return kBadSampleRateError;
1102 }
peah192164e2015-11-17 02:16:45 -08001103
peahdf3efa82015-11-28 12:35:15 -08001104 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001105 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001106 {
1107 // Aquire lock for the access of api_format.
1108 // The lock is released immediately due to the conditional
1109 // reinitialization.
1110 rtc::CritScope cs_capture(&crit_capture_);
1111 // TODO(ajm): The input and output rates and channels are currently
1112 // constrained to be identical in the int16 interface.
1113 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001114
1115 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001116 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001117 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1118 processing_config.input_stream().set_num_channels(frame->num_channels_);
1119 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1120 processing_config.output_stream().set_num_channels(frame->num_channels_);
1121
peahdf3efa82015-11-28 12:35:15 -08001122 {
1123 // Do conditional reinitialization.
1124 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001125 RETURN_ON_ERR(
1126 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001127 }
1128 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001129 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001130 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001131 return kBadDataLengthError;
1132 }
1133
aleloi868f32f2017-05-23 07:20:05 -07001134 if (aec_dump_) {
1135 RecordUnprocessedCaptureStream(*frame);
1136 }
1137
peahdf3efa82015-11-28 12:35:15 -08001138 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001139 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001140 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001141 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1142 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001143
aleloi868f32f2017-05-23 07:20:05 -07001144 if (aec_dump_) {
1145 RecordProcessedCaptureStream(*frame);
1146 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001147
1148 return kNoError;
1149}
1150
peahde65ddc2016-09-16 15:02:15 -07001151int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001152 // Ensure that not both the AEC and AECM are active at the same time.
1153 // TODO(peah): Simplify once the public API Enable functions for these
1154 // are moved to APM.
1155 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1156 public_submodules_->echo_control_mobile->is_enabled()));
1157
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001158 MaybeUpdateHistograms();
1159
peahde65ddc2016-09-16 15:02:15 -07001160 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001161
peah1b08dc32016-12-20 13:45:58 -08001162 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001163 capture_buffer->channels_const()[0],
1164 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001165 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1166 if (log_rms) {
1167 capture_rms_interval_counter_ = 0;
1168 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001169 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1170 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1171 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1172 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001173 }
1174
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001175 if (private_submodules_->echo_controller) {
Per Ã…hgren9aed31c2017-06-29 20:23:27 +02001176 // TODO(peah): Reactivate analogue AGC gain detection once the analogue AGC
1177 // issues have been addressed.
1178 capture_.echo_path_gain_change = false;
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001179 private_submodules_->echo_controller->AnalyzeCapture(capture_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001180 }
1181
peahbe615622016-02-13 16:40:47 -08001182 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001183 public_submodules_->gain_control->is_enabled()) {
1184 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001185 capture_buffer->channels()[0], capture_buffer->num_channels(),
1186 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001187 }
1188
peah2ace3f92016-09-10 04:42:27 -07001189 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1190 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001191 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1192 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001193 }
1194
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001195 if (private_submodules_->echo_controller) {
peah522d71b2017-02-23 05:16:26 -08001196 // Force down-mixing of the number of channels after the detection of
1197 // capture signal saturation.
1198 // TODO(peah): Look into ensuring that this kind of tampering with the
1199 // AudioBuffer functionality should not be needed.
1200 capture_buffer->set_num_channels(1);
1201 }
1202
aluebsb2328d12016-01-11 20:32:29 -08001203 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001204 private_submodules_->beamformer->AnalyzeChunk(
1205 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001206 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001207 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001208 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001209
peahe0eae3c2016-12-14 01:16:23 -08001210 // TODO(peah): Move the AEC3 low-cut filter to this place.
1211 if (private_submodules_->low_cut_filter &&
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001212 !private_submodules_->echo_controller) {
peah8271d042016-11-22 07:24:52 -08001213 private_submodules_->low_cut_filter->Process(capture_buffer);
1214 }
peahde65ddc2016-09-16 15:02:15 -07001215 RETURN_ON_ERR(
1216 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1217 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001218
1219 // Ensure that the stream delay was set before the call to the
1220 // AEC ProcessCaptureAudio function.
1221 if (public_submodules_->echo_cancellation->is_enabled() &&
1222 !was_stream_delay_set()) {
1223 return AudioProcessing::kStreamParameterNotSetError;
1224 }
1225
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001226 if (private_submodules_->echo_controller) {
1227 private_submodules_->echo_controller->ProcessCapture(
peah67995532017-04-10 14:12:41 -07001228 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001229 } else {
1230 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1231 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001232 }
1233
peahdf3efa82015-11-28 12:35:15 -08001234 if (public_submodules_->echo_control_mobile->is_enabled() &&
1235 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001236 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001237 }
peahde65ddc2016-09-16 15:02:15 -07001238 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001239#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001240 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001241 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001242 int gain_db = public_submodules_->gain_control->is_enabled() ?
1243 public_submodules_->gain_control->compression_gain_db() :
1244 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001245 float gain = std::pow(10.f, gain_db / 20.f);
1246 gain *= capture_nonlocked_.level_controller_enabled ?
1247 private_submodules_->level_controller->GetLastGain() :
1248 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001249 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001250 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001251 }
peah1bcfce52016-08-26 07:16:04 -07001252#endif
peah253534d2016-03-15 04:32:28 -07001253
1254 // Ensure that the stream delay was set before the call to the
1255 // AECM ProcessCaptureAudio function.
1256 if (public_submodules_->echo_control_mobile->is_enabled() &&
1257 !was_stream_delay_set()) {
1258 return AudioProcessing::kStreamParameterNotSetError;
1259 }
1260
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001261 if (!(private_submodules_->echo_controller ||
Per Ã…hgren46537a32017-06-07 10:08:10 +02001262 public_submodules_->echo_cancellation->is_enabled())) {
1263 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1264 capture_buffer, stream_delay_ms()));
1265 }
ivoc9f4a4a02016-10-28 05:39:16 -07001266
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001267 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001268 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001269 }
1270
peahde65ddc2016-09-16 15:02:15 -07001271 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001272
peahbe615622016-02-13 16:40:47 -08001273 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001274 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001275 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001276 private_submodules_->beamformer->is_target_present())) {
1277 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001278 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1279 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001280 }
peahb8fbb542016-03-15 02:28:08 -07001281 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001282 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001283
peah2ace3f92016-09-10 04:42:27 -07001284 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1285 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001286 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1287 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001288 }
1289
peah9e6a2902017-05-15 07:19:21 -07001290 if (config_.residual_echo_detector.enabled) {
1291 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1292 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1293 capture_buffer->num_frames()));
1294 }
1295
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001296 // TODO(aluebs): Investigate if the transient suppression placement should be
1297 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001298 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001299 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001300 private_submodules_->agc_manager.get()
1301 ? private_submodules_->agc_manager->voice_probability()
1302 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001303
peahdf3efa82015-11-28 12:35:15 -08001304 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001305 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1306 capture_buffer->num_channels(),
1307 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1308 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1309 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001310 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001311 }
1312
alessiob3ec96df2017-05-22 06:57:06 -07001313 if (capture_nonlocked_.gain_controller2_enabled) {
1314 private_submodules_->gain_controller2->Process(capture_buffer);
1315 }
1316
peahca4cac72016-06-29 15:26:12 -07001317 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001318 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001319 }
1320
Sam Zackrisson0beac582017-09-25 12:04:02 +02001321 if (private_submodules_->capture_post_processor) {
1322 private_submodules_->capture_post_processor->Process(capture_buffer);
1323 }
1324
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001325 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001326 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001327
peah1b08dc32016-12-20 13:45:58 -08001328 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1329 capture_buffer->channels_const()[0],
1330 capture_nonlocked_.capture_processing_format.num_frames()));
1331 if (log_rms) {
1332 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1333 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1334 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1335 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1336 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1337 }
1338
peahdf3efa82015-11-28 12:35:15 -08001339 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001340 return kNoError;
1341}
1342
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001343int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001344 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001345 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001346 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001347 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001348 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001349 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001350 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001351 };
1352 if (samples_per_channel != reverse_config.num_frames()) {
1353 return kBadDataLengthError;
1354 }
peahdf3efa82015-11-28 12:35:15 -08001355 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001356}
1357
peahde65ddc2016-09-16 15:02:15 -07001358int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1359 const StreamConfig& input_config,
1360 const StreamConfig& output_config,
1361 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001362 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001363 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001364 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001365 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001366 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1367 dest);
peah2ace3f92016-09-10 04:42:27 -07001368 } else if (formats_.api_format.reverse_input_stream() !=
1369 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001370 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1371 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001372 } else {
peahde65ddc2016-09-16 15:02:15 -07001373 CopyAudioIfNeeded(src, input_config.num_frames(),
1374 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001375 }
1376
1377 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001378}
1379
peahdf3efa82015-11-28 12:35:15 -08001380int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001381 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001382 const StreamConfig& input_config,
1383 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001384 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001385 return kNullPointerError;
1386 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001387
peahde65ddc2016-09-16 15:02:15 -07001388 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001389 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001390 }
1391
peahdf3efa82015-11-28 12:35:15 -08001392 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001393 processing_config.reverse_input_stream() = input_config;
1394 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001395
peahdf3efa82015-11-28 12:35:15 -08001396 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001397 assert(input_config.num_frames() ==
1398 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001399
aleloi868f32f2017-05-23 07:20:05 -07001400 if (aec_dump_) {
1401 const size_t channel_size =
1402 formats_.api_format.reverse_input_stream().num_frames();
1403 const size_t num_channels =
1404 formats_.api_format.reverse_input_stream().num_channels();
1405 aec_dump_->WriteRenderStreamMessage(
1406 FloatAudioFrame(src, num_channels, channel_size));
1407 }
peahdf3efa82015-11-28 12:35:15 -08001408 render_.render_audio->CopyFrom(src,
1409 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001410 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001411}
1412
1413int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001414 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001415 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001416 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001417 return kNullPointerError;
1418 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001419 // Must be a native rate.
1420 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1421 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001422 frame->sample_rate_hz_ != kSampleRate32kHz &&
1423 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001424 return kBadSampleRateError;
1425 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001426
Michael Graczyk86c6d332015-07-23 11:41:39 -07001427 if (frame->num_channels_ <= 0) {
1428 return kBadNumberChannelsError;
1429 }
1430
peahdf3efa82015-11-28 12:35:15 -08001431 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001432 processing_config.reverse_input_stream().set_sample_rate_hz(
1433 frame->sample_rate_hz_);
1434 processing_config.reverse_input_stream().set_num_channels(
1435 frame->num_channels_);
1436 processing_config.reverse_output_stream().set_sample_rate_hz(
1437 frame->sample_rate_hz_);
1438 processing_config.reverse_output_stream().set_num_channels(
1439 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001440
peahdf3efa82015-11-28 12:35:15 -08001441 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001442 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001443 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001444 return kBadDataLengthError;
1445 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001446
aleloi868f32f2017-05-23 07:20:05 -07001447 if (aec_dump_) {
1448 aec_dump_->WriteRenderStreamMessage(*frame);
1449 }
1450
peahdf3efa82015-11-28 12:35:15 -08001451 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001452 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001453 render_.render_audio->InterleaveTo(
1454 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001455 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001456}
niklase@google.com470e71d2011-07-07 08:21:25 +00001457
peahde65ddc2016-09-16 15:02:15 -07001458int AudioProcessingImpl::ProcessRenderStreamLocked() {
1459 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001460
1461 QueueNonbandedRenderAudio(render_buffer);
1462
peah2ace3f92016-09-10 04:42:27 -07001463 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001464 SampleRateSupportsMultiBand(
1465 formats_.render_processing_format.sample_rate_hz())) {
1466 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001467 }
1468
peah1bcfce52016-08-26 07:16:04 -07001469#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001470 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001471 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001472 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001473 }
peah1bcfce52016-08-26 07:16:04 -07001474#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001475
peahce4d9152017-05-19 01:28:05 -07001476 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1477 QueueBandedRenderAudio(render_buffer);
1478 }
1479
peahe0eae3c2016-12-14 01:16:23 -08001480 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001481 if (private_submodules_->echo_controller) {
1482 private_submodules_->echo_controller->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001483 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001484
peah2ace3f92016-09-10 04:42:27 -07001485 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001486 SampleRateSupportsMultiBand(
1487 formats_.render_processing_format.sample_rate_hz())) {
1488 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001489 }
1490
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001491 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001492}
1493
1494int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001495 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001496 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001497 capture_.was_stream_delay_set = true;
1498 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001499
niklase@google.com470e71d2011-07-07 08:21:25 +00001500 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001501 delay = 0;
1502 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001503 }
1504
1505 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1506 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001507 delay = 500;
1508 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001509 }
1510
peahdf3efa82015-11-28 12:35:15 -08001511 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001512 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001513}
1514
1515int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001516 // Used as callback from submodules, hence locking is not allowed.
1517 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001518}
1519
1520bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001521 // Used as callback from submodules, hence locking is not allowed.
1522 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001523}
1524
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001525void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001526 rtc::CritScope cs(&crit_capture_);
1527 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001528}
1529
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001530void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001531 rtc::CritScope cs(&crit_capture_);
1532 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001533}
1534
1535int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001536 rtc::CritScope cs(&crit_capture_);
1537 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001538}
1539
aleloi868f32f2017-05-23 07:20:05 -07001540void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1541 RTC_DCHECK(aec_dump);
1542 rtc::CritScope cs_render(&crit_render_);
1543 rtc::CritScope cs_capture(&crit_capture_);
1544
1545 // The previously attached AecDump will be destroyed with the
1546 // 'aec_dump' parameter, which is after locks are released.
1547 aec_dump_.swap(aec_dump);
1548 WriteAecDumpConfigMessage(true);
1549 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1550}
1551
1552void AudioProcessingImpl::DetachAecDump() {
1553 // The d-tor of a task-queue based AecDump blocks until all pending
1554 // tasks are done. This construction avoids blocking while holding
1555 // the render and capture locks.
1556 std::unique_ptr<AecDump> aec_dump = nullptr;
1557 {
1558 rtc::CritScope cs_render(&crit_render_);
1559 rtc::CritScope cs_capture(&crit_capture_);
1560 aec_dump = std::move(aec_dump_);
1561 }
1562}
1563
ivoc4e477a12017-01-15 08:29:46 -08001564AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1565 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1566 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1567 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1568 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1569}
1570
1571AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1572 const AudioProcessingStatistics& other) = default;
1573
1574AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1575 default;
1576
ivoc3e9a5372016-10-28 07:55:33 -07001577// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1578AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1579 const {
1580 return AudioProcessingStatistics();
1581}
1582
1583AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1584 const {
1585 AudioProcessingStatistics stats;
1586 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001587 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1588 if (success == Error::kNoError) {
1589 stats.a_nlp.Set(metrics.a_nlp);
1590 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1591 stats.echo_return_loss.Set(metrics.echo_return_loss);
1592 stats.echo_return_loss_enhancement.Set(
1593 metrics.echo_return_loss_enhancement);
1594 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1595 }
ivoc9c192b22017-03-16 04:22:14 -07001596 {
1597 rtc::CritScope cs_capture(&crit_capture_);
1598 stats.residual_echo_likelihood =
1599 private_submodules_->residual_echo_detector->echo_likelihood();
1600 stats.residual_echo_likelihood_recent_max =
1601 private_submodules_->residual_echo_detector
1602 ->echo_likelihood_recent_max();
1603 }
ivoc3e9a5372016-10-28 07:55:33 -07001604 public_submodules_->echo_cancellation->GetDelayMetrics(
1605 &stats.delay_median, &stats.delay_standard_deviation,
1606 &stats.fraction_poor_delays);
1607 return stats;
1608}
1609
niklase@google.com470e71d2011-07-07 08:21:25 +00001610EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001611 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001612}
1613
1614EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001615 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001616}
1617
1618GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001619 if (constants_.use_experimental_agc) {
1620 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001621 }
peahbfa97112016-03-10 21:09:04 -08001622 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001623}
1624
1625HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001626 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001627}
1628
1629LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001630 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001631}
1632
1633NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001634 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001635}
1636
1637VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001638 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001639}
1640
peah8271d042016-11-22 07:24:52 -08001641void AudioProcessingImpl::MutateConfig(
1642 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1643 rtc::CritScope cs_render(&crit_render_);
1644 rtc::CritScope cs_capture(&crit_capture_);
1645 mutator(&config_);
1646 ApplyConfig(config_);
1647}
1648
1649AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1650 rtc::CritScope cs_render(&crit_render_);
1651 rtc::CritScope cs_capture(&crit_capture_);
1652 return config_;
1653}
1654
peah2ace3f92016-09-10 04:42:27 -07001655bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1656 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001657 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001658 public_submodules_->echo_cancellation->is_enabled(),
1659 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001660 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001661 public_submodules_->noise_suppression->is_enabled(),
1662 capture_nonlocked_.intelligibility_enabled,
1663 capture_nonlocked_.beamformer_enabled,
1664 public_submodules_->gain_control->is_enabled(),
alessiob3ec96df2017-05-22 06:57:06 -07001665 capture_nonlocked_.gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -07001666 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001667 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001668 public_submodules_->voice_detection->is_enabled(),
1669 public_submodules_->level_estimator->is_enabled(),
1670 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001671}
1672
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001673
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001674void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001675 if (capture_.transient_suppressor_enabled) {
1676 if (!public_submodules_->transient_suppressor.get()) {
1677 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001678 }
peahdf3efa82015-11-28 12:35:15 -08001679 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001680 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1681 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001682 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001683}
1684
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001685void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001686 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001687 if (!private_submodules_->beamformer) {
1688 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001689 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001690 }
peahdf3efa82015-11-28 12:35:15 -08001691 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1692 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001693 }
1694}
1695
ekmeyerson60d9b332015-08-14 10:35:55 -07001696void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001697#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001698 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001699 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001700 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001701 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001702 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001703 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001704 }
peah1bcfce52016-08-26 07:16:04 -07001705#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001706}
1707
peah8271d042016-11-22 07:24:52 -08001708void AudioProcessingImpl::InitializeLowCutFilter() {
1709 if (config_.high_pass_filter.enabled) {
1710 private_submodules_->low_cut_filter.reset(
1711 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1712 } else {
1713 private_submodules_->low_cut_filter.reset();
1714 }
1715}
alessiob3ec96df2017-05-22 06:57:06 -07001716
peahe0eae3c2016-12-14 01:16:23 -08001717void AudioProcessingImpl::InitializeEchoCanceller3() {
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02001718 if (!echo_control_factory_.empty()) {
1719 private_submodules_->echo_controller.reset(
1720 echo_control_factory_(proc_sample_rate_hz()));
1721 } else if (capture_nonlocked_.echo_canceller3_enabled) {
1722 // TODO(gustaf): Remove once injection is used.
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001723 private_submodules_->echo_controller.reset(new EchoCanceller3(
peah697a5902017-06-30 07:06:10 -07001724 config_.echo_canceller3, proc_sample_rate_hz(), true));
peahe0eae3c2016-12-14 01:16:23 -08001725 } else {
Gustaf Ullberg59ff0e22017-10-09 10:20:34 +02001726 private_submodules_->echo_controller.reset();
peahe0eae3c2016-12-14 01:16:23 -08001727 }
1728}
peah8271d042016-11-22 07:24:52 -08001729
alessiob3ec96df2017-05-22 06:57:06 -07001730void AudioProcessingImpl::InitializeGainController2() {
1731 if (capture_nonlocked_.gain_controller2_enabled) {
1732 private_submodules_->gain_controller2.reset(
1733 new GainController2(proc_sample_rate_hz()));
1734 } else {
1735 private_submodules_->gain_controller2.reset();
1736 }
1737}
1738
peahca4cac72016-06-29 15:26:12 -07001739void AudioProcessingImpl::InitializeLevelController() {
1740 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1741}
1742
ivoc9f4a4a02016-10-28 05:39:16 -07001743void AudioProcessingImpl::InitializeResidualEchoDetector() {
1744 private_submodules_->residual_echo_detector->Initialize();
1745}
1746
Sam Zackrisson0beac582017-09-25 12:04:02 +02001747void AudioProcessingImpl::InitializePostProcessor() {
1748 if (private_submodules_->capture_post_processor) {
1749 private_submodules_->capture_post_processor->Initialize(
1750 proc_sample_rate_hz(), num_proc_channels());
1751 }
1752}
1753
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001754void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001755 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001756
1757 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001758 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1759 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001760 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001761 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001762 capture_.stream_delay_jumps = 0;
1763 }
1764 if (capture_.aec_system_delay_jumps == -1 &&
1765 echo_cancellation()->stream_has_echo()) {
1766 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001767 }
1768
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001769 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001770 const int diff_stream_delay_ms =
1771 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1772 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1773 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001774 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1775 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001776 if (capture_.stream_delay_jumps == -1) {
1777 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001778 }
peahdf3efa82015-11-28 12:35:15 -08001779 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001780 }
peahdf3efa82015-11-28 12:35:15 -08001781 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001782
1783 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001784 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001785 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001786 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001787 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001788 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1789 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001790 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001791 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001792 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001793 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001794 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1795 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1796 100);
peahdf3efa82015-11-28 12:35:15 -08001797 if (capture_.aec_system_delay_jumps == -1) {
1798 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001799 }
peahdf3efa82015-11-28 12:35:15 -08001800 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001801 }
peahdf3efa82015-11-28 12:35:15 -08001802 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001803 }
1804}
1805
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001806void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001807 // Run in a single-threaded manner.
1808 rtc::CritScope cs_render(&crit_render_);
1809 rtc::CritScope cs_capture(&crit_capture_);
1810
1811 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001812 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001813 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001814 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001815 }
peahdf3efa82015-11-28 12:35:15 -08001816 capture_.stream_delay_jumps = -1;
1817 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001818
peahdf3efa82015-11-28 12:35:15 -08001819 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001820 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1821 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001822 }
peahdf3efa82015-11-28 12:35:15 -08001823 capture_.aec_system_delay_jumps = -1;
1824 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001825}
1826
aleloi868f32f2017-05-23 07:20:05 -07001827void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1828 if (!aec_dump_) {
1829 return;
1830 }
1831 std::string experiments_description =
1832 public_submodules_->echo_cancellation->GetExperimentsDescription();
1833 // TODO(peah): Add semicolon-separated concatenations of experiment
1834 // descriptions for other submodules.
1835 if (capture_nonlocked_.level_controller_enabled) {
1836 experiments_description += "LevelController;";
1837 }
1838 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1839 experiments_description += "AgcClippingLevelExperiment;";
1840 }
1841 if (capture_nonlocked_.echo_canceller3_enabled) {
1842 experiments_description += "EchoCanceller3;";
1843 }
1844
1845 InternalAPMConfig apm_config;
1846
1847 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1848 apm_config.aec_delay_agnostic_enabled =
1849 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1850 apm_config.aec_drift_compensation_enabled =
1851 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
1852 apm_config.aec_extended_filter_enabled =
1853 public_submodules_->echo_cancellation->is_extended_filter_enabled();
1854 apm_config.aec_suppression_level = static_cast<int>(
1855 public_submodules_->echo_cancellation->suppression_level());
1856
1857 apm_config.aecm_enabled =
1858 public_submodules_->echo_control_mobile->is_enabled();
1859 apm_config.aecm_comfort_noise_enabled =
1860 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
1861 apm_config.aecm_routing_mode =
1862 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
1863
1864 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
1865 apm_config.agc_mode =
1866 static_cast<int>(public_submodules_->gain_control->mode());
1867 apm_config.agc_limiter_enabled =
1868 public_submodules_->gain_control->is_limiter_enabled();
1869 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
1870
1871 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
1872
1873 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
1874 apm_config.ns_level =
1875 static_cast<int>(public_submodules_->noise_suppression->level());
1876
1877 apm_config.transient_suppression_enabled =
1878 capture_.transient_suppressor_enabled;
1879 apm_config.intelligibility_enhancer_enabled =
1880 capture_nonlocked_.intelligibility_enabled;
1881 apm_config.experiments_description = experiments_description;
1882
1883 if (!forced && apm_config == apm_config_for_aec_dump_) {
1884 return;
1885 }
1886 aec_dump_->WriteConfig(apm_config);
1887 apm_config_for_aec_dump_ = apm_config;
1888}
1889
1890void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1891 const float* const* src) {
1892 RTC_DCHECK(aec_dump_);
1893 WriteAecDumpConfigMessage(false);
1894
1895 const size_t channel_size = formats_.api_format.input_stream().num_frames();
1896 const size_t num_channels = formats_.api_format.input_stream().num_channels();
1897 aec_dump_->AddCaptureStreamInput(
1898 FloatAudioFrame(src, num_channels, channel_size));
1899 RecordAudioProcessingState();
1900}
1901
1902void AudioProcessingImpl::RecordUnprocessedCaptureStream(
1903 const AudioFrame& capture_frame) {
1904 RTC_DCHECK(aec_dump_);
1905 WriteAecDumpConfigMessage(false);
1906
1907 aec_dump_->AddCaptureStreamInput(capture_frame);
1908 RecordAudioProcessingState();
1909}
1910
1911void AudioProcessingImpl::RecordProcessedCaptureStream(
1912 const float* const* processed_capture_stream) {
1913 RTC_DCHECK(aec_dump_);
1914
1915 const size_t channel_size = formats_.api_format.output_stream().num_frames();
1916 const size_t num_channels =
1917 formats_.api_format.output_stream().num_channels();
1918 aec_dump_->AddCaptureStreamOutput(
1919 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
1920 aec_dump_->WriteCaptureStreamMessage();
1921}
1922
1923void AudioProcessingImpl::RecordProcessedCaptureStream(
1924 const AudioFrame& processed_capture_frame) {
1925 RTC_DCHECK(aec_dump_);
1926
1927 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
1928 aec_dump_->WriteCaptureStreamMessage();
1929}
1930
1931void AudioProcessingImpl::RecordAudioProcessingState() {
1932 RTC_DCHECK(aec_dump_);
1933 AecDump::AudioProcessingState audio_proc_state;
1934 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
1935 audio_proc_state.drift =
1936 public_submodules_->echo_cancellation->stream_drift_samples();
1937 audio_proc_state.level = gain_control()->stream_analog_level();
1938 audio_proc_state.keypress = capture_.key_pressed;
1939 aec_dump_->AddAudioProcessingState(audio_proc_state);
1940}
1941
kwiberg83ffe452016-08-29 14:46:07 -07001942AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1943 bool transient_suppressor_enabled,
1944 const std::vector<Point>& array_geometry,
1945 SphericalPointf target_direction)
1946 : aec_system_delay_jumps(-1),
1947 delay_offset_ms(0),
1948 was_stream_delay_set(false),
1949 last_stream_delay_ms(0),
1950 last_aec_system_delay_ms(0),
1951 stream_delay_jumps(-1),
1952 output_will_be_muted(false),
1953 key_pressed(false),
1954 transient_suppressor_enabled(transient_suppressor_enabled),
1955 array_geometry(array_geometry),
1956 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001957 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001958 split_rate(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07001959 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07001960
1961AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1962
1963AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1964
1965AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1966
niklase@google.com470e71d2011-07-07 08:21:25 +00001967} // namespace webrtc