blob: 88229b4829aea7f0a4a9e68893c96f643e7944d1 [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
peahde65ddc2016-09-16 15:02:15 -0700565 int render_processing_rate = FindNativeProcessRateToUse(
peah2ace3f92016-09-10 04:42:27 -0700566 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
567 formats_.api_format.reverse_output_stream().sample_rate_hz()),
568 submodule_states_.CaptureMultiBandSubModulesActive() ||
569 submodule_states_.RenderMultiBandSubModulesActive());
aluebseb3603b2016-04-20 15:27:58 -0700570 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
571 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700572 if (render_processing_rate > kSampleRate32kHz &&
573 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700574 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
575 ? kSampleRate32kHz
576 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700577 }
peahde65ddc2016-09-16 15:02:15 -0700578 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700579 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700580 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
581 kSampleRate8kHz) {
582 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000583 } else {
peahde65ddc2016-09-16 15:02:15 -0700584 render_processing_rate =
585 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000586 }
587
peahde65ddc2016-09-16 15:02:15 -0700588 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000589 // demonstrated to work well for AEC in most practical scenarios.
peahde65ddc2016-09-16 15:02:15 -0700590 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000591
peahde65ddc2016-09-16 15:02:15 -0700592 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
593 kSampleRate32kHz ||
594 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
595 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800596 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000597 } else {
peahdf3efa82015-11-28 12:35:15 -0800598 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700599 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000600 }
601
602 return InitializeLocked();
603}
604
peah88ac8532016-09-12 16:47:25 -0700605void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700606 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700607
peahc19f3122016-10-07 14:54:10 -0700608 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700609 if (!config_ok) {
610 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
611 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700612 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700613 << std::endl
614 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700615 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700616 }
617
618 // Run in a single-threaded manner when applying the settings.
619 rtc::CritScope cs_render(&crit_render_);
620 rtc::CritScope cs_capture(&crit_capture_);
621
peahc19f3122016-10-07 14:54:10 -0700622 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
623 // with the value in config_ everywhere in the code.
624 if (capture_nonlocked_.level_controller_enabled !=
625 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700626 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700627 config_.level_controller.enabled;
628 // TODO(peah): Remove the conditional initialization to always initialize
629 // the level controller regardless of whether it is enabled or not.
630 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700631 }
peahc19f3122016-10-07 14:54:10 -0700632 LOG(LS_INFO) << "Level controller activated: "
633 << capture_nonlocked_.level_controller_enabled;
634
635 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800636
637 InitializeLowCutFilter();
638
639 LOG(LS_INFO) << "Highpass filter activated: "
640 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800641
642 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
643 if (!config_ok) {
644 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
645 << "echo canceller 3: "
646 << EchoCanceller3::ToString(config_.echo_canceller3)
647 << std::endl
648 << "Reverting to default parameter set";
649 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
650 }
651
652 if (config.echo_canceller3.enabled !=
653 capture_nonlocked_.echo_canceller3_enabled) {
654 capture_nonlocked_.echo_canceller3_enabled =
655 config_.echo_canceller3.enabled;
656 InitializeEchoCanceller3();
657 LOG(LS_INFO) << "Echo canceller 3 activated: "
658 << capture_nonlocked_.echo_canceller3_enabled;
659 }
peah88ac8532016-09-12 16:47:25 -0700660}
661
662void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800663 // Run in a single-threaded manner when setting the extra options.
664 rtc::CritScope cs_render(&crit_render_);
665 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000666
peahb624d8c2016-03-05 03:01:14 -0800667 public_submodules_->echo_cancellation->SetExtraOptions(config);
668
peahdf3efa82015-11-28 12:35:15 -0800669 if (capture_.transient_suppressor_enabled !=
670 config.Get<ExperimentalNs>().enabled) {
671 capture_.transient_suppressor_enabled =
672 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000673 InitializeTransient();
674 }
aluebs2a346882016-01-11 18:04:30 -0800675
peah1bcfce52016-08-26 07:16:04 -0700676#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700677 if(capture_nonlocked_.intelligibility_enabled !=
678 config.Get<Intelligibility>().enabled) {
679 capture_nonlocked_.intelligibility_enabled =
680 config.Get<Intelligibility>().enabled;
681 InitializeIntelligibility();
682 }
peah1bcfce52016-08-26 07:16:04 -0700683#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700684
aluebs2a346882016-01-11 18:04:30 -0800685#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800686 if (capture_nonlocked_.beamformer_enabled !=
687 config.Get<Beamforming>().enabled) {
688 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800689 if (config.Get<Beamforming>().array_geometry.size() > 1) {
690 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
691 }
692 capture_.target_direction = config.Get<Beamforming>().target_direction;
693 InitializeBeamformer();
694 }
695#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000696}
697
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000698int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800699 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700700 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000701}
702
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000703int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800704 // Used as callback from submodules, hence locking is not allowed.
705 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000706}
707
Peter Kasting69558702016-01-12 16:26:35 -0800708size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800709 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700710 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000711}
712
Peter Kasting69558702016-01-12 16:26:35 -0800713size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800714 // Used as callback from submodules, hence locking is not allowed.
715 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000716}
717
Peter Kasting69558702016-01-12 16:26:35 -0800718size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800719 // Used as callback from submodules, hence locking is not allowed.
720 return capture_nonlocked_.beamformer_enabled ? 1 : num_output_channels();
721}
722
Peter Kasting69558702016-01-12 16:26:35 -0800723size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800724 // Used as callback from submodules, hence locking is not allowed.
725 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000726}
727
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000728void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800729 rtc::CritScope cs(&crit_capture_);
730 capture_.output_will_be_muted = muted;
731 if (private_submodules_->agc_manager.get()) {
732 private_submodules_->agc_manager->SetCaptureMuted(
733 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000734 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000735}
736
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000737
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000738int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700739 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000740 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000741 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000742 int output_sample_rate_hz,
743 ChannelLayout output_layout,
744 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800745 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800746 StreamConfig input_stream;
747 StreamConfig output_stream;
748 {
749 // Access the formats_.api_format.input_stream beneath the capture lock.
750 // The lock must be released as it is later required in the call
751 // to ProcessStream(,,,);
752 rtc::CritScope cs(&crit_capture_);
753 input_stream = formats_.api_format.input_stream();
754 output_stream = formats_.api_format.output_stream();
755 }
756
Michael Graczyk86c6d332015-07-23 11:41:39 -0700757 input_stream.set_sample_rate_hz(input_sample_rate_hz);
758 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
759 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700760 output_stream.set_sample_rate_hz(output_sample_rate_hz);
761 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
762 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
763
764 if (samples_per_channel != input_stream.num_frames()) {
765 return kBadDataLengthError;
766 }
767 return ProcessStream(src, input_stream, output_stream, dest);
768}
769
770int AudioProcessingImpl::ProcessStream(const float* const* src,
771 const StreamConfig& input_config,
772 const StreamConfig& output_config,
773 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800774 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800775 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700776 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800777 {
778 // Acquire the capture lock in order to safely call the function
779 // that retrieves the render side data. This function accesses apm
780 // getters that need the capture lock held when being called.
781 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700782 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800783
784 if (!src || !dest) {
785 return kNullPointerError;
786 }
787
788 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700789 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000790 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000791
Michael Graczyk86c6d332015-07-23 11:41:39 -0700792 processing_config.input_stream() = input_config;
793 processing_config.output_stream() = output_config;
794
peahdf3efa82015-11-28 12:35:15 -0800795 {
796 // Do conditional reinitialization.
797 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700798 RETURN_ON_ERR(
799 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800800 }
801 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700802 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
803 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000804
805#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700806 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200807 RETURN_ON_ERR(WriteConfigMessage(false));
808
peahdf3efa82015-11-28 12:35:15 -0800809 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
810 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000811 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800812 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800813 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
814 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000815 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000816 }
817#endif
818
peahdf3efa82015-11-28 12:35:15 -0800819 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700820 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800821 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000822
823#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700824 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800825 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000826 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800827 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800828 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
829 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000830 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800831 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800832 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800833 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000834 }
835#endif
836
837 return kNoError;
838}
839
peah701d6282016-10-25 05:42:20 -0700840void AudioProcessingImpl::QueueRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700841 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
842 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700843 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700844
kwibergaf476c72016-11-28 15:21:39 -0800845 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700846
847 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700848 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700849 // The data queue is full and needs to be emptied.
850 EmptyQueuedRenderAudio();
851
852 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700853 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700854 RTC_DCHECK(result);
855 }
856
857 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
858 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700859 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700860
861 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700862 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700863 // The data queue is full and needs to be emptied.
864 EmptyQueuedRenderAudio();
865
866 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700867 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700868 RTC_DCHECK(result);
869 }
peah701d6282016-10-25 05:42:20 -0700870
871 if (!constants_.use_experimental_agc) {
872 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
873 // Insert the samples into the queue.
874 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
875 // The data queue is full and needs to be emptied.
876 EmptyQueuedRenderAudio();
877
878 // Retry the insert (should always work).
879 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
880 RTC_DCHECK(result);
881 }
882 }
ivoc9f4a4a02016-10-28 05:39:16 -0700883
884 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
885
886 // Insert the samples into the queue.
887 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
888 // The data queue is full and needs to be emptied.
889 EmptyQueuedRenderAudio();
890
891 // Retry the insert (should always work).
892 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
893 RTC_DCHECK(result);
894 }
peah764e3642016-10-22 05:04:30 -0700895}
896
897void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700898 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700899 std::max(static_cast<size_t>(1),
900 kMaxAllowedValuesOfSamplesPerFrame *
901 EchoCancellationImpl::NumCancellersRequired(
902 num_output_channels(), num_reverse_channels()));
903
peah701d6282016-10-25 05:42:20 -0700904 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700905 std::max(static_cast<size_t>(1),
906 kMaxAllowedValuesOfSamplesPerFrame *
907 EchoControlMobileImpl::NumCancellersRequired(
908 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700909
peah701d6282016-10-25 05:42:20 -0700910 const size_t new_agc_render_queue_element_max_size =
911 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
912
ivoc9f4a4a02016-10-28 05:39:16 -0700913 const size_t new_red_render_queue_element_max_size =
914 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
915
peaha0624602016-10-25 04:45:24 -0700916 // Reallocate the queues if the queue item sizes are too small to fit the
917 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700918 if (aec_render_queue_element_max_size_ <
919 new_aec_render_queue_element_max_size) {
920 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700921
peaha0624602016-10-25 04:45:24 -0700922 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700923 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700924
peah701d6282016-10-25 05:42:20 -0700925 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700926 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
927 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700928 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700929 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700930
peah701d6282016-10-25 05:42:20 -0700931 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
932 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700933 } else {
peah701d6282016-10-25 05:42:20 -0700934 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700935 }
936
peah701d6282016-10-25 05:42:20 -0700937 if (aecm_render_queue_element_max_size_ <
938 new_aecm_render_queue_element_max_size) {
939 aecm_render_queue_element_max_size_ =
940 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700941
942 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700943 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700944
peah701d6282016-10-25 05:42:20 -0700945 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700946 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
947 kMaxNumFramesToBuffer, template_queue_element,
948 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700949 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700950
peah701d6282016-10-25 05:42:20 -0700951 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
952 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700953 } else {
peah701d6282016-10-25 05:42:20 -0700954 aecm_render_signal_queue_->Clear();
955 }
956
957 if (agc_render_queue_element_max_size_ <
958 new_agc_render_queue_element_max_size) {
959 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
960
961 std::vector<int16_t> template_queue_element(
962 agc_render_queue_element_max_size_);
963
964 agc_render_signal_queue_.reset(
965 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
966 kMaxNumFramesToBuffer, template_queue_element,
967 RenderQueueItemVerifier<int16_t>(
968 agc_render_queue_element_max_size_)));
969
970 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
971 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
972 } else {
973 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700974 }
ivoc9f4a4a02016-10-28 05:39:16 -0700975
976 if (red_render_queue_element_max_size_ <
977 new_red_render_queue_element_max_size) {
978 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
979
980 std::vector<float> template_queue_element(
981 red_render_queue_element_max_size_);
982
983 red_render_signal_queue_.reset(
984 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
985 kMaxNumFramesToBuffer, template_queue_element,
986 RenderQueueItemVerifier<float>(
987 red_render_queue_element_max_size_)));
988
989 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
990 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
991 } else {
992 red_render_signal_queue_->Clear();
993 }
peah764e3642016-10-22 05:04:30 -0700994}
995
996void AudioProcessingImpl::EmptyQueuedRenderAudio() {
997 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -0700998 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700999 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001000 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001001 }
1002
peah701d6282016-10-25 05:42:20 -07001003 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001004 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001005 aecm_capture_queue_buffer_);
1006 }
1007
1008 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1009 public_submodules_->gain_control->ProcessRenderAudio(
1010 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001011 }
ivoc9f4a4a02016-10-28 05:39:16 -07001012
1013 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1014 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1015 red_capture_queue_buffer_);
1016 }
peah764e3642016-10-22 05:04:30 -07001017}
1018
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001019int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001020 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001021 {
1022 // Acquire the capture lock in order to safely call the function
1023 // that retrieves the render side data. This function accesses apm
1024 // getters that need the capture lock held when being called.
1025 // The lock needs to be released as
1026 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1027 // as well.
1028 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001029 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001030 }
peahfa6228e2015-11-16 16:27:42 -08001031
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001032 if (!frame) {
1033 return kNullPointerError;
1034 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001035 // Must be a native rate.
1036 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1037 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001038 frame->sample_rate_hz_ != kSampleRate32kHz &&
1039 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001040 return kBadSampleRateError;
1041 }
peah192164e2015-11-17 02:16:45 -08001042
peahdf3efa82015-11-28 12:35:15 -08001043 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001044 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001045 {
1046 // Aquire lock for the access of api_format.
1047 // The lock is released immediately due to the conditional
1048 // reinitialization.
1049 rtc::CritScope cs_capture(&crit_capture_);
1050 // TODO(ajm): The input and output rates and channels are currently
1051 // constrained to be identical in the int16 interface.
1052 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001053
1054 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001055 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001056 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1057 processing_config.input_stream().set_num_channels(frame->num_channels_);
1058 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1059 processing_config.output_stream().set_num_channels(frame->num_channels_);
1060
peahdf3efa82015-11-28 12:35:15 -08001061 {
1062 // Do conditional reinitialization.
1063 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001064 RETURN_ON_ERR(
1065 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001066 }
1067 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001068 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001069 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001070 return kBadDataLengthError;
1071 }
1072
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001073#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001074 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001075 RETURN_ON_ERR(WriteConfigMessage(false));
1076
peahdf3efa82015-11-28 12:35:15 -08001077 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1078 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001079 const size_t data_size =
1080 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001081 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001082 }
1083#endif
1084
peahdf3efa82015-11-28 12:35:15 -08001085 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001086 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001087 capture_.capture_audio->InterleaveTo(
1088 frame, submodule_states_.CaptureMultiBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001089
1090#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001091 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001092 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001093 const size_t data_size =
1094 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001095 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001096 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001097 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001098 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001099 }
1100#endif
1101
1102 return kNoError;
1103}
1104
peahde65ddc2016-09-16 15:02:15 -07001105int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001106 // Ensure that not both the AEC and AECM are active at the same time.
1107 // TODO(peah): Simplify once the public API Enable functions for these
1108 // are moved to APM.
1109 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1110 public_submodules_->echo_control_mobile->is_enabled()));
1111
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001112#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001113 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001114 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1115 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1116 msg->set_drift(
1117 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001118 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001119 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001120 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001121#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001122
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001123 MaybeUpdateHistograms();
1124
peahde65ddc2016-09-16 15:02:15 -07001125 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001126
peah1b08dc32016-12-20 13:45:58 -08001127 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001128 capture_buffer->channels_const()[0],
1129 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001130 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1131 if (log_rms) {
1132 capture_rms_interval_counter_ = 0;
1133 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001134 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1135 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1136 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1137 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001138 }
1139
peahe0eae3c2016-12-14 01:16:23 -08001140 if (private_submodules_->echo_canceller3) {
1141 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1142 }
1143
peahbe615622016-02-13 16:40:47 -08001144 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001145 public_submodules_->gain_control->is_enabled()) {
1146 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001147 capture_buffer->channels()[0], capture_buffer->num_channels(),
1148 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001149 }
1150
peah2ace3f92016-09-10 04:42:27 -07001151 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1152 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001153 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1154 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001155 }
1156
peah522d71b2017-02-23 05:16:26 -08001157 if (private_submodules_->echo_canceller3) {
1158 // Force down-mixing of the number of channels after the detection of
1159 // capture signal saturation.
1160 // TODO(peah): Look into ensuring that this kind of tampering with the
1161 // AudioBuffer functionality should not be needed.
1162 capture_buffer->set_num_channels(1);
1163 }
1164
aluebsb2328d12016-01-11 20:32:29 -08001165 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001166 private_submodules_->beamformer->AnalyzeChunk(
1167 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001168 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001169 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001170 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001171
peahe0eae3c2016-12-14 01:16:23 -08001172 // TODO(peah): Move the AEC3 low-cut filter to this place.
1173 if (private_submodules_->low_cut_filter &&
1174 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001175 private_submodules_->low_cut_filter->Process(capture_buffer);
1176 }
peahde65ddc2016-09-16 15:02:15 -07001177 RETURN_ON_ERR(
1178 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1179 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001180
1181 // Ensure that the stream delay was set before the call to the
1182 // AEC ProcessCaptureAudio function.
1183 if (public_submodules_->echo_cancellation->is_enabled() &&
1184 !was_stream_delay_set()) {
1185 return AudioProcessing::kStreamParameterNotSetError;
1186 }
1187
peahe0eae3c2016-12-14 01:16:23 -08001188 if (private_submodules_->echo_canceller3) {
1189 private_submodules_->echo_canceller3->ProcessCapture(capture_buffer, false);
peah61202ac2017-02-06 03:39:42 -08001190 } else {
1191 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1192 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001193 }
1194
peahdf3efa82015-11-28 12:35:15 -08001195 if (public_submodules_->echo_control_mobile->is_enabled() &&
1196 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001197 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001198 }
peahde65ddc2016-09-16 15:02:15 -07001199 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001200#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001201 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001202 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001203 int gain_db = public_submodules_->gain_control->is_enabled() ?
1204 public_submodules_->gain_control->compression_gain_db() :
1205 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001206 float gain = std::pow(10.f, gain_db / 20.f);
1207 gain *= capture_nonlocked_.level_controller_enabled ?
1208 private_submodules_->level_controller->GetLastGain() :
1209 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001210 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001211 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001212 }
peah1bcfce52016-08-26 07:16:04 -07001213#endif
peah253534d2016-03-15 04:32:28 -07001214
1215 // Ensure that the stream delay was set before the call to the
1216 // AECM ProcessCaptureAudio function.
1217 if (public_submodules_->echo_control_mobile->is_enabled() &&
1218 !was_stream_delay_set()) {
1219 return AudioProcessing::kStreamParameterNotSetError;
1220 }
1221
1222 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001223 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001224
ivoc9f4a4a02016-10-28 05:39:16 -07001225 if (config_.residual_echo_detector.enabled) {
1226 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1227 rtc::ArrayView<const float>(
1228 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1229 capture_buffer->num_frames_per_band()));
1230 }
1231
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001232 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001233 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001234 }
1235
peahde65ddc2016-09-16 15:02:15 -07001236 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001237
peahbe615622016-02-13 16:40:47 -08001238 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001239 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001240 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001241 private_submodules_->beamformer->is_target_present())) {
1242 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001243 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1244 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001245 }
peahb8fbb542016-03-15 02:28:08 -07001246 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001247 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001248
peah2ace3f92016-09-10 04:42:27 -07001249 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1250 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001251 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1252 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001253 }
1254
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001255 // TODO(aluebs): Investigate if the transient suppression placement should be
1256 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001257 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001258 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001259 private_submodules_->agc_manager.get()
1260 ? private_submodules_->agc_manager->voice_probability()
1261 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001262
peahdf3efa82015-11-28 12:35:15 -08001263 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001264 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1265 capture_buffer->num_channels(),
1266 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1267 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1268 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001269 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001270 }
1271
peahca4cac72016-06-29 15:26:12 -07001272 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001273 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001274 }
1275
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001276 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001277 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001278
peah1b08dc32016-12-20 13:45:58 -08001279 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1280 capture_buffer->channels_const()[0],
1281 capture_nonlocked_.capture_processing_format.num_frames()));
1282 if (log_rms) {
1283 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1284 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1285 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1286 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1287 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1288 }
1289
peahdf3efa82015-11-28 12:35:15 -08001290 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001291 return kNoError;
1292}
1293
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001294int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001295 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001296 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001297 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001298 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001299 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001300 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001301 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001302 };
1303 if (samples_per_channel != reverse_config.num_frames()) {
1304 return kBadDataLengthError;
1305 }
peahdf3efa82015-11-28 12:35:15 -08001306 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001307}
1308
peahde65ddc2016-09-16 15:02:15 -07001309int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1310 const StreamConfig& input_config,
1311 const StreamConfig& output_config,
1312 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001313 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001314 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001315 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001316 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001317 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1318 dest);
peah2ace3f92016-09-10 04:42:27 -07001319 } else if (formats_.api_format.reverse_input_stream() !=
1320 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001321 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1322 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001323 } else {
peahde65ddc2016-09-16 15:02:15 -07001324 CopyAudioIfNeeded(src, input_config.num_frames(),
1325 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001326 }
1327
1328 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001329}
1330
peahdf3efa82015-11-28 12:35:15 -08001331int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001332 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001333 const StreamConfig& input_config,
1334 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001335 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001336 return kNullPointerError;
1337 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001338
peahde65ddc2016-09-16 15:02:15 -07001339 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001340 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001341 }
1342
peahdf3efa82015-11-28 12:35:15 -08001343 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001344 processing_config.reverse_input_stream() = input_config;
1345 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001346
peahdf3efa82015-11-28 12:35:15 -08001347 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001348 assert(input_config.num_frames() ==
1349 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001350
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001351#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001352 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001353 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1354 audioproc::ReverseStream* msg =
1355 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001356 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001357 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001358 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001359 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001360 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001361 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001362 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001363 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001364 }
1365#endif
1366
peahdf3efa82015-11-28 12:35:15 -08001367 render_.render_audio->CopyFrom(src,
1368 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001369 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001370}
1371
1372int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001373 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001374 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001375 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001376 return kNullPointerError;
1377 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001378 // Must be a native rate.
1379 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1380 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001381 frame->sample_rate_hz_ != kSampleRate32kHz &&
1382 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001383 return kBadSampleRateError;
1384 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001385
Michael Graczyk86c6d332015-07-23 11:41:39 -07001386 if (frame->num_channels_ <= 0) {
1387 return kBadNumberChannelsError;
1388 }
1389
peahdf3efa82015-11-28 12:35:15 -08001390 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001391 processing_config.reverse_input_stream().set_sample_rate_hz(
1392 frame->sample_rate_hz_);
1393 processing_config.reverse_input_stream().set_num_channels(
1394 frame->num_channels_);
1395 processing_config.reverse_output_stream().set_sample_rate_hz(
1396 frame->sample_rate_hz_);
1397 processing_config.reverse_output_stream().set_num_channels(
1398 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001399
peahdf3efa82015-11-28 12:35:15 -08001400 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001401 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001402 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001403 return kBadDataLengthError;
1404 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001405
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001406#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001407 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001408 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1409 audioproc::ReverseStream* msg =
1410 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001411 const size_t data_size =
1412 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001413 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001414 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001415 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001416 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001417 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001418#endif
peahdf3efa82015-11-28 12:35:15 -08001419 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001420 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001421 render_.render_audio->InterleaveTo(
1422 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001423 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001424}
niklase@google.com470e71d2011-07-07 08:21:25 +00001425
peahde65ddc2016-09-16 15:02:15 -07001426int AudioProcessingImpl::ProcessRenderStreamLocked() {
1427 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah2ace3f92016-09-10 04:42:27 -07001428 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001429 SampleRateSupportsMultiBand(
1430 formats_.render_processing_format.sample_rate_hz())) {
1431 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001432 }
1433
peah1bcfce52016-08-26 07:16:04 -07001434#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001435 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001436 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001437 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001438 }
peah1bcfce52016-08-26 07:16:04 -07001439#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001440
peah764e3642016-10-22 05:04:30 -07001441 QueueRenderAudio(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001442 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1443 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001444 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001445 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001446
peah2ace3f92016-09-10 04:42:27 -07001447 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001448 SampleRateSupportsMultiBand(
1449 formats_.render_processing_format.sample_rate_hz())) {
1450 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001451 }
1452
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001453 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001454}
1455
1456int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001457 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001458 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001459 capture_.was_stream_delay_set = true;
1460 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001461
niklase@google.com470e71d2011-07-07 08:21:25 +00001462 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001463 delay = 0;
1464 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001465 }
1466
1467 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1468 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001469 delay = 500;
1470 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001471 }
1472
peahdf3efa82015-11-28 12:35:15 -08001473 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001474 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001475}
1476
1477int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001478 // Used as callback from submodules, hence locking is not allowed.
1479 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001480}
1481
1482bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001483 // Used as callback from submodules, hence locking is not allowed.
1484 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001485}
1486
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001487void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001488 rtc::CritScope cs(&crit_capture_);
1489 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001490}
1491
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001492void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001493 rtc::CritScope cs(&crit_capture_);
1494 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001495}
1496
1497int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001498 rtc::CritScope cs(&crit_capture_);
1499 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001500}
1501
niklase@google.com470e71d2011-07-07 08:21:25 +00001502int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001503 const char filename[AudioProcessing::kMaxFilenameSize],
1504 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001505 // Run in a single-threaded manner.
1506 rtc::CritScope cs_render(&crit_render_);
1507 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001508 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001509
peahdf3efa82015-11-28 12:35:15 -08001510 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001511 return kNullPointerError;
1512 }
1513
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001514#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001515 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001516 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001517 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001518
tommia6219cc2016-06-15 10:30:14 -07001519 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001520 return kFileError;
1521 }
1522
Minyue13b96ba2015-10-03 00:39:14 +02001523 RETURN_ON_ERR(WriteConfigMessage(true));
1524 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001525 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001526#else
1527 return kUnsupportedFunctionError;
1528#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001529}
1530
ivocd66b44d2016-01-15 03:06:36 -08001531int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1532 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001533 // Run in a single-threaded manner.
1534 rtc::CritScope cs_render(&crit_render_);
1535 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001536
peahdf3efa82015-11-28 12:35:15 -08001537 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001538 return kNullPointerError;
1539 }
1540
1541#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001542 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1543
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001544 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001545 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001546
tommia6219cc2016-06-15 10:30:14 -07001547 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001548 return kFileError;
1549 }
1550
Minyue13b96ba2015-10-03 00:39:14 +02001551 RETURN_ON_ERR(WriteConfigMessage(true));
1552 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001553 return kNoError;
1554#else
1555 return kUnsupportedFunctionError;
1556#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1557}
1558
peah73a28ee2016-10-12 03:01:49 -07001559int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1560 return StartDebugRecording(handle, -1);
1561}
1562
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001563int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1564 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001565 // Run in a single-threaded manner.
1566 rtc::CritScope cs_render(&crit_render_);
1567 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001568 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001569 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001570}
1571
niklase@google.com470e71d2011-07-07 08:21:25 +00001572int AudioProcessingImpl::StopDebugRecording() {
peahdf3efa82015-11-28 12:35:15 -08001573 // Run in a single-threaded manner.
1574 rtc::CritScope cs_render(&crit_render_);
1575 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001576
1577#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001578 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001579 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001580 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001581#else
1582 return kUnsupportedFunctionError;
1583#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001584}
1585
ivoc4e477a12017-01-15 08:29:46 -08001586AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1587 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1588 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1589 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1590 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1591}
1592
1593AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1594 const AudioProcessingStatistics& other) = default;
1595
1596AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1597 default;
1598
ivoc3e9a5372016-10-28 07:55:33 -07001599// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1600AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1601 const {
1602 return AudioProcessingStatistics();
1603}
1604
1605AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1606 const {
1607 AudioProcessingStatistics stats;
1608 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001609 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1610 if (success == Error::kNoError) {
1611 stats.a_nlp.Set(metrics.a_nlp);
1612 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1613 stats.echo_return_loss.Set(metrics.echo_return_loss);
1614 stats.echo_return_loss_enhancement.Set(
1615 metrics.echo_return_loss_enhancement);
1616 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1617 }
ivoc9c192b22017-03-16 04:22:14 -07001618 {
1619 rtc::CritScope cs_capture(&crit_capture_);
1620 stats.residual_echo_likelihood =
1621 private_submodules_->residual_echo_detector->echo_likelihood();
1622 stats.residual_echo_likelihood_recent_max =
1623 private_submodules_->residual_echo_detector
1624 ->echo_likelihood_recent_max();
1625 }
ivoc3e9a5372016-10-28 07:55:33 -07001626 public_submodules_->echo_cancellation->GetDelayMetrics(
1627 &stats.delay_median, &stats.delay_standard_deviation,
1628 &stats.fraction_poor_delays);
1629 return stats;
1630}
1631
niklase@google.com470e71d2011-07-07 08:21:25 +00001632EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001633 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001634}
1635
1636EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001637 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001638}
1639
1640GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001641 if (constants_.use_experimental_agc) {
1642 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001643 }
peahbfa97112016-03-10 21:09:04 -08001644 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001645}
1646
1647HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001648 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001649}
1650
1651LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001652 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001653}
1654
1655NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001656 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001657}
1658
1659VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001660 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001661}
1662
peah8271d042016-11-22 07:24:52 -08001663void AudioProcessingImpl::MutateConfig(
1664 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1665 rtc::CritScope cs_render(&crit_render_);
1666 rtc::CritScope cs_capture(&crit_capture_);
1667 mutator(&config_);
1668 ApplyConfig(config_);
1669}
1670
1671AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1672 rtc::CritScope cs_render(&crit_render_);
1673 rtc::CritScope cs_capture(&crit_capture_);
1674 return config_;
1675}
1676
peah2ace3f92016-09-10 04:42:27 -07001677bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1678 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001679 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001680 public_submodules_->echo_cancellation->is_enabled(),
1681 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001682 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001683 public_submodules_->noise_suppression->is_enabled(),
1684 capture_nonlocked_.intelligibility_enabled,
1685 capture_nonlocked_.beamformer_enabled,
1686 public_submodules_->gain_control->is_enabled(),
1687 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001688 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001689 public_submodules_->voice_detection->is_enabled(),
1690 public_submodules_->level_estimator->is_enabled(),
1691 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001692}
1693
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001694
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001695void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001696 if (capture_.transient_suppressor_enabled) {
1697 if (!public_submodules_->transient_suppressor.get()) {
1698 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001699 }
peahdf3efa82015-11-28 12:35:15 -08001700 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001701 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1702 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001703 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001704}
1705
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001706void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001707 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001708 if (!private_submodules_->beamformer) {
1709 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001710 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001711 }
peahdf3efa82015-11-28 12:35:15 -08001712 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1713 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001714 }
1715}
1716
ekmeyerson60d9b332015-08-14 10:35:55 -07001717void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001718#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001719 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001720 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001721 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001722 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001723 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001724 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001725 }
peah1bcfce52016-08-26 07:16:04 -07001726#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001727}
1728
peah8271d042016-11-22 07:24:52 -08001729void AudioProcessingImpl::InitializeLowCutFilter() {
1730 if (config_.high_pass_filter.enabled) {
1731 private_submodules_->low_cut_filter.reset(
1732 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1733 } else {
1734 private_submodules_->low_cut_filter.reset();
1735 }
1736}
peahe0eae3c2016-12-14 01:16:23 -08001737void AudioProcessingImpl::InitializeEchoCanceller3() {
1738 if (capture_nonlocked_.echo_canceller3_enabled) {
1739 private_submodules_->echo_canceller3.reset(
1740 new EchoCanceller3(proc_sample_rate_hz(), true));
1741 } else {
1742 private_submodules_->echo_canceller3.reset();
1743 }
1744}
peah8271d042016-11-22 07:24:52 -08001745
peahca4cac72016-06-29 15:26:12 -07001746void AudioProcessingImpl::InitializeLevelController() {
1747 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1748}
1749
ivoc9f4a4a02016-10-28 05:39:16 -07001750void AudioProcessingImpl::InitializeResidualEchoDetector() {
1751 private_submodules_->residual_echo_detector->Initialize();
1752}
1753
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001754void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001755 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001756
1757 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001758 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1759 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001760 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001761 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001762 capture_.stream_delay_jumps = 0;
1763 }
1764 if (capture_.aec_system_delay_jumps == -1 &&
1765 echo_cancellation()->stream_has_echo()) {
1766 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001767 }
1768
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001769 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001770 const int diff_stream_delay_ms =
1771 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1772 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1773 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001774 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1775 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001776 if (capture_.stream_delay_jumps == -1) {
1777 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001778 }
peahdf3efa82015-11-28 12:35:15 -08001779 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001780 }
peahdf3efa82015-11-28 12:35:15 -08001781 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001782
1783 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001784 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001785 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001786 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001787 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001788 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1789 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001790 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001791 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001792 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001793 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001794 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1795 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1796 100);
peahdf3efa82015-11-28 12:35:15 -08001797 if (capture_.aec_system_delay_jumps == -1) {
1798 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001799 }
peahdf3efa82015-11-28 12:35:15 -08001800 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001801 }
peahdf3efa82015-11-28 12:35:15 -08001802 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001803 }
1804}
1805
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001806void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001807 // Run in a single-threaded manner.
1808 rtc::CritScope cs_render(&crit_render_);
1809 rtc::CritScope cs_capture(&crit_capture_);
1810
1811 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001812 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001813 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001814 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001815 }
peahdf3efa82015-11-28 12:35:15 -08001816 capture_.stream_delay_jumps = -1;
1817 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001818
peahdf3efa82015-11-28 12:35:15 -08001819 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001820 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1821 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001822 }
peahdf3efa82015-11-28 12:35:15 -08001823 capture_.aec_system_delay_jumps = -1;
1824 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001825}
1826
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001827#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001828int AudioProcessingImpl::WriteMessageToDebugFile(
1829 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08001830 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08001831 rtc::CriticalSection* crit_debug,
1832 ApmDebugDumpThreadState* debug_state) {
1833 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00001834 if (size <= 0) {
1835 return kUnspecifiedError;
1836 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00001837#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07001838// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
1839// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00001840#endif
1841
peahdf3efa82015-11-28 12:35:15 -08001842 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00001843 return kUnspecifiedError;
1844 }
1845
peahdf3efa82015-11-28 12:35:15 -08001846 {
1847 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08001848 rtc::CritScope cs_debug(crit_debug);
1849
tommia6219cc2016-06-15 10:30:14 -07001850 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08001851 // Update the byte counter.
1852 if (*filesize_limit_bytes >= 0) {
1853 *filesize_limit_bytes -=
1854 (sizeof(int32_t) + debug_state->event_str.length());
1855 if (*filesize_limit_bytes < 0) {
1856 // Not enough bytes are left to write this message, so stop logging.
1857 debug_file->CloseFile();
1858 return kNoError;
1859 }
1860 }
peahdf3efa82015-11-28 12:35:15 -08001861 // Write message preceded by its size.
1862 if (!debug_file->Write(&size, sizeof(int32_t))) {
1863 return kFileError;
1864 }
1865 if (!debug_file->Write(debug_state->event_str.data(),
1866 debug_state->event_str.length())) {
1867 return kFileError;
1868 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001869 }
1870
peahdf3efa82015-11-28 12:35:15 -08001871 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00001872
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001873 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001874}
1875
1876int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08001877 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
1878 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
1879 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00001880
mbonadeid00aad52017-03-31 03:08:07 -07001881 msg->set_num_input_channels(static_cast<google::protobuf::int32>(
Peter Kasting69558702016-01-12 16:26:35 -08001882 formats_.api_format.input_stream().num_channels()));
mbonadeid00aad52017-03-31 03:08:07 -07001883 msg->set_num_output_channels(static_cast<google::protobuf::int32>(
Peter Kasting69558702016-01-12 16:26:35 -08001884 formats_.api_format.output_stream().num_channels()));
mbonadeid00aad52017-03-31 03:08:07 -07001885 msg->set_num_reverse_channels(static_cast<google::protobuf::int32>(
Peter Kasting69558702016-01-12 16:26:35 -08001886 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08001887 msg->set_reverse_sample_rate(
1888 formats_.api_format.reverse_input_stream().sample_rate_hz());
1889 msg->set_output_sample_rate(
1890 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07001891 msg->set_reverse_output_sample_rate(
1892 formats_.api_format.reverse_output_stream().sample_rate_hz());
1893 msg->set_num_reverse_output_channels(
1894 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08001895
1896 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001897 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001898 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02001899 return kNoError;
1900}
1901
1902int AudioProcessingImpl::WriteConfigMessage(bool forced) {
1903 audioproc::Config config;
1904
peahdf3efa82015-11-28 12:35:15 -08001905 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001906 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08001907 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001908 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08001909 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001910 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08001911 public_submodules_->echo_cancellation->is_extended_filter_enabled());
1912 config.set_aec_suppression_level(static_cast<int>(
1913 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02001914
peahdf3efa82015-11-28 12:35:15 -08001915 config.set_aecm_enabled(
1916 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001917 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08001918 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
1919 config.set_aecm_routing_mode(static_cast<int>(
1920 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02001921
peahdf3efa82015-11-28 12:35:15 -08001922 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
1923 config.set_agc_mode(
1924 static_cast<int>(public_submodules_->gain_control->mode()));
1925 config.set_agc_limiter_enabled(
1926 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08001927 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02001928
peah8271d042016-11-22 07:24:52 -08001929 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001930
peahdf3efa82015-11-28 12:35:15 -08001931 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
1932 config.set_ns_level(
1933 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02001934
peahdf3efa82015-11-28 12:35:15 -08001935 config.set_transient_suppression_enabled(
1936 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001937 config.set_intelligibility_enhancer_enabled(
1938 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001939
peah7789fe72016-04-15 01:19:44 -07001940 std::string experiments_description =
1941 public_submodules_->echo_cancellation->GetExperimentsDescription();
1942 // TODO(peah): Add semicolon-separated concatenations of experiment
1943 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07001944 if (capture_nonlocked_.level_controller_enabled) {
1945 experiments_description += "LevelController;";
1946 }
henrik.lundinbd681b92016-12-05 09:08:42 -08001947 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1948 experiments_description += "AgcClippingLevelExperiment;";
1949 }
peahe0eae3c2016-12-14 01:16:23 -08001950 if (capture_nonlocked_.echo_canceller3_enabled) {
1951 experiments_description += "EchoCanceller3;";
1952 }
peah7789fe72016-04-15 01:19:44 -07001953 config.set_experiments_description(experiments_description);
1954
mbonadeid00aad52017-03-31 03:08:07 -07001955 std::string serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08001956 if (!forced &&
1957 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02001958 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001959 }
1960
peahdf3efa82015-11-28 12:35:15 -08001961 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02001962
peahdf3efa82015-11-28 12:35:15 -08001963 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
1964 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02001965
peahdf3efa82015-11-28 12:35:15 -08001966 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001967 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001968 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00001969 return kNoError;
1970}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001971#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001972
kwiberg83ffe452016-08-29 14:46:07 -07001973AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1974 bool transient_suppressor_enabled,
1975 const std::vector<Point>& array_geometry,
1976 SphericalPointf target_direction)
1977 : aec_system_delay_jumps(-1),
1978 delay_offset_ms(0),
1979 was_stream_delay_set(false),
1980 last_stream_delay_ms(0),
1981 last_aec_system_delay_ms(0),
1982 stream_delay_jumps(-1),
1983 output_will_be_muted(false),
1984 key_pressed(false),
1985 transient_suppressor_enabled(transient_suppressor_enabled),
1986 array_geometry(array_geometry),
1987 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001988 capture_processing_format(kSampleRate16kHz),
kwiberg83ffe452016-08-29 14:46:07 -07001989 split_rate(kSampleRate16kHz) {}
1990
1991AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1992
1993AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1994
1995AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1996
niklase@google.com470e71d2011-07-07 08:21:25 +00001997} // namespace webrtc