blob: af5e94b60293ba74d2524a2a9036cd88c2bdd6fa [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
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
niklase@google.com470e71d2011-07-07 08:21:25 +000014
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020015#include "webrtc/base/checks.h"
nisse368f5cf2017-04-05 05:00:33 -070016#include "webrtc/base/logging.h"
xians@webrtc.orge46bc772014-10-10 08:36:56 +000017#include "webrtc/base/platform_file.h"
peah369f8282015-12-17 06:42:29 -080018#include "webrtc/base/trace_event.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070019#include "webrtc/common_audio/audio_converter.h"
Michael Graczykdfa36052015-03-25 16:37:27 -070020#include "webrtc/common_audio/channel_buffer.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070021#include "webrtc/common_audio/include/audio_util.h"
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000022#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020023#include "webrtc/modules/audio_processing/aec/aec_core.h"
peahe0eae3c2016-12-14 01:16:23 -080024#include "webrtc/modules/audio_processing/aec3/echo_canceller3.h"
pbos@webrtc.org788acd12014-12-15 09:41:24 +000025#include "webrtc/modules/audio_processing/agc/agc_manager_direct.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000026#include "webrtc/modules/audio_processing/audio_buffer.h"
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +000027#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000028#include "webrtc/modules/audio_processing/common.h"
andrew@webrtc.org56e4a052014-02-27 22:23:17 +000029#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000030#include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
peahbe615622016-02-13 16:40:47 -080031#include "webrtc/modules/audio_processing/gain_control_for_experimental_agc.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000032#include "webrtc/modules/audio_processing/gain_control_impl.h"
peah1bcfce52016-08-26 07:16:04 -070033#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -070034#include "webrtc/modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070035#endif
peahca4cac72016-06-29 15:26:12 -070036#include "webrtc/modules/audio_processing/level_controller/level_controller.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000037#include "webrtc/modules/audio_processing/level_estimator_impl.h"
peah8271d042016-11-22 07:24:52 -080038#include "webrtc/modules/audio_processing/low_cut_filter.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000039#include "webrtc/modules/audio_processing/noise_suppression_impl.h"
ivoc9f4a4a02016-10-28 05:39:16 -070040#include "webrtc/modules/audio_processing/residual_echo_detector.h"
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +000041#include "webrtc/modules/audio_processing/transient/transient_suppressor.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000042#include "webrtc/modules/audio_processing/voice_detection_impl.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010043#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010044#include "webrtc/system_wrappers/include/file_wrapper.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010045#include "webrtc/system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000046
47#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
48// Files generated at build-time by the protobuf compiler.
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000049#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000050#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000051#else
kjellander78ddd732016-02-09 08:13:06 -080052#include "webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000053#endif
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000054#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +000055
peah1bcfce52016-08-26 07:16:04 -070056// Check to verify that the define for the intelligibility enhancer is properly
57// set.
58#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
59 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
60 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
61#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
62#endif
63
Michael Graczyk86c6d332015-07-23 11:41:39 -070064#define RETURN_ON_ERR(expr) \
65 do { \
66 int err = (expr); \
67 if (err != kNoError) { \
68 return err; \
69 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000070 } while (0)
71
niklase@google.com470e71d2011-07-07 08:21:25 +000072namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070073
kwibergd59d3bb2016-09-13 07:49:33 -070074constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070075
Michael Graczyk86c6d332015-07-23 11:41:39 -070076namespace {
77
78static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
79 switch (layout) {
80 case AudioProcessing::kMono:
81 case AudioProcessing::kStereo:
82 return false;
83 case AudioProcessing::kMonoAndKeyboard:
84 case AudioProcessing::kStereoAndKeyboard:
85 return true;
86 }
87
kwiberg9e2be5f2016-09-14 05:23:22 -070088 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070089 return false;
90}
aluebsdf6416a2016-03-16 18:26:35 -070091
peah2ace3f92016-09-10 04:42:27 -070092bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070093 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
94 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
95}
96
peah2ace3f92016-09-10 04:42:27 -070097int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
98#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070099 constexpr int kMaxSplittingNativeProcessRate =
100 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -0700101#else
kwibergd59d3bb2016-09-13 07:49:33 -0700102 constexpr int kMaxSplittingNativeProcessRate =
103 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700104#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700105 static_assert(
106 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
107 "");
peah2ace3f92016-09-10 04:42:27 -0700108 const int uppermost_native_rate = band_splitting_required
109 ? kMaxSplittingNativeProcessRate
110 : AudioProcessing::kSampleRate48kHz;
111
112 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
113 if (rate >= uppermost_native_rate) {
114 return uppermost_native_rate;
115 }
116 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700117 return rate;
118 }
119 }
peah2ace3f92016-09-10 04:42:27 -0700120 RTC_NOTREACHED();
121 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700122}
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum length that a frame of samples can have.
125static const size_t kMaxAllowedValuesOfSamplesPerFrame = 160;
126// Maximum number of frames to buffer in the render queue.
127// TODO(peah): Decrease this once we properly handle hugely unbalanced
128// reverse and forward call numbers.
129static const size_t kMaxNumFramesToBuffer = 100;
130
peah8271d042016-11-22 07:24:52 -0800131class HighPassFilterImpl : public HighPassFilter {
132 public:
133 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
134 ~HighPassFilterImpl() override = default;
135
136 // HighPassFilter implementation.
137 int Enable(bool enable) override {
138 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
139 config->high_pass_filter.enabled = enable;
140 });
141
142 return AudioProcessing::kNoError;
143 }
144
145 bool is_enabled() const override {
146 return apm_->GetConfig().high_pass_filter.enabled;
147 }
148
149 private:
150 AudioProcessingImpl* apm_;
151 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
152};
153
Michael Graczyk86c6d332015-07-23 11:41:39 -0700154} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000155
156// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000157static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000158
peah2ace3f92016-09-10 04:42:27 -0700159AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates() {}
160
161bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800162 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700163 bool echo_canceller_enabled,
164 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700165 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool noise_suppressor_enabled,
167 bool intelligibility_enhancer_enabled,
168 bool beamformer_enabled,
169 bool adaptive_gain_controller_enabled,
170 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800171 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700172 bool voice_activity_detector_enabled,
173 bool level_estimator_enabled,
174 bool transient_suppressor_enabled) {
175 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800176 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700177 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
178 changed |=
179 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700180 changed |=
181 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700182 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
183 changed |=
184 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
185 changed |= (beamformer_enabled != beamformer_enabled_);
186 changed |=
187 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
188 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800189 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700190 changed |= (level_estimator_enabled != level_estimator_enabled_);
191 changed |=
192 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
193 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
194 if (changed) {
peah8271d042016-11-22 07:24:52 -0800195 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700196 echo_canceller_enabled_ = echo_canceller_enabled;
197 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700198 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700199 noise_suppressor_enabled_ = noise_suppressor_enabled;
200 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
201 beamformer_enabled_ = beamformer_enabled;
202 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
203 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800204 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700205 level_estimator_enabled_ = level_estimator_enabled;
206 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
207 transient_suppressor_enabled_ = transient_suppressor_enabled;
208 }
209
210 changed |= first_update_;
211 first_update_ = false;
212 return changed;
213}
214
215bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
216 const {
217#if WEBRTC_INTELLIGIBILITY_ENHANCER
218 return CaptureMultiBandProcessingActive() ||
ivoc20270be2016-11-15 05:24:35 -0800219 intelligibility_enhancer_enabled_ ||
220 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700221#else
ivoc20270be2016-11-15 05:24:35 -0800222 return CaptureMultiBandProcessingActive() ||
223 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700224#endif
225}
226
227bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
228 const {
peah8271d042016-11-22 07:24:52 -0800229 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700230 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800231 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
232 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700233}
234
235bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
236 const {
237 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800238 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800239 residual_echo_detector_enabled_ || echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700240}
241
242bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
243 const {
244#if WEBRTC_INTELLIGIBILITY_ENHANCER
245 return intelligibility_enhancer_enabled_;
246#else
247 return false;
248#endif
249}
250
solenberg5e465c32015-12-08 13:22:33 -0800251struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800252 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800253 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800254 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800255 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800256 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800257 std::unique_ptr<LevelEstimatorImpl> level_estimator;
258 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
259 std::unique_ptr<VoiceDetectionImpl> voice_detection;
260 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800261 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800262
263 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800264 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700265#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800266 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700267#endif
solenberg5e465c32015-12-08 13:22:33 -0800268};
269
270struct AudioProcessingImpl::ApmPrivateSubmodules {
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700271 explicit ApmPrivateSubmodules(NonlinearBeamformer* beamformer)
solenberg5e465c32015-12-08 13:22:33 -0800272 : beamformer(beamformer) {}
273 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700274 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800275 std::unique_ptr<AgcManagerDirect> agc_manager;
peah8271d042016-11-22 07:24:52 -0800276 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700277 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700278 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
peahe0eae3c2016-12-14 01:16:23 -0800279 std::unique_ptr<EchoCanceller3> echo_canceller3;
solenberg5e465c32015-12-08 13:22:33 -0800280};
281
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000282AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700283 webrtc::Config config;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000284 return Create(config, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000285}
286
peah88ac8532016-09-12 16:47:25 -0700287AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000288 return Create(config, nullptr);
289}
290
peah88ac8532016-09-12 16:47:25 -0700291AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700292 NonlinearBeamformer* beamformer) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000293 AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000294 if (apm->Initialize() != kNoError) {
295 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800296 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000297 }
298
299 return apm;
300}
301
peah88ac8532016-09-12 16:47:25 -0700302AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000303 : AudioProcessingImpl(config, nullptr) {}
304
peah88ac8532016-09-12 16:47:25 -0700305AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700306 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800307 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
308 public_submodules_(new ApmPublicSubmodules()),
peahdf3efa82015-11-28 12:35:15 -0800309 private_submodules_(new ApmPrivateSubmodules(beamformer)),
310 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800311 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000312#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700313 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000314#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700315 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000316#endif
andrew1c7075f2015-06-24 18:14:14 -0700317#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800318 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700319#else
aluebs2a346882016-01-11 18:04:30 -0800320 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700321#endif
aluebs2a346882016-01-11 18:04:30 -0800322 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800323 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700324 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700325 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800326 {
327 rtc::CritScope cs_render(&crit_render_);
328 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000329
peahb624d8c2016-03-05 03:01:14 -0800330 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700331 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800332 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700333 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800334 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700335 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800336 public_submodules_->level_estimator.reset(
337 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800338 public_submodules_->noise_suppression.reset(
339 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800340 public_submodules_->voice_detection.reset(
341 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800342 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800343 new GainControlForExperimentalAgc(
344 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700345 private_submodules_->residual_echo_detector.reset(
346 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700347
peahc19f3122016-10-07 14:54:10 -0700348 // TODO(peah): Move this creation to happen only when the level controller
349 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700350 private_submodules_->level_controller.reset(new LevelController());
peahdf3efa82015-11-28 12:35:15 -0800351 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000352
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000353 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000354}
355
356AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800357 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800358 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800359 private_submodules_->agc_manager.reset();
360 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800361 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000362
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000363#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700364 debug_dump_.debug_file->CloseFile();
peahdf3efa82015-11-28 12:35:15 -0800365#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000366}
367
niklase@google.com470e71d2011-07-07 08:21:25 +0000368int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800369 // Run in a single-threaded manner during initialization.
370 rtc::CritScope cs_render(&crit_render_);
371 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000372 return InitializeLocked();
373}
374
peahde65ddc2016-09-16 15:02:15 -0700375int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
376 int capture_output_sample_rate_hz,
377 int render_input_sample_rate_hz,
378 ChannelLayout capture_input_layout,
379 ChannelLayout capture_output_layout,
380 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700381 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700382 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
383 LayoutHasKeyboard(capture_input_layout)},
384 {capture_output_sample_rate_hz,
385 ChannelsFromLayout(capture_output_layout),
386 LayoutHasKeyboard(capture_output_layout)},
387 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
388 LayoutHasKeyboard(render_input_layout)},
389 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
390 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700391
392 return Initialize(processing_config);
393}
394
395int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800396 // Run in a single-threaded manner during initialization.
397 rtc::CritScope cs_render(&crit_render_);
398 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700399 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000400}
401
peahdf3efa82015-11-28 12:35:15 -0800402int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800403 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700404 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800405}
406
peahdf3efa82015-11-28 12:35:15 -0800407int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700408 const ProcessingConfig& processing_config,
409 bool force_initialization) {
410 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800411}
412
kwiberg83ffe452016-08-29 14:46:07 -0700413#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
414
415AudioProcessingImpl::ApmDebugDumpThreadState::ApmDebugDumpThreadState()
416 : event_msg(new audioproc::Event()) {}
417
418AudioProcessingImpl::ApmDebugDumpThreadState::~ApmDebugDumpThreadState() {}
419
420AudioProcessingImpl::ApmDebugDumpState::ApmDebugDumpState()
421 : debug_file(FileWrapper::Create()) {}
422
423AudioProcessingImpl::ApmDebugDumpState::~ApmDebugDumpState() {}
424
425#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
426
peah192164e2015-11-17 02:16:45 -0800427// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800428// their current values (needs to be called while holding the crit_render_lock).
429int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700430 const ProcessingConfig& processing_config,
431 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800432 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700433 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800434 return kNoError;
435 }
peahdf3efa82015-11-28 12:35:15 -0800436
437 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800438 return InitializeLocked(processing_config);
439}
440
niklase@google.com470e71d2011-07-07 08:21:25 +0000441int AudioProcessingImpl::InitializeLocked() {
peah522d71b2017-02-23 05:16:26 -0800442 const int capture_audiobuffer_num_channels =
443 capture_nonlocked_.beamformer_enabled
444 ? formats_.api_format.input_stream().num_channels()
445 : formats_.api_format.output_stream().num_channels();
446
peahde65ddc2016-09-16 15:02:15 -0700447 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800448 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700449 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800450 : formats_.api_format.reverse_output_stream().num_frames();
451 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
452 render_.render_audio.reset(new AudioBuffer(
453 formats_.api_format.reverse_input_stream().num_frames(),
454 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700455 formats_.render_processing_format.num_frames(),
456 formats_.render_processing_format.num_channels(),
457 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700458 if (formats_.api_format.reverse_input_stream() !=
459 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800460 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800461 formats_.api_format.reverse_input_stream().num_channels(),
462 formats_.api_format.reverse_input_stream().num_frames(),
463 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800464 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700465 } else {
peahdf3efa82015-11-28 12:35:15 -0800466 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700467 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700468 } else {
peahdf3efa82015-11-28 12:35:15 -0800469 render_.render_audio.reset(nullptr);
470 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700471 }
peahdf3efa82015-11-28 12:35:15 -0800472 capture_.capture_audio.reset(
473 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
474 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700475 capture_nonlocked_.capture_processing_format.num_frames(),
476 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800477 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000478
peahde65ddc2016-09-16 15:02:15 -0700479 public_submodules_->echo_cancellation->Initialize(
480 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
481 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700482 AllocateRenderQueue();
483
ivoc3e9a5372016-10-28 07:55:33 -0700484 int success = public_submodules_->echo_cancellation->enable_metrics(true);
485 RTC_DCHECK_EQ(0, success);
486 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
487 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700488 public_submodules_->echo_control_mobile->Initialize(
489 proc_split_sample_rate_hz(), num_reverse_channels(),
490 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700491
492 public_submodules_->gain_control->Initialize(num_proc_channels(),
493 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700494 if (constants_.use_experimental_agc) {
495 if (!private_submodules_->agc_manager.get()) {
496 private_submodules_->agc_manager.reset(new AgcManagerDirect(
497 public_submodules_->gain_control.get(),
498 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800499 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700500 }
501 private_submodules_->agc_manager->Initialize();
502 private_submodules_->agc_manager->SetCaptureMuted(
503 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700504 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700505 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200506 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000507 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700508#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700509 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700510#endif
peah8271d042016-11-22 07:24:52 -0800511 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700512 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
513 proc_sample_rate_hz());
514 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
515 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700516 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700517 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800518 InitializeEchoCanceller3();
solenberg70f99032015-12-08 11:07:32 -0800519
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000520#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700521 if (debug_dump_.debug_file->is_open()) {
ajm@google.com808e0e02011-08-03 21:08:51 +0000522 int err = WriteInitMessage();
523 if (err != kNoError) {
524 return err;
525 }
526 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000527#endif
ajm@google.com808e0e02011-08-03 21:08:51 +0000528
niklase@google.com470e71d2011-07-07 08:21:25 +0000529 return kNoError;
530}
531
Michael Graczyk86c6d332015-07-23 11:41:39 -0700532int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
533 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700534 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
535 return kBadSampleRateError;
536 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000537 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700538
Peter Kasting69558702016-01-12 16:26:35 -0800539 const size_t num_in_channels = config.input_stream().num_channels();
540 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700541
542 // Need at least one input channel.
543 // Need either one output channel or as many outputs as there are inputs.
544 if (num_in_channels == 0 ||
545 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700546 return kBadNumberChannelsError;
547 }
548
aluebsb2328d12016-01-11 20:32:29 -0800549 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800550 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700551 return kBadNumberChannelsError;
552 }
553
peahdf3efa82015-11-28 12:35:15 -0800554 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000555
peahde65ddc2016-09-16 15:02:15 -0700556 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700557 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700558 formats_.api_format.output_stream().sample_rate_hz()),
559 submodule_states_.CaptureMultiBandSubModulesActive() ||
560 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000561
peahde65ddc2016-09-16 15:02:15 -0700562 capture_nonlocked_.capture_processing_format =
563 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700564
peah2ce640f2017-04-07 03:57:48 -0700565 int render_processing_rate;
566 if (!config_.echo_canceller3.enabled) {
567 render_processing_rate = FindNativeProcessRateToUse(
568 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
569 formats_.api_format.reverse_output_stream().sample_rate_hz()),
570 submodule_states_.CaptureMultiBandSubModulesActive() ||
571 submodule_states_.RenderMultiBandSubModulesActive());
572 } else {
573 render_processing_rate = capture_processing_rate;
574 }
575
aluebseb3603b2016-04-20 15:27:58 -0700576 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
577 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700578 if (render_processing_rate > kSampleRate32kHz &&
579 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700580 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
581 ? kSampleRate32kHz
582 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700583 }
peah2ce640f2017-04-07 03:57:48 -0700584
peahde65ddc2016-09-16 15:02:15 -0700585 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700586 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700587 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
588 kSampleRate8kHz) {
589 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000590 } else {
peahde65ddc2016-09-16 15:02:15 -0700591 render_processing_rate =
592 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000593 }
594
peahde65ddc2016-09-16 15:02:15 -0700595 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000596 // demonstrated to work well for AEC in most practical scenarios.
peahde65ddc2016-09-16 15:02:15 -0700597 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000598
peahde65ddc2016-09-16 15:02:15 -0700599 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
600 kSampleRate32kHz ||
601 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
602 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800603 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000604 } else {
peahdf3efa82015-11-28 12:35:15 -0800605 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700606 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000607 }
608
609 return InitializeLocked();
610}
611
peah88ac8532016-09-12 16:47:25 -0700612void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700613 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700614
peahc19f3122016-10-07 14:54:10 -0700615 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700616 if (!config_ok) {
617 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
618 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700619 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700620 << std::endl
621 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700622 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700623 }
624
625 // Run in a single-threaded manner when applying the settings.
626 rtc::CritScope cs_render(&crit_render_);
627 rtc::CritScope cs_capture(&crit_capture_);
628
peahc19f3122016-10-07 14:54:10 -0700629 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
630 // with the value in config_ everywhere in the code.
631 if (capture_nonlocked_.level_controller_enabled !=
632 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700633 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700634 config_.level_controller.enabled;
635 // TODO(peah): Remove the conditional initialization to always initialize
636 // the level controller regardless of whether it is enabled or not.
637 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700638 }
peahc19f3122016-10-07 14:54:10 -0700639 LOG(LS_INFO) << "Level controller activated: "
640 << capture_nonlocked_.level_controller_enabled;
641
642 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800643
644 InitializeLowCutFilter();
645
646 LOG(LS_INFO) << "Highpass filter activated: "
647 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800648
649 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
650 if (!config_ok) {
651 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
652 << "echo canceller 3: "
653 << EchoCanceller3::ToString(config_.echo_canceller3)
654 << std::endl
655 << "Reverting to default parameter set";
656 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
657 }
658
659 if (config.echo_canceller3.enabled !=
660 capture_nonlocked_.echo_canceller3_enabled) {
661 capture_nonlocked_.echo_canceller3_enabled =
662 config_.echo_canceller3.enabled;
663 InitializeEchoCanceller3();
664 LOG(LS_INFO) << "Echo canceller 3 activated: "
665 << capture_nonlocked_.echo_canceller3_enabled;
666 }
peah88ac8532016-09-12 16:47:25 -0700667}
668
669void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800670 // Run in a single-threaded manner when setting the extra options.
671 rtc::CritScope cs_render(&crit_render_);
672 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000673
peahb624d8c2016-03-05 03:01:14 -0800674 public_submodules_->echo_cancellation->SetExtraOptions(config);
675
peahdf3efa82015-11-28 12:35:15 -0800676 if (capture_.transient_suppressor_enabled !=
677 config.Get<ExperimentalNs>().enabled) {
678 capture_.transient_suppressor_enabled =
679 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000680 InitializeTransient();
681 }
aluebs2a346882016-01-11 18:04:30 -0800682
peah1bcfce52016-08-26 07:16:04 -0700683#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700684 if(capture_nonlocked_.intelligibility_enabled !=
685 config.Get<Intelligibility>().enabled) {
686 capture_nonlocked_.intelligibility_enabled =
687 config.Get<Intelligibility>().enabled;
688 InitializeIntelligibility();
689 }
peah1bcfce52016-08-26 07:16:04 -0700690#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700691
aluebs2a346882016-01-11 18:04:30 -0800692#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800693 if (capture_nonlocked_.beamformer_enabled !=
694 config.Get<Beamforming>().enabled) {
695 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800696 if (config.Get<Beamforming>().array_geometry.size() > 1) {
697 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
698 }
699 capture_.target_direction = config.Get<Beamforming>().target_direction;
700 InitializeBeamformer();
701 }
702#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000703}
704
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000705int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800706 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700707 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000708}
709
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000710int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800711 // Used as callback from submodules, hence locking is not allowed.
712 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000713}
714
Peter Kasting69558702016-01-12 16:26:35 -0800715size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800716 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700717 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000718}
719
Peter Kasting69558702016-01-12 16:26:35 -0800720size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800721 // Used as callback from submodules, hence locking is not allowed.
722 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000723}
724
Peter Kasting69558702016-01-12 16:26:35 -0800725size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800726 // Used as callback from submodules, hence locking is not allowed.
727 return capture_nonlocked_.beamformer_enabled ? 1 : num_output_channels();
728}
729
Peter Kasting69558702016-01-12 16:26:35 -0800730size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800731 // Used as callback from submodules, hence locking is not allowed.
732 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000733}
734
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000735void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800736 rtc::CritScope cs(&crit_capture_);
737 capture_.output_will_be_muted = muted;
738 if (private_submodules_->agc_manager.get()) {
739 private_submodules_->agc_manager->SetCaptureMuted(
740 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000741 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000742}
743
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000744
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000745int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700746 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000747 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000748 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000749 int output_sample_rate_hz,
750 ChannelLayout output_layout,
751 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800752 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800753 StreamConfig input_stream;
754 StreamConfig output_stream;
755 {
756 // Access the formats_.api_format.input_stream beneath the capture lock.
757 // The lock must be released as it is later required in the call
758 // to ProcessStream(,,,);
759 rtc::CritScope cs(&crit_capture_);
760 input_stream = formats_.api_format.input_stream();
761 output_stream = formats_.api_format.output_stream();
762 }
763
Michael Graczyk86c6d332015-07-23 11:41:39 -0700764 input_stream.set_sample_rate_hz(input_sample_rate_hz);
765 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
766 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700767 output_stream.set_sample_rate_hz(output_sample_rate_hz);
768 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
769 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
770
771 if (samples_per_channel != input_stream.num_frames()) {
772 return kBadDataLengthError;
773 }
774 return ProcessStream(src, input_stream, output_stream, dest);
775}
776
777int AudioProcessingImpl::ProcessStream(const float* const* src,
778 const StreamConfig& input_config,
779 const StreamConfig& output_config,
780 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800781 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800782 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700783 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800784 {
785 // Acquire the capture lock in order to safely call the function
786 // that retrieves the render side data. This function accesses apm
787 // getters that need the capture lock held when being called.
788 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700789 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800790
791 if (!src || !dest) {
792 return kNullPointerError;
793 }
794
795 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700796 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000797 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000798
Michael Graczyk86c6d332015-07-23 11:41:39 -0700799 processing_config.input_stream() = input_config;
800 processing_config.output_stream() = output_config;
801
peahdf3efa82015-11-28 12:35:15 -0800802 {
803 // Do conditional reinitialization.
804 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700805 RETURN_ON_ERR(
806 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800807 }
808 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700809 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
810 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000811
812#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700813 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200814 RETURN_ON_ERR(WriteConfigMessage(false));
815
peahdf3efa82015-11-28 12:35:15 -0800816 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
817 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000818 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800819 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800820 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
821 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000822 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000823 }
824#endif
825
peahdf3efa82015-11-28 12:35:15 -0800826 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700827 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800828 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000829
830#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700831 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800832 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000833 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800834 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800835 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
836 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000837 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800838 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800839 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800840 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000841 }
842#endif
843
844 return kNoError;
845}
846
peah701d6282016-10-25 05:42:20 -0700847void AudioProcessingImpl::QueueRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700848 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
849 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700850 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700851
kwibergaf476c72016-11-28 15:21:39 -0800852 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700853
854 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700855 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700856 // The data queue is full and needs to be emptied.
857 EmptyQueuedRenderAudio();
858
859 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700860 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700861 RTC_DCHECK(result);
862 }
863
864 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
865 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700866 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700867
868 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700869 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700870 // The data queue is full and needs to be emptied.
871 EmptyQueuedRenderAudio();
872
873 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700874 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700875 RTC_DCHECK(result);
876 }
peah701d6282016-10-25 05:42:20 -0700877
878 if (!constants_.use_experimental_agc) {
879 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
880 // Insert the samples into the queue.
881 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
882 // The data queue is full and needs to be emptied.
883 EmptyQueuedRenderAudio();
884
885 // Retry the insert (should always work).
886 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
887 RTC_DCHECK(result);
888 }
889 }
ivoc9f4a4a02016-10-28 05:39:16 -0700890
891 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
892
893 // Insert the samples into the queue.
894 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
895 // The data queue is full and needs to be emptied.
896 EmptyQueuedRenderAudio();
897
898 // Retry the insert (should always work).
899 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
900 RTC_DCHECK(result);
901 }
peah764e3642016-10-22 05:04:30 -0700902}
903
904void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700905 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700906 std::max(static_cast<size_t>(1),
907 kMaxAllowedValuesOfSamplesPerFrame *
908 EchoCancellationImpl::NumCancellersRequired(
909 num_output_channels(), num_reverse_channels()));
910
peah701d6282016-10-25 05:42:20 -0700911 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700912 std::max(static_cast<size_t>(1),
913 kMaxAllowedValuesOfSamplesPerFrame *
914 EchoControlMobileImpl::NumCancellersRequired(
915 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700916
peah701d6282016-10-25 05:42:20 -0700917 const size_t new_agc_render_queue_element_max_size =
918 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
919
ivoc9f4a4a02016-10-28 05:39:16 -0700920 const size_t new_red_render_queue_element_max_size =
921 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
922
peaha0624602016-10-25 04:45:24 -0700923 // Reallocate the queues if the queue item sizes are too small to fit the
924 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700925 if (aec_render_queue_element_max_size_ <
926 new_aec_render_queue_element_max_size) {
927 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700928
peaha0624602016-10-25 04:45:24 -0700929 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700930 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700931
peah701d6282016-10-25 05:42:20 -0700932 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700933 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
934 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700935 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700936 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700937
peah701d6282016-10-25 05:42:20 -0700938 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
939 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700940 } else {
peah701d6282016-10-25 05:42:20 -0700941 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700942 }
943
peah701d6282016-10-25 05:42:20 -0700944 if (aecm_render_queue_element_max_size_ <
945 new_aecm_render_queue_element_max_size) {
946 aecm_render_queue_element_max_size_ =
947 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700948
949 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700950 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700951
peah701d6282016-10-25 05:42:20 -0700952 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700953 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
954 kMaxNumFramesToBuffer, template_queue_element,
955 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700956 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700957
peah701d6282016-10-25 05:42:20 -0700958 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
959 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700960 } else {
peah701d6282016-10-25 05:42:20 -0700961 aecm_render_signal_queue_->Clear();
962 }
963
964 if (agc_render_queue_element_max_size_ <
965 new_agc_render_queue_element_max_size) {
966 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
967
968 std::vector<int16_t> template_queue_element(
969 agc_render_queue_element_max_size_);
970
971 agc_render_signal_queue_.reset(
972 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
973 kMaxNumFramesToBuffer, template_queue_element,
974 RenderQueueItemVerifier<int16_t>(
975 agc_render_queue_element_max_size_)));
976
977 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
978 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
979 } else {
980 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700981 }
ivoc9f4a4a02016-10-28 05:39:16 -0700982
983 if (red_render_queue_element_max_size_ <
984 new_red_render_queue_element_max_size) {
985 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
986
987 std::vector<float> template_queue_element(
988 red_render_queue_element_max_size_);
989
990 red_render_signal_queue_.reset(
991 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
992 kMaxNumFramesToBuffer, template_queue_element,
993 RenderQueueItemVerifier<float>(
994 red_render_queue_element_max_size_)));
995
996 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
997 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
998 } else {
999 red_render_signal_queue_->Clear();
1000 }
peah764e3642016-10-22 05:04:30 -07001001}
1002
1003void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1004 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001005 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001006 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001007 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001008 }
1009
peah701d6282016-10-25 05:42:20 -07001010 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001011 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001012 aecm_capture_queue_buffer_);
1013 }
1014
1015 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1016 public_submodules_->gain_control->ProcessRenderAudio(
1017 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001018 }
ivoc9f4a4a02016-10-28 05:39:16 -07001019
1020 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1021 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1022 red_capture_queue_buffer_);
1023 }
peah764e3642016-10-22 05:04:30 -07001024}
1025
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001026int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001027 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001028 {
1029 // Acquire the capture lock in order to safely call the function
1030 // that retrieves the render side data. This function accesses apm
1031 // getters that need the capture lock held when being called.
1032 // The lock needs to be released as
1033 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1034 // as well.
1035 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001036 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001037 }
peahfa6228e2015-11-16 16:27:42 -08001038
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001039 if (!frame) {
1040 return kNullPointerError;
1041 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001042 // Must be a native rate.
1043 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1044 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001045 frame->sample_rate_hz_ != kSampleRate32kHz &&
1046 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001047 return kBadSampleRateError;
1048 }
peah192164e2015-11-17 02:16:45 -08001049
peahdf3efa82015-11-28 12:35:15 -08001050 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001051 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001052 {
1053 // Aquire lock for the access of api_format.
1054 // The lock is released immediately due to the conditional
1055 // reinitialization.
1056 rtc::CritScope cs_capture(&crit_capture_);
1057 // TODO(ajm): The input and output rates and channels are currently
1058 // constrained to be identical in the int16 interface.
1059 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001060
1061 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001062 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001063 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1064 processing_config.input_stream().set_num_channels(frame->num_channels_);
1065 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1066 processing_config.output_stream().set_num_channels(frame->num_channels_);
1067
peahdf3efa82015-11-28 12:35:15 -08001068 {
1069 // Do conditional reinitialization.
1070 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001071 RETURN_ON_ERR(
1072 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001073 }
1074 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001075 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001076 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001077 return kBadDataLengthError;
1078 }
1079
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001080#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001081 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001082 RETURN_ON_ERR(WriteConfigMessage(false));
1083
peahdf3efa82015-11-28 12:35:15 -08001084 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1085 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001086 const size_t data_size =
1087 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001088 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001089 }
1090#endif
1091
peahdf3efa82015-11-28 12:35:15 -08001092 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001093 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001094 capture_.capture_audio->InterleaveTo(
1095 frame, submodule_states_.CaptureMultiBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001096
1097#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001098 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001099 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001100 const size_t data_size =
1101 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001102 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001103 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001104 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001105 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001106 }
1107#endif
1108
1109 return kNoError;
1110}
1111
peahde65ddc2016-09-16 15:02:15 -07001112int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001113 // Ensure that not both the AEC and AECM are active at the same time.
1114 // TODO(peah): Simplify once the public API Enable functions for these
1115 // are moved to APM.
1116 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1117 public_submodules_->echo_control_mobile->is_enabled()));
1118
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001119#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001120 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001121 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1122 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1123 msg->set_drift(
1124 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001125 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001126 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001127 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001128#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001129
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001130 MaybeUpdateHistograms();
1131
peahde65ddc2016-09-16 15:02:15 -07001132 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001133
peah1b08dc32016-12-20 13:45:58 -08001134 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001135 capture_buffer->channels_const()[0],
1136 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001137 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1138 if (log_rms) {
1139 capture_rms_interval_counter_ = 0;
1140 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001141 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1142 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1143 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1144 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001145 }
1146
peahe0eae3c2016-12-14 01:16:23 -08001147 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001148 const int new_agc_level = gain_control()->stream_analog_level();
1149 capture_.echo_path_gain_change =
1150 (capture_.previous_agc_level != new_agc_level);
1151 capture_.previous_agc_level = new_agc_level;
peahe0eae3c2016-12-14 01:16:23 -08001152 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1153 }
1154
peahbe615622016-02-13 16:40:47 -08001155 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001156 public_submodules_->gain_control->is_enabled()) {
1157 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001158 capture_buffer->channels()[0], capture_buffer->num_channels(),
1159 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001160 }
1161
peah2ace3f92016-09-10 04:42:27 -07001162 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1163 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001164 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1165 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001166 }
1167
peah522d71b2017-02-23 05:16:26 -08001168 if (private_submodules_->echo_canceller3) {
1169 // Force down-mixing of the number of channels after the detection of
1170 // capture signal saturation.
1171 // TODO(peah): Look into ensuring that this kind of tampering with the
1172 // AudioBuffer functionality should not be needed.
1173 capture_buffer->set_num_channels(1);
1174 }
1175
aluebsb2328d12016-01-11 20:32:29 -08001176 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001177 private_submodules_->beamformer->AnalyzeChunk(
1178 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001179 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001180 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001181 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001182
peahe0eae3c2016-12-14 01:16:23 -08001183 // TODO(peah): Move the AEC3 low-cut filter to this place.
1184 if (private_submodules_->low_cut_filter &&
1185 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001186 private_submodules_->low_cut_filter->Process(capture_buffer);
1187 }
peahde65ddc2016-09-16 15:02:15 -07001188 RETURN_ON_ERR(
1189 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1190 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001191
1192 // Ensure that the stream delay was set before the call to the
1193 // AEC ProcessCaptureAudio function.
1194 if (public_submodules_->echo_cancellation->is_enabled() &&
1195 !was_stream_delay_set()) {
1196 return AudioProcessing::kStreamParameterNotSetError;
1197 }
1198
peahe0eae3c2016-12-14 01:16:23 -08001199 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001200 private_submodules_->echo_canceller3->ProcessCapture(
1201 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001202 } else {
1203 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1204 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001205 }
1206
peahdf3efa82015-11-28 12:35:15 -08001207 if (public_submodules_->echo_control_mobile->is_enabled() &&
1208 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001209 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001210 }
peahde65ddc2016-09-16 15:02:15 -07001211 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001212#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001213 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001214 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001215 int gain_db = public_submodules_->gain_control->is_enabled() ?
1216 public_submodules_->gain_control->compression_gain_db() :
1217 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001218 float gain = std::pow(10.f, gain_db / 20.f);
1219 gain *= capture_nonlocked_.level_controller_enabled ?
1220 private_submodules_->level_controller->GetLastGain() :
1221 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001222 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001223 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001224 }
peah1bcfce52016-08-26 07:16:04 -07001225#endif
peah253534d2016-03-15 04:32:28 -07001226
1227 // Ensure that the stream delay was set before the call to the
1228 // AECM ProcessCaptureAudio function.
1229 if (public_submodules_->echo_control_mobile->is_enabled() &&
1230 !was_stream_delay_set()) {
1231 return AudioProcessing::kStreamParameterNotSetError;
1232 }
1233
1234 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001235 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001236
ivoc9f4a4a02016-10-28 05:39:16 -07001237 if (config_.residual_echo_detector.enabled) {
1238 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1239 rtc::ArrayView<const float>(
1240 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1241 capture_buffer->num_frames_per_band()));
1242 }
1243
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001244 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001245 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001246 }
1247
peahde65ddc2016-09-16 15:02:15 -07001248 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001249
peahbe615622016-02-13 16:40:47 -08001250 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001251 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001252 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001253 private_submodules_->beamformer->is_target_present())) {
1254 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001255 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1256 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001257 }
peahb8fbb542016-03-15 02:28:08 -07001258 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001259 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001260
peah2ace3f92016-09-10 04:42:27 -07001261 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1262 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001263 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1264 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001265 }
1266
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001267 // TODO(aluebs): Investigate if the transient suppression placement should be
1268 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001269 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001270 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001271 private_submodules_->agc_manager.get()
1272 ? private_submodules_->agc_manager->voice_probability()
1273 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001274
peahdf3efa82015-11-28 12:35:15 -08001275 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001276 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1277 capture_buffer->num_channels(),
1278 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1279 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1280 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001281 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001282 }
1283
peahca4cac72016-06-29 15:26:12 -07001284 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001285 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001286 }
1287
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001288 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001289 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001290
peah1b08dc32016-12-20 13:45:58 -08001291 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1292 capture_buffer->channels_const()[0],
1293 capture_nonlocked_.capture_processing_format.num_frames()));
1294 if (log_rms) {
1295 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1296 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1297 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1298 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1299 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1300 }
1301
peahdf3efa82015-11-28 12:35:15 -08001302 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001303 return kNoError;
1304}
1305
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001306int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001307 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001308 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001309 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001310 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001311 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001312 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001313 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001314 };
1315 if (samples_per_channel != reverse_config.num_frames()) {
1316 return kBadDataLengthError;
1317 }
peahdf3efa82015-11-28 12:35:15 -08001318 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001319}
1320
peahde65ddc2016-09-16 15:02:15 -07001321int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1322 const StreamConfig& input_config,
1323 const StreamConfig& output_config,
1324 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001325 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001326 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001327 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001328 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001329 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1330 dest);
peah2ace3f92016-09-10 04:42:27 -07001331 } else if (formats_.api_format.reverse_input_stream() !=
1332 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001333 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1334 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001335 } else {
peahde65ddc2016-09-16 15:02:15 -07001336 CopyAudioIfNeeded(src, input_config.num_frames(),
1337 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001338 }
1339
1340 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001341}
1342
peahdf3efa82015-11-28 12:35:15 -08001343int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001344 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001345 const StreamConfig& input_config,
1346 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001347 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001348 return kNullPointerError;
1349 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001350
peahde65ddc2016-09-16 15:02:15 -07001351 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001352 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001353 }
1354
peahdf3efa82015-11-28 12:35:15 -08001355 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001356 processing_config.reverse_input_stream() = input_config;
1357 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001358
peahdf3efa82015-11-28 12:35:15 -08001359 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001360 assert(input_config.num_frames() ==
1361 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001362
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001363#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001364 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001365 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1366 audioproc::ReverseStream* msg =
1367 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001368 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001369 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001370 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001371 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001372 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001373 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001374 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001375 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001376 }
1377#endif
1378
peahdf3efa82015-11-28 12:35:15 -08001379 render_.render_audio->CopyFrom(src,
1380 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001381 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001382}
1383
1384int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001385 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001386 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001387 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001388 return kNullPointerError;
1389 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001390 // Must be a native rate.
1391 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1392 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001393 frame->sample_rate_hz_ != kSampleRate32kHz &&
1394 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001395 return kBadSampleRateError;
1396 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001397
Michael Graczyk86c6d332015-07-23 11:41:39 -07001398 if (frame->num_channels_ <= 0) {
1399 return kBadNumberChannelsError;
1400 }
1401
peahdf3efa82015-11-28 12:35:15 -08001402 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001403 processing_config.reverse_input_stream().set_sample_rate_hz(
1404 frame->sample_rate_hz_);
1405 processing_config.reverse_input_stream().set_num_channels(
1406 frame->num_channels_);
1407 processing_config.reverse_output_stream().set_sample_rate_hz(
1408 frame->sample_rate_hz_);
1409 processing_config.reverse_output_stream().set_num_channels(
1410 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001411
peahdf3efa82015-11-28 12:35:15 -08001412 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001413 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001414 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001415 return kBadDataLengthError;
1416 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001417
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001418#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001419 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001420 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1421 audioproc::ReverseStream* msg =
1422 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001423 const size_t data_size =
1424 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001425 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001426 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001427 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001428 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001429 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001430#endif
peahdf3efa82015-11-28 12:35:15 -08001431 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001432 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001433 render_.render_audio->InterleaveTo(
1434 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001435 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001436}
niklase@google.com470e71d2011-07-07 08:21:25 +00001437
peahde65ddc2016-09-16 15:02:15 -07001438int AudioProcessingImpl::ProcessRenderStreamLocked() {
1439 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah2ace3f92016-09-10 04:42:27 -07001440 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001441 SampleRateSupportsMultiBand(
1442 formats_.render_processing_format.sample_rate_hz())) {
1443 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001444 }
1445
peah1bcfce52016-08-26 07:16:04 -07001446#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001447 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001448 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001449 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001450 }
peah1bcfce52016-08-26 07:16:04 -07001451#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001452
peah764e3642016-10-22 05:04:30 -07001453 QueueRenderAudio(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001454 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1455 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001456 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001457 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001458
peah2ace3f92016-09-10 04:42:27 -07001459 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001460 SampleRateSupportsMultiBand(
1461 formats_.render_processing_format.sample_rate_hz())) {
1462 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001463 }
1464
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001465 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466}
1467
1468int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001469 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001470 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001471 capture_.was_stream_delay_set = true;
1472 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001473
niklase@google.com470e71d2011-07-07 08:21:25 +00001474 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001475 delay = 0;
1476 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001477 }
1478
1479 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1480 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001481 delay = 500;
1482 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001483 }
1484
peahdf3efa82015-11-28 12:35:15 -08001485 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001486 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001487}
1488
1489int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001490 // Used as callback from submodules, hence locking is not allowed.
1491 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001492}
1493
1494bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001495 // Used as callback from submodules, hence locking is not allowed.
1496 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001497}
1498
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001499void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001500 rtc::CritScope cs(&crit_capture_);
1501 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001502}
1503
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001504void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001505 rtc::CritScope cs(&crit_capture_);
1506 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001507}
1508
1509int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001510 rtc::CritScope cs(&crit_capture_);
1511 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001512}
1513
niklase@google.com470e71d2011-07-07 08:21:25 +00001514int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001515 const char filename[AudioProcessing::kMaxFilenameSize],
1516 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001517 // Run in a single-threaded manner.
1518 rtc::CritScope cs_render(&crit_render_);
1519 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001520 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001521
peahdf3efa82015-11-28 12:35:15 -08001522 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001523 return kNullPointerError;
1524 }
1525
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001526#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001527 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001528 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001529 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001530
tommia6219cc2016-06-15 10:30:14 -07001531 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001532 return kFileError;
1533 }
1534
Minyue13b96ba2015-10-03 00:39:14 +02001535 RETURN_ON_ERR(WriteConfigMessage(true));
1536 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001537 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001538#else
1539 return kUnsupportedFunctionError;
1540#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001541}
1542
ivocd66b44d2016-01-15 03:06:36 -08001543int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1544 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001545 // Run in a single-threaded manner.
1546 rtc::CritScope cs_render(&crit_render_);
1547 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001548
peahdf3efa82015-11-28 12:35:15 -08001549 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001550 return kNullPointerError;
1551 }
1552
1553#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001554 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1555
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001556 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001557 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001558
tommia6219cc2016-06-15 10:30:14 -07001559 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001560 return kFileError;
1561 }
1562
Minyue13b96ba2015-10-03 00:39:14 +02001563 RETURN_ON_ERR(WriteConfigMessage(true));
1564 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001565 return kNoError;
1566#else
1567 return kUnsupportedFunctionError;
1568#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1569}
1570
peah73a28ee2016-10-12 03:01:49 -07001571int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1572 return StartDebugRecording(handle, -1);
1573}
1574
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001575int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1576 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001577 // Run in a single-threaded manner.
1578 rtc::CritScope cs_render(&crit_render_);
1579 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001580 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001581 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001582}
1583
niklase@google.com470e71d2011-07-07 08:21:25 +00001584int AudioProcessingImpl::StopDebugRecording() {
peahdf3efa82015-11-28 12:35:15 -08001585 // Run in a single-threaded manner.
1586 rtc::CritScope cs_render(&crit_render_);
1587 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001588
1589#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001590 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001591 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001592 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001593#else
1594 return kUnsupportedFunctionError;
1595#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001596}
1597
ivoc4e477a12017-01-15 08:29:46 -08001598AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1599 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1600 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1601 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1602 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1603}
1604
1605AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1606 const AudioProcessingStatistics& other) = default;
1607
1608AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1609 default;
1610
ivoc3e9a5372016-10-28 07:55:33 -07001611// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1612AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1613 const {
1614 return AudioProcessingStatistics();
1615}
1616
1617AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1618 const {
1619 AudioProcessingStatistics stats;
1620 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001621 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1622 if (success == Error::kNoError) {
1623 stats.a_nlp.Set(metrics.a_nlp);
1624 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1625 stats.echo_return_loss.Set(metrics.echo_return_loss);
1626 stats.echo_return_loss_enhancement.Set(
1627 metrics.echo_return_loss_enhancement);
1628 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1629 }
ivoc9c192b22017-03-16 04:22:14 -07001630 {
1631 rtc::CritScope cs_capture(&crit_capture_);
1632 stats.residual_echo_likelihood =
1633 private_submodules_->residual_echo_detector->echo_likelihood();
1634 stats.residual_echo_likelihood_recent_max =
1635 private_submodules_->residual_echo_detector
1636 ->echo_likelihood_recent_max();
1637 }
ivoc3e9a5372016-10-28 07:55:33 -07001638 public_submodules_->echo_cancellation->GetDelayMetrics(
1639 &stats.delay_median, &stats.delay_standard_deviation,
1640 &stats.fraction_poor_delays);
1641 return stats;
1642}
1643
niklase@google.com470e71d2011-07-07 08:21:25 +00001644EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001645 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001646}
1647
1648EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001649 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001650}
1651
1652GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001653 if (constants_.use_experimental_agc) {
1654 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001655 }
peahbfa97112016-03-10 21:09:04 -08001656 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001657}
1658
1659HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001660 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001661}
1662
1663LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001664 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001665}
1666
1667NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001668 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001669}
1670
1671VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001672 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001673}
1674
peah8271d042016-11-22 07:24:52 -08001675void AudioProcessingImpl::MutateConfig(
1676 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1677 rtc::CritScope cs_render(&crit_render_);
1678 rtc::CritScope cs_capture(&crit_capture_);
1679 mutator(&config_);
1680 ApplyConfig(config_);
1681}
1682
1683AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1684 rtc::CritScope cs_render(&crit_render_);
1685 rtc::CritScope cs_capture(&crit_capture_);
1686 return config_;
1687}
1688
peah2ace3f92016-09-10 04:42:27 -07001689bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1690 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001691 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001692 public_submodules_->echo_cancellation->is_enabled(),
1693 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001694 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001695 public_submodules_->noise_suppression->is_enabled(),
1696 capture_nonlocked_.intelligibility_enabled,
1697 capture_nonlocked_.beamformer_enabled,
1698 public_submodules_->gain_control->is_enabled(),
1699 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001700 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001701 public_submodules_->voice_detection->is_enabled(),
1702 public_submodules_->level_estimator->is_enabled(),
1703 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001704}
1705
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001706
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001707void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001708 if (capture_.transient_suppressor_enabled) {
1709 if (!public_submodules_->transient_suppressor.get()) {
1710 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001711 }
peahdf3efa82015-11-28 12:35:15 -08001712 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001713 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1714 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001715 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001716}
1717
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001718void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001719 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001720 if (!private_submodules_->beamformer) {
1721 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001722 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001723 }
peahdf3efa82015-11-28 12:35:15 -08001724 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1725 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001726 }
1727}
1728
ekmeyerson60d9b332015-08-14 10:35:55 -07001729void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001730#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001731 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001732 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001733 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001734 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001735 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001736 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001737 }
peah1bcfce52016-08-26 07:16:04 -07001738#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001739}
1740
peah8271d042016-11-22 07:24:52 -08001741void AudioProcessingImpl::InitializeLowCutFilter() {
1742 if (config_.high_pass_filter.enabled) {
1743 private_submodules_->low_cut_filter.reset(
1744 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1745 } else {
1746 private_submodules_->low_cut_filter.reset();
1747 }
1748}
peahe0eae3c2016-12-14 01:16:23 -08001749void AudioProcessingImpl::InitializeEchoCanceller3() {
1750 if (capture_nonlocked_.echo_canceller3_enabled) {
1751 private_submodules_->echo_canceller3.reset(
1752 new EchoCanceller3(proc_sample_rate_hz(), true));
1753 } else {
1754 private_submodules_->echo_canceller3.reset();
1755 }
1756}
peah8271d042016-11-22 07:24:52 -08001757
peahca4cac72016-06-29 15:26:12 -07001758void AudioProcessingImpl::InitializeLevelController() {
1759 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1760}
1761
ivoc9f4a4a02016-10-28 05:39:16 -07001762void AudioProcessingImpl::InitializeResidualEchoDetector() {
1763 private_submodules_->residual_echo_detector->Initialize();
1764}
1765
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001766void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001767 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001768
1769 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001770 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1771 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001772 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001773 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001774 capture_.stream_delay_jumps = 0;
1775 }
1776 if (capture_.aec_system_delay_jumps == -1 &&
1777 echo_cancellation()->stream_has_echo()) {
1778 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001779 }
1780
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001781 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001782 const int diff_stream_delay_ms =
1783 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1784 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1785 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001786 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1787 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001788 if (capture_.stream_delay_jumps == -1) {
1789 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001790 }
peahdf3efa82015-11-28 12:35:15 -08001791 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001792 }
peahdf3efa82015-11-28 12:35:15 -08001793 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001794
1795 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001796 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001797 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001798 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001799 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001800 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1801 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001802 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001803 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001804 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001805 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001806 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1807 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1808 100);
peahdf3efa82015-11-28 12:35:15 -08001809 if (capture_.aec_system_delay_jumps == -1) {
1810 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001811 }
peahdf3efa82015-11-28 12:35:15 -08001812 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001813 }
peahdf3efa82015-11-28 12:35:15 -08001814 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001815 }
1816}
1817
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001818void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001819 // Run in a single-threaded manner.
1820 rtc::CritScope cs_render(&crit_render_);
1821 rtc::CritScope cs_capture(&crit_capture_);
1822
1823 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001824 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001825 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001826 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001827 }
peahdf3efa82015-11-28 12:35:15 -08001828 capture_.stream_delay_jumps = -1;
1829 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001830
peahdf3efa82015-11-28 12:35:15 -08001831 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001832 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1833 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001834 }
peahdf3efa82015-11-28 12:35:15 -08001835 capture_.aec_system_delay_jumps = -1;
1836 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001837}
1838
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001839#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001840int AudioProcessingImpl::WriteMessageToDebugFile(
1841 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08001842 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08001843 rtc::CriticalSection* crit_debug,
1844 ApmDebugDumpThreadState* debug_state) {
1845 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00001846 if (size <= 0) {
1847 return kUnspecifiedError;
1848 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00001849#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07001850// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
1851// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00001852#endif
1853
peahdf3efa82015-11-28 12:35:15 -08001854 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00001855 return kUnspecifiedError;
1856 }
1857
peahdf3efa82015-11-28 12:35:15 -08001858 {
1859 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08001860 rtc::CritScope cs_debug(crit_debug);
1861
tommia6219cc2016-06-15 10:30:14 -07001862 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08001863 // Update the byte counter.
1864 if (*filesize_limit_bytes >= 0) {
1865 *filesize_limit_bytes -=
1866 (sizeof(int32_t) + debug_state->event_str.length());
1867 if (*filesize_limit_bytes < 0) {
1868 // Not enough bytes are left to write this message, so stop logging.
1869 debug_file->CloseFile();
1870 return kNoError;
1871 }
1872 }
peahdf3efa82015-11-28 12:35:15 -08001873 // Write message preceded by its size.
1874 if (!debug_file->Write(&size, sizeof(int32_t))) {
1875 return kFileError;
1876 }
1877 if (!debug_file->Write(debug_state->event_str.data(),
1878 debug_state->event_str.length())) {
1879 return kFileError;
1880 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001881 }
1882
peahdf3efa82015-11-28 12:35:15 -08001883 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00001884
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001885 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001886}
1887
1888int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08001889 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
1890 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
1891 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00001892
mbonadei7c2c8432017-04-07 00:59:12 -07001893 msg->set_num_input_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001894 formats_.api_format.input_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07001895 msg->set_num_output_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001896 formats_.api_format.output_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07001897 msg->set_num_reverse_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08001898 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08001899 msg->set_reverse_sample_rate(
1900 formats_.api_format.reverse_input_stream().sample_rate_hz());
1901 msg->set_output_sample_rate(
1902 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07001903 msg->set_reverse_output_sample_rate(
1904 formats_.api_format.reverse_output_stream().sample_rate_hz());
1905 msg->set_num_reverse_output_channels(
1906 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08001907
1908 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001909 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001910 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02001911 return kNoError;
1912}
1913
1914int AudioProcessingImpl::WriteConfigMessage(bool forced) {
1915 audioproc::Config config;
1916
peahdf3efa82015-11-28 12:35:15 -08001917 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001918 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08001919 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001920 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08001921 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001922 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08001923 public_submodules_->echo_cancellation->is_extended_filter_enabled());
1924 config.set_aec_suppression_level(static_cast<int>(
1925 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02001926
peahdf3efa82015-11-28 12:35:15 -08001927 config.set_aecm_enabled(
1928 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001929 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08001930 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
1931 config.set_aecm_routing_mode(static_cast<int>(
1932 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02001933
peahdf3efa82015-11-28 12:35:15 -08001934 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
1935 config.set_agc_mode(
1936 static_cast<int>(public_submodules_->gain_control->mode()));
1937 config.set_agc_limiter_enabled(
1938 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08001939 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02001940
peah8271d042016-11-22 07:24:52 -08001941 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001942
peahdf3efa82015-11-28 12:35:15 -08001943 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
1944 config.set_ns_level(
1945 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02001946
peahdf3efa82015-11-28 12:35:15 -08001947 config.set_transient_suppression_enabled(
1948 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001949 config.set_intelligibility_enhancer_enabled(
1950 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001951
peah7789fe72016-04-15 01:19:44 -07001952 std::string experiments_description =
1953 public_submodules_->echo_cancellation->GetExperimentsDescription();
1954 // TODO(peah): Add semicolon-separated concatenations of experiment
1955 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07001956 if (capture_nonlocked_.level_controller_enabled) {
1957 experiments_description += "LevelController;";
1958 }
henrik.lundinbd681b92016-12-05 09:08:42 -08001959 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1960 experiments_description += "AgcClippingLevelExperiment;";
1961 }
peahe0eae3c2016-12-14 01:16:23 -08001962 if (capture_nonlocked_.echo_canceller3_enabled) {
1963 experiments_description += "EchoCanceller3;";
1964 }
peah7789fe72016-04-15 01:19:44 -07001965 config.set_experiments_description(experiments_description);
1966
mbonadei7c2c8432017-04-07 00:59:12 -07001967 ProtoString serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08001968 if (!forced &&
1969 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02001970 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001971 }
1972
peahdf3efa82015-11-28 12:35:15 -08001973 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02001974
peahdf3efa82015-11-28 12:35:15 -08001975 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
1976 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02001977
peahdf3efa82015-11-28 12:35:15 -08001978 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001979 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001980 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00001981 return kNoError;
1982}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001983#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001984
kwiberg83ffe452016-08-29 14:46:07 -07001985AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1986 bool transient_suppressor_enabled,
1987 const std::vector<Point>& array_geometry,
1988 SphericalPointf target_direction)
1989 : aec_system_delay_jumps(-1),
1990 delay_offset_ms(0),
1991 was_stream_delay_set(false),
1992 last_stream_delay_ms(0),
1993 last_aec_system_delay_ms(0),
1994 stream_delay_jumps(-1),
1995 output_will_be_muted(false),
1996 key_pressed(false),
1997 transient_suppressor_enabled(transient_suppressor_enabled),
1998 array_geometry(array_geometry),
1999 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002000 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002001 split_rate(kSampleRate16kHz),
2002 previous_agc_level(0),
2003 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002004
2005AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2006
2007AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2008
2009AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2010
niklase@google.com470e71d2011-07-07 08:21:25 +00002011} // namespace webrtc