blob: 1f73c5984a68af29d7dd941a64f88a834fd9e72a [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"
xians@webrtc.orge46bc772014-10-10 08:36:56 +000016#include "webrtc/base/platform_file.h"
peah369f8282015-12-17 06:42:29 -080017#include "webrtc/base/trace_event.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070018#include "webrtc/common_audio/audio_converter.h"
Michael Graczykdfa36052015-03-25 16:37:27 -070019#include "webrtc/common_audio/channel_buffer.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070020#include "webrtc/common_audio/include/audio_util.h"
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000021#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020022#include "webrtc/modules/audio_processing/aec/aec_core.h"
peahe0eae3c2016-12-14 01:16:23 -080023#include "webrtc/modules/audio_processing/aec3/echo_canceller3.h"
pbos@webrtc.org788acd12014-12-15 09:41:24 +000024#include "webrtc/modules/audio_processing/agc/agc_manager_direct.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000025#include "webrtc/modules/audio_processing/audio_buffer.h"
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +000026#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000027#include "webrtc/modules/audio_processing/common.h"
andrew@webrtc.org56e4a052014-02-27 22:23:17 +000028#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000029#include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
peahbe615622016-02-13 16:40:47 -080030#include "webrtc/modules/audio_processing/gain_control_for_experimental_agc.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000031#include "webrtc/modules/audio_processing/gain_control_impl.h"
peah1bcfce52016-08-26 07:16:04 -070032#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -070033#include "webrtc/modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070034#endif
peahca4cac72016-06-29 15:26:12 -070035#include "webrtc/modules/audio_processing/level_controller/level_controller.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000036#include "webrtc/modules/audio_processing/level_estimator_impl.h"
peah8271d042016-11-22 07:24:52 -080037#include "webrtc/modules/audio_processing/low_cut_filter.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000038#include "webrtc/modules/audio_processing/noise_suppression_impl.h"
ivoc9f4a4a02016-10-28 05:39:16 -070039#include "webrtc/modules/audio_processing/residual_echo_detector.h"
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +000040#include "webrtc/modules/audio_processing/transient/transient_suppressor.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000041#include "webrtc/modules/audio_processing/voice_detection_impl.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010042#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/file_wrapper.h"
44#include "webrtc/system_wrappers/include/logging.h"
45#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.
peah522d71b2017-02-23 05:16:26 -0800572 if (render_processing_rate > kSampleRate32kHz) {
peahde65ddc2016-09-16 15:02:15 -0700573 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
574 ? kSampleRate32kHz
575 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700576 }
peahde65ddc2016-09-16 15:02:15 -0700577 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700578 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700579 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
580 kSampleRate8kHz) {
581 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000582 } else {
peahde65ddc2016-09-16 15:02:15 -0700583 render_processing_rate =
584 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000585 }
586
peahde65ddc2016-09-16 15:02:15 -0700587 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000588 // demonstrated to work well for AEC in most practical scenarios.
peahde65ddc2016-09-16 15:02:15 -0700589 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000590
peahde65ddc2016-09-16 15:02:15 -0700591 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
592 kSampleRate32kHz ||
593 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
594 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800595 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000596 } else {
peahdf3efa82015-11-28 12:35:15 -0800597 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700598 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000599 }
600
601 return InitializeLocked();
602}
603
peah88ac8532016-09-12 16:47:25 -0700604void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700605 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700606
peahc19f3122016-10-07 14:54:10 -0700607 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700608 if (!config_ok) {
609 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
610 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700611 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700612 << std::endl
613 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700614 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700615 }
616
617 // Run in a single-threaded manner when applying the settings.
618 rtc::CritScope cs_render(&crit_render_);
619 rtc::CritScope cs_capture(&crit_capture_);
620
peahc19f3122016-10-07 14:54:10 -0700621 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
622 // with the value in config_ everywhere in the code.
623 if (capture_nonlocked_.level_controller_enabled !=
624 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700625 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700626 config_.level_controller.enabled;
627 // TODO(peah): Remove the conditional initialization to always initialize
628 // the level controller regardless of whether it is enabled or not.
629 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700630 }
peahc19f3122016-10-07 14:54:10 -0700631 LOG(LS_INFO) << "Level controller activated: "
632 << capture_nonlocked_.level_controller_enabled;
633
634 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800635
636 InitializeLowCutFilter();
637
638 LOG(LS_INFO) << "Highpass filter activated: "
639 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800640
641 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
642 if (!config_ok) {
643 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
644 << "echo canceller 3: "
645 << EchoCanceller3::ToString(config_.echo_canceller3)
646 << std::endl
647 << "Reverting to default parameter set";
648 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
649 }
650
651 if (config.echo_canceller3.enabled !=
652 capture_nonlocked_.echo_canceller3_enabled) {
653 capture_nonlocked_.echo_canceller3_enabled =
654 config_.echo_canceller3.enabled;
655 InitializeEchoCanceller3();
656 LOG(LS_INFO) << "Echo canceller 3 activated: "
657 << capture_nonlocked_.echo_canceller3_enabled;
658 }
peah88ac8532016-09-12 16:47:25 -0700659}
660
661void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800662 // Run in a single-threaded manner when setting the extra options.
663 rtc::CritScope cs_render(&crit_render_);
664 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000665
peahb624d8c2016-03-05 03:01:14 -0800666 public_submodules_->echo_cancellation->SetExtraOptions(config);
667
peahdf3efa82015-11-28 12:35:15 -0800668 if (capture_.transient_suppressor_enabled !=
669 config.Get<ExperimentalNs>().enabled) {
670 capture_.transient_suppressor_enabled =
671 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000672 InitializeTransient();
673 }
aluebs2a346882016-01-11 18:04:30 -0800674
peah1bcfce52016-08-26 07:16:04 -0700675#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700676 if(capture_nonlocked_.intelligibility_enabled !=
677 config.Get<Intelligibility>().enabled) {
678 capture_nonlocked_.intelligibility_enabled =
679 config.Get<Intelligibility>().enabled;
680 InitializeIntelligibility();
681 }
peah1bcfce52016-08-26 07:16:04 -0700682#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700683
aluebs2a346882016-01-11 18:04:30 -0800684#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800685 if (capture_nonlocked_.beamformer_enabled !=
686 config.Get<Beamforming>().enabled) {
687 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800688 if (config.Get<Beamforming>().array_geometry.size() > 1) {
689 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
690 }
691 capture_.target_direction = config.Get<Beamforming>().target_direction;
692 InitializeBeamformer();
693 }
694#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000695}
696
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000697int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800698 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700699 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000700}
701
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000702int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800703 // Used as callback from submodules, hence locking is not allowed.
704 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000705}
706
Peter Kasting69558702016-01-12 16:26:35 -0800707size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800708 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700709 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000710}
711
Peter Kasting69558702016-01-12 16:26:35 -0800712size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800713 // Used as callback from submodules, hence locking is not allowed.
714 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000715}
716
Peter Kasting69558702016-01-12 16:26:35 -0800717size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800718 // Used as callback from submodules, hence locking is not allowed.
719 return capture_nonlocked_.beamformer_enabled ? 1 : num_output_channels();
720}
721
Peter Kasting69558702016-01-12 16:26:35 -0800722size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800723 // Used as callback from submodules, hence locking is not allowed.
724 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000727void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800728 rtc::CritScope cs(&crit_capture_);
729 capture_.output_will_be_muted = muted;
730 if (private_submodules_->agc_manager.get()) {
731 private_submodules_->agc_manager->SetCaptureMuted(
732 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000733 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000734}
735
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000736
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000737int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700738 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000739 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000740 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000741 int output_sample_rate_hz,
742 ChannelLayout output_layout,
743 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800744 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800745 StreamConfig input_stream;
746 StreamConfig output_stream;
747 {
748 // Access the formats_.api_format.input_stream beneath the capture lock.
749 // The lock must be released as it is later required in the call
750 // to ProcessStream(,,,);
751 rtc::CritScope cs(&crit_capture_);
752 input_stream = formats_.api_format.input_stream();
753 output_stream = formats_.api_format.output_stream();
754 }
755
Michael Graczyk86c6d332015-07-23 11:41:39 -0700756 input_stream.set_sample_rate_hz(input_sample_rate_hz);
757 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
758 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700759 output_stream.set_sample_rate_hz(output_sample_rate_hz);
760 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
761 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
762
763 if (samples_per_channel != input_stream.num_frames()) {
764 return kBadDataLengthError;
765 }
766 return ProcessStream(src, input_stream, output_stream, dest);
767}
768
769int AudioProcessingImpl::ProcessStream(const float* const* src,
770 const StreamConfig& input_config,
771 const StreamConfig& output_config,
772 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800773 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800774 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700775 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800776 {
777 // Acquire the capture lock in order to safely call the function
778 // that retrieves the render side data. This function accesses apm
779 // getters that need the capture lock held when being called.
780 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700781 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800782
783 if (!src || !dest) {
784 return kNullPointerError;
785 }
786
787 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700788 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000789 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000790
Michael Graczyk86c6d332015-07-23 11:41:39 -0700791 processing_config.input_stream() = input_config;
792 processing_config.output_stream() = output_config;
793
peahdf3efa82015-11-28 12:35:15 -0800794 {
795 // Do conditional reinitialization.
796 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700797 RETURN_ON_ERR(
798 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800799 }
800 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700801 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
802 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000803
804#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700805 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200806 RETURN_ON_ERR(WriteConfigMessage(false));
807
peahdf3efa82015-11-28 12:35:15 -0800808 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
809 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000810 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800811 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800812 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
813 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000814 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000815 }
816#endif
817
peahdf3efa82015-11-28 12:35:15 -0800818 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700819 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800820 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000821
822#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700823 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800824 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000825 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800826 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800827 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
828 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000829 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800830 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800831 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800832 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000833 }
834#endif
835
836 return kNoError;
837}
838
peah701d6282016-10-25 05:42:20 -0700839void AudioProcessingImpl::QueueRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700840 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
841 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700842 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700843
kwibergaf476c72016-11-28 15:21:39 -0800844 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700845
846 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700847 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700848 // The data queue is full and needs to be emptied.
849 EmptyQueuedRenderAudio();
850
851 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700852 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700853 RTC_DCHECK(result);
854 }
855
856 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
857 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700858 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700859
860 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700861 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700862 // The data queue is full and needs to be emptied.
863 EmptyQueuedRenderAudio();
864
865 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700866 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700867 RTC_DCHECK(result);
868 }
peah701d6282016-10-25 05:42:20 -0700869
870 if (!constants_.use_experimental_agc) {
871 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
872 // Insert the samples into the queue.
873 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
874 // The data queue is full and needs to be emptied.
875 EmptyQueuedRenderAudio();
876
877 // Retry the insert (should always work).
878 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
879 RTC_DCHECK(result);
880 }
881 }
ivoc9f4a4a02016-10-28 05:39:16 -0700882
883 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
884
885 // Insert the samples into the queue.
886 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
887 // The data queue is full and needs to be emptied.
888 EmptyQueuedRenderAudio();
889
890 // Retry the insert (should always work).
891 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
892 RTC_DCHECK(result);
893 }
peah764e3642016-10-22 05:04:30 -0700894}
895
896void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700897 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700898 std::max(static_cast<size_t>(1),
899 kMaxAllowedValuesOfSamplesPerFrame *
900 EchoCancellationImpl::NumCancellersRequired(
901 num_output_channels(), num_reverse_channels()));
902
peah701d6282016-10-25 05:42:20 -0700903 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700904 std::max(static_cast<size_t>(1),
905 kMaxAllowedValuesOfSamplesPerFrame *
906 EchoControlMobileImpl::NumCancellersRequired(
907 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700908
peah701d6282016-10-25 05:42:20 -0700909 const size_t new_agc_render_queue_element_max_size =
910 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
911
ivoc9f4a4a02016-10-28 05:39:16 -0700912 const size_t new_red_render_queue_element_max_size =
913 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
914
peaha0624602016-10-25 04:45:24 -0700915 // Reallocate the queues if the queue item sizes are too small to fit the
916 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700917 if (aec_render_queue_element_max_size_ <
918 new_aec_render_queue_element_max_size) {
919 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700920
peaha0624602016-10-25 04:45:24 -0700921 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700922 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700923
peah701d6282016-10-25 05:42:20 -0700924 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700925 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
926 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700927 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700928 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700929
peah701d6282016-10-25 05:42:20 -0700930 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
931 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700932 } else {
peah701d6282016-10-25 05:42:20 -0700933 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700934 }
935
peah701d6282016-10-25 05:42:20 -0700936 if (aecm_render_queue_element_max_size_ <
937 new_aecm_render_queue_element_max_size) {
938 aecm_render_queue_element_max_size_ =
939 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700940
941 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700942 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700943
peah701d6282016-10-25 05:42:20 -0700944 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700945 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
946 kMaxNumFramesToBuffer, template_queue_element,
947 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700948 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700949
peah701d6282016-10-25 05:42:20 -0700950 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
951 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700952 } else {
peah701d6282016-10-25 05:42:20 -0700953 aecm_render_signal_queue_->Clear();
954 }
955
956 if (agc_render_queue_element_max_size_ <
957 new_agc_render_queue_element_max_size) {
958 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
959
960 std::vector<int16_t> template_queue_element(
961 agc_render_queue_element_max_size_);
962
963 agc_render_signal_queue_.reset(
964 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
965 kMaxNumFramesToBuffer, template_queue_element,
966 RenderQueueItemVerifier<int16_t>(
967 agc_render_queue_element_max_size_)));
968
969 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
970 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
971 } else {
972 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700973 }
ivoc9f4a4a02016-10-28 05:39:16 -0700974
975 if (red_render_queue_element_max_size_ <
976 new_red_render_queue_element_max_size) {
977 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
978
979 std::vector<float> template_queue_element(
980 red_render_queue_element_max_size_);
981
982 red_render_signal_queue_.reset(
983 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
984 kMaxNumFramesToBuffer, template_queue_element,
985 RenderQueueItemVerifier<float>(
986 red_render_queue_element_max_size_)));
987
988 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
989 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
990 } else {
991 red_render_signal_queue_->Clear();
992 }
peah764e3642016-10-22 05:04:30 -0700993}
994
995void AudioProcessingImpl::EmptyQueuedRenderAudio() {
996 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -0700997 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700998 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -0700999 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001000 }
1001
peah701d6282016-10-25 05:42:20 -07001002 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001003 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001004 aecm_capture_queue_buffer_);
1005 }
1006
1007 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1008 public_submodules_->gain_control->ProcessRenderAudio(
1009 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001010 }
ivoc9f4a4a02016-10-28 05:39:16 -07001011
1012 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1013 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1014 red_capture_queue_buffer_);
1015 }
peah764e3642016-10-22 05:04:30 -07001016}
1017
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001018int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001019 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001020 {
1021 // Acquire the capture lock in order to safely call the function
1022 // that retrieves the render side data. This function accesses apm
1023 // getters that need the capture lock held when being called.
1024 // The lock needs to be released as
1025 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1026 // as well.
1027 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001028 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001029 }
peahfa6228e2015-11-16 16:27:42 -08001030
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001031 if (!frame) {
1032 return kNullPointerError;
1033 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001034 // Must be a native rate.
1035 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1036 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001037 frame->sample_rate_hz_ != kSampleRate32kHz &&
1038 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001039 return kBadSampleRateError;
1040 }
peah192164e2015-11-17 02:16:45 -08001041
peahdf3efa82015-11-28 12:35:15 -08001042 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001043 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001044 {
1045 // Aquire lock for the access of api_format.
1046 // The lock is released immediately due to the conditional
1047 // reinitialization.
1048 rtc::CritScope cs_capture(&crit_capture_);
1049 // TODO(ajm): The input and output rates and channels are currently
1050 // constrained to be identical in the int16 interface.
1051 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001052
1053 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001054 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001055 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1056 processing_config.input_stream().set_num_channels(frame->num_channels_);
1057 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1058 processing_config.output_stream().set_num_channels(frame->num_channels_);
1059
peahdf3efa82015-11-28 12:35:15 -08001060 {
1061 // Do conditional reinitialization.
1062 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001063 RETURN_ON_ERR(
1064 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001065 }
1066 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001067 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001068 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001069 return kBadDataLengthError;
1070 }
1071
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001072#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001073 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001074 RETURN_ON_ERR(WriteConfigMessage(false));
1075
peahdf3efa82015-11-28 12:35:15 -08001076 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1077 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001078 const size_t data_size =
1079 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001080 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001081 }
1082#endif
1083
peahdf3efa82015-11-28 12:35:15 -08001084 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001085 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001086 capture_.capture_audio->InterleaveTo(
1087 frame, submodule_states_.CaptureMultiBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001088
1089#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001090 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001091 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001092 const size_t data_size =
1093 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001094 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001095 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001096 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001097 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001098 }
1099#endif
1100
1101 return kNoError;
1102}
1103
peahde65ddc2016-09-16 15:02:15 -07001104int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001105 // Ensure that not both the AEC and AECM are active at the same time.
1106 // TODO(peah): Simplify once the public API Enable functions for these
1107 // are moved to APM.
1108 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1109 public_submodules_->echo_control_mobile->is_enabled()));
1110
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001111#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001112 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001113 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1114 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1115 msg->set_drift(
1116 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001117 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001118 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001119 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001120#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001121
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001122 MaybeUpdateHistograms();
1123
peahde65ddc2016-09-16 15:02:15 -07001124 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001125
peah1b08dc32016-12-20 13:45:58 -08001126 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001127 capture_buffer->channels_const()[0],
1128 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001129 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1130 if (log_rms) {
1131 capture_rms_interval_counter_ = 0;
1132 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001133 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1134 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1135 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1136 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001137 }
1138
peahe0eae3c2016-12-14 01:16:23 -08001139 if (private_submodules_->echo_canceller3) {
1140 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1141 }
1142
peahbe615622016-02-13 16:40:47 -08001143 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001144 public_submodules_->gain_control->is_enabled()) {
1145 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001146 capture_buffer->channels()[0], capture_buffer->num_channels(),
1147 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001148 }
1149
peah2ace3f92016-09-10 04:42:27 -07001150 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1151 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001152 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1153 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001154 }
1155
peah522d71b2017-02-23 05:16:26 -08001156 if (private_submodules_->echo_canceller3) {
1157 // Force down-mixing of the number of channels after the detection of
1158 // capture signal saturation.
1159 // TODO(peah): Look into ensuring that this kind of tampering with the
1160 // AudioBuffer functionality should not be needed.
1161 capture_buffer->set_num_channels(1);
1162 }
1163
aluebsb2328d12016-01-11 20:32:29 -08001164 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001165 private_submodules_->beamformer->AnalyzeChunk(
1166 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001167 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001168 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001169 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001170
peahe0eae3c2016-12-14 01:16:23 -08001171 // TODO(peah): Move the AEC3 low-cut filter to this place.
1172 if (private_submodules_->low_cut_filter &&
1173 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001174 private_submodules_->low_cut_filter->Process(capture_buffer);
1175 }
peahde65ddc2016-09-16 15:02:15 -07001176 RETURN_ON_ERR(
1177 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1178 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001179
1180 // Ensure that the stream delay was set before the call to the
1181 // AEC ProcessCaptureAudio function.
1182 if (public_submodules_->echo_cancellation->is_enabled() &&
1183 !was_stream_delay_set()) {
1184 return AudioProcessing::kStreamParameterNotSetError;
1185 }
1186
peahe0eae3c2016-12-14 01:16:23 -08001187 if (private_submodules_->echo_canceller3) {
1188 private_submodules_->echo_canceller3->ProcessCapture(capture_buffer, false);
peah61202ac2017-02-06 03:39:42 -08001189 } else {
1190 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1191 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001192 }
1193
peahdf3efa82015-11-28 12:35:15 -08001194 if (public_submodules_->echo_control_mobile->is_enabled() &&
1195 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001196 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001197 }
peahde65ddc2016-09-16 15:02:15 -07001198 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001199#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001200 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001201 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001202 int gain_db = public_submodules_->gain_control->is_enabled() ?
1203 public_submodules_->gain_control->compression_gain_db() :
1204 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001205 float gain = std::pow(10.f, gain_db / 20.f);
1206 gain *= capture_nonlocked_.level_controller_enabled ?
1207 private_submodules_->level_controller->GetLastGain() :
1208 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001209 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001210 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001211 }
peah1bcfce52016-08-26 07:16:04 -07001212#endif
peah253534d2016-03-15 04:32:28 -07001213
1214 // Ensure that the stream delay was set before the call to the
1215 // AECM ProcessCaptureAudio function.
1216 if (public_submodules_->echo_control_mobile->is_enabled() &&
1217 !was_stream_delay_set()) {
1218 return AudioProcessing::kStreamParameterNotSetError;
1219 }
1220
1221 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001222 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001223
ivoc9f4a4a02016-10-28 05:39:16 -07001224 if (config_.residual_echo_detector.enabled) {
1225 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1226 rtc::ArrayView<const float>(
1227 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1228 capture_buffer->num_frames_per_band()));
1229 }
1230
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001231 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001232 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001233 }
1234
peahde65ddc2016-09-16 15:02:15 -07001235 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001236
peahbe615622016-02-13 16:40:47 -08001237 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001238 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001239 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001240 private_submodules_->beamformer->is_target_present())) {
1241 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001242 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1243 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001244 }
peahb8fbb542016-03-15 02:28:08 -07001245 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001246 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001247
peah2ace3f92016-09-10 04:42:27 -07001248 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1249 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001250 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1251 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001252 }
1253
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001254 // TODO(aluebs): Investigate if the transient suppression placement should be
1255 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001256 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001257 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001258 private_submodules_->agc_manager.get()
1259 ? private_submodules_->agc_manager->voice_probability()
1260 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001261
peahdf3efa82015-11-28 12:35:15 -08001262 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001263 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1264 capture_buffer->num_channels(),
1265 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1266 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1267 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001268 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001269 }
1270
peahca4cac72016-06-29 15:26:12 -07001271 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001272 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001273 }
1274
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001275 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001276 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001277
peah1b08dc32016-12-20 13:45:58 -08001278 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1279 capture_buffer->channels_const()[0],
1280 capture_nonlocked_.capture_processing_format.num_frames()));
1281 if (log_rms) {
1282 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1283 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1284 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1285 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1286 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1287 }
1288
peahdf3efa82015-11-28 12:35:15 -08001289 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001290 return kNoError;
1291}
1292
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001293int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001294 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001295 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001296 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001297 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001298 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001299 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001300 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001301 };
1302 if (samples_per_channel != reverse_config.num_frames()) {
1303 return kBadDataLengthError;
1304 }
peahdf3efa82015-11-28 12:35:15 -08001305 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001306}
1307
peahde65ddc2016-09-16 15:02:15 -07001308int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1309 const StreamConfig& input_config,
1310 const StreamConfig& output_config,
1311 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001312 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001313 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001314 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001315 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001316 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1317 dest);
peah2ace3f92016-09-10 04:42:27 -07001318 } else if (formats_.api_format.reverse_input_stream() !=
1319 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001320 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1321 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001322 } else {
peahde65ddc2016-09-16 15:02:15 -07001323 CopyAudioIfNeeded(src, input_config.num_frames(),
1324 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001325 }
1326
1327 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001328}
1329
peahdf3efa82015-11-28 12:35:15 -08001330int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001331 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001332 const StreamConfig& input_config,
1333 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001334 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001335 return kNullPointerError;
1336 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001337
peahde65ddc2016-09-16 15:02:15 -07001338 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001339 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001340 }
1341
peahdf3efa82015-11-28 12:35:15 -08001342 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001343 processing_config.reverse_input_stream() = input_config;
1344 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001345
peahdf3efa82015-11-28 12:35:15 -08001346 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001347 assert(input_config.num_frames() ==
1348 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001349
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001350#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001351 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001352 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1353 audioproc::ReverseStream* msg =
1354 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001355 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001356 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001357 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001358 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001359 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001360 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001361 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001362 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001363 }
1364#endif
1365
peahdf3efa82015-11-28 12:35:15 -08001366 render_.render_audio->CopyFrom(src,
1367 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001368 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001369}
1370
1371int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001372 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001373 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001374 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001375 return kNullPointerError;
1376 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001377 // Must be a native rate.
1378 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1379 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001380 frame->sample_rate_hz_ != kSampleRate32kHz &&
1381 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001382 return kBadSampleRateError;
1383 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001384
Michael Graczyk86c6d332015-07-23 11:41:39 -07001385 if (frame->num_channels_ <= 0) {
1386 return kBadNumberChannelsError;
1387 }
1388
peahdf3efa82015-11-28 12:35:15 -08001389 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001390 processing_config.reverse_input_stream().set_sample_rate_hz(
1391 frame->sample_rate_hz_);
1392 processing_config.reverse_input_stream().set_num_channels(
1393 frame->num_channels_);
1394 processing_config.reverse_output_stream().set_sample_rate_hz(
1395 frame->sample_rate_hz_);
1396 processing_config.reverse_output_stream().set_num_channels(
1397 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001398
peahdf3efa82015-11-28 12:35:15 -08001399 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001400 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001401 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001402 return kBadDataLengthError;
1403 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001404
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001405#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001406 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001407 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1408 audioproc::ReverseStream* msg =
1409 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001410 const size_t data_size =
1411 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001412 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001413 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001414 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001415 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001416 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001417#endif
peahdf3efa82015-11-28 12:35:15 -08001418 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001419 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001420 render_.render_audio->InterleaveTo(
1421 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001422 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001423}
niklase@google.com470e71d2011-07-07 08:21:25 +00001424
peahde65ddc2016-09-16 15:02:15 -07001425int AudioProcessingImpl::ProcessRenderStreamLocked() {
1426 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah2ace3f92016-09-10 04:42:27 -07001427 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001428 SampleRateSupportsMultiBand(
1429 formats_.render_processing_format.sample_rate_hz())) {
1430 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001431 }
1432
peah1bcfce52016-08-26 07:16:04 -07001433#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001434 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001435 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001436 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001437 }
peah1bcfce52016-08-26 07:16:04 -07001438#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001439
peah764e3642016-10-22 05:04:30 -07001440 QueueRenderAudio(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001441 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1442 if (private_submodules_->echo_canceller3) {
1443 if (!private_submodules_->echo_canceller3->AnalyzeRender(render_buffer)) {
1444 // TODO(peah): Lock and empty render queue, and try again.
1445 }
1446 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001447
peah2ace3f92016-09-10 04:42:27 -07001448 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001449 SampleRateSupportsMultiBand(
1450 formats_.render_processing_format.sample_rate_hz())) {
1451 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001452 }
1453
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001454 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001455}
1456
1457int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001458 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001459 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001460 capture_.was_stream_delay_set = true;
1461 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001462
niklase@google.com470e71d2011-07-07 08:21:25 +00001463 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001464 delay = 0;
1465 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466 }
1467
1468 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1469 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001470 delay = 500;
1471 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001472 }
1473
peahdf3efa82015-11-28 12:35:15 -08001474 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001475 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001476}
1477
1478int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001479 // Used as callback from submodules, hence locking is not allowed.
1480 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001481}
1482
1483bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001484 // Used as callback from submodules, hence locking is not allowed.
1485 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001486}
1487
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001488void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001489 rtc::CritScope cs(&crit_capture_);
1490 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001491}
1492
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001493void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001494 rtc::CritScope cs(&crit_capture_);
1495 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001496}
1497
1498int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001499 rtc::CritScope cs(&crit_capture_);
1500 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001501}
1502
niklase@google.com470e71d2011-07-07 08:21:25 +00001503int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001504 const char filename[AudioProcessing::kMaxFilenameSize],
1505 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001506 // Run in a single-threaded manner.
1507 rtc::CritScope cs_render(&crit_render_);
1508 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001509 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001510
peahdf3efa82015-11-28 12:35:15 -08001511 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001512 return kNullPointerError;
1513 }
1514
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001515#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001516 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001517 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001518 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001519
tommia6219cc2016-06-15 10:30:14 -07001520 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001521 return kFileError;
1522 }
1523
Minyue13b96ba2015-10-03 00:39:14 +02001524 RETURN_ON_ERR(WriteConfigMessage(true));
1525 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001526 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001527#else
1528 return kUnsupportedFunctionError;
1529#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001530}
1531
ivocd66b44d2016-01-15 03:06:36 -08001532int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1533 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001534 // Run in a single-threaded manner.
1535 rtc::CritScope cs_render(&crit_render_);
1536 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001537
peahdf3efa82015-11-28 12:35:15 -08001538 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001539 return kNullPointerError;
1540 }
1541
1542#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001543 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1544
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001545 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001546 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001547
tommia6219cc2016-06-15 10:30:14 -07001548 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001549 return kFileError;
1550 }
1551
Minyue13b96ba2015-10-03 00:39:14 +02001552 RETURN_ON_ERR(WriteConfigMessage(true));
1553 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001554 return kNoError;
1555#else
1556 return kUnsupportedFunctionError;
1557#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1558}
1559
peah73a28ee2016-10-12 03:01:49 -07001560int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1561 return StartDebugRecording(handle, -1);
1562}
1563
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001564int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1565 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001566 // Run in a single-threaded manner.
1567 rtc::CritScope cs_render(&crit_render_);
1568 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001569 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001570 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001571}
1572
niklase@google.com470e71d2011-07-07 08:21:25 +00001573int AudioProcessingImpl::StopDebugRecording() {
peahdf3efa82015-11-28 12:35:15 -08001574 // Run in a single-threaded manner.
1575 rtc::CritScope cs_render(&crit_render_);
1576 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001577
1578#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001579 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001580 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001581 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001582#else
1583 return kUnsupportedFunctionError;
1584#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001585}
1586
ivoc4e477a12017-01-15 08:29:46 -08001587AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1588 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1589 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1590 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1591 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1592}
1593
1594AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1595 const AudioProcessingStatistics& other) = default;
1596
1597AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1598 default;
1599
ivoc3e9a5372016-10-28 07:55:33 -07001600// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1601AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1602 const {
1603 return AudioProcessingStatistics();
1604}
1605
1606AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1607 const {
1608 AudioProcessingStatistics stats;
1609 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001610 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1611 if (success == Error::kNoError) {
1612 stats.a_nlp.Set(metrics.a_nlp);
1613 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1614 stats.echo_return_loss.Set(metrics.echo_return_loss);
1615 stats.echo_return_loss_enhancement.Set(
1616 metrics.echo_return_loss_enhancement);
1617 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1618 }
ivoc9c192b22017-03-16 04:22:14 -07001619 {
1620 rtc::CritScope cs_capture(&crit_capture_);
1621 stats.residual_echo_likelihood =
1622 private_submodules_->residual_echo_detector->echo_likelihood();
1623 stats.residual_echo_likelihood_recent_max =
1624 private_submodules_->residual_echo_detector
1625 ->echo_likelihood_recent_max();
1626 }
ivoc3e9a5372016-10-28 07:55:33 -07001627 public_submodules_->echo_cancellation->GetDelayMetrics(
1628 &stats.delay_median, &stats.delay_standard_deviation,
1629 &stats.fraction_poor_delays);
1630 return stats;
1631}
1632
niklase@google.com470e71d2011-07-07 08:21:25 +00001633EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001634 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001635}
1636
1637EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001638 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001639}
1640
1641GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001642 if (constants_.use_experimental_agc) {
1643 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001644 }
peahbfa97112016-03-10 21:09:04 -08001645 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001646}
1647
1648HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001649 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001650}
1651
1652LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001653 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001654}
1655
1656NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001657 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001658}
1659
1660VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001661 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001662}
1663
peah8271d042016-11-22 07:24:52 -08001664void AudioProcessingImpl::MutateConfig(
1665 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1666 rtc::CritScope cs_render(&crit_render_);
1667 rtc::CritScope cs_capture(&crit_capture_);
1668 mutator(&config_);
1669 ApplyConfig(config_);
1670}
1671
1672AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1673 rtc::CritScope cs_render(&crit_render_);
1674 rtc::CritScope cs_capture(&crit_capture_);
1675 return config_;
1676}
1677
peah2ace3f92016-09-10 04:42:27 -07001678bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1679 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001680 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001681 public_submodules_->echo_cancellation->is_enabled(),
1682 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001683 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001684 public_submodules_->noise_suppression->is_enabled(),
1685 capture_nonlocked_.intelligibility_enabled,
1686 capture_nonlocked_.beamformer_enabled,
1687 public_submodules_->gain_control->is_enabled(),
1688 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001689 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001690 public_submodules_->voice_detection->is_enabled(),
1691 public_submodules_->level_estimator->is_enabled(),
1692 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001693}
1694
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001695
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001696void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001697 if (capture_.transient_suppressor_enabled) {
1698 if (!public_submodules_->transient_suppressor.get()) {
1699 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001700 }
peahdf3efa82015-11-28 12:35:15 -08001701 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001702 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1703 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001704 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001705}
1706
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001707void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001708 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001709 if (!private_submodules_->beamformer) {
1710 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001711 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001712 }
peahdf3efa82015-11-28 12:35:15 -08001713 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1714 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001715 }
1716}
1717
ekmeyerson60d9b332015-08-14 10:35:55 -07001718void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001719#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001720 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001721 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001722 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001723 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001724 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001725 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001726 }
peah1bcfce52016-08-26 07:16:04 -07001727#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001728}
1729
peah8271d042016-11-22 07:24:52 -08001730void AudioProcessingImpl::InitializeLowCutFilter() {
1731 if (config_.high_pass_filter.enabled) {
1732 private_submodules_->low_cut_filter.reset(
1733 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1734 } else {
1735 private_submodules_->low_cut_filter.reset();
1736 }
1737}
peahe0eae3c2016-12-14 01:16:23 -08001738void AudioProcessingImpl::InitializeEchoCanceller3() {
1739 if (capture_nonlocked_.echo_canceller3_enabled) {
1740 private_submodules_->echo_canceller3.reset(
1741 new EchoCanceller3(proc_sample_rate_hz(), true));
1742 } else {
1743 private_submodules_->echo_canceller3.reset();
1744 }
1745}
peah8271d042016-11-22 07:24:52 -08001746
peahca4cac72016-06-29 15:26:12 -07001747void AudioProcessingImpl::InitializeLevelController() {
1748 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1749}
1750
ivoc9f4a4a02016-10-28 05:39:16 -07001751void AudioProcessingImpl::InitializeResidualEchoDetector() {
1752 private_submodules_->residual_echo_detector->Initialize();
1753}
1754
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001755void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001756 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001757
1758 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001759 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1760 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001761 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001762 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001763 capture_.stream_delay_jumps = 0;
1764 }
1765 if (capture_.aec_system_delay_jumps == -1 &&
1766 echo_cancellation()->stream_has_echo()) {
1767 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001768 }
1769
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001770 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001771 const int diff_stream_delay_ms =
1772 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1773 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1774 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001775 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1776 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001777 if (capture_.stream_delay_jumps == -1) {
1778 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001779 }
peahdf3efa82015-11-28 12:35:15 -08001780 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001781 }
peahdf3efa82015-11-28 12:35:15 -08001782 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001783
1784 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001785 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001786 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001787 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001788 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001789 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1790 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001791 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001792 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001793 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001794 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001795 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1796 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1797 100);
peahdf3efa82015-11-28 12:35:15 -08001798 if (capture_.aec_system_delay_jumps == -1) {
1799 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001800 }
peahdf3efa82015-11-28 12:35:15 -08001801 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001802 }
peahdf3efa82015-11-28 12:35:15 -08001803 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001804 }
1805}
1806
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001807void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001808 // Run in a single-threaded manner.
1809 rtc::CritScope cs_render(&crit_render_);
1810 rtc::CritScope cs_capture(&crit_capture_);
1811
1812 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001813 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001814 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001815 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001816 }
peahdf3efa82015-11-28 12:35:15 -08001817 capture_.stream_delay_jumps = -1;
1818 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001819
peahdf3efa82015-11-28 12:35:15 -08001820 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001821 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1822 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001823 }
peahdf3efa82015-11-28 12:35:15 -08001824 capture_.aec_system_delay_jumps = -1;
1825 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001826}
1827
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001828#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001829int AudioProcessingImpl::WriteMessageToDebugFile(
1830 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08001831 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08001832 rtc::CriticalSection* crit_debug,
1833 ApmDebugDumpThreadState* debug_state) {
1834 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00001835 if (size <= 0) {
1836 return kUnspecifiedError;
1837 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00001838#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07001839// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
1840// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00001841#endif
1842
peahdf3efa82015-11-28 12:35:15 -08001843 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00001844 return kUnspecifiedError;
1845 }
1846
peahdf3efa82015-11-28 12:35:15 -08001847 {
1848 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08001849 rtc::CritScope cs_debug(crit_debug);
1850
tommia6219cc2016-06-15 10:30:14 -07001851 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08001852 // Update the byte counter.
1853 if (*filesize_limit_bytes >= 0) {
1854 *filesize_limit_bytes -=
1855 (sizeof(int32_t) + debug_state->event_str.length());
1856 if (*filesize_limit_bytes < 0) {
1857 // Not enough bytes are left to write this message, so stop logging.
1858 debug_file->CloseFile();
1859 return kNoError;
1860 }
1861 }
peahdf3efa82015-11-28 12:35:15 -08001862 // Write message preceded by its size.
1863 if (!debug_file->Write(&size, sizeof(int32_t))) {
1864 return kFileError;
1865 }
1866 if (!debug_file->Write(debug_state->event_str.data(),
1867 debug_state->event_str.length())) {
1868 return kFileError;
1869 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001870 }
1871
peahdf3efa82015-11-28 12:35:15 -08001872 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00001873
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001874 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001875}
1876
1877int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08001878 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
1879 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
1880 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00001881
Peter Kasting69558702016-01-12 16:26:35 -08001882 msg->set_num_input_channels(static_cast<google::protobuf::int32>(
1883 formats_.api_format.input_stream().num_channels()));
1884 msg->set_num_output_channels(static_cast<google::protobuf::int32>(
1885 formats_.api_format.output_stream().num_channels()));
1886 msg->set_num_reverse_channels(static_cast<google::protobuf::int32>(
1887 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08001888 msg->set_reverse_sample_rate(
1889 formats_.api_format.reverse_input_stream().sample_rate_hz());
1890 msg->set_output_sample_rate(
1891 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07001892 msg->set_reverse_output_sample_rate(
1893 formats_.api_format.reverse_output_stream().sample_rate_hz());
1894 msg->set_num_reverse_output_channels(
1895 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08001896
1897 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001898 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001899 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02001900 return kNoError;
1901}
1902
1903int AudioProcessingImpl::WriteConfigMessage(bool forced) {
1904 audioproc::Config config;
1905
peahdf3efa82015-11-28 12:35:15 -08001906 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001907 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08001908 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001909 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08001910 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001911 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08001912 public_submodules_->echo_cancellation->is_extended_filter_enabled());
1913 config.set_aec_suppression_level(static_cast<int>(
1914 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02001915
peahdf3efa82015-11-28 12:35:15 -08001916 config.set_aecm_enabled(
1917 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001918 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08001919 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
1920 config.set_aecm_routing_mode(static_cast<int>(
1921 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02001922
peahdf3efa82015-11-28 12:35:15 -08001923 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
1924 config.set_agc_mode(
1925 static_cast<int>(public_submodules_->gain_control->mode()));
1926 config.set_agc_limiter_enabled(
1927 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08001928 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02001929
peah8271d042016-11-22 07:24:52 -08001930 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001931
peahdf3efa82015-11-28 12:35:15 -08001932 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
1933 config.set_ns_level(
1934 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02001935
peahdf3efa82015-11-28 12:35:15 -08001936 config.set_transient_suppression_enabled(
1937 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001938 config.set_intelligibility_enhancer_enabled(
1939 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001940
peah7789fe72016-04-15 01:19:44 -07001941 std::string experiments_description =
1942 public_submodules_->echo_cancellation->GetExperimentsDescription();
1943 // TODO(peah): Add semicolon-separated concatenations of experiment
1944 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07001945 if (capture_nonlocked_.level_controller_enabled) {
1946 experiments_description += "LevelController;";
1947 }
henrik.lundinbd681b92016-12-05 09:08:42 -08001948 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1949 experiments_description += "AgcClippingLevelExperiment;";
1950 }
peahe0eae3c2016-12-14 01:16:23 -08001951 if (capture_nonlocked_.echo_canceller3_enabled) {
1952 experiments_description += "EchoCanceller3;";
1953 }
peah7789fe72016-04-15 01:19:44 -07001954 config.set_experiments_description(experiments_description);
1955
Minyue13b96ba2015-10-03 00:39:14 +02001956 std::string serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08001957 if (!forced &&
1958 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02001959 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001960 }
1961
peahdf3efa82015-11-28 12:35:15 -08001962 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02001963
peahdf3efa82015-11-28 12:35:15 -08001964 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
1965 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02001966
peahdf3efa82015-11-28 12:35:15 -08001967 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001968 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001969 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00001970 return kNoError;
1971}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001972#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001973
kwiberg83ffe452016-08-29 14:46:07 -07001974AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1975 bool transient_suppressor_enabled,
1976 const std::vector<Point>& array_geometry,
1977 SphericalPointf target_direction)
1978 : aec_system_delay_jumps(-1),
1979 delay_offset_ms(0),
1980 was_stream_delay_set(false),
1981 last_stream_delay_ms(0),
1982 last_aec_system_delay_ms(0),
1983 stream_delay_jumps(-1),
1984 output_will_be_muted(false),
1985 key_pressed(false),
1986 transient_suppressor_enabled(transient_suppressor_enabled),
1987 array_geometry(array_geometry),
1988 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001989 capture_processing_format(kSampleRate16kHz),
kwiberg83ffe452016-08-29 14:46:07 -07001990 split_rate(kSampleRate16kHz) {}
1991
1992AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1993
1994AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1995
1996AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1997
niklase@google.com470e71d2011-07-07 08:21:25 +00001998} // namespace webrtc