blob: 900a8ec437abdf069ec29e02afe678ea7fb939c5 [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() ||
ivoc20270be2016-11-15 05:24:35 -0800223 intelligibility_enhancer_enabled_ ||
224 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700225#else
ivoc20270be2016-11-15 05:24:35 -0800226 return CaptureMultiBandProcessingActive() ||
227 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700228#endif
229}
230
231bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
232 const {
peah8271d042016-11-22 07:24:52 -0800233 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700234 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800235 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
236 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700237}
238
239bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
240 const {
241 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800242 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800243 residual_echo_detector_enabled_ || echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700244}
245
246bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
247 const {
248#if WEBRTC_INTELLIGIBILITY_ENHANCER
249 return intelligibility_enhancer_enabled_;
250#else
251 return false;
252#endif
253}
254
solenberg5e465c32015-12-08 13:22:33 -0800255struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800256 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800257 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800258 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800259 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800260 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800261 std::unique_ptr<LevelEstimatorImpl> level_estimator;
262 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
263 std::unique_ptr<VoiceDetectionImpl> voice_detection;
264 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800265 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800266
267 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800268 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700269#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800270 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700271#endif
solenberg5e465c32015-12-08 13:22:33 -0800272};
273
274struct AudioProcessingImpl::ApmPrivateSubmodules {
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700275 explicit ApmPrivateSubmodules(NonlinearBeamformer* beamformer)
solenberg5e465c32015-12-08 13:22:33 -0800276 : beamformer(beamformer) {}
277 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700278 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800279 std::unique_ptr<AgcManagerDirect> agc_manager;
peah8271d042016-11-22 07:24:52 -0800280 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700281 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700282 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
peahe0eae3c2016-12-14 01:16:23 -0800283 std::unique_ptr<EchoCanceller3> echo_canceller3;
solenberg5e465c32015-12-08 13:22:33 -0800284};
285
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000286AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700287 webrtc::Config config;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000288 return Create(config, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000289}
290
peah88ac8532016-09-12 16:47:25 -0700291AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000292 return Create(config, nullptr);
293}
294
peah88ac8532016-09-12 16:47:25 -0700295AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700296 NonlinearBeamformer* beamformer) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000297 AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000298 if (apm->Initialize() != kNoError) {
299 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800300 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000301 }
302
303 return apm;
304}
305
peah88ac8532016-09-12 16:47:25 -0700306AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000307 : AudioProcessingImpl(config, nullptr) {}
308
peah88ac8532016-09-12 16:47:25 -0700309AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700310 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800311 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
312 public_submodules_(new ApmPublicSubmodules()),
peahdf3efa82015-11-28 12:35:15 -0800313 private_submodules_(new ApmPrivateSubmodules(beamformer)),
314 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800315 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000316#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700317 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000318#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700319 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000320#endif
andrew1c7075f2015-06-24 18:14:14 -0700321#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800322 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700323#else
aluebs2a346882016-01-11 18:04:30 -0800324 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700325#endif
aluebs2a346882016-01-11 18:04:30 -0800326 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800327 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700328 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700329 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800330 {
331 rtc::CritScope cs_render(&crit_render_);
332 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000333
peahb624d8c2016-03-05 03:01:14 -0800334 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700335 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800336 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700337 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800338 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700339 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800340 public_submodules_->level_estimator.reset(
341 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800342 public_submodules_->noise_suppression.reset(
343 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800344 public_submodules_->voice_detection.reset(
345 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800346 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800347 new GainControlForExperimentalAgc(
348 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700349 private_submodules_->residual_echo_detector.reset(
350 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700351
peahc19f3122016-10-07 14:54:10 -0700352 // TODO(peah): Move this creation to happen only when the level controller
353 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700354 private_submodules_->level_controller.reset(new LevelController());
peahdf3efa82015-11-28 12:35:15 -0800355 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000356
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000357 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000358}
359
360AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800361 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800362 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800363 private_submodules_->agc_manager.reset();
364 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800365 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000366
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000367#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700368 debug_dump_.debug_file->CloseFile();
peahdf3efa82015-11-28 12:35:15 -0800369#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000370}
371
niklase@google.com470e71d2011-07-07 08:21:25 +0000372int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800373 // Run in a single-threaded manner during initialization.
374 rtc::CritScope cs_render(&crit_render_);
375 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000376 return InitializeLocked();
377}
378
peahde65ddc2016-09-16 15:02:15 -0700379int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
380 int capture_output_sample_rate_hz,
381 int render_input_sample_rate_hz,
382 ChannelLayout capture_input_layout,
383 ChannelLayout capture_output_layout,
384 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700385 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700386 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
387 LayoutHasKeyboard(capture_input_layout)},
388 {capture_output_sample_rate_hz,
389 ChannelsFromLayout(capture_output_layout),
390 LayoutHasKeyboard(capture_output_layout)},
391 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
392 LayoutHasKeyboard(render_input_layout)},
393 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
394 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700395
396 return Initialize(processing_config);
397}
398
399int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800400 // Run in a single-threaded manner during initialization.
401 rtc::CritScope cs_render(&crit_render_);
402 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700403 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000404}
405
peahdf3efa82015-11-28 12:35:15 -0800406int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800407 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700408 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800409}
410
peahdf3efa82015-11-28 12:35:15 -0800411int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700412 const ProcessingConfig& processing_config,
413 bool force_initialization) {
414 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800415}
416
kwiberg83ffe452016-08-29 14:46:07 -0700417#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
418
419AudioProcessingImpl::ApmDebugDumpThreadState::ApmDebugDumpThreadState()
420 : event_msg(new audioproc::Event()) {}
421
422AudioProcessingImpl::ApmDebugDumpThreadState::~ApmDebugDumpThreadState() {}
423
424AudioProcessingImpl::ApmDebugDumpState::ApmDebugDumpState()
425 : debug_file(FileWrapper::Create()) {}
426
427AudioProcessingImpl::ApmDebugDumpState::~ApmDebugDumpState() {}
428
429#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
430
peah192164e2015-11-17 02:16:45 -0800431// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800432// their current values (needs to be called while holding the crit_render_lock).
433int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700434 const ProcessingConfig& processing_config,
435 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800436 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700437 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800438 return kNoError;
439 }
peahdf3efa82015-11-28 12:35:15 -0800440
441 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800442 return InitializeLocked(processing_config);
443}
444
niklase@google.com470e71d2011-07-07 08:21:25 +0000445int AudioProcessingImpl::InitializeLocked() {
peah522d71b2017-02-23 05:16:26 -0800446 const int capture_audiobuffer_num_channels =
447 capture_nonlocked_.beamformer_enabled
448 ? formats_.api_format.input_stream().num_channels()
449 : formats_.api_format.output_stream().num_channels();
450
peahde65ddc2016-09-16 15:02:15 -0700451 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800452 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700453 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800454 : formats_.api_format.reverse_output_stream().num_frames();
455 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
456 render_.render_audio.reset(new AudioBuffer(
457 formats_.api_format.reverse_input_stream().num_frames(),
458 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700459 formats_.render_processing_format.num_frames(),
460 formats_.render_processing_format.num_channels(),
461 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700462 if (formats_.api_format.reverse_input_stream() !=
463 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800464 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800465 formats_.api_format.reverse_input_stream().num_channels(),
466 formats_.api_format.reverse_input_stream().num_frames(),
467 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800468 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700469 } else {
peahdf3efa82015-11-28 12:35:15 -0800470 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700471 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700472 } else {
peahdf3efa82015-11-28 12:35:15 -0800473 render_.render_audio.reset(nullptr);
474 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700475 }
peahdf3efa82015-11-28 12:35:15 -0800476 capture_.capture_audio.reset(
477 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
478 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700479 capture_nonlocked_.capture_processing_format.num_frames(),
480 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800481 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000482
peahde65ddc2016-09-16 15:02:15 -0700483 public_submodules_->echo_cancellation->Initialize(
484 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
485 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700486 AllocateRenderQueue();
487
ivoc3e9a5372016-10-28 07:55:33 -0700488 int success = public_submodules_->echo_cancellation->enable_metrics(true);
489 RTC_DCHECK_EQ(0, success);
490 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
491 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700492 public_submodules_->echo_control_mobile->Initialize(
493 proc_split_sample_rate_hz(), num_reverse_channels(),
494 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700495
496 public_submodules_->gain_control->Initialize(num_proc_channels(),
497 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700498 if (constants_.use_experimental_agc) {
499 if (!private_submodules_->agc_manager.get()) {
500 private_submodules_->agc_manager.reset(new AgcManagerDirect(
501 public_submodules_->gain_control.get(),
502 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800503 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700504 }
505 private_submodules_->agc_manager->Initialize();
506 private_submodules_->agc_manager->SetCaptureMuted(
507 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700508 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700509 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200510 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000511 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700512#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700513 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700514#endif
peah8271d042016-11-22 07:24:52 -0800515 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700516 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
517 proc_sample_rate_hz());
518 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
519 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700520 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700521 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800522 InitializeEchoCanceller3();
solenberg70f99032015-12-08 11:07:32 -0800523
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000524#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700525 if (debug_dump_.debug_file->is_open()) {
ajm@google.com808e0e02011-08-03 21:08:51 +0000526 int err = WriteInitMessage();
527 if (err != kNoError) {
528 return err;
529 }
530 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000531#endif
ajm@google.com808e0e02011-08-03 21:08:51 +0000532
niklase@google.com470e71d2011-07-07 08:21:25 +0000533 return kNoError;
534}
535
Michael Graczyk86c6d332015-07-23 11:41:39 -0700536int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
537 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700538 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
539 return kBadSampleRateError;
540 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000541 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700542
Peter Kasting69558702016-01-12 16:26:35 -0800543 const size_t num_in_channels = config.input_stream().num_channels();
544 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700545
546 // Need at least one input channel.
547 // Need either one output channel or as many outputs as there are inputs.
548 if (num_in_channels == 0 ||
549 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700550 return kBadNumberChannelsError;
551 }
552
aluebsb2328d12016-01-11 20:32:29 -0800553 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800554 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700555 return kBadNumberChannelsError;
556 }
557
peahdf3efa82015-11-28 12:35:15 -0800558 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000559
peahde65ddc2016-09-16 15:02:15 -0700560 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700561 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700562 formats_.api_format.output_stream().sample_rate_hz()),
563 submodule_states_.CaptureMultiBandSubModulesActive() ||
564 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000565
peahde65ddc2016-09-16 15:02:15 -0700566 capture_nonlocked_.capture_processing_format =
567 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700568
peah2ce640f2017-04-07 03:57:48 -0700569 int render_processing_rate;
570 if (!config_.echo_canceller3.enabled) {
571 render_processing_rate = FindNativeProcessRateToUse(
572 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
573 formats_.api_format.reverse_output_stream().sample_rate_hz()),
574 submodule_states_.CaptureMultiBandSubModulesActive() ||
575 submodule_states_.RenderMultiBandSubModulesActive());
576 } else {
577 render_processing_rate = capture_processing_rate;
578 }
579
aluebseb3603b2016-04-20 15:27:58 -0700580 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
581 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700582 if (render_processing_rate > kSampleRate32kHz &&
583 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700584 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
585 ? kSampleRate32kHz
586 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700587 }
peah2ce640f2017-04-07 03:57:48 -0700588
peahde65ddc2016-09-16 15:02:15 -0700589 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700590 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700591 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
592 kSampleRate8kHz) {
593 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000594 } else {
peahde65ddc2016-09-16 15:02:15 -0700595 render_processing_rate =
596 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000597 }
598
peahde65ddc2016-09-16 15:02:15 -0700599 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000600 // demonstrated to work well for AEC in most practical scenarios.
peahde65ddc2016-09-16 15:02:15 -0700601 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000602
peahde65ddc2016-09-16 15:02:15 -0700603 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
604 kSampleRate32kHz ||
605 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
606 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800607 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000608 } else {
peahdf3efa82015-11-28 12:35:15 -0800609 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700610 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000611 }
612
613 return InitializeLocked();
614}
615
peah88ac8532016-09-12 16:47:25 -0700616void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700617 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700618
peahc19f3122016-10-07 14:54:10 -0700619 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700620 if (!config_ok) {
621 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
622 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700623 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700624 << std::endl
625 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700626 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700627 }
628
629 // Run in a single-threaded manner when applying the settings.
630 rtc::CritScope cs_render(&crit_render_);
631 rtc::CritScope cs_capture(&crit_capture_);
632
peahc19f3122016-10-07 14:54:10 -0700633 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
634 // with the value in config_ everywhere in the code.
635 if (capture_nonlocked_.level_controller_enabled !=
636 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700637 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700638 config_.level_controller.enabled;
639 // TODO(peah): Remove the conditional initialization to always initialize
640 // the level controller regardless of whether it is enabled or not.
641 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700642 }
peahc19f3122016-10-07 14:54:10 -0700643 LOG(LS_INFO) << "Level controller activated: "
644 << capture_nonlocked_.level_controller_enabled;
645
646 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800647
648 InitializeLowCutFilter();
649
650 LOG(LS_INFO) << "Highpass filter activated: "
651 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800652
653 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
654 if (!config_ok) {
655 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
656 << "echo canceller 3: "
657 << EchoCanceller3::ToString(config_.echo_canceller3)
658 << std::endl
659 << "Reverting to default parameter set";
660 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
661 }
662
663 if (config.echo_canceller3.enabled !=
664 capture_nonlocked_.echo_canceller3_enabled) {
665 capture_nonlocked_.echo_canceller3_enabled =
666 config_.echo_canceller3.enabled;
667 InitializeEchoCanceller3();
668 LOG(LS_INFO) << "Echo canceller 3 activated: "
669 << capture_nonlocked_.echo_canceller3_enabled;
670 }
peah88ac8532016-09-12 16:47:25 -0700671}
672
673void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800674 // Run in a single-threaded manner when setting the extra options.
675 rtc::CritScope cs_render(&crit_render_);
676 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000677
peahb624d8c2016-03-05 03:01:14 -0800678 public_submodules_->echo_cancellation->SetExtraOptions(config);
679
peahdf3efa82015-11-28 12:35:15 -0800680 if (capture_.transient_suppressor_enabled !=
681 config.Get<ExperimentalNs>().enabled) {
682 capture_.transient_suppressor_enabled =
683 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000684 InitializeTransient();
685 }
aluebs2a346882016-01-11 18:04:30 -0800686
peah1bcfce52016-08-26 07:16:04 -0700687#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700688 if(capture_nonlocked_.intelligibility_enabled !=
689 config.Get<Intelligibility>().enabled) {
690 capture_nonlocked_.intelligibility_enabled =
691 config.Get<Intelligibility>().enabled;
692 InitializeIntelligibility();
693 }
peah1bcfce52016-08-26 07:16:04 -0700694#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700695
aluebs2a346882016-01-11 18:04:30 -0800696#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800697 if (capture_nonlocked_.beamformer_enabled !=
698 config.Get<Beamforming>().enabled) {
699 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800700 if (config.Get<Beamforming>().array_geometry.size() > 1) {
701 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
702 }
703 capture_.target_direction = config.Get<Beamforming>().target_direction;
704 InitializeBeamformer();
705 }
706#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000707}
708
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000709int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800710 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700711 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000712}
713
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000714int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800715 // Used as callback from submodules, hence locking is not allowed.
716 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000717}
718
Peter Kasting69558702016-01-12 16:26:35 -0800719size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800720 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700721 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000722}
723
Peter Kasting69558702016-01-12 16:26:35 -0800724size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800725 // Used as callback from submodules, hence locking is not allowed.
726 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000727}
728
Peter Kasting69558702016-01-12 16:26:35 -0800729size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800730 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700731 return (capture_nonlocked_.beamformer_enabled ||
732 capture_nonlocked_.echo_canceller3_enabled)
733 ? 1
734 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800735}
736
Peter Kasting69558702016-01-12 16:26:35 -0800737size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800738 // Used as callback from submodules, hence locking is not allowed.
739 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000740}
741
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000742void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800743 rtc::CritScope cs(&crit_capture_);
744 capture_.output_will_be_muted = muted;
745 if (private_submodules_->agc_manager.get()) {
746 private_submodules_->agc_manager->SetCaptureMuted(
747 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000748 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000749}
750
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000751
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000752int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700753 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000754 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000755 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000756 int output_sample_rate_hz,
757 ChannelLayout output_layout,
758 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800759 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800760 StreamConfig input_stream;
761 StreamConfig output_stream;
762 {
763 // Access the formats_.api_format.input_stream beneath the capture lock.
764 // The lock must be released as it is later required in the call
765 // to ProcessStream(,,,);
766 rtc::CritScope cs(&crit_capture_);
767 input_stream = formats_.api_format.input_stream();
768 output_stream = formats_.api_format.output_stream();
769 }
770
Michael Graczyk86c6d332015-07-23 11:41:39 -0700771 input_stream.set_sample_rate_hz(input_sample_rate_hz);
772 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
773 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700774 output_stream.set_sample_rate_hz(output_sample_rate_hz);
775 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
776 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
777
778 if (samples_per_channel != input_stream.num_frames()) {
779 return kBadDataLengthError;
780 }
781 return ProcessStream(src, input_stream, output_stream, dest);
782}
783
784int AudioProcessingImpl::ProcessStream(const float* const* src,
785 const StreamConfig& input_config,
786 const StreamConfig& output_config,
787 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800788 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800789 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700790 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800791 {
792 // Acquire the capture lock in order to safely call the function
793 // that retrieves the render side data. This function accesses apm
794 // getters that need the capture lock held when being called.
795 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700796 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800797
798 if (!src || !dest) {
799 return kNullPointerError;
800 }
801
802 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700803 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000804 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000805
Michael Graczyk86c6d332015-07-23 11:41:39 -0700806 processing_config.input_stream() = input_config;
807 processing_config.output_stream() = output_config;
808
peahdf3efa82015-11-28 12:35:15 -0800809 {
810 // Do conditional reinitialization.
811 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700812 RETURN_ON_ERR(
813 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800814 }
815 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700816 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
817 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000818
819#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700820 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200821 RETURN_ON_ERR(WriteConfigMessage(false));
822
peahdf3efa82015-11-28 12:35:15 -0800823 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
824 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000825 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800826 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800827 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
828 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000829 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000830 }
831#endif
832
peahdf3efa82015-11-28 12:35:15 -0800833 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700834 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800835 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000836
837#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700838 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800839 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000840 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800841 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800842 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
843 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000844 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800845 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800846 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800847 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000848 }
849#endif
850
851 return kNoError;
852}
853
peah9e6a2902017-05-15 07:19:21 -0700854void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700855 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
856 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700857 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700858
kwibergaf476c72016-11-28 15:21:39 -0800859 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700860
861 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700862 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700863 // The data queue is full and needs to be emptied.
864 EmptyQueuedRenderAudio();
865
866 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700867 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700868 RTC_DCHECK(result);
869 }
870
871 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
872 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700873 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700874
875 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700876 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700877 // The data queue is full and needs to be emptied.
878 EmptyQueuedRenderAudio();
879
880 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700881 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700882 RTC_DCHECK(result);
883 }
peah701d6282016-10-25 05:42:20 -0700884
885 if (!constants_.use_experimental_agc) {
886 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
887 // Insert the samples into the queue.
888 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
889 // The data queue is full and needs to be emptied.
890 EmptyQueuedRenderAudio();
891
892 // Retry the insert (should always work).
893 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
894 RTC_DCHECK(result);
895 }
896 }
peah9e6a2902017-05-15 07:19:21 -0700897}
ivoc9f4a4a02016-10-28 05:39:16 -0700898
peah9e6a2902017-05-15 07:19:21 -0700899void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700900 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
901
902 // Insert the samples into the queue.
903 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
904 // The data queue is full and needs to be emptied.
905 EmptyQueuedRenderAudio();
906
907 // Retry the insert (should always work).
908 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
909 RTC_DCHECK(result);
910 }
peah764e3642016-10-22 05:04:30 -0700911}
912
913void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700914 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700915 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700916 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700917 EchoCancellationImpl::NumCancellersRequired(
918 num_output_channels(), num_reverse_channels()));
919
peah701d6282016-10-25 05:42:20 -0700920 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700921 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700922 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700923 EchoControlMobileImpl::NumCancellersRequired(
924 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700925
peah701d6282016-10-25 05:42:20 -0700926 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700927 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700928
ivoc9f4a4a02016-10-28 05:39:16 -0700929 const size_t new_red_render_queue_element_max_size =
930 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
931
peaha0624602016-10-25 04:45:24 -0700932 // Reallocate the queues if the queue item sizes are too small to fit the
933 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700934 if (aec_render_queue_element_max_size_ <
935 new_aec_render_queue_element_max_size) {
936 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700937
peaha0624602016-10-25 04:45:24 -0700938 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700939 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700940
peah701d6282016-10-25 05:42:20 -0700941 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700942 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
943 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700944 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700945 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700946
peah701d6282016-10-25 05:42:20 -0700947 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
948 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700949 } else {
peah701d6282016-10-25 05:42:20 -0700950 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700951 }
952
peah701d6282016-10-25 05:42:20 -0700953 if (aecm_render_queue_element_max_size_ <
954 new_aecm_render_queue_element_max_size) {
955 aecm_render_queue_element_max_size_ =
956 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700957
958 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700959 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700960
peah701d6282016-10-25 05:42:20 -0700961 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700962 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
963 kMaxNumFramesToBuffer, template_queue_element,
964 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700965 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700966
peah701d6282016-10-25 05:42:20 -0700967 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
968 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700969 } else {
peah701d6282016-10-25 05:42:20 -0700970 aecm_render_signal_queue_->Clear();
971 }
972
973 if (agc_render_queue_element_max_size_ <
974 new_agc_render_queue_element_max_size) {
975 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
976
977 std::vector<int16_t> template_queue_element(
978 agc_render_queue_element_max_size_);
979
980 agc_render_signal_queue_.reset(
981 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
982 kMaxNumFramesToBuffer, template_queue_element,
983 RenderQueueItemVerifier<int16_t>(
984 agc_render_queue_element_max_size_)));
985
986 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
987 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
988 } else {
989 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700990 }
ivoc9f4a4a02016-10-28 05:39:16 -0700991
992 if (red_render_queue_element_max_size_ <
993 new_red_render_queue_element_max_size) {
994 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
995
996 std::vector<float> template_queue_element(
997 red_render_queue_element_max_size_);
998
999 red_render_signal_queue_.reset(
1000 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1001 kMaxNumFramesToBuffer, template_queue_element,
1002 RenderQueueItemVerifier<float>(
1003 red_render_queue_element_max_size_)));
1004
1005 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1006 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1007 } else {
1008 red_render_signal_queue_->Clear();
1009 }
peah764e3642016-10-22 05:04:30 -07001010}
1011
1012void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1013 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001014 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001015 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001016 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001017 }
1018
peah701d6282016-10-25 05:42:20 -07001019 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001020 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001021 aecm_capture_queue_buffer_);
1022 }
1023
1024 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1025 public_submodules_->gain_control->ProcessRenderAudio(
1026 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001027 }
ivoc9f4a4a02016-10-28 05:39:16 -07001028
1029 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1030 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1031 red_capture_queue_buffer_);
1032 }
peah764e3642016-10-22 05:04:30 -07001033}
1034
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001035int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001036 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001037 {
1038 // Acquire the capture lock in order to safely call the function
1039 // that retrieves the render side data. This function accesses apm
1040 // getters that need the capture lock held when being called.
1041 // The lock needs to be released as
1042 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1043 // as well.
1044 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001045 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001046 }
peahfa6228e2015-11-16 16:27:42 -08001047
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001048 if (!frame) {
1049 return kNullPointerError;
1050 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001051 // Must be a native rate.
1052 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1053 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001054 frame->sample_rate_hz_ != kSampleRate32kHz &&
1055 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001056 return kBadSampleRateError;
1057 }
peah192164e2015-11-17 02:16:45 -08001058
peahdf3efa82015-11-28 12:35:15 -08001059 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001060 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001061 {
1062 // Aquire lock for the access of api_format.
1063 // The lock is released immediately due to the conditional
1064 // reinitialization.
1065 rtc::CritScope cs_capture(&crit_capture_);
1066 // TODO(ajm): The input and output rates and channels are currently
1067 // constrained to be identical in the int16 interface.
1068 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001069
1070 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001071 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001072 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1073 processing_config.input_stream().set_num_channels(frame->num_channels_);
1074 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1075 processing_config.output_stream().set_num_channels(frame->num_channels_);
1076
peahdf3efa82015-11-28 12:35:15 -08001077 {
1078 // Do conditional reinitialization.
1079 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001080 RETURN_ON_ERR(
1081 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001082 }
1083 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001084 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001085 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001086 return kBadDataLengthError;
1087 }
1088
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001089#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001090 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001091 RETURN_ON_ERR(WriteConfigMessage(false));
1092
peahdf3efa82015-11-28 12:35:15 -08001093 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1094 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001095 const size_t data_size =
1096 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001097 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001098 }
1099#endif
1100
peahdf3efa82015-11-28 12:35:15 -08001101 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001102 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001103 capture_.capture_audio->InterleaveTo(
1104 frame, submodule_states_.CaptureMultiBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001105
1106#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001107 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001108 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001109 const size_t data_size =
1110 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001111 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001112 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001113 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001114 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001115 }
1116#endif
1117
1118 return kNoError;
1119}
1120
peahde65ddc2016-09-16 15:02:15 -07001121int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001122 // Ensure that not both the AEC and AECM are active at the same time.
1123 // TODO(peah): Simplify once the public API Enable functions for these
1124 // are moved to APM.
1125 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1126 public_submodules_->echo_control_mobile->is_enabled()));
1127
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001128#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001129 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001130 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1131 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1132 msg->set_drift(
1133 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001134 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001135 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001136 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001137#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001138
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001139 MaybeUpdateHistograms();
1140
peahde65ddc2016-09-16 15:02:15 -07001141 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001142
peah1b08dc32016-12-20 13:45:58 -08001143 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001144 capture_buffer->channels_const()[0],
1145 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001146 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1147 if (log_rms) {
1148 capture_rms_interval_counter_ = 0;
1149 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001150 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1151 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1152 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1153 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001154 }
1155
peahe0eae3c2016-12-14 01:16:23 -08001156 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001157 const int new_agc_level = gain_control()->stream_analog_level();
1158 capture_.echo_path_gain_change =
peah103ac7e2017-04-12 05:40:55 -07001159 abs(capture_.previous_agc_level - new_agc_level) > 5;
peah67995532017-04-10 14:12:41 -07001160 capture_.previous_agc_level = new_agc_level;
peahe0eae3c2016-12-14 01:16:23 -08001161 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1162 }
1163
peahbe615622016-02-13 16:40:47 -08001164 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001165 public_submodules_->gain_control->is_enabled()) {
1166 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001167 capture_buffer->channels()[0], capture_buffer->num_channels(),
1168 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001169 }
1170
peah2ace3f92016-09-10 04:42:27 -07001171 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1172 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001173 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1174 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001175 }
1176
peah522d71b2017-02-23 05:16:26 -08001177 if (private_submodules_->echo_canceller3) {
1178 // Force down-mixing of the number of channels after the detection of
1179 // capture signal saturation.
1180 // TODO(peah): Look into ensuring that this kind of tampering with the
1181 // AudioBuffer functionality should not be needed.
1182 capture_buffer->set_num_channels(1);
1183 }
1184
aluebsb2328d12016-01-11 20:32:29 -08001185 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001186 private_submodules_->beamformer->AnalyzeChunk(
1187 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001188 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001189 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001190 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001191
peahe0eae3c2016-12-14 01:16:23 -08001192 // TODO(peah): Move the AEC3 low-cut filter to this place.
1193 if (private_submodules_->low_cut_filter &&
1194 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001195 private_submodules_->low_cut_filter->Process(capture_buffer);
1196 }
peahde65ddc2016-09-16 15:02:15 -07001197 RETURN_ON_ERR(
1198 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1199 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001200
1201 // Ensure that the stream delay was set before the call to the
1202 // AEC ProcessCaptureAudio function.
1203 if (public_submodules_->echo_cancellation->is_enabled() &&
1204 !was_stream_delay_set()) {
1205 return AudioProcessing::kStreamParameterNotSetError;
1206 }
1207
peahe0eae3c2016-12-14 01:16:23 -08001208 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001209 private_submodules_->echo_canceller3->ProcessCapture(
1210 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001211 } else {
1212 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1213 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001214 }
1215
peahdf3efa82015-11-28 12:35:15 -08001216 if (public_submodules_->echo_control_mobile->is_enabled() &&
1217 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001218 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001219 }
peahde65ddc2016-09-16 15:02:15 -07001220 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001221#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001222 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001223 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001224 int gain_db = public_submodules_->gain_control->is_enabled() ?
1225 public_submodules_->gain_control->compression_gain_db() :
1226 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001227 float gain = std::pow(10.f, gain_db / 20.f);
1228 gain *= capture_nonlocked_.level_controller_enabled ?
1229 private_submodules_->level_controller->GetLastGain() :
1230 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001231 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001232 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001233 }
peah1bcfce52016-08-26 07:16:04 -07001234#endif
peah253534d2016-03-15 04:32:28 -07001235
1236 // Ensure that the stream delay was set before the call to the
1237 // AECM ProcessCaptureAudio function.
1238 if (public_submodules_->echo_control_mobile->is_enabled() &&
1239 !was_stream_delay_set()) {
1240 return AudioProcessing::kStreamParameterNotSetError;
1241 }
1242
1243 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001244 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001245
ivoc9f4a4a02016-10-28 05:39:16 -07001246
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001247 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001248 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001249 }
1250
peahde65ddc2016-09-16 15:02:15 -07001251 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001252
peahbe615622016-02-13 16:40:47 -08001253 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001254 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001255 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001256 private_submodules_->beamformer->is_target_present())) {
1257 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001258 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1259 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001260 }
peahb8fbb542016-03-15 02:28:08 -07001261 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001262 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001263
peah2ace3f92016-09-10 04:42:27 -07001264 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1265 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001266 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1267 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001268 }
1269
peah9e6a2902017-05-15 07:19:21 -07001270 if (config_.residual_echo_detector.enabled) {
1271 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1272 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1273 capture_buffer->num_frames()));
1274 }
1275
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001276 // TODO(aluebs): Investigate if the transient suppression placement should be
1277 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001278 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001279 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001280 private_submodules_->agc_manager.get()
1281 ? private_submodules_->agc_manager->voice_probability()
1282 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001283
peahdf3efa82015-11-28 12:35:15 -08001284 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001285 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1286 capture_buffer->num_channels(),
1287 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1288 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1289 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001290 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001291 }
1292
peahca4cac72016-06-29 15:26:12 -07001293 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001294 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001295 }
1296
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001297 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001298 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001299
peah1b08dc32016-12-20 13:45:58 -08001300 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1301 capture_buffer->channels_const()[0],
1302 capture_nonlocked_.capture_processing_format.num_frames()));
1303 if (log_rms) {
1304 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1305 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1306 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1307 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1308 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1309 }
1310
peahdf3efa82015-11-28 12:35:15 -08001311 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001312 return kNoError;
1313}
1314
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001315int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001316 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001317 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001318 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001319 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001320 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001321 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001322 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001323 };
1324 if (samples_per_channel != reverse_config.num_frames()) {
1325 return kBadDataLengthError;
1326 }
peahdf3efa82015-11-28 12:35:15 -08001327 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001328}
1329
peahde65ddc2016-09-16 15:02:15 -07001330int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1331 const StreamConfig& input_config,
1332 const StreamConfig& output_config,
1333 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001334 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001335 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001336 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001337 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001338 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1339 dest);
peah2ace3f92016-09-10 04:42:27 -07001340 } else if (formats_.api_format.reverse_input_stream() !=
1341 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001342 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1343 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001344 } else {
peahde65ddc2016-09-16 15:02:15 -07001345 CopyAudioIfNeeded(src, input_config.num_frames(),
1346 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001347 }
1348
1349 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001350}
1351
peahdf3efa82015-11-28 12:35:15 -08001352int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001353 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001354 const StreamConfig& input_config,
1355 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001356 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001357 return kNullPointerError;
1358 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001359
peahde65ddc2016-09-16 15:02:15 -07001360 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001361 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001362 }
1363
peahdf3efa82015-11-28 12:35:15 -08001364 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001365 processing_config.reverse_input_stream() = input_config;
1366 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001367
peahdf3efa82015-11-28 12:35:15 -08001368 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001369 assert(input_config.num_frames() ==
1370 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001371
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001372#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001373 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001374 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1375 audioproc::ReverseStream* msg =
1376 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001377 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001378 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001379 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001380 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001381 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001382 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001383 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001384 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001385 }
1386#endif
1387
peahdf3efa82015-11-28 12:35:15 -08001388 render_.render_audio->CopyFrom(src,
1389 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001390 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001391}
1392
1393int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001394 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001395 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001396 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001397 return kNullPointerError;
1398 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001399 // Must be a native rate.
1400 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1401 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001402 frame->sample_rate_hz_ != kSampleRate32kHz &&
1403 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001404 return kBadSampleRateError;
1405 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001406
Michael Graczyk86c6d332015-07-23 11:41:39 -07001407 if (frame->num_channels_ <= 0) {
1408 return kBadNumberChannelsError;
1409 }
1410
peahdf3efa82015-11-28 12:35:15 -08001411 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001412 processing_config.reverse_input_stream().set_sample_rate_hz(
1413 frame->sample_rate_hz_);
1414 processing_config.reverse_input_stream().set_num_channels(
1415 frame->num_channels_);
1416 processing_config.reverse_output_stream().set_sample_rate_hz(
1417 frame->sample_rate_hz_);
1418 processing_config.reverse_output_stream().set_num_channels(
1419 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001420
peahdf3efa82015-11-28 12:35:15 -08001421 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001422 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001423 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001424 return kBadDataLengthError;
1425 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001426
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001427#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001428 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001429 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1430 audioproc::ReverseStream* msg =
1431 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001432 const size_t data_size =
1433 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001434 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001435 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001436 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001437 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001438 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001439#endif
peahdf3efa82015-11-28 12:35:15 -08001440 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001441 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001442 render_.render_audio->InterleaveTo(
1443 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001444 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001445}
niklase@google.com470e71d2011-07-07 08:21:25 +00001446
peahde65ddc2016-09-16 15:02:15 -07001447int AudioProcessingImpl::ProcessRenderStreamLocked() {
1448 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001449
1450 QueueNonbandedRenderAudio(render_buffer);
1451
peah2ace3f92016-09-10 04:42:27 -07001452 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001453 SampleRateSupportsMultiBand(
1454 formats_.render_processing_format.sample_rate_hz())) {
1455 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001456 }
1457
peah1bcfce52016-08-26 07:16:04 -07001458#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001459 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001460 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001461 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001462 }
peah1bcfce52016-08-26 07:16:04 -07001463#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001464
peah9e6a2902017-05-15 07:19:21 -07001465 QueueBandedRenderAudio(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001466 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1467 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001468 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001469 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001470
peah2ace3f92016-09-10 04:42:27 -07001471 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001472 SampleRateSupportsMultiBand(
1473 formats_.render_processing_format.sample_rate_hz())) {
1474 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001475 }
1476
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001477 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001478}
1479
1480int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001481 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001482 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001483 capture_.was_stream_delay_set = true;
1484 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001485
niklase@google.com470e71d2011-07-07 08:21:25 +00001486 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001487 delay = 0;
1488 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001489 }
1490
1491 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1492 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001493 delay = 500;
1494 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001495 }
1496
peahdf3efa82015-11-28 12:35:15 -08001497 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001498 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001499}
1500
1501int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001502 // Used as callback from submodules, hence locking is not allowed.
1503 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001504}
1505
1506bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001507 // Used as callback from submodules, hence locking is not allowed.
1508 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001509}
1510
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001511void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001512 rtc::CritScope cs(&crit_capture_);
1513 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001514}
1515
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001516void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001517 rtc::CritScope cs(&crit_capture_);
1518 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001519}
1520
1521int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001522 rtc::CritScope cs(&crit_capture_);
1523 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001524}
1525
niklase@google.com470e71d2011-07-07 08:21:25 +00001526int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001527 const char filename[AudioProcessing::kMaxFilenameSize],
1528 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001529 // Run in a single-threaded manner.
1530 rtc::CritScope cs_render(&crit_render_);
1531 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001532 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001533
peahdf3efa82015-11-28 12:35:15 -08001534 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001535 return kNullPointerError;
1536 }
1537
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001538#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001539 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001540 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001541 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001542
tommia6219cc2016-06-15 10:30:14 -07001543 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001544 return kFileError;
1545 }
1546
Minyue13b96ba2015-10-03 00:39:14 +02001547 RETURN_ON_ERR(WriteConfigMessage(true));
1548 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001549 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001550#else
1551 return kUnsupportedFunctionError;
1552#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001553}
1554
ivocd66b44d2016-01-15 03:06:36 -08001555int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1556 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001557 // Run in a single-threaded manner.
1558 rtc::CritScope cs_render(&crit_render_);
1559 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001560
peahdf3efa82015-11-28 12:35:15 -08001561 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001562 return kNullPointerError;
1563 }
1564
1565#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001566 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1567
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001568 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001569 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001570
tommia6219cc2016-06-15 10:30:14 -07001571 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001572 return kFileError;
1573 }
1574
Minyue13b96ba2015-10-03 00:39:14 +02001575 RETURN_ON_ERR(WriteConfigMessage(true));
1576 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001577 return kNoError;
1578#else
1579 return kUnsupportedFunctionError;
1580#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1581}
1582
peah73a28ee2016-10-12 03:01:49 -07001583int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1584 return StartDebugRecording(handle, -1);
1585}
1586
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001587int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1588 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001589 // Run in a single-threaded manner.
1590 rtc::CritScope cs_render(&crit_render_);
1591 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001592 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001593 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001594}
1595
niklase@google.com470e71d2011-07-07 08:21:25 +00001596int AudioProcessingImpl::StopDebugRecording() {
peahdf3efa82015-11-28 12:35:15 -08001597 // Run in a single-threaded manner.
1598 rtc::CritScope cs_render(&crit_render_);
1599 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001600
1601#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001602 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001603 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001604 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001605#else
1606 return kUnsupportedFunctionError;
1607#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001608}
1609
ivoc4e477a12017-01-15 08:29:46 -08001610AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1611 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1612 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1613 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1614 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1615}
1616
1617AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1618 const AudioProcessingStatistics& other) = default;
1619
1620AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1621 default;
1622
ivoc3e9a5372016-10-28 07:55:33 -07001623// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1624AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1625 const {
1626 return AudioProcessingStatistics();
1627}
1628
1629AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1630 const {
1631 AudioProcessingStatistics stats;
1632 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001633 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1634 if (success == Error::kNoError) {
1635 stats.a_nlp.Set(metrics.a_nlp);
1636 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1637 stats.echo_return_loss.Set(metrics.echo_return_loss);
1638 stats.echo_return_loss_enhancement.Set(
1639 metrics.echo_return_loss_enhancement);
1640 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1641 }
ivoc9c192b22017-03-16 04:22:14 -07001642 {
1643 rtc::CritScope cs_capture(&crit_capture_);
1644 stats.residual_echo_likelihood =
1645 private_submodules_->residual_echo_detector->echo_likelihood();
1646 stats.residual_echo_likelihood_recent_max =
1647 private_submodules_->residual_echo_detector
1648 ->echo_likelihood_recent_max();
1649 }
ivoc3e9a5372016-10-28 07:55:33 -07001650 public_submodules_->echo_cancellation->GetDelayMetrics(
1651 &stats.delay_median, &stats.delay_standard_deviation,
1652 &stats.fraction_poor_delays);
1653 return stats;
1654}
1655
niklase@google.com470e71d2011-07-07 08:21:25 +00001656EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001657 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001658}
1659
1660EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001661 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001662}
1663
1664GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001665 if (constants_.use_experimental_agc) {
1666 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001667 }
peahbfa97112016-03-10 21:09:04 -08001668 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001669}
1670
1671HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001672 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001673}
1674
1675LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001676 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001677}
1678
1679NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001680 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001681}
1682
1683VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001684 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001685}
1686
peah8271d042016-11-22 07:24:52 -08001687void AudioProcessingImpl::MutateConfig(
1688 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1689 rtc::CritScope cs_render(&crit_render_);
1690 rtc::CritScope cs_capture(&crit_capture_);
1691 mutator(&config_);
1692 ApplyConfig(config_);
1693}
1694
1695AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1696 rtc::CritScope cs_render(&crit_render_);
1697 rtc::CritScope cs_capture(&crit_capture_);
1698 return config_;
1699}
1700
peah2ace3f92016-09-10 04:42:27 -07001701bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1702 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001703 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001704 public_submodules_->echo_cancellation->is_enabled(),
1705 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001706 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001707 public_submodules_->noise_suppression->is_enabled(),
1708 capture_nonlocked_.intelligibility_enabled,
1709 capture_nonlocked_.beamformer_enabled,
1710 public_submodules_->gain_control->is_enabled(),
1711 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001712 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001713 public_submodules_->voice_detection->is_enabled(),
1714 public_submodules_->level_estimator->is_enabled(),
1715 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001716}
1717
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001718
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001719void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001720 if (capture_.transient_suppressor_enabled) {
1721 if (!public_submodules_->transient_suppressor.get()) {
1722 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001723 }
peahdf3efa82015-11-28 12:35:15 -08001724 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001725 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1726 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001727 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001728}
1729
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001730void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001731 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001732 if (!private_submodules_->beamformer) {
1733 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001734 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001735 }
peahdf3efa82015-11-28 12:35:15 -08001736 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1737 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001738 }
1739}
1740
ekmeyerson60d9b332015-08-14 10:35:55 -07001741void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001742#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001743 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001744 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001745 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001746 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001747 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001748 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001749 }
peah1bcfce52016-08-26 07:16:04 -07001750#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001751}
1752
peah8271d042016-11-22 07:24:52 -08001753void AudioProcessingImpl::InitializeLowCutFilter() {
1754 if (config_.high_pass_filter.enabled) {
1755 private_submodules_->low_cut_filter.reset(
1756 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1757 } else {
1758 private_submodules_->low_cut_filter.reset();
1759 }
1760}
peahe0eae3c2016-12-14 01:16:23 -08001761void AudioProcessingImpl::InitializeEchoCanceller3() {
1762 if (capture_nonlocked_.echo_canceller3_enabled) {
1763 private_submodules_->echo_canceller3.reset(
1764 new EchoCanceller3(proc_sample_rate_hz(), true));
1765 } else {
1766 private_submodules_->echo_canceller3.reset();
1767 }
1768}
peah8271d042016-11-22 07:24:52 -08001769
peahca4cac72016-06-29 15:26:12 -07001770void AudioProcessingImpl::InitializeLevelController() {
1771 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1772}
1773
ivoc9f4a4a02016-10-28 05:39:16 -07001774void AudioProcessingImpl::InitializeResidualEchoDetector() {
1775 private_submodules_->residual_echo_detector->Initialize();
1776}
1777
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001778void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001779 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001780
1781 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001782 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1783 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001784 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001785 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001786 capture_.stream_delay_jumps = 0;
1787 }
1788 if (capture_.aec_system_delay_jumps == -1 &&
1789 echo_cancellation()->stream_has_echo()) {
1790 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001791 }
1792
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001793 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001794 const int diff_stream_delay_ms =
1795 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1796 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1797 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001798 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1799 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001800 if (capture_.stream_delay_jumps == -1) {
1801 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001802 }
peahdf3efa82015-11-28 12:35:15 -08001803 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001804 }
peahdf3efa82015-11-28 12:35:15 -08001805 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001806
1807 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001808 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001809 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001810 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001811 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001812 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1813 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001814 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001815 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001816 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001817 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001818 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1819 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1820 100);
peahdf3efa82015-11-28 12:35:15 -08001821 if (capture_.aec_system_delay_jumps == -1) {
1822 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001823 }
peahdf3efa82015-11-28 12:35:15 -08001824 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001825 }
peahdf3efa82015-11-28 12:35:15 -08001826 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001827 }
1828}
1829
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001830void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001831 // Run in a single-threaded manner.
1832 rtc::CritScope cs_render(&crit_render_);
1833 rtc::CritScope cs_capture(&crit_capture_);
1834
1835 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001836 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001837 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001838 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001839 }
peahdf3efa82015-11-28 12:35:15 -08001840 capture_.stream_delay_jumps = -1;
1841 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001842
peahdf3efa82015-11-28 12:35:15 -08001843 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001844 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1845 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001846 }
peahdf3efa82015-11-28 12:35:15 -08001847 capture_.aec_system_delay_jumps = -1;
1848 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001849}
1850
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001851#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001852int AudioProcessingImpl::WriteMessageToDebugFile(
1853 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08001854 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08001855 rtc::CriticalSection* crit_debug,
1856 ApmDebugDumpThreadState* debug_state) {
1857 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00001858 if (size <= 0) {
1859 return kUnspecifiedError;
1860 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00001861#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07001862// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
1863// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00001864#endif
1865
peahdf3efa82015-11-28 12:35:15 -08001866 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00001867 return kUnspecifiedError;
1868 }
1869
peahdf3efa82015-11-28 12:35:15 -08001870 {
1871 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08001872 rtc::CritScope cs_debug(crit_debug);
1873
tommia6219cc2016-06-15 10:30:14 -07001874 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08001875 // Update the byte counter.
1876 if (*filesize_limit_bytes >= 0) {
1877 *filesize_limit_bytes -=
1878 (sizeof(int32_t) + debug_state->event_str.length());
1879 if (*filesize_limit_bytes < 0) {
1880 // Not enough bytes are left to write this message, so stop logging.
1881 debug_file->CloseFile();
1882 return kNoError;
1883 }
1884 }
peahdf3efa82015-11-28 12:35:15 -08001885 // Write message preceded by its size.
1886 if (!debug_file->Write(&size, sizeof(int32_t))) {
1887 return kFileError;
1888 }
1889 if (!debug_file->Write(debug_state->event_str.data(),
1890 debug_state->event_str.length())) {
1891 return kFileError;
1892 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001893 }
1894
peahdf3efa82015-11-28 12:35:15 -08001895 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00001896
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001897 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001898}
1899
1900int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08001901 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
1902 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
1903 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00001904
mbonadei7c2c8432017-04-07 00:59:12 -07001905 msg->set_num_input_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001906 formats_.api_format.input_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07001907 msg->set_num_output_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001908 formats_.api_format.output_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07001909 msg->set_num_reverse_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001910 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08001911 msg->set_reverse_sample_rate(
1912 formats_.api_format.reverse_input_stream().sample_rate_hz());
1913 msg->set_output_sample_rate(
1914 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07001915 msg->set_reverse_output_sample_rate(
1916 formats_.api_format.reverse_output_stream().sample_rate_hz());
1917 msg->set_num_reverse_output_channels(
1918 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08001919
1920 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001921 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001922 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02001923 return kNoError;
1924}
1925
1926int AudioProcessingImpl::WriteConfigMessage(bool forced) {
1927 audioproc::Config config;
1928
peahdf3efa82015-11-28 12:35:15 -08001929 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001930 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08001931 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001932 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08001933 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001934 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08001935 public_submodules_->echo_cancellation->is_extended_filter_enabled());
1936 config.set_aec_suppression_level(static_cast<int>(
1937 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02001938
peahdf3efa82015-11-28 12:35:15 -08001939 config.set_aecm_enabled(
1940 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001941 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08001942 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
1943 config.set_aecm_routing_mode(static_cast<int>(
1944 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02001945
peahdf3efa82015-11-28 12:35:15 -08001946 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
1947 config.set_agc_mode(
1948 static_cast<int>(public_submodules_->gain_control->mode()));
1949 config.set_agc_limiter_enabled(
1950 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08001951 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02001952
peah8271d042016-11-22 07:24:52 -08001953 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001954
peahdf3efa82015-11-28 12:35:15 -08001955 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
1956 config.set_ns_level(
1957 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02001958
peahdf3efa82015-11-28 12:35:15 -08001959 config.set_transient_suppression_enabled(
1960 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001961 config.set_intelligibility_enhancer_enabled(
1962 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001963
peah7789fe72016-04-15 01:19:44 -07001964 std::string experiments_description =
1965 public_submodules_->echo_cancellation->GetExperimentsDescription();
1966 // TODO(peah): Add semicolon-separated concatenations of experiment
1967 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07001968 if (capture_nonlocked_.level_controller_enabled) {
1969 experiments_description += "LevelController;";
1970 }
henrik.lundinbd681b92016-12-05 09:08:42 -08001971 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1972 experiments_description += "AgcClippingLevelExperiment;";
1973 }
peahe0eae3c2016-12-14 01:16:23 -08001974 if (capture_nonlocked_.echo_canceller3_enabled) {
1975 experiments_description += "EchoCanceller3;";
1976 }
peah7789fe72016-04-15 01:19:44 -07001977 config.set_experiments_description(experiments_description);
1978
mbonadei7c2c8432017-04-07 00:59:12 -07001979 ProtoString serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08001980 if (!forced &&
1981 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02001982 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001983 }
1984
peahdf3efa82015-11-28 12:35:15 -08001985 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02001986
peahdf3efa82015-11-28 12:35:15 -08001987 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
1988 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02001989
peahdf3efa82015-11-28 12:35:15 -08001990 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001991 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001992 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00001993 return kNoError;
1994}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001995#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001996
kwiberg83ffe452016-08-29 14:46:07 -07001997AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1998 bool transient_suppressor_enabled,
1999 const std::vector<Point>& array_geometry,
2000 SphericalPointf target_direction)
2001 : aec_system_delay_jumps(-1),
2002 delay_offset_ms(0),
2003 was_stream_delay_set(false),
2004 last_stream_delay_ms(0),
2005 last_aec_system_delay_ms(0),
2006 stream_delay_jumps(-1),
2007 output_will_be_muted(false),
2008 key_pressed(false),
2009 transient_suppressor_enabled(transient_suppressor_enabled),
2010 array_geometry(array_geometry),
2011 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002012 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002013 split_rate(kSampleRate16kHz),
2014 previous_agc_level(0),
2015 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002016
2017AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2018
2019AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2020
2021AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2022
niklase@google.com470e71d2011-07-07 08:21:25 +00002023} // namespace webrtc