blob: 756cc0cca572b8bb0df7a901f2a58bf8fbf57031 [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
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000011#include "webrtc/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>
niklase@google.com470e71d2011-07-07 08:21:25 +000015
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020016#include "webrtc/base/checks.h"
nisse368f5cf2017-04-05 05:00:33 -070017#include "webrtc/base/logging.h"
xians@webrtc.orge46bc772014-10-10 08:36:56 +000018#include "webrtc/base/platform_file.h"
peah369f8282015-12-17 06:42:29 -080019#include "webrtc/base/trace_event.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070020#include "webrtc/common_audio/audio_converter.h"
Michael Graczykdfa36052015-03-25 16:37:27 -070021#include "webrtc/common_audio/channel_buffer.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070022#include "webrtc/common_audio/include/audio_util.h"
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000023#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020024#include "webrtc/modules/audio_processing/aec/aec_core.h"
peahe0eae3c2016-12-14 01:16:23 -080025#include "webrtc/modules/audio_processing/aec3/echo_canceller3.h"
pbos@webrtc.org788acd12014-12-15 09:41:24 +000026#include "webrtc/modules/audio_processing/agc/agc_manager_direct.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000027#include "webrtc/modules/audio_processing/audio_buffer.h"
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +000028#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000029#include "webrtc/modules/audio_processing/common.h"
andrew@webrtc.org56e4a052014-02-27 22:23:17 +000030#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000031#include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
peahbe615622016-02-13 16:40:47 -080032#include "webrtc/modules/audio_processing/gain_control_for_experimental_agc.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000033#include "webrtc/modules/audio_processing/gain_control_impl.h"
peah1bcfce52016-08-26 07:16:04 -070034#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -070035#include "webrtc/modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070036#endif
peahca4cac72016-06-29 15:26:12 -070037#include "webrtc/modules/audio_processing/level_controller/level_controller.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000038#include "webrtc/modules/audio_processing/level_estimator_impl.h"
peah8271d042016-11-22 07:24:52 -080039#include "webrtc/modules/audio_processing/low_cut_filter.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000040#include "webrtc/modules/audio_processing/noise_suppression_impl.h"
ivoc9f4a4a02016-10-28 05:39:16 -070041#include "webrtc/modules/audio_processing/residual_echo_detector.h"
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +000042#include "webrtc/modules/audio_processing/transient/transient_suppressor.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000043#include "webrtc/modules/audio_processing/voice_detection_impl.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010044#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010045#include "webrtc/system_wrappers/include/file_wrapper.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010046#include "webrtc/system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000047
48#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
49// Files generated at build-time by the protobuf compiler.
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000050#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000051#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000052#else
kjellander78ddd732016-02-09 08:13:06 -080053#include "webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000054#endif
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000055#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +000056
peah1bcfce52016-08-26 07:16:04 -070057// Check to verify that the define for the intelligibility enhancer is properly
58// set.
59#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
60 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
61 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
62#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
63#endif
64
Michael Graczyk86c6d332015-07-23 11:41:39 -070065#define RETURN_ON_ERR(expr) \
66 do { \
67 int err = (expr); \
68 if (err != kNoError) { \
69 return err; \
70 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000071 } while (0)
72
niklase@google.com470e71d2011-07-07 08:21:25 +000073namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070074
kwibergd59d3bb2016-09-13 07:49:33 -070075constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070076
Michael Graczyk86c6d332015-07-23 11:41:39 -070077namespace {
78
79static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
80 switch (layout) {
81 case AudioProcessing::kMono:
82 case AudioProcessing::kStereo:
83 return false;
84 case AudioProcessing::kMonoAndKeyboard:
85 case AudioProcessing::kStereoAndKeyboard:
86 return true;
87 }
88
kwiberg9e2be5f2016-09-14 05:23:22 -070089 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070090 return false;
91}
aluebsdf6416a2016-03-16 18:26:35 -070092
peah2ace3f92016-09-10 04:42:27 -070093bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070094 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
95 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
96}
97
peah2ace3f92016-09-10 04:42:27 -070098int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
99#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -0700100 constexpr int kMaxSplittingNativeProcessRate =
101 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -0700102#else
kwibergd59d3bb2016-09-13 07:49:33 -0700103 constexpr int kMaxSplittingNativeProcessRate =
104 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700105#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700106 static_assert(
107 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
108 "");
peah2ace3f92016-09-10 04:42:27 -0700109 const int uppermost_native_rate = band_splitting_required
110 ? kMaxSplittingNativeProcessRate
111 : AudioProcessing::kSampleRate48kHz;
112
113 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
114 if (rate >= uppermost_native_rate) {
115 return uppermost_native_rate;
116 }
117 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700118 return rate;
119 }
120 }
peah2ace3f92016-09-10 04:42:27 -0700121 RTC_NOTREACHED();
122 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700123}
124
peah9e6a2902017-05-15 07:19:21 -0700125// Maximum lengths that frame of samples being passed from the render side to
126// the capture side can have (does not apply to AEC3).
127static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
128static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
129
peah764e3642016-10-22 05:04:30 -0700130// Maximum number of frames to buffer in the render queue.
131// TODO(peah): Decrease this once we properly handle hugely unbalanced
132// reverse and forward call numbers.
133static const size_t kMaxNumFramesToBuffer = 100;
134
peah8271d042016-11-22 07:24:52 -0800135class HighPassFilterImpl : public HighPassFilter {
136 public:
137 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
138 ~HighPassFilterImpl() override = default;
139
140 // HighPassFilter implementation.
141 int Enable(bool enable) override {
142 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
143 config->high_pass_filter.enabled = enable;
144 });
145
146 return AudioProcessing::kNoError;
147 }
148
149 bool is_enabled() const override {
150 return apm_->GetConfig().high_pass_filter.enabled;
151 }
152
153 private:
154 AudioProcessingImpl* apm_;
155 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
156};
157
Michael Graczyk86c6d332015-07-23 11:41:39 -0700158} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000159
160// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000161static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000162
peah2ace3f92016-09-10 04:42:27 -0700163AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates() {}
164
165bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800166 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700167 bool echo_canceller_enabled,
168 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700169 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700170 bool noise_suppressor_enabled,
171 bool intelligibility_enhancer_enabled,
172 bool beamformer_enabled,
173 bool adaptive_gain_controller_enabled,
174 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800175 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700176 bool voice_activity_detector_enabled,
177 bool level_estimator_enabled,
178 bool transient_suppressor_enabled) {
179 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800180 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700181 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
182 changed |=
183 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700184 changed |=
185 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700186 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
187 changed |=
188 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
189 changed |= (beamformer_enabled != beamformer_enabled_);
190 changed |=
191 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
192 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800193 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700194 changed |= (level_estimator_enabled != level_estimator_enabled_);
195 changed |=
196 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
197 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
198 if (changed) {
peah8271d042016-11-22 07:24:52 -0800199 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700200 echo_canceller_enabled_ = echo_canceller_enabled;
201 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700202 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700203 noise_suppressor_enabled_ = noise_suppressor_enabled;
204 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
205 beamformer_enabled_ = beamformer_enabled;
206 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
207 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800208 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700209 level_estimator_enabled_ = level_estimator_enabled;
210 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
211 transient_suppressor_enabled_ = transient_suppressor_enabled;
212 }
213
214 changed |= first_update_;
215 first_update_ = false;
216 return changed;
217}
218
219bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
220 const {
221#if WEBRTC_INTELLIGIBILITY_ENHANCER
222 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700223 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700224#else
peah52775842017-05-16 06:14:09 -0700225 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700226#endif
227}
228
229bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
230 const {
peah8271d042016-11-22 07:24:52 -0800231 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700232 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800233 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
234 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700235}
236
237bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
238 const {
239 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800240 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peah52775842017-05-16 06:14:09 -0700241 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700242}
243
244bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
245 const {
246#if WEBRTC_INTELLIGIBILITY_ENHANCER
247 return intelligibility_enhancer_enabled_;
248#else
249 return false;
250#endif
251}
252
solenberg5e465c32015-12-08 13:22:33 -0800253struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800254 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800255 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800256 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800257 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800258 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800259 std::unique_ptr<LevelEstimatorImpl> level_estimator;
260 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
261 std::unique_ptr<VoiceDetectionImpl> voice_detection;
262 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800263 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800264
265 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800266 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700267#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800268 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700269#endif
solenberg5e465c32015-12-08 13:22:33 -0800270};
271
272struct AudioProcessingImpl::ApmPrivateSubmodules {
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700273 explicit ApmPrivateSubmodules(NonlinearBeamformer* beamformer)
solenberg5e465c32015-12-08 13:22:33 -0800274 : beamformer(beamformer) {}
275 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700276 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800277 std::unique_ptr<AgcManagerDirect> agc_manager;
peah8271d042016-11-22 07:24:52 -0800278 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700279 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700280 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
peahe0eae3c2016-12-14 01:16:23 -0800281 std::unique_ptr<EchoCanceller3> echo_canceller3;
solenberg5e465c32015-12-08 13:22:33 -0800282};
283
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000284AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700285 webrtc::Config config;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000286 return Create(config, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000287}
288
peah88ac8532016-09-12 16:47:25 -0700289AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000290 return Create(config, nullptr);
291}
292
peah88ac8532016-09-12 16:47:25 -0700293AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700294 NonlinearBeamformer* beamformer) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000295 AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000296 if (apm->Initialize() != kNoError) {
297 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800298 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000299 }
300
301 return apm;
302}
303
peah88ac8532016-09-12 16:47:25 -0700304AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000305 : AudioProcessingImpl(config, nullptr) {}
306
peah88ac8532016-09-12 16:47:25 -0700307AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700308 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800309 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
310 public_submodules_(new ApmPublicSubmodules()),
peahdf3efa82015-11-28 12:35:15 -0800311 private_submodules_(new ApmPrivateSubmodules(beamformer)),
312 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800313 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000314#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700315 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000316#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700317 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000318#endif
andrew1c7075f2015-06-24 18:14:14 -0700319#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800320 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700321#else
aluebs2a346882016-01-11 18:04:30 -0800322 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700323#endif
aluebs2a346882016-01-11 18:04:30 -0800324 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800325 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700326 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700327 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800328 {
329 rtc::CritScope cs_render(&crit_render_);
330 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000331
peahb624d8c2016-03-05 03:01:14 -0800332 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700333 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800334 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700335 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800336 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700337 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800338 public_submodules_->level_estimator.reset(
339 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800340 public_submodules_->noise_suppression.reset(
341 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800342 public_submodules_->voice_detection.reset(
343 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800344 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800345 new GainControlForExperimentalAgc(
346 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700347 private_submodules_->residual_echo_detector.reset(
348 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700349
peahc19f3122016-10-07 14:54:10 -0700350 // TODO(peah): Move this creation to happen only when the level controller
351 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700352 private_submodules_->level_controller.reset(new LevelController());
peahdf3efa82015-11-28 12:35:15 -0800353 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000354
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000355 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000356}
357
358AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800359 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800360 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800361 private_submodules_->agc_manager.reset();
362 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800363 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000364
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000365#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700366 debug_dump_.debug_file->CloseFile();
peahdf3efa82015-11-28 12:35:15 -0800367#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000368}
369
niklase@google.com470e71d2011-07-07 08:21:25 +0000370int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800371 // Run in a single-threaded manner during initialization.
372 rtc::CritScope cs_render(&crit_render_);
373 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000374 return InitializeLocked();
375}
376
peahde65ddc2016-09-16 15:02:15 -0700377int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
378 int capture_output_sample_rate_hz,
379 int render_input_sample_rate_hz,
380 ChannelLayout capture_input_layout,
381 ChannelLayout capture_output_layout,
382 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700383 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700384 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
385 LayoutHasKeyboard(capture_input_layout)},
386 {capture_output_sample_rate_hz,
387 ChannelsFromLayout(capture_output_layout),
388 LayoutHasKeyboard(capture_output_layout)},
389 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
390 LayoutHasKeyboard(render_input_layout)},
391 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
392 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700393
394 return Initialize(processing_config);
395}
396
397int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800398 // Run in a single-threaded manner during initialization.
399 rtc::CritScope cs_render(&crit_render_);
400 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700401 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000402}
403
peahdf3efa82015-11-28 12:35:15 -0800404int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800405 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700406 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800407}
408
peahdf3efa82015-11-28 12:35:15 -0800409int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700410 const ProcessingConfig& processing_config,
411 bool force_initialization) {
412 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800413}
414
kwiberg83ffe452016-08-29 14:46:07 -0700415#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
416
417AudioProcessingImpl::ApmDebugDumpThreadState::ApmDebugDumpThreadState()
418 : event_msg(new audioproc::Event()) {}
419
420AudioProcessingImpl::ApmDebugDumpThreadState::~ApmDebugDumpThreadState() {}
421
422AudioProcessingImpl::ApmDebugDumpState::ApmDebugDumpState()
423 : debug_file(FileWrapper::Create()) {}
424
425AudioProcessingImpl::ApmDebugDumpState::~ApmDebugDumpState() {}
426
427#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
428
peah192164e2015-11-17 02:16:45 -0800429// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800430// their current values (needs to be called while holding the crit_render_lock).
431int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700432 const ProcessingConfig& processing_config,
433 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800434 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700435 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800436 return kNoError;
437 }
peahdf3efa82015-11-28 12:35:15 -0800438
439 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800440 return InitializeLocked(processing_config);
441}
442
niklase@google.com470e71d2011-07-07 08:21:25 +0000443int AudioProcessingImpl::InitializeLocked() {
peah522d71b2017-02-23 05:16:26 -0800444 const int capture_audiobuffer_num_channels =
445 capture_nonlocked_.beamformer_enabled
446 ? formats_.api_format.input_stream().num_channels()
447 : formats_.api_format.output_stream().num_channels();
448
peahde65ddc2016-09-16 15:02:15 -0700449 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800450 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700451 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800452 : formats_.api_format.reverse_output_stream().num_frames();
453 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
454 render_.render_audio.reset(new AudioBuffer(
455 formats_.api_format.reverse_input_stream().num_frames(),
456 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700457 formats_.render_processing_format.num_frames(),
458 formats_.render_processing_format.num_channels(),
459 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700460 if (formats_.api_format.reverse_input_stream() !=
461 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800462 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800463 formats_.api_format.reverse_input_stream().num_channels(),
464 formats_.api_format.reverse_input_stream().num_frames(),
465 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800466 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700467 } else {
peahdf3efa82015-11-28 12:35:15 -0800468 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700469 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700470 } else {
peahdf3efa82015-11-28 12:35:15 -0800471 render_.render_audio.reset(nullptr);
472 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700473 }
peahdf3efa82015-11-28 12:35:15 -0800474 capture_.capture_audio.reset(
475 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
476 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700477 capture_nonlocked_.capture_processing_format.num_frames(),
478 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800479 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000480
peahde65ddc2016-09-16 15:02:15 -0700481 public_submodules_->echo_cancellation->Initialize(
482 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
483 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700484 AllocateRenderQueue();
485
ivoc3e9a5372016-10-28 07:55:33 -0700486 int success = public_submodules_->echo_cancellation->enable_metrics(true);
487 RTC_DCHECK_EQ(0, success);
488 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
489 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700490 public_submodules_->echo_control_mobile->Initialize(
491 proc_split_sample_rate_hz(), num_reverse_channels(),
492 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700493
494 public_submodules_->gain_control->Initialize(num_proc_channels(),
495 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700496 if (constants_.use_experimental_agc) {
497 if (!private_submodules_->agc_manager.get()) {
498 private_submodules_->agc_manager.reset(new AgcManagerDirect(
499 public_submodules_->gain_control.get(),
500 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800501 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700502 }
503 private_submodules_->agc_manager->Initialize();
504 private_submodules_->agc_manager->SetCaptureMuted(
505 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700506 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700507 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200508 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000509 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700510#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700511 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700512#endif
peah8271d042016-11-22 07:24:52 -0800513 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700514 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
515 proc_sample_rate_hz());
516 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
517 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700518 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700519 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800520 InitializeEchoCanceller3();
solenberg70f99032015-12-08 11:07:32 -0800521
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000522#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700523 if (debug_dump_.debug_file->is_open()) {
ajm@google.com808e0e02011-08-03 21:08:51 +0000524 int err = WriteInitMessage();
525 if (err != kNoError) {
526 return err;
527 }
528 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000529#endif
ajm@google.com808e0e02011-08-03 21:08:51 +0000530
niklase@google.com470e71d2011-07-07 08:21:25 +0000531 return kNoError;
532}
533
Michael Graczyk86c6d332015-07-23 11:41:39 -0700534int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
535 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700536 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
537 return kBadSampleRateError;
538 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000539 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700540
Peter Kasting69558702016-01-12 16:26:35 -0800541 const size_t num_in_channels = config.input_stream().num_channels();
542 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700543
544 // Need at least one input channel.
545 // Need either one output channel or as many outputs as there are inputs.
546 if (num_in_channels == 0 ||
547 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700548 return kBadNumberChannelsError;
549 }
550
aluebsb2328d12016-01-11 20:32:29 -0800551 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800552 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700553 return kBadNumberChannelsError;
554 }
555
peahdf3efa82015-11-28 12:35:15 -0800556 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000557
peahde65ddc2016-09-16 15:02:15 -0700558 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700559 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700560 formats_.api_format.output_stream().sample_rate_hz()),
561 submodule_states_.CaptureMultiBandSubModulesActive() ||
562 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000563
peahde65ddc2016-09-16 15:02:15 -0700564 capture_nonlocked_.capture_processing_format =
565 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700566
peah2ce640f2017-04-07 03:57:48 -0700567 int render_processing_rate;
568 if (!config_.echo_canceller3.enabled) {
569 render_processing_rate = FindNativeProcessRateToUse(
570 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
571 formats_.api_format.reverse_output_stream().sample_rate_hz()),
572 submodule_states_.CaptureMultiBandSubModulesActive() ||
573 submodule_states_.RenderMultiBandSubModulesActive());
574 } else {
575 render_processing_rate = capture_processing_rate;
576 }
577
aluebseb3603b2016-04-20 15:27:58 -0700578 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
579 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700580 if (render_processing_rate > kSampleRate32kHz &&
581 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700582 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
583 ? kSampleRate32kHz
584 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700585 }
peah2ce640f2017-04-07 03:57:48 -0700586
peahde65ddc2016-09-16 15:02:15 -0700587 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700588 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700589 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
590 kSampleRate8kHz) {
591 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000592 } else {
peahde65ddc2016-09-16 15:02:15 -0700593 render_processing_rate =
594 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000595 }
596
peahde65ddc2016-09-16 15:02:15 -0700597 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000598 // demonstrated to work well for AEC in most practical scenarios.
peahde65ddc2016-09-16 15:02:15 -0700599 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000600
peahde65ddc2016-09-16 15:02:15 -0700601 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
602 kSampleRate32kHz ||
603 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
604 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800605 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000606 } else {
peahdf3efa82015-11-28 12:35:15 -0800607 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700608 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000609 }
610
611 return InitializeLocked();
612}
613
peah88ac8532016-09-12 16:47:25 -0700614void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700615 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700616
peahc19f3122016-10-07 14:54:10 -0700617 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700618 if (!config_ok) {
619 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
620 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700621 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700622 << std::endl
623 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700624 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700625 }
626
627 // Run in a single-threaded manner when applying the settings.
628 rtc::CritScope cs_render(&crit_render_);
629 rtc::CritScope cs_capture(&crit_capture_);
630
peahc19f3122016-10-07 14:54:10 -0700631 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
632 // with the value in config_ everywhere in the code.
633 if (capture_nonlocked_.level_controller_enabled !=
634 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700635 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700636 config_.level_controller.enabled;
637 // TODO(peah): Remove the conditional initialization to always initialize
638 // the level controller regardless of whether it is enabled or not.
639 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700640 }
peahc19f3122016-10-07 14:54:10 -0700641 LOG(LS_INFO) << "Level controller activated: "
642 << capture_nonlocked_.level_controller_enabled;
643
644 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800645
646 InitializeLowCutFilter();
647
648 LOG(LS_INFO) << "Highpass filter activated: "
649 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800650
651 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
652 if (!config_ok) {
653 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
654 << "echo canceller 3: "
655 << EchoCanceller3::ToString(config_.echo_canceller3)
656 << std::endl
657 << "Reverting to default parameter set";
658 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
659 }
660
661 if (config.echo_canceller3.enabled !=
662 capture_nonlocked_.echo_canceller3_enabled) {
663 capture_nonlocked_.echo_canceller3_enabled =
664 config_.echo_canceller3.enabled;
665 InitializeEchoCanceller3();
666 LOG(LS_INFO) << "Echo canceller 3 activated: "
667 << capture_nonlocked_.echo_canceller3_enabled;
668 }
peah88ac8532016-09-12 16:47:25 -0700669}
670
671void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800672 // Run in a single-threaded manner when setting the extra options.
673 rtc::CritScope cs_render(&crit_render_);
674 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000675
peahb624d8c2016-03-05 03:01:14 -0800676 public_submodules_->echo_cancellation->SetExtraOptions(config);
677
peahdf3efa82015-11-28 12:35:15 -0800678 if (capture_.transient_suppressor_enabled !=
679 config.Get<ExperimentalNs>().enabled) {
680 capture_.transient_suppressor_enabled =
681 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000682 InitializeTransient();
683 }
aluebs2a346882016-01-11 18:04:30 -0800684
peah1bcfce52016-08-26 07:16:04 -0700685#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700686 if(capture_nonlocked_.intelligibility_enabled !=
687 config.Get<Intelligibility>().enabled) {
688 capture_nonlocked_.intelligibility_enabled =
689 config.Get<Intelligibility>().enabled;
690 InitializeIntelligibility();
691 }
peah1bcfce52016-08-26 07:16:04 -0700692#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700693
aluebs2a346882016-01-11 18:04:30 -0800694#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800695 if (capture_nonlocked_.beamformer_enabled !=
696 config.Get<Beamforming>().enabled) {
697 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800698 if (config.Get<Beamforming>().array_geometry.size() > 1) {
699 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
700 }
701 capture_.target_direction = config.Get<Beamforming>().target_direction;
702 InitializeBeamformer();
703 }
704#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000705}
706
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000707int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800708 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700709 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000710}
711
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000712int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800713 // Used as callback from submodules, hence locking is not allowed.
714 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000715}
716
Peter Kasting69558702016-01-12 16:26:35 -0800717size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800718 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700719 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000720}
721
Peter Kasting69558702016-01-12 16:26:35 -0800722size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800723 // Used as callback from submodules, hence locking is not allowed.
724 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
Peter Kasting69558702016-01-12 16:26:35 -0800727size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800728 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700729 return (capture_nonlocked_.beamformer_enabled ||
730 capture_nonlocked_.echo_canceller3_enabled)
731 ? 1
732 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800733}
734
Peter Kasting69558702016-01-12 16:26:35 -0800735size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800736 // Used as callback from submodules, hence locking is not allowed.
737 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000738}
739
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000740void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800741 rtc::CritScope cs(&crit_capture_);
742 capture_.output_will_be_muted = muted;
743 if (private_submodules_->agc_manager.get()) {
744 private_submodules_->agc_manager->SetCaptureMuted(
745 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000746 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000747}
748
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000749
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000750int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700751 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000752 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000753 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000754 int output_sample_rate_hz,
755 ChannelLayout output_layout,
756 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800757 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800758 StreamConfig input_stream;
759 StreamConfig output_stream;
760 {
761 // Access the formats_.api_format.input_stream beneath the capture lock.
762 // The lock must be released as it is later required in the call
763 // to ProcessStream(,,,);
764 rtc::CritScope cs(&crit_capture_);
765 input_stream = formats_.api_format.input_stream();
766 output_stream = formats_.api_format.output_stream();
767 }
768
Michael Graczyk86c6d332015-07-23 11:41:39 -0700769 input_stream.set_sample_rate_hz(input_sample_rate_hz);
770 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
771 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700772 output_stream.set_sample_rate_hz(output_sample_rate_hz);
773 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
774 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
775
776 if (samples_per_channel != input_stream.num_frames()) {
777 return kBadDataLengthError;
778 }
779 return ProcessStream(src, input_stream, output_stream, dest);
780}
781
782int AudioProcessingImpl::ProcessStream(const float* const* src,
783 const StreamConfig& input_config,
784 const StreamConfig& output_config,
785 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800786 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800787 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700788 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800789 {
790 // Acquire the capture lock in order to safely call the function
791 // that retrieves the render side data. This function accesses apm
792 // getters that need the capture lock held when being called.
793 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700794 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800795
796 if (!src || !dest) {
797 return kNullPointerError;
798 }
799
800 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700801 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000802 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000803
Michael Graczyk86c6d332015-07-23 11:41:39 -0700804 processing_config.input_stream() = input_config;
805 processing_config.output_stream() = output_config;
806
peahdf3efa82015-11-28 12:35:15 -0800807 {
808 // Do conditional reinitialization.
809 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700810 RETURN_ON_ERR(
811 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800812 }
813 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700814 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
815 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000816
817#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700818 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200819 RETURN_ON_ERR(WriteConfigMessage(false));
820
peahdf3efa82015-11-28 12:35:15 -0800821 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
822 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000823 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800824 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800825 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
826 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000827 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000828 }
829#endif
830
peahdf3efa82015-11-28 12:35:15 -0800831 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700832 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800833 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000834
835#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700836 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800837 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000838 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800839 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800840 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
841 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000842 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800843 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800844 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800845 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000846 }
847#endif
848
849 return kNoError;
850}
851
peah9e6a2902017-05-15 07:19:21 -0700852void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700853 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
854 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700855 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700856
kwibergaf476c72016-11-28 15:21:39 -0800857 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700858
859 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700860 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700861 // The data queue is full and needs to be emptied.
862 EmptyQueuedRenderAudio();
863
864 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700865 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700866 RTC_DCHECK(result);
867 }
868
869 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
870 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700871 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700872
873 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700874 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700875 // The data queue is full and needs to be emptied.
876 EmptyQueuedRenderAudio();
877
878 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700879 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700880 RTC_DCHECK(result);
881 }
peah701d6282016-10-25 05:42:20 -0700882
883 if (!constants_.use_experimental_agc) {
884 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
885 // Insert the samples into the queue.
886 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
887 // The data queue is full and needs to be emptied.
888 EmptyQueuedRenderAudio();
889
890 // Retry the insert (should always work).
891 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
892 RTC_DCHECK(result);
893 }
894 }
peah9e6a2902017-05-15 07:19:21 -0700895}
ivoc9f4a4a02016-10-28 05:39:16 -0700896
peah9e6a2902017-05-15 07:19:21 -0700897void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700898 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
899
900 // Insert the samples into the queue.
901 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
902 // The data queue is full and needs to be emptied.
903 EmptyQueuedRenderAudio();
904
905 // Retry the insert (should always work).
906 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
907 RTC_DCHECK(result);
908 }
peah764e3642016-10-22 05:04:30 -0700909}
910
911void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700912 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700913 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700914 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700915 EchoCancellationImpl::NumCancellersRequired(
916 num_output_channels(), num_reverse_channels()));
917
peah701d6282016-10-25 05:42:20 -0700918 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700919 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700920 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700921 EchoControlMobileImpl::NumCancellersRequired(
922 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700923
peah701d6282016-10-25 05:42:20 -0700924 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700925 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700926
ivoc9f4a4a02016-10-28 05:39:16 -0700927 const size_t new_red_render_queue_element_max_size =
928 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
929
peaha0624602016-10-25 04:45:24 -0700930 // Reallocate the queues if the queue item sizes are too small to fit the
931 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700932 if (aec_render_queue_element_max_size_ <
933 new_aec_render_queue_element_max_size) {
934 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700935
peaha0624602016-10-25 04:45:24 -0700936 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700937 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700938
peah701d6282016-10-25 05:42:20 -0700939 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700940 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
941 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700942 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700943 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700944
peah701d6282016-10-25 05:42:20 -0700945 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
946 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700947 } else {
peah701d6282016-10-25 05:42:20 -0700948 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700949 }
950
peah701d6282016-10-25 05:42:20 -0700951 if (aecm_render_queue_element_max_size_ <
952 new_aecm_render_queue_element_max_size) {
953 aecm_render_queue_element_max_size_ =
954 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700955
956 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700957 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700958
peah701d6282016-10-25 05:42:20 -0700959 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700960 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
961 kMaxNumFramesToBuffer, template_queue_element,
962 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700963 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700964
peah701d6282016-10-25 05:42:20 -0700965 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
966 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700967 } else {
peah701d6282016-10-25 05:42:20 -0700968 aecm_render_signal_queue_->Clear();
969 }
970
971 if (agc_render_queue_element_max_size_ <
972 new_agc_render_queue_element_max_size) {
973 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
974
975 std::vector<int16_t> template_queue_element(
976 agc_render_queue_element_max_size_);
977
978 agc_render_signal_queue_.reset(
979 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
980 kMaxNumFramesToBuffer, template_queue_element,
981 RenderQueueItemVerifier<int16_t>(
982 agc_render_queue_element_max_size_)));
983
984 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
985 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
986 } else {
987 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700988 }
ivoc9f4a4a02016-10-28 05:39:16 -0700989
990 if (red_render_queue_element_max_size_ <
991 new_red_render_queue_element_max_size) {
992 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
993
994 std::vector<float> template_queue_element(
995 red_render_queue_element_max_size_);
996
997 red_render_signal_queue_.reset(
998 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
999 kMaxNumFramesToBuffer, template_queue_element,
1000 RenderQueueItemVerifier<float>(
1001 red_render_queue_element_max_size_)));
1002
1003 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1004 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1005 } else {
1006 red_render_signal_queue_->Clear();
1007 }
peah764e3642016-10-22 05:04:30 -07001008}
1009
1010void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1011 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001012 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001013 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001014 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001015 }
1016
peah701d6282016-10-25 05:42:20 -07001017 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001018 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001019 aecm_capture_queue_buffer_);
1020 }
1021
1022 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1023 public_submodules_->gain_control->ProcessRenderAudio(
1024 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001025 }
ivoc9f4a4a02016-10-28 05:39:16 -07001026
1027 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1028 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1029 red_capture_queue_buffer_);
1030 }
peah764e3642016-10-22 05:04:30 -07001031}
1032
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001033int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001034 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001035 {
1036 // Acquire the capture lock in order to safely call the function
1037 // that retrieves the render side data. This function accesses apm
1038 // getters that need the capture lock held when being called.
1039 // The lock needs to be released as
1040 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1041 // as well.
1042 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001043 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001044 }
peahfa6228e2015-11-16 16:27:42 -08001045
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001046 if (!frame) {
1047 return kNullPointerError;
1048 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001049 // Must be a native rate.
1050 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1051 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001052 frame->sample_rate_hz_ != kSampleRate32kHz &&
1053 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001054 return kBadSampleRateError;
1055 }
peah192164e2015-11-17 02:16:45 -08001056
peahdf3efa82015-11-28 12:35:15 -08001057 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001058 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001059 {
1060 // Aquire lock for the access of api_format.
1061 // The lock is released immediately due to the conditional
1062 // reinitialization.
1063 rtc::CritScope cs_capture(&crit_capture_);
1064 // TODO(ajm): The input and output rates and channels are currently
1065 // constrained to be identical in the int16 interface.
1066 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001067
1068 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001069 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001070 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1071 processing_config.input_stream().set_num_channels(frame->num_channels_);
1072 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1073 processing_config.output_stream().set_num_channels(frame->num_channels_);
1074
peahdf3efa82015-11-28 12:35:15 -08001075 {
1076 // Do conditional reinitialization.
1077 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001078 RETURN_ON_ERR(
1079 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001080 }
1081 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001082 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001083 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001084 return kBadDataLengthError;
1085 }
1086
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001087#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001088 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001089 RETURN_ON_ERR(WriteConfigMessage(false));
1090
peahdf3efa82015-11-28 12:35:15 -08001091 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1092 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001093 const size_t data_size =
1094 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001095 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001096 }
1097#endif
1098
peahdf3efa82015-11-28 12:35:15 -08001099 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001100 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001101 capture_.capture_audio->InterleaveTo(
1102 frame, submodule_states_.CaptureMultiBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001103
1104#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001105 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001106 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001107 const size_t data_size =
1108 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001109 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001110 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001111 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001112 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001113 }
1114#endif
1115
1116 return kNoError;
1117}
1118
peahde65ddc2016-09-16 15:02:15 -07001119int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001120 // Ensure that not both the AEC and AECM are active at the same time.
1121 // TODO(peah): Simplify once the public API Enable functions for these
1122 // are moved to APM.
1123 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1124 public_submodules_->echo_control_mobile->is_enabled()));
1125
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001126#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001127 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001128 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1129 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1130 msg->set_drift(
1131 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001132 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001133 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001134 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001135#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001136
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001137 MaybeUpdateHistograms();
1138
peahde65ddc2016-09-16 15:02:15 -07001139 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001140
peah1b08dc32016-12-20 13:45:58 -08001141 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001142 capture_buffer->channels_const()[0],
1143 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001144 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1145 if (log_rms) {
1146 capture_rms_interval_counter_ = 0;
1147 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001148 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1149 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1150 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1151 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001152 }
1153
peahe0eae3c2016-12-14 01:16:23 -08001154 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001155 const int new_agc_level = gain_control()->stream_analog_level();
1156 capture_.echo_path_gain_change =
peah103ac7e2017-04-12 05:40:55 -07001157 abs(capture_.previous_agc_level - new_agc_level) > 5;
peah67995532017-04-10 14:12:41 -07001158 capture_.previous_agc_level = new_agc_level;
peahe0eae3c2016-12-14 01:16:23 -08001159 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1160 }
1161
peahbe615622016-02-13 16:40:47 -08001162 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001163 public_submodules_->gain_control->is_enabled()) {
1164 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001165 capture_buffer->channels()[0], capture_buffer->num_channels(),
1166 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001167 }
1168
peah2ace3f92016-09-10 04:42:27 -07001169 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1170 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001171 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1172 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001173 }
1174
peah522d71b2017-02-23 05:16:26 -08001175 if (private_submodules_->echo_canceller3) {
1176 // Force down-mixing of the number of channels after the detection of
1177 // capture signal saturation.
1178 // TODO(peah): Look into ensuring that this kind of tampering with the
1179 // AudioBuffer functionality should not be needed.
1180 capture_buffer->set_num_channels(1);
1181 }
1182
aluebsb2328d12016-01-11 20:32:29 -08001183 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001184 private_submodules_->beamformer->AnalyzeChunk(
1185 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001186 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001187 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001188 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001189
peahe0eae3c2016-12-14 01:16:23 -08001190 // TODO(peah): Move the AEC3 low-cut filter to this place.
1191 if (private_submodules_->low_cut_filter &&
1192 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001193 private_submodules_->low_cut_filter->Process(capture_buffer);
1194 }
peahde65ddc2016-09-16 15:02:15 -07001195 RETURN_ON_ERR(
1196 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1197 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001198
1199 // Ensure that the stream delay was set before the call to the
1200 // AEC ProcessCaptureAudio function.
1201 if (public_submodules_->echo_cancellation->is_enabled() &&
1202 !was_stream_delay_set()) {
1203 return AudioProcessing::kStreamParameterNotSetError;
1204 }
1205
peahe0eae3c2016-12-14 01:16:23 -08001206 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001207 private_submodules_->echo_canceller3->ProcessCapture(
1208 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001209 } else {
1210 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1211 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001212 }
1213
peahdf3efa82015-11-28 12:35:15 -08001214 if (public_submodules_->echo_control_mobile->is_enabled() &&
1215 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001216 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001217 }
peahde65ddc2016-09-16 15:02:15 -07001218 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001219#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001220 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001221 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001222 int gain_db = public_submodules_->gain_control->is_enabled() ?
1223 public_submodules_->gain_control->compression_gain_db() :
1224 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001225 float gain = std::pow(10.f, gain_db / 20.f);
1226 gain *= capture_nonlocked_.level_controller_enabled ?
1227 private_submodules_->level_controller->GetLastGain() :
1228 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001229 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001230 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001231 }
peah1bcfce52016-08-26 07:16:04 -07001232#endif
peah253534d2016-03-15 04:32:28 -07001233
1234 // Ensure that the stream delay was set before the call to the
1235 // AECM ProcessCaptureAudio function.
1236 if (public_submodules_->echo_control_mobile->is_enabled() &&
1237 !was_stream_delay_set()) {
1238 return AudioProcessing::kStreamParameterNotSetError;
1239 }
1240
1241 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001242 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001243
ivoc9f4a4a02016-10-28 05:39:16 -07001244
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001245 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001246 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001247 }
1248
peahde65ddc2016-09-16 15:02:15 -07001249 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001250
peahbe615622016-02-13 16:40:47 -08001251 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001252 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001253 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001254 private_submodules_->beamformer->is_target_present())) {
1255 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001256 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1257 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001258 }
peahb8fbb542016-03-15 02:28:08 -07001259 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001260 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001261
peah2ace3f92016-09-10 04:42:27 -07001262 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1263 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001264 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1265 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001266 }
1267
peah9e6a2902017-05-15 07:19:21 -07001268 if (config_.residual_echo_detector.enabled) {
1269 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1270 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1271 capture_buffer->num_frames()));
1272 }
1273
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001274 // TODO(aluebs): Investigate if the transient suppression placement should be
1275 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001276 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001277 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001278 private_submodules_->agc_manager.get()
1279 ? private_submodules_->agc_manager->voice_probability()
1280 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001281
peahdf3efa82015-11-28 12:35:15 -08001282 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001283 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1284 capture_buffer->num_channels(),
1285 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1286 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1287 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001288 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001289 }
1290
peahca4cac72016-06-29 15:26:12 -07001291 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001292 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001293 }
1294
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001295 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001296 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001297
peah1b08dc32016-12-20 13:45:58 -08001298 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1299 capture_buffer->channels_const()[0],
1300 capture_nonlocked_.capture_processing_format.num_frames()));
1301 if (log_rms) {
1302 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1303 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1304 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1305 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1306 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1307 }
1308
peahdf3efa82015-11-28 12:35:15 -08001309 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001310 return kNoError;
1311}
1312
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001313int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001314 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001315 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001316 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001317 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001318 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001319 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001320 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001321 };
1322 if (samples_per_channel != reverse_config.num_frames()) {
1323 return kBadDataLengthError;
1324 }
peahdf3efa82015-11-28 12:35:15 -08001325 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001326}
1327
peahde65ddc2016-09-16 15:02:15 -07001328int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1329 const StreamConfig& input_config,
1330 const StreamConfig& output_config,
1331 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001332 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001333 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001334 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001335 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001336 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1337 dest);
peah2ace3f92016-09-10 04:42:27 -07001338 } else if (formats_.api_format.reverse_input_stream() !=
1339 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001340 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1341 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001342 } else {
peahde65ddc2016-09-16 15:02:15 -07001343 CopyAudioIfNeeded(src, input_config.num_frames(),
1344 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001345 }
1346
1347 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001348}
1349
peahdf3efa82015-11-28 12:35:15 -08001350int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001351 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001352 const StreamConfig& input_config,
1353 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001354 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001355 return kNullPointerError;
1356 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001357
peahde65ddc2016-09-16 15:02:15 -07001358 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001359 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001360 }
1361
peahdf3efa82015-11-28 12:35:15 -08001362 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001363 processing_config.reverse_input_stream() = input_config;
1364 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001365
peahdf3efa82015-11-28 12:35:15 -08001366 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001367 assert(input_config.num_frames() ==
1368 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001369
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001370#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001371 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001372 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1373 audioproc::ReverseStream* msg =
1374 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001375 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001376 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001377 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001378 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001379 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001380 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001381 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001382 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001383 }
1384#endif
1385
peahdf3efa82015-11-28 12:35:15 -08001386 render_.render_audio->CopyFrom(src,
1387 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001388 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001389}
1390
1391int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001392 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001393 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001394 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001395 return kNullPointerError;
1396 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001397 // Must be a native rate.
1398 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1399 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001400 frame->sample_rate_hz_ != kSampleRate32kHz &&
1401 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001402 return kBadSampleRateError;
1403 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001404
Michael Graczyk86c6d332015-07-23 11:41:39 -07001405 if (frame->num_channels_ <= 0) {
1406 return kBadNumberChannelsError;
1407 }
1408
peahdf3efa82015-11-28 12:35:15 -08001409 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001410 processing_config.reverse_input_stream().set_sample_rate_hz(
1411 frame->sample_rate_hz_);
1412 processing_config.reverse_input_stream().set_num_channels(
1413 frame->num_channels_);
1414 processing_config.reverse_output_stream().set_sample_rate_hz(
1415 frame->sample_rate_hz_);
1416 processing_config.reverse_output_stream().set_num_channels(
1417 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001418
peahdf3efa82015-11-28 12:35:15 -08001419 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001420 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001421 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001422 return kBadDataLengthError;
1423 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001424
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001425#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001426 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001427 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1428 audioproc::ReverseStream* msg =
1429 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001430 const size_t data_size =
1431 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001432 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001433 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001434 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001435 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001436 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001437#endif
peahdf3efa82015-11-28 12:35:15 -08001438 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001439 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001440 render_.render_audio->InterleaveTo(
1441 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001442 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001443}
niklase@google.com470e71d2011-07-07 08:21:25 +00001444
peahde65ddc2016-09-16 15:02:15 -07001445int AudioProcessingImpl::ProcessRenderStreamLocked() {
1446 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001447
1448 QueueNonbandedRenderAudio(render_buffer);
1449
peah2ace3f92016-09-10 04:42:27 -07001450 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001451 SampleRateSupportsMultiBand(
1452 formats_.render_processing_format.sample_rate_hz())) {
1453 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001454 }
1455
peah1bcfce52016-08-26 07:16:04 -07001456#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001457 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001458 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001459 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001460 }
peah1bcfce52016-08-26 07:16:04 -07001461#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001462
peah9e6a2902017-05-15 07:19:21 -07001463 QueueBandedRenderAudio(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001464 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1465 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001466 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001467 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001468
peah2ace3f92016-09-10 04:42:27 -07001469 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001470 SampleRateSupportsMultiBand(
1471 formats_.render_processing_format.sample_rate_hz())) {
1472 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001473 }
1474
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001475 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001476}
1477
1478int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001479 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001480 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001481 capture_.was_stream_delay_set = true;
1482 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001483
niklase@google.com470e71d2011-07-07 08:21:25 +00001484 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001485 delay = 0;
1486 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001487 }
1488
1489 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1490 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001491 delay = 500;
1492 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001493 }
1494
peahdf3efa82015-11-28 12:35:15 -08001495 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001496 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001497}
1498
1499int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001500 // Used as callback from submodules, hence locking is not allowed.
1501 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001502}
1503
1504bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001505 // Used as callback from submodules, hence locking is not allowed.
1506 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001507}
1508
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001509void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001510 rtc::CritScope cs(&crit_capture_);
1511 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001512}
1513
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001514void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001515 rtc::CritScope cs(&crit_capture_);
1516 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001517}
1518
1519int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001520 rtc::CritScope cs(&crit_capture_);
1521 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001522}
1523
niklase@google.com470e71d2011-07-07 08:21:25 +00001524int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001525 const char filename[AudioProcessing::kMaxFilenameSize],
1526 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001527 // Run in a single-threaded manner.
1528 rtc::CritScope cs_render(&crit_render_);
1529 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001530 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001531
peahdf3efa82015-11-28 12:35:15 -08001532 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001533 return kNullPointerError;
1534 }
1535
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001536#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001537 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001538 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001539 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001540
tommia6219cc2016-06-15 10:30:14 -07001541 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001542 return kFileError;
1543 }
1544
Minyue13b96ba2015-10-03 00:39:14 +02001545 RETURN_ON_ERR(WriteConfigMessage(true));
1546 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001547 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001548#else
1549 return kUnsupportedFunctionError;
1550#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001551}
1552
ivocd66b44d2016-01-15 03:06:36 -08001553int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1554 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001555 // Run in a single-threaded manner.
1556 rtc::CritScope cs_render(&crit_render_);
1557 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001558
peahdf3efa82015-11-28 12:35:15 -08001559 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001560 return kNullPointerError;
1561 }
1562
1563#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001564 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1565
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001566 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001567 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001568
tommia6219cc2016-06-15 10:30:14 -07001569 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001570 return kFileError;
1571 }
1572
Minyue13b96ba2015-10-03 00:39:14 +02001573 RETURN_ON_ERR(WriteConfigMessage(true));
1574 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001575 return kNoError;
1576#else
1577 return kUnsupportedFunctionError;
1578#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1579}
1580
peah73a28ee2016-10-12 03:01:49 -07001581int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1582 return StartDebugRecording(handle, -1);
1583}
1584
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001585int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1586 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001587 // Run in a single-threaded manner.
1588 rtc::CritScope cs_render(&crit_render_);
1589 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001590 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001591 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001592}
1593
niklase@google.com470e71d2011-07-07 08:21:25 +00001594int AudioProcessingImpl::StopDebugRecording() {
peahdf3efa82015-11-28 12:35:15 -08001595 // Run in a single-threaded manner.
1596 rtc::CritScope cs_render(&crit_render_);
1597 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001598
1599#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001600 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001601 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001602 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001603#else
1604 return kUnsupportedFunctionError;
1605#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001606}
1607
ivoc4e477a12017-01-15 08:29:46 -08001608AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1609 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1610 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1611 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1612 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1613}
1614
1615AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1616 const AudioProcessingStatistics& other) = default;
1617
1618AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1619 default;
1620
ivoc3e9a5372016-10-28 07:55:33 -07001621// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1622AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1623 const {
1624 return AudioProcessingStatistics();
1625}
1626
1627AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1628 const {
1629 AudioProcessingStatistics stats;
1630 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001631 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1632 if (success == Error::kNoError) {
1633 stats.a_nlp.Set(metrics.a_nlp);
1634 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1635 stats.echo_return_loss.Set(metrics.echo_return_loss);
1636 stats.echo_return_loss_enhancement.Set(
1637 metrics.echo_return_loss_enhancement);
1638 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1639 }
ivoc9c192b22017-03-16 04:22:14 -07001640 {
1641 rtc::CritScope cs_capture(&crit_capture_);
1642 stats.residual_echo_likelihood =
1643 private_submodules_->residual_echo_detector->echo_likelihood();
1644 stats.residual_echo_likelihood_recent_max =
1645 private_submodules_->residual_echo_detector
1646 ->echo_likelihood_recent_max();
1647 }
ivoc3e9a5372016-10-28 07:55:33 -07001648 public_submodules_->echo_cancellation->GetDelayMetrics(
1649 &stats.delay_median, &stats.delay_standard_deviation,
1650 &stats.fraction_poor_delays);
1651 return stats;
1652}
1653
niklase@google.com470e71d2011-07-07 08:21:25 +00001654EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001655 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001656}
1657
1658EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001659 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001660}
1661
1662GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001663 if (constants_.use_experimental_agc) {
1664 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001665 }
peahbfa97112016-03-10 21:09:04 -08001666 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001667}
1668
1669HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001670 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001671}
1672
1673LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001674 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001675}
1676
1677NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001678 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001679}
1680
1681VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001682 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001683}
1684
peah8271d042016-11-22 07:24:52 -08001685void AudioProcessingImpl::MutateConfig(
1686 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1687 rtc::CritScope cs_render(&crit_render_);
1688 rtc::CritScope cs_capture(&crit_capture_);
1689 mutator(&config_);
1690 ApplyConfig(config_);
1691}
1692
1693AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1694 rtc::CritScope cs_render(&crit_render_);
1695 rtc::CritScope cs_capture(&crit_capture_);
1696 return config_;
1697}
1698
peah2ace3f92016-09-10 04:42:27 -07001699bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1700 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001701 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001702 public_submodules_->echo_cancellation->is_enabled(),
1703 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001704 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001705 public_submodules_->noise_suppression->is_enabled(),
1706 capture_nonlocked_.intelligibility_enabled,
1707 capture_nonlocked_.beamformer_enabled,
1708 public_submodules_->gain_control->is_enabled(),
1709 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001710 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001711 public_submodules_->voice_detection->is_enabled(),
1712 public_submodules_->level_estimator->is_enabled(),
1713 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001714}
1715
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001716
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001717void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001718 if (capture_.transient_suppressor_enabled) {
1719 if (!public_submodules_->transient_suppressor.get()) {
1720 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001721 }
peahdf3efa82015-11-28 12:35:15 -08001722 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001723 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1724 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001725 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001726}
1727
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001728void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001729 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001730 if (!private_submodules_->beamformer) {
1731 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001732 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001733 }
peahdf3efa82015-11-28 12:35:15 -08001734 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1735 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001736 }
1737}
1738
ekmeyerson60d9b332015-08-14 10:35:55 -07001739void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001740#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001741 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001742 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001743 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001744 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001745 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001746 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001747 }
peah1bcfce52016-08-26 07:16:04 -07001748#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001749}
1750
peah8271d042016-11-22 07:24:52 -08001751void AudioProcessingImpl::InitializeLowCutFilter() {
1752 if (config_.high_pass_filter.enabled) {
1753 private_submodules_->low_cut_filter.reset(
1754 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1755 } else {
1756 private_submodules_->low_cut_filter.reset();
1757 }
1758}
peahe0eae3c2016-12-14 01:16:23 -08001759void AudioProcessingImpl::InitializeEchoCanceller3() {
1760 if (capture_nonlocked_.echo_canceller3_enabled) {
1761 private_submodules_->echo_canceller3.reset(
1762 new EchoCanceller3(proc_sample_rate_hz(), true));
1763 } else {
1764 private_submodules_->echo_canceller3.reset();
1765 }
1766}
peah8271d042016-11-22 07:24:52 -08001767
peahca4cac72016-06-29 15:26:12 -07001768void AudioProcessingImpl::InitializeLevelController() {
1769 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1770}
1771
ivoc9f4a4a02016-10-28 05:39:16 -07001772void AudioProcessingImpl::InitializeResidualEchoDetector() {
1773 private_submodules_->residual_echo_detector->Initialize();
1774}
1775
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001776void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001777 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001778
1779 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001780 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1781 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001782 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001783 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001784 capture_.stream_delay_jumps = 0;
1785 }
1786 if (capture_.aec_system_delay_jumps == -1 &&
1787 echo_cancellation()->stream_has_echo()) {
1788 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001789 }
1790
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001791 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001792 const int diff_stream_delay_ms =
1793 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1794 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1795 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001796 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1797 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001798 if (capture_.stream_delay_jumps == -1) {
1799 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001800 }
peahdf3efa82015-11-28 12:35:15 -08001801 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001802 }
peahdf3efa82015-11-28 12:35:15 -08001803 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001804
1805 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001806 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001807 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001808 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001809 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001810 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1811 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001812 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001813 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001814 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001815 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001816 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1817 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1818 100);
peahdf3efa82015-11-28 12:35:15 -08001819 if (capture_.aec_system_delay_jumps == -1) {
1820 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001821 }
peahdf3efa82015-11-28 12:35:15 -08001822 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001823 }
peahdf3efa82015-11-28 12:35:15 -08001824 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001825 }
1826}
1827
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001828void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001829 // Run in a single-threaded manner.
1830 rtc::CritScope cs_render(&crit_render_);
1831 rtc::CritScope cs_capture(&crit_capture_);
1832
1833 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001834 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001835 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001836 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001837 }
peahdf3efa82015-11-28 12:35:15 -08001838 capture_.stream_delay_jumps = -1;
1839 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001840
peahdf3efa82015-11-28 12:35:15 -08001841 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001842 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1843 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001844 }
peahdf3efa82015-11-28 12:35:15 -08001845 capture_.aec_system_delay_jumps = -1;
1846 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001847}
1848
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001849#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001850int AudioProcessingImpl::WriteMessageToDebugFile(
1851 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08001852 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08001853 rtc::CriticalSection* crit_debug,
1854 ApmDebugDumpThreadState* debug_state) {
1855 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00001856 if (size <= 0) {
1857 return kUnspecifiedError;
1858 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00001859#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07001860// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
1861// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00001862#endif
1863
peahdf3efa82015-11-28 12:35:15 -08001864 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00001865 return kUnspecifiedError;
1866 }
1867
peahdf3efa82015-11-28 12:35:15 -08001868 {
1869 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08001870 rtc::CritScope cs_debug(crit_debug);
1871
tommia6219cc2016-06-15 10:30:14 -07001872 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08001873 // Update the byte counter.
1874 if (*filesize_limit_bytes >= 0) {
1875 *filesize_limit_bytes -=
1876 (sizeof(int32_t) + debug_state->event_str.length());
1877 if (*filesize_limit_bytes < 0) {
1878 // Not enough bytes are left to write this message, so stop logging.
1879 debug_file->CloseFile();
1880 return kNoError;
1881 }
1882 }
peahdf3efa82015-11-28 12:35:15 -08001883 // Write message preceded by its size.
1884 if (!debug_file->Write(&size, sizeof(int32_t))) {
1885 return kFileError;
1886 }
1887 if (!debug_file->Write(debug_state->event_str.data(),
1888 debug_state->event_str.length())) {
1889 return kFileError;
1890 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001891 }
1892
peahdf3efa82015-11-28 12:35:15 -08001893 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00001894
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001895 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001896}
1897
1898int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08001899 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
1900 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
1901 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00001902
mbonadei7c2c8432017-04-07 00:59:12 -07001903 msg->set_num_input_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001904 formats_.api_format.input_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07001905 msg->set_num_output_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001906 formats_.api_format.output_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07001907 msg->set_num_reverse_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001908 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08001909 msg->set_reverse_sample_rate(
1910 formats_.api_format.reverse_input_stream().sample_rate_hz());
1911 msg->set_output_sample_rate(
1912 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07001913 msg->set_reverse_output_sample_rate(
1914 formats_.api_format.reverse_output_stream().sample_rate_hz());
1915 msg->set_num_reverse_output_channels(
1916 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08001917
1918 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001919 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001920 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02001921 return kNoError;
1922}
1923
1924int AudioProcessingImpl::WriteConfigMessage(bool forced) {
1925 audioproc::Config config;
1926
peahdf3efa82015-11-28 12:35:15 -08001927 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001928 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08001929 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001930 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08001931 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001932 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08001933 public_submodules_->echo_cancellation->is_extended_filter_enabled());
1934 config.set_aec_suppression_level(static_cast<int>(
1935 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02001936
peahdf3efa82015-11-28 12:35:15 -08001937 config.set_aecm_enabled(
1938 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001939 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08001940 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
1941 config.set_aecm_routing_mode(static_cast<int>(
1942 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02001943
peahdf3efa82015-11-28 12:35:15 -08001944 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
1945 config.set_agc_mode(
1946 static_cast<int>(public_submodules_->gain_control->mode()));
1947 config.set_agc_limiter_enabled(
1948 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08001949 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02001950
peah8271d042016-11-22 07:24:52 -08001951 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001952
peahdf3efa82015-11-28 12:35:15 -08001953 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
1954 config.set_ns_level(
1955 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02001956
peahdf3efa82015-11-28 12:35:15 -08001957 config.set_transient_suppression_enabled(
1958 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001959 config.set_intelligibility_enhancer_enabled(
1960 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001961
peah7789fe72016-04-15 01:19:44 -07001962 std::string experiments_description =
1963 public_submodules_->echo_cancellation->GetExperimentsDescription();
1964 // TODO(peah): Add semicolon-separated concatenations of experiment
1965 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07001966 if (capture_nonlocked_.level_controller_enabled) {
1967 experiments_description += "LevelController;";
1968 }
henrik.lundinbd681b92016-12-05 09:08:42 -08001969 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1970 experiments_description += "AgcClippingLevelExperiment;";
1971 }
peahe0eae3c2016-12-14 01:16:23 -08001972 if (capture_nonlocked_.echo_canceller3_enabled) {
1973 experiments_description += "EchoCanceller3;";
1974 }
peah7789fe72016-04-15 01:19:44 -07001975 config.set_experiments_description(experiments_description);
1976
mbonadei7c2c8432017-04-07 00:59:12 -07001977 ProtoString serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08001978 if (!forced &&
1979 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02001980 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001981 }
1982
peahdf3efa82015-11-28 12:35:15 -08001983 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02001984
peahdf3efa82015-11-28 12:35:15 -08001985 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
1986 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02001987
peahdf3efa82015-11-28 12:35:15 -08001988 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001989 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001990 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00001991 return kNoError;
1992}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001993#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001994
kwiberg83ffe452016-08-29 14:46:07 -07001995AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1996 bool transient_suppressor_enabled,
1997 const std::vector<Point>& array_geometry,
1998 SphericalPointf target_direction)
1999 : aec_system_delay_jumps(-1),
2000 delay_offset_ms(0),
2001 was_stream_delay_set(false),
2002 last_stream_delay_ms(0),
2003 last_aec_system_delay_ms(0),
2004 stream_delay_jumps(-1),
2005 output_will_be_muted(false),
2006 key_pressed(false),
2007 transient_suppressor_enabled(transient_suppressor_enabled),
2008 array_geometry(array_geometry),
2009 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002010 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002011 split_rate(kSampleRate16kHz),
2012 previous_agc_level(0),
2013 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002014
2015AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2016
2017AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2018
2019AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2020
niklase@google.com470e71d2011-07-07 08:21:25 +00002021} // namespace webrtc