blob: 061495d9a2c983dd9e8286e4639e2b44fae57067 [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"
pbos@webrtc.org788acd12014-12-15 09:41:24 +000023#include "webrtc/modules/audio_processing/agc/agc_manager_direct.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000024#include "webrtc/modules/audio_processing/audio_buffer.h"
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +000025#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000026#include "webrtc/modules/audio_processing/common.h"
andrew@webrtc.org56e4a052014-02-27 22:23:17 +000027#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000028#include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
peahbe615622016-02-13 16:40:47 -080029#include "webrtc/modules/audio_processing/gain_control_for_experimental_agc.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000030#include "webrtc/modules/audio_processing/gain_control_impl.h"
peah1bcfce52016-08-26 07:16:04 -070031#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -070032#include "webrtc/modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070033#endif
peahca4cac72016-06-29 15:26:12 -070034#include "webrtc/modules/audio_processing/level_controller/level_controller.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000035#include "webrtc/modules/audio_processing/level_estimator_impl.h"
peah8271d042016-11-22 07:24:52 -080036#include "webrtc/modules/audio_processing/low_cut_filter.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000037#include "webrtc/modules/audio_processing/noise_suppression_impl.h"
ivoc9f4a4a02016-10-28 05:39:16 -070038#include "webrtc/modules/audio_processing/residual_echo_detector.h"
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +000039#include "webrtc/modules/audio_processing/transient/transient_suppressor.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000040#include "webrtc/modules/audio_processing/voice_detection_impl.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010041#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010042#include "webrtc/system_wrappers/include/file_wrapper.h"
43#include "webrtc/system_wrappers/include/logging.h"
44#include "webrtc/system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000045
46#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
47// Files generated at build-time by the protobuf compiler.
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000048#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000049#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000050#else
kjellander78ddd732016-02-09 08:13:06 -080051#include "webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000052#endif
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000053#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +000054
peah1bcfce52016-08-26 07:16:04 -070055// Check to verify that the define for the intelligibility enhancer is properly
56// set.
57#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
58 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
59 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
60#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
61#endif
62
Michael Graczyk86c6d332015-07-23 11:41:39 -070063#define RETURN_ON_ERR(expr) \
64 do { \
65 int err = (expr); \
66 if (err != kNoError) { \
67 return err; \
68 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000069 } while (0)
70
niklase@google.com470e71d2011-07-07 08:21:25 +000071namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070072
kwibergd59d3bb2016-09-13 07:49:33 -070073constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070074
Michael Graczyk86c6d332015-07-23 11:41:39 -070075namespace {
76
77static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
78 switch (layout) {
79 case AudioProcessing::kMono:
80 case AudioProcessing::kStereo:
81 return false;
82 case AudioProcessing::kMonoAndKeyboard:
83 case AudioProcessing::kStereoAndKeyboard:
84 return true;
85 }
86
kwiberg9e2be5f2016-09-14 05:23:22 -070087 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070088 return false;
89}
aluebsdf6416a2016-03-16 18:26:35 -070090
peah2ace3f92016-09-10 04:42:27 -070091bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070092 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
93 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
94}
95
peah2ace3f92016-09-10 04:42:27 -070096int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
97#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070098 constexpr int kMaxSplittingNativeProcessRate =
99 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -0700100#else
kwibergd59d3bb2016-09-13 07:49:33 -0700101 constexpr int kMaxSplittingNativeProcessRate =
102 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700103#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700104 static_assert(
105 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
106 "");
peah2ace3f92016-09-10 04:42:27 -0700107 const int uppermost_native_rate = band_splitting_required
108 ? kMaxSplittingNativeProcessRate
109 : AudioProcessing::kSampleRate48kHz;
110
111 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
112 if (rate >= uppermost_native_rate) {
113 return uppermost_native_rate;
114 }
115 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700116 return rate;
117 }
118 }
peah2ace3f92016-09-10 04:42:27 -0700119 RTC_NOTREACHED();
120 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700121}
122
peah764e3642016-10-22 05:04:30 -0700123// Maximum length that a frame of samples can have.
124static const size_t kMaxAllowedValuesOfSamplesPerFrame = 160;
125// Maximum number of frames to buffer in the render queue.
126// TODO(peah): Decrease this once we properly handle hugely unbalanced
127// reverse and forward call numbers.
128static const size_t kMaxNumFramesToBuffer = 100;
129
peah8271d042016-11-22 07:24:52 -0800130class HighPassFilterImpl : public HighPassFilter {
131 public:
132 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
133 ~HighPassFilterImpl() override = default;
134
135 // HighPassFilter implementation.
136 int Enable(bool enable) override {
137 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
138 config->high_pass_filter.enabled = enable;
139 });
140
141 return AudioProcessing::kNoError;
142 }
143
144 bool is_enabled() const override {
145 return apm_->GetConfig().high_pass_filter.enabled;
146 }
147
148 private:
149 AudioProcessingImpl* apm_;
150 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
151};
152
Michael Graczyk86c6d332015-07-23 11:41:39 -0700153} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000154
155// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000156static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000157
peah2ace3f92016-09-10 04:42:27 -0700158AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates() {}
159
160bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800161 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700162 bool echo_canceller_enabled,
163 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700164 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700165 bool noise_suppressor_enabled,
166 bool intelligibility_enhancer_enabled,
167 bool beamformer_enabled,
168 bool adaptive_gain_controller_enabled,
169 bool level_controller_enabled,
170 bool voice_activity_detector_enabled,
171 bool level_estimator_enabled,
172 bool transient_suppressor_enabled) {
173 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800174 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700175 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
176 changed |=
177 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700178 changed |=
179 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700180 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
181 changed |=
182 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
183 changed |= (beamformer_enabled != beamformer_enabled_);
184 changed |=
185 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
186 changed |= (level_controller_enabled != level_controller_enabled_);
187 changed |= (level_estimator_enabled != level_estimator_enabled_);
188 changed |=
189 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
190 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
191 if (changed) {
peah8271d042016-11-22 07:24:52 -0800192 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700193 echo_canceller_enabled_ = echo_canceller_enabled;
194 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700195 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700196 noise_suppressor_enabled_ = noise_suppressor_enabled;
197 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
198 beamformer_enabled_ = beamformer_enabled;
199 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
200 level_controller_enabled_ = level_controller_enabled;
201 level_estimator_enabled_ = level_estimator_enabled;
202 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
203 transient_suppressor_enabled_ = transient_suppressor_enabled;
204 }
205
206 changed |= first_update_;
207 first_update_ = false;
208 return changed;
209}
210
211bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
212 const {
213#if WEBRTC_INTELLIGIBILITY_ENHANCER
214 return CaptureMultiBandProcessingActive() ||
ivoc20270be2016-11-15 05:24:35 -0800215 intelligibility_enhancer_enabled_ ||
216 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700217#else
ivoc20270be2016-11-15 05:24:35 -0800218 return CaptureMultiBandProcessingActive() ||
219 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700220#endif
221}
222
223bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
224 const {
peah8271d042016-11-22 07:24:52 -0800225 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700226 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
227 beamformer_enabled_ || adaptive_gain_controller_enabled_;
228}
229
230bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
231 const {
232 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800233 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
234 residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700235}
236
237bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
238 const {
239#if WEBRTC_INTELLIGIBILITY_ENHANCER
240 return intelligibility_enhancer_enabled_;
241#else
242 return false;
243#endif
244}
245
solenberg5e465c32015-12-08 13:22:33 -0800246struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800247 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800248 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800249 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800250 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800251 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800252 std::unique_ptr<LevelEstimatorImpl> level_estimator;
253 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
254 std::unique_ptr<VoiceDetectionImpl> voice_detection;
255 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800256 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800257
258 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800259 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700260#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800261 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700262#endif
solenberg5e465c32015-12-08 13:22:33 -0800263};
264
265struct AudioProcessingImpl::ApmPrivateSubmodules {
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700266 explicit ApmPrivateSubmodules(NonlinearBeamformer* beamformer)
solenberg5e465c32015-12-08 13:22:33 -0800267 : beamformer(beamformer) {}
268 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700269 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800270 std::unique_ptr<AgcManagerDirect> agc_manager;
peah8271d042016-11-22 07:24:52 -0800271 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700272 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700273 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
solenberg5e465c32015-12-08 13:22:33 -0800274};
275
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000276AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700277 webrtc::Config config;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000278 return Create(config, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000279}
280
peah88ac8532016-09-12 16:47:25 -0700281AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000282 return Create(config, nullptr);
283}
284
peah88ac8532016-09-12 16:47:25 -0700285AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700286 NonlinearBeamformer* beamformer) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000287 AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000288 if (apm->Initialize() != kNoError) {
289 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800290 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000291 }
292
293 return apm;
294}
295
peah88ac8532016-09-12 16:47:25 -0700296AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000297 : AudioProcessingImpl(config, nullptr) {}
298
peah88ac8532016-09-12 16:47:25 -0700299AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700300 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800301 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
302 public_submodules_(new ApmPublicSubmodules()),
peahdf3efa82015-11-28 12:35:15 -0800303 private_submodules_(new ApmPrivateSubmodules(beamformer)),
304 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000305#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700306 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000307#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700308 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000309#endif
andrew1c7075f2015-06-24 18:14:14 -0700310#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800311 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700312#else
aluebs2a346882016-01-11 18:04:30 -0800313 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700314#endif
aluebs2a346882016-01-11 18:04:30 -0800315 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800316 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700317 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700318 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800319 {
320 rtc::CritScope cs_render(&crit_render_);
321 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000322
peahb624d8c2016-03-05 03:01:14 -0800323 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700324 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800325 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700326 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800327 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700328 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800329 public_submodules_->level_estimator.reset(
330 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800331 public_submodules_->noise_suppression.reset(
332 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800333 public_submodules_->voice_detection.reset(
334 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800335 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800336 new GainControlForExperimentalAgc(
337 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700338 private_submodules_->residual_echo_detector.reset(
339 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700340
peahc19f3122016-10-07 14:54:10 -0700341 // TODO(peah): Move this creation to happen only when the level controller
342 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700343 private_submodules_->level_controller.reset(new LevelController());
peahdf3efa82015-11-28 12:35:15 -0800344 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000345
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000346 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000347}
348
349AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800350 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800351 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800352 private_submodules_->agc_manager.reset();
353 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800354 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000355
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000356#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700357 debug_dump_.debug_file->CloseFile();
peahdf3efa82015-11-28 12:35:15 -0800358#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000359}
360
niklase@google.com470e71d2011-07-07 08:21:25 +0000361int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800362 // Run in a single-threaded manner during initialization.
363 rtc::CritScope cs_render(&crit_render_);
364 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000365 return InitializeLocked();
366}
367
peahde65ddc2016-09-16 15:02:15 -0700368int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
369 int capture_output_sample_rate_hz,
370 int render_input_sample_rate_hz,
371 ChannelLayout capture_input_layout,
372 ChannelLayout capture_output_layout,
373 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700374 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700375 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
376 LayoutHasKeyboard(capture_input_layout)},
377 {capture_output_sample_rate_hz,
378 ChannelsFromLayout(capture_output_layout),
379 LayoutHasKeyboard(capture_output_layout)},
380 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
381 LayoutHasKeyboard(render_input_layout)},
382 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
383 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700384
385 return Initialize(processing_config);
386}
387
388int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800389 // Run in a single-threaded manner during initialization.
390 rtc::CritScope cs_render(&crit_render_);
391 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700392 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000393}
394
peahdf3efa82015-11-28 12:35:15 -0800395int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800396 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700397 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800398}
399
peahdf3efa82015-11-28 12:35:15 -0800400int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700401 const ProcessingConfig& processing_config,
402 bool force_initialization) {
403 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800404}
405
kwiberg83ffe452016-08-29 14:46:07 -0700406#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
407
408AudioProcessingImpl::ApmDebugDumpThreadState::ApmDebugDumpThreadState()
409 : event_msg(new audioproc::Event()) {}
410
411AudioProcessingImpl::ApmDebugDumpThreadState::~ApmDebugDumpThreadState() {}
412
413AudioProcessingImpl::ApmDebugDumpState::ApmDebugDumpState()
414 : debug_file(FileWrapper::Create()) {}
415
416AudioProcessingImpl::ApmDebugDumpState::~ApmDebugDumpState() {}
417
418#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
419
peah192164e2015-11-17 02:16:45 -0800420// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800421// their current values (needs to be called while holding the crit_render_lock).
422int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700423 const ProcessingConfig& processing_config,
424 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800425 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700426 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800427 return kNoError;
428 }
peahdf3efa82015-11-28 12:35:15 -0800429
430 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800431 return InitializeLocked(processing_config);
432}
433
niklase@google.com470e71d2011-07-07 08:21:25 +0000434int AudioProcessingImpl::InitializeLocked() {
peahde65ddc2016-09-16 15:02:15 -0700435 const int capture_audiobuffer_num_channels =
aluebsb2328d12016-01-11 20:32:29 -0800436 capture_nonlocked_.beamformer_enabled
peahdf3efa82015-11-28 12:35:15 -0800437 ? formats_.api_format.input_stream().num_channels()
438 : formats_.api_format.output_stream().num_channels();
peahde65ddc2016-09-16 15:02:15 -0700439 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800440 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700441 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800442 : formats_.api_format.reverse_output_stream().num_frames();
443 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
444 render_.render_audio.reset(new AudioBuffer(
445 formats_.api_format.reverse_input_stream().num_frames(),
446 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700447 formats_.render_processing_format.num_frames(),
448 formats_.render_processing_format.num_channels(),
449 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700450 if (formats_.api_format.reverse_input_stream() !=
451 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800452 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800453 formats_.api_format.reverse_input_stream().num_channels(),
454 formats_.api_format.reverse_input_stream().num_frames(),
455 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800456 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700457 } else {
peahdf3efa82015-11-28 12:35:15 -0800458 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700459 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700460 } else {
peahdf3efa82015-11-28 12:35:15 -0800461 render_.render_audio.reset(nullptr);
462 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700463 }
peahdf3efa82015-11-28 12:35:15 -0800464 capture_.capture_audio.reset(
465 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
466 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700467 capture_nonlocked_.capture_processing_format.num_frames(),
468 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800469 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000470
peahde65ddc2016-09-16 15:02:15 -0700471 public_submodules_->echo_cancellation->Initialize(
472 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
473 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700474 AllocateRenderQueue();
475
ivoc3e9a5372016-10-28 07:55:33 -0700476 int success = public_submodules_->echo_cancellation->enable_metrics(true);
477 RTC_DCHECK_EQ(0, success);
478 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
479 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700480 public_submodules_->echo_control_mobile->Initialize(
481 proc_split_sample_rate_hz(), num_reverse_channels(),
482 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700483
484 public_submodules_->gain_control->Initialize(num_proc_channels(),
485 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700486 if (constants_.use_experimental_agc) {
487 if (!private_submodules_->agc_manager.get()) {
488 private_submodules_->agc_manager.reset(new AgcManagerDirect(
489 public_submodules_->gain_control.get(),
490 public_submodules_->gain_control_for_experimental_agc.get(),
491 constants_.agc_startup_min_volume));
492 }
493 private_submodules_->agc_manager->Initialize();
494 private_submodules_->agc_manager->SetCaptureMuted(
495 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700496 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700497 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200498 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000499 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700500#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700501 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700502#endif
peah8271d042016-11-22 07:24:52 -0800503 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700504 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
505 proc_sample_rate_hz());
506 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
507 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700508 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700509 InitializeResidualEchoDetector();
solenberg70f99032015-12-08 11:07:32 -0800510
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000511#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700512 if (debug_dump_.debug_file->is_open()) {
ajm@google.com808e0e02011-08-03 21:08:51 +0000513 int err = WriteInitMessage();
514 if (err != kNoError) {
515 return err;
516 }
517 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000518#endif
ajm@google.com808e0e02011-08-03 21:08:51 +0000519
niklase@google.com470e71d2011-07-07 08:21:25 +0000520 return kNoError;
521}
522
Michael Graczyk86c6d332015-07-23 11:41:39 -0700523int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
524 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700525 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
526 return kBadSampleRateError;
527 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000528 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700529
Peter Kasting69558702016-01-12 16:26:35 -0800530 const size_t num_in_channels = config.input_stream().num_channels();
531 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700532
533 // Need at least one input channel.
534 // Need either one output channel or as many outputs as there are inputs.
535 if (num_in_channels == 0 ||
536 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700537 return kBadNumberChannelsError;
538 }
539
aluebsb2328d12016-01-11 20:32:29 -0800540 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800541 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700542 return kBadNumberChannelsError;
543 }
544
peahdf3efa82015-11-28 12:35:15 -0800545 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000546
peahde65ddc2016-09-16 15:02:15 -0700547 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700548 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700549 formats_.api_format.output_stream().sample_rate_hz()),
550 submodule_states_.CaptureMultiBandSubModulesActive() ||
551 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000552
peahde65ddc2016-09-16 15:02:15 -0700553 capture_nonlocked_.capture_processing_format =
554 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700555
peahde65ddc2016-09-16 15:02:15 -0700556 int render_processing_rate = FindNativeProcessRateToUse(
peah2ace3f92016-09-10 04:42:27 -0700557 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
558 formats_.api_format.reverse_output_stream().sample_rate_hz()),
559 submodule_states_.CaptureMultiBandSubModulesActive() ||
560 submodule_states_.RenderMultiBandSubModulesActive());
aluebseb3603b2016-04-20 15:27:58 -0700561 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
562 // splitting filter degrades the AEC performance.
peahde65ddc2016-09-16 15:02:15 -0700563 if (render_processing_rate > kSampleRate32kHz) {
564 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
565 ? kSampleRate32kHz
566 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700567 }
peahde65ddc2016-09-16 15:02:15 -0700568 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700569 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700570 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
571 kSampleRate8kHz) {
572 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000573 } else {
peahde65ddc2016-09-16 15:02:15 -0700574 render_processing_rate =
575 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000576 }
577
peahde65ddc2016-09-16 15:02:15 -0700578 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000579 // demonstrated to work well for AEC in most practical scenarios.
peahde65ddc2016-09-16 15:02:15 -0700580 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000581
peahde65ddc2016-09-16 15:02:15 -0700582 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
583 kSampleRate32kHz ||
584 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
585 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800586 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000587 } else {
peahdf3efa82015-11-28 12:35:15 -0800588 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700589 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000590 }
591
592 return InitializeLocked();
593}
594
peah88ac8532016-09-12 16:47:25 -0700595void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700596 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700597
peahc19f3122016-10-07 14:54:10 -0700598 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700599 if (!config_ok) {
600 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
601 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700602 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700603 << std::endl
604 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700605 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700606 }
607
608 // Run in a single-threaded manner when applying the settings.
609 rtc::CritScope cs_render(&crit_render_);
610 rtc::CritScope cs_capture(&crit_capture_);
611
peahc19f3122016-10-07 14:54:10 -0700612 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
613 // with the value in config_ everywhere in the code.
614 if (capture_nonlocked_.level_controller_enabled !=
615 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700616 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700617 config_.level_controller.enabled;
618 // TODO(peah): Remove the conditional initialization to always initialize
619 // the level controller regardless of whether it is enabled or not.
620 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700621 }
peahc19f3122016-10-07 14:54:10 -0700622 LOG(LS_INFO) << "Level controller activated: "
623 << capture_nonlocked_.level_controller_enabled;
624
625 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800626
627 InitializeLowCutFilter();
628
629 LOG(LS_INFO) << "Highpass filter activated: "
630 << config_.high_pass_filter.enabled;
peah88ac8532016-09-12 16:47:25 -0700631}
632
633void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800634 // Run in a single-threaded manner when setting the extra options.
635 rtc::CritScope cs_render(&crit_render_);
636 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000637
peahb624d8c2016-03-05 03:01:14 -0800638 public_submodules_->echo_cancellation->SetExtraOptions(config);
639
peahdf3efa82015-11-28 12:35:15 -0800640 if (capture_.transient_suppressor_enabled !=
641 config.Get<ExperimentalNs>().enabled) {
642 capture_.transient_suppressor_enabled =
643 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000644 InitializeTransient();
645 }
aluebs2a346882016-01-11 18:04:30 -0800646
peah1bcfce52016-08-26 07:16:04 -0700647#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700648 if(capture_nonlocked_.intelligibility_enabled !=
649 config.Get<Intelligibility>().enabled) {
650 capture_nonlocked_.intelligibility_enabled =
651 config.Get<Intelligibility>().enabled;
652 InitializeIntelligibility();
653 }
peah1bcfce52016-08-26 07:16:04 -0700654#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700655
aluebs2a346882016-01-11 18:04:30 -0800656#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800657 if (capture_nonlocked_.beamformer_enabled !=
658 config.Get<Beamforming>().enabled) {
659 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800660 if (config.Get<Beamforming>().array_geometry.size() > 1) {
661 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
662 }
663 capture_.target_direction = config.Get<Beamforming>().target_direction;
664 InitializeBeamformer();
665 }
666#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000667}
668
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000669int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800670 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700671 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000672}
673
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000674int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800675 // Used as callback from submodules, hence locking is not allowed.
676 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000677}
678
Peter Kasting69558702016-01-12 16:26:35 -0800679size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800680 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700681 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000682}
683
Peter Kasting69558702016-01-12 16:26:35 -0800684size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800685 // Used as callback from submodules, hence locking is not allowed.
686 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000687}
688
Peter Kasting69558702016-01-12 16:26:35 -0800689size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800690 // Used as callback from submodules, hence locking is not allowed.
691 return capture_nonlocked_.beamformer_enabled ? 1 : num_output_channels();
692}
693
Peter Kasting69558702016-01-12 16:26:35 -0800694size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800695 // Used as callback from submodules, hence locking is not allowed.
696 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000697}
698
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000699void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800700 rtc::CritScope cs(&crit_capture_);
701 capture_.output_will_be_muted = muted;
702 if (private_submodules_->agc_manager.get()) {
703 private_submodules_->agc_manager->SetCaptureMuted(
704 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000705 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000706}
707
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000708
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000709int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700710 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000711 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000712 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000713 int output_sample_rate_hz,
714 ChannelLayout output_layout,
715 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800716 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800717 StreamConfig input_stream;
718 StreamConfig output_stream;
719 {
720 // Access the formats_.api_format.input_stream beneath the capture lock.
721 // The lock must be released as it is later required in the call
722 // to ProcessStream(,,,);
723 rtc::CritScope cs(&crit_capture_);
724 input_stream = formats_.api_format.input_stream();
725 output_stream = formats_.api_format.output_stream();
726 }
727
Michael Graczyk86c6d332015-07-23 11:41:39 -0700728 input_stream.set_sample_rate_hz(input_sample_rate_hz);
729 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
730 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700731 output_stream.set_sample_rate_hz(output_sample_rate_hz);
732 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
733 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
734
735 if (samples_per_channel != input_stream.num_frames()) {
736 return kBadDataLengthError;
737 }
738 return ProcessStream(src, input_stream, output_stream, dest);
739}
740
741int AudioProcessingImpl::ProcessStream(const float* const* src,
742 const StreamConfig& input_config,
743 const StreamConfig& output_config,
744 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800745 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800746 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700747 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800748 {
749 // Acquire the capture lock in order to safely call the function
750 // that retrieves the render side data. This function accesses apm
751 // getters that need the capture lock held when being called.
752 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700753 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800754
755 if (!src || !dest) {
756 return kNullPointerError;
757 }
758
759 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700760 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000761 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000762
Michael Graczyk86c6d332015-07-23 11:41:39 -0700763 processing_config.input_stream() = input_config;
764 processing_config.output_stream() = output_config;
765
peahdf3efa82015-11-28 12:35:15 -0800766 {
767 // Do conditional reinitialization.
768 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700769 RETURN_ON_ERR(
770 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800771 }
772 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700773 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
774 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000775
776#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700777 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200778 RETURN_ON_ERR(WriteConfigMessage(false));
779
peahdf3efa82015-11-28 12:35:15 -0800780 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
781 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000782 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800783 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800784 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
785 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000786 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000787 }
788#endif
789
peahdf3efa82015-11-28 12:35:15 -0800790 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700791 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800792 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000793
794#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700795 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800796 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000797 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800798 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800799 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
800 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000801 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800802 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800803 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800804 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000805 }
806#endif
807
808 return kNoError;
809}
810
peah701d6282016-10-25 05:42:20 -0700811void AudioProcessingImpl::QueueRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700812 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
813 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700814 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700815
kwibergaf476c72016-11-28 15:21:39 -0800816 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700817
818 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700819 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700820 // The data queue is full and needs to be emptied.
821 EmptyQueuedRenderAudio();
822
823 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700824 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700825 RTC_DCHECK(result);
826 }
827
828 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
829 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700830 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700831
832 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700833 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700834 // The data queue is full and needs to be emptied.
835 EmptyQueuedRenderAudio();
836
837 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700838 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700839 RTC_DCHECK(result);
840 }
peah701d6282016-10-25 05:42:20 -0700841
842 if (!constants_.use_experimental_agc) {
843 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
844 // Insert the samples into the queue.
845 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
846 // The data queue is full and needs to be emptied.
847 EmptyQueuedRenderAudio();
848
849 // Retry the insert (should always work).
850 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
851 RTC_DCHECK(result);
852 }
853 }
ivoc9f4a4a02016-10-28 05:39:16 -0700854
855 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
856
857 // Insert the samples into the queue.
858 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
859 // The data queue is full and needs to be emptied.
860 EmptyQueuedRenderAudio();
861
862 // Retry the insert (should always work).
863 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
864 RTC_DCHECK(result);
865 }
peah764e3642016-10-22 05:04:30 -0700866}
867
868void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700869 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700870 std::max(static_cast<size_t>(1),
871 kMaxAllowedValuesOfSamplesPerFrame *
872 EchoCancellationImpl::NumCancellersRequired(
873 num_output_channels(), num_reverse_channels()));
874
peah701d6282016-10-25 05:42:20 -0700875 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700876 std::max(static_cast<size_t>(1),
877 kMaxAllowedValuesOfSamplesPerFrame *
878 EchoControlMobileImpl::NumCancellersRequired(
879 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700880
peah701d6282016-10-25 05:42:20 -0700881 const size_t new_agc_render_queue_element_max_size =
882 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
883
ivoc9f4a4a02016-10-28 05:39:16 -0700884 const size_t new_red_render_queue_element_max_size =
885 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
886
peaha0624602016-10-25 04:45:24 -0700887 // Reallocate the queues if the queue item sizes are too small to fit the
888 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700889 if (aec_render_queue_element_max_size_ <
890 new_aec_render_queue_element_max_size) {
891 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700892
peaha0624602016-10-25 04:45:24 -0700893 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700894 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700895
peah701d6282016-10-25 05:42:20 -0700896 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700897 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
898 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700899 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700900 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700901
peah701d6282016-10-25 05:42:20 -0700902 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
903 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700904 } else {
peah701d6282016-10-25 05:42:20 -0700905 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700906 }
907
peah701d6282016-10-25 05:42:20 -0700908 if (aecm_render_queue_element_max_size_ <
909 new_aecm_render_queue_element_max_size) {
910 aecm_render_queue_element_max_size_ =
911 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700912
913 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700914 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700915
peah701d6282016-10-25 05:42:20 -0700916 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700917 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
918 kMaxNumFramesToBuffer, template_queue_element,
919 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700920 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700921
peah701d6282016-10-25 05:42:20 -0700922 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
923 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700924 } else {
peah701d6282016-10-25 05:42:20 -0700925 aecm_render_signal_queue_->Clear();
926 }
927
928 if (agc_render_queue_element_max_size_ <
929 new_agc_render_queue_element_max_size) {
930 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
931
932 std::vector<int16_t> template_queue_element(
933 agc_render_queue_element_max_size_);
934
935 agc_render_signal_queue_.reset(
936 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
937 kMaxNumFramesToBuffer, template_queue_element,
938 RenderQueueItemVerifier<int16_t>(
939 agc_render_queue_element_max_size_)));
940
941 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
942 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
943 } else {
944 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700945 }
ivoc9f4a4a02016-10-28 05:39:16 -0700946
947 if (red_render_queue_element_max_size_ <
948 new_red_render_queue_element_max_size) {
949 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
950
951 std::vector<float> template_queue_element(
952 red_render_queue_element_max_size_);
953
954 red_render_signal_queue_.reset(
955 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
956 kMaxNumFramesToBuffer, template_queue_element,
957 RenderQueueItemVerifier<float>(
958 red_render_queue_element_max_size_)));
959
960 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
961 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
962 } else {
963 red_render_signal_queue_->Clear();
964 }
peah764e3642016-10-22 05:04:30 -0700965}
966
967void AudioProcessingImpl::EmptyQueuedRenderAudio() {
968 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -0700969 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700970 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -0700971 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700972 }
973
peah701d6282016-10-25 05:42:20 -0700974 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700975 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -0700976 aecm_capture_queue_buffer_);
977 }
978
979 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
980 public_submodules_->gain_control->ProcessRenderAudio(
981 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700982 }
ivoc9f4a4a02016-10-28 05:39:16 -0700983
984 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
985 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
986 red_capture_queue_buffer_);
987 }
peah764e3642016-10-22 05:04:30 -0700988}
989
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000990int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -0800991 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -0800992 {
993 // Acquire the capture lock in order to safely call the function
994 // that retrieves the render side data. This function accesses apm
995 // getters that need the capture lock held when being called.
996 // The lock needs to be released as
997 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
998 // as well.
999 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001000 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001001 }
peahfa6228e2015-11-16 16:27:42 -08001002
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001003 if (!frame) {
1004 return kNullPointerError;
1005 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001006 // Must be a native rate.
1007 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1008 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001009 frame->sample_rate_hz_ != kSampleRate32kHz &&
1010 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001011 return kBadSampleRateError;
1012 }
peah192164e2015-11-17 02:16:45 -08001013
peahdf3efa82015-11-28 12:35:15 -08001014 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001015 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001016 {
1017 // Aquire lock for the access of api_format.
1018 // The lock is released immediately due to the conditional
1019 // reinitialization.
1020 rtc::CritScope cs_capture(&crit_capture_);
1021 // TODO(ajm): The input and output rates and channels are currently
1022 // constrained to be identical in the int16 interface.
1023 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001024
1025 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001026 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001027 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1028 processing_config.input_stream().set_num_channels(frame->num_channels_);
1029 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1030 processing_config.output_stream().set_num_channels(frame->num_channels_);
1031
peahdf3efa82015-11-28 12:35:15 -08001032 {
1033 // Do conditional reinitialization.
1034 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001035 RETURN_ON_ERR(
1036 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001037 }
1038 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001039 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001040 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001041 return kBadDataLengthError;
1042 }
1043
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001044#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001045 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001046 RETURN_ON_ERR(WriteConfigMessage(false));
1047
peahdf3efa82015-11-28 12:35:15 -08001048 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1049 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001050 const size_t data_size =
1051 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001052 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001053 }
1054#endif
1055
peahdf3efa82015-11-28 12:35:15 -08001056 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001057 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001058 capture_.capture_audio->InterleaveTo(
1059 frame, submodule_states_.CaptureMultiBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001060
1061#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001062 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001063 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001064 const size_t data_size =
1065 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001066 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001067 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001068 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001069 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001070 }
1071#endif
1072
1073 return kNoError;
1074}
1075
peahde65ddc2016-09-16 15:02:15 -07001076int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001077 // Ensure that not both the AEC and AECM are active at the same time.
1078 // TODO(peah): Simplify once the public API Enable functions for these
1079 // are moved to APM.
1080 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1081 public_submodules_->echo_control_mobile->is_enabled()));
1082
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001083#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001084 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001085 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1086 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1087 msg->set_drift(
1088 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001089 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001090 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001091 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001092#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001093
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001094 MaybeUpdateHistograms();
1095
peahde65ddc2016-09-16 15:02:15 -07001096 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001097
peahbe615622016-02-13 16:40:47 -08001098 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001099 public_submodules_->gain_control->is_enabled()) {
1100 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001101 capture_buffer->channels()[0], capture_buffer->num_channels(),
1102 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001103 }
1104
peah2ace3f92016-09-10 04:42:27 -07001105 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1106 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001107 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1108 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001109 }
1110
aluebsb2328d12016-01-11 20:32:29 -08001111 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001112 private_submodules_->beamformer->AnalyzeChunk(
1113 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001114 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001115 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001116 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001117
peah8271d042016-11-22 07:24:52 -08001118 if (private_submodules_->low_cut_filter) {
1119 private_submodules_->low_cut_filter->Process(capture_buffer);
1120 }
peahde65ddc2016-09-16 15:02:15 -07001121 RETURN_ON_ERR(
1122 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1123 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001124
1125 // Ensure that the stream delay was set before the call to the
1126 // AEC ProcessCaptureAudio function.
1127 if (public_submodules_->echo_cancellation->is_enabled() &&
1128 !was_stream_delay_set()) {
1129 return AudioProcessing::kStreamParameterNotSetError;
1130 }
1131
1132 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001133 capture_buffer, stream_delay_ms()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001134
peahdf3efa82015-11-28 12:35:15 -08001135 if (public_submodules_->echo_control_mobile->is_enabled() &&
1136 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001137 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001138 }
peahde65ddc2016-09-16 15:02:15 -07001139 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001140#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001141 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001142 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001143 int gain_db = public_submodules_->gain_control->is_enabled() ?
1144 public_submodules_->gain_control->compression_gain_db() :
1145 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001146 float gain = std::pow(10.f, gain_db / 20.f);
1147 gain *= capture_nonlocked_.level_controller_enabled ?
1148 private_submodules_->level_controller->GetLastGain() :
1149 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001150 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001151 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001152 }
peah1bcfce52016-08-26 07:16:04 -07001153#endif
peah253534d2016-03-15 04:32:28 -07001154
1155 // Ensure that the stream delay was set before the call to the
1156 // AECM ProcessCaptureAudio function.
1157 if (public_submodules_->echo_control_mobile->is_enabled() &&
1158 !was_stream_delay_set()) {
1159 return AudioProcessing::kStreamParameterNotSetError;
1160 }
1161
1162 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001163 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001164
ivoc9f4a4a02016-10-28 05:39:16 -07001165 if (config_.residual_echo_detector.enabled) {
1166 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1167 rtc::ArrayView<const float>(
1168 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1169 capture_buffer->num_frames_per_band()));
1170 }
1171
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001172 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001173 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001174 }
1175
peahde65ddc2016-09-16 15:02:15 -07001176 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001177
peahbe615622016-02-13 16:40:47 -08001178 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001179 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001180 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001181 private_submodules_->beamformer->is_target_present())) {
1182 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001183 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1184 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001185 }
peahb8fbb542016-03-15 02:28:08 -07001186 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001187 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001188
peah2ace3f92016-09-10 04:42:27 -07001189 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1190 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001191 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1192 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001193 }
1194
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001195 // TODO(aluebs): Investigate if the transient suppression placement should be
1196 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001197 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001198 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001199 private_submodules_->agc_manager.get()
1200 ? private_submodules_->agc_manager->voice_probability()
1201 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001202
peahdf3efa82015-11-28 12:35:15 -08001203 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001204 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1205 capture_buffer->num_channels(),
1206 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1207 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1208 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001209 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001210 }
1211
peahca4cac72016-06-29 15:26:12 -07001212 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001213 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001214 }
1215
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001216 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001217 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001218
peahdf3efa82015-11-28 12:35:15 -08001219 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001220 return kNoError;
1221}
1222
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001223int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001224 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001225 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001226 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001227 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001228 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001229 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001230 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001231 };
1232 if (samples_per_channel != reverse_config.num_frames()) {
1233 return kBadDataLengthError;
1234 }
peahdf3efa82015-11-28 12:35:15 -08001235 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001236}
1237
peahde65ddc2016-09-16 15:02:15 -07001238int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1239 const StreamConfig& input_config,
1240 const StreamConfig& output_config,
1241 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001242 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001243 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001244 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001245 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001246 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1247 dest);
peah2ace3f92016-09-10 04:42:27 -07001248 } else if (formats_.api_format.reverse_input_stream() !=
1249 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001250 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1251 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001252 } else {
peahde65ddc2016-09-16 15:02:15 -07001253 CopyAudioIfNeeded(src, input_config.num_frames(),
1254 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001255 }
1256
1257 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001258}
1259
peahdf3efa82015-11-28 12:35:15 -08001260int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001261 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001262 const StreamConfig& input_config,
1263 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001264 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001265 return kNullPointerError;
1266 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001267
peahde65ddc2016-09-16 15:02:15 -07001268 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001269 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001270 }
1271
peahdf3efa82015-11-28 12:35:15 -08001272 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001273 processing_config.reverse_input_stream() = input_config;
1274 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001275
peahdf3efa82015-11-28 12:35:15 -08001276 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001277 assert(input_config.num_frames() ==
1278 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001279
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001280#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001281 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001282 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1283 audioproc::ReverseStream* msg =
1284 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001285 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001286 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001287 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001288 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001289 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001290 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001291 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001292 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001293 }
1294#endif
1295
peahdf3efa82015-11-28 12:35:15 -08001296 render_.render_audio->CopyFrom(src,
1297 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001298 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001299}
1300
1301int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001302 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001303 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001304 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001305 return kNullPointerError;
1306 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001307 // Must be a native rate.
1308 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1309 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001310 frame->sample_rate_hz_ != kSampleRate32kHz &&
1311 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001312 return kBadSampleRateError;
1313 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001314
Michael Graczyk86c6d332015-07-23 11:41:39 -07001315 if (frame->num_channels_ <= 0) {
1316 return kBadNumberChannelsError;
1317 }
1318
peahdf3efa82015-11-28 12:35:15 -08001319 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001320 processing_config.reverse_input_stream().set_sample_rate_hz(
1321 frame->sample_rate_hz_);
1322 processing_config.reverse_input_stream().set_num_channels(
1323 frame->num_channels_);
1324 processing_config.reverse_output_stream().set_sample_rate_hz(
1325 frame->sample_rate_hz_);
1326 processing_config.reverse_output_stream().set_num_channels(
1327 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001328
peahdf3efa82015-11-28 12:35:15 -08001329 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001330 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001331 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001332 return kBadDataLengthError;
1333 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001334
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001335#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001336 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001337 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1338 audioproc::ReverseStream* msg =
1339 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001340 const size_t data_size =
1341 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001342 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001343 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001344 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001345 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001346 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001347#endif
peahdf3efa82015-11-28 12:35:15 -08001348 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001349 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001350 render_.render_audio->InterleaveTo(
1351 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001352 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001353}
niklase@google.com470e71d2011-07-07 08:21:25 +00001354
peahde65ddc2016-09-16 15:02:15 -07001355int AudioProcessingImpl::ProcessRenderStreamLocked() {
1356 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah2ace3f92016-09-10 04:42:27 -07001357 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001358 SampleRateSupportsMultiBand(
1359 formats_.render_processing_format.sample_rate_hz())) {
1360 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001361 }
1362
peah1bcfce52016-08-26 07:16:04 -07001363#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001364 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001365 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001366 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001367 }
peah1bcfce52016-08-26 07:16:04 -07001368#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001369
peah764e3642016-10-22 05:04:30 -07001370 QueueRenderAudio(render_buffer);
niklase@google.com470e71d2011-07-07 08:21:25 +00001371
peah2ace3f92016-09-10 04:42:27 -07001372 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001373 SampleRateSupportsMultiBand(
1374 formats_.render_processing_format.sample_rate_hz())) {
1375 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001376 }
1377
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001378 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001379}
1380
1381int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001382 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001383 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001384 capture_.was_stream_delay_set = true;
1385 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001386
niklase@google.com470e71d2011-07-07 08:21:25 +00001387 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001388 delay = 0;
1389 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001390 }
1391
1392 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1393 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001394 delay = 500;
1395 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001396 }
1397
peahdf3efa82015-11-28 12:35:15 -08001398 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001399 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001400}
1401
1402int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001403 // Used as callback from submodules, hence locking is not allowed.
1404 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001405}
1406
1407bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001408 // Used as callback from submodules, hence locking is not allowed.
1409 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001410}
1411
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001412void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001413 rtc::CritScope cs(&crit_capture_);
1414 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001415}
1416
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001417void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001418 rtc::CritScope cs(&crit_capture_);
1419 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001420}
1421
1422int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001423 rtc::CritScope cs(&crit_capture_);
1424 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001425}
1426
niklase@google.com470e71d2011-07-07 08:21:25 +00001427int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001428 const char filename[AudioProcessing::kMaxFilenameSize],
1429 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001430 // Run in a single-threaded manner.
1431 rtc::CritScope cs_render(&crit_render_);
1432 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001433 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001434
peahdf3efa82015-11-28 12:35:15 -08001435 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001436 return kNullPointerError;
1437 }
1438
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001439#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001440 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001441 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001442 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001443
tommia6219cc2016-06-15 10:30:14 -07001444 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001445 return kFileError;
1446 }
1447
Minyue13b96ba2015-10-03 00:39:14 +02001448 RETURN_ON_ERR(WriteConfigMessage(true));
1449 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001450 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001451#else
1452 return kUnsupportedFunctionError;
1453#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001454}
1455
ivocd66b44d2016-01-15 03:06:36 -08001456int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1457 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001458 // Run in a single-threaded manner.
1459 rtc::CritScope cs_render(&crit_render_);
1460 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001461
peahdf3efa82015-11-28 12:35:15 -08001462 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001463 return kNullPointerError;
1464 }
1465
1466#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001467 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1468
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001469 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001470 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001471
tommia6219cc2016-06-15 10:30:14 -07001472 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001473 return kFileError;
1474 }
1475
Minyue13b96ba2015-10-03 00:39:14 +02001476 RETURN_ON_ERR(WriteConfigMessage(true));
1477 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001478 return kNoError;
1479#else
1480 return kUnsupportedFunctionError;
1481#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1482}
1483
peah73a28ee2016-10-12 03:01:49 -07001484int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1485 return StartDebugRecording(handle, -1);
1486}
1487
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001488int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1489 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001490 // Run in a single-threaded manner.
1491 rtc::CritScope cs_render(&crit_render_);
1492 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001493 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001494 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001495}
1496
niklase@google.com470e71d2011-07-07 08:21:25 +00001497int AudioProcessingImpl::StopDebugRecording() {
peahdf3efa82015-11-28 12:35:15 -08001498 // Run in a single-threaded manner.
1499 rtc::CritScope cs_render(&crit_render_);
1500 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001501
1502#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001503 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001504 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001505 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001506#else
1507 return kUnsupportedFunctionError;
1508#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001509}
1510
ivoc3e9a5372016-10-28 07:55:33 -07001511// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1512AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1513 const {
1514 return AudioProcessingStatistics();
1515}
1516
1517AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1518 const {
1519 AudioProcessingStatistics stats;
1520 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001521 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1522 if (success == Error::kNoError) {
1523 stats.a_nlp.Set(metrics.a_nlp);
1524 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1525 stats.echo_return_loss.Set(metrics.echo_return_loss);
1526 stats.echo_return_loss_enhancement.Set(
1527 metrics.echo_return_loss_enhancement);
1528 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1529 }
ivoc87d1a782016-11-14 07:55:03 -08001530 stats.residual_echo_likelihood =
1531 private_submodules_->residual_echo_detector->echo_likelihood();
ivoc3e9a5372016-10-28 07:55:33 -07001532 public_submodules_->echo_cancellation->GetDelayMetrics(
1533 &stats.delay_median, &stats.delay_standard_deviation,
1534 &stats.fraction_poor_delays);
1535 return stats;
1536}
1537
niklase@google.com470e71d2011-07-07 08:21:25 +00001538EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001539 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001540}
1541
1542EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001543 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001544}
1545
1546GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001547 if (constants_.use_experimental_agc) {
1548 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001549 }
peahbfa97112016-03-10 21:09:04 -08001550 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001551}
1552
1553HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001554 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001555}
1556
1557LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001558 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001559}
1560
1561NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001562 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001563}
1564
1565VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001566 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001567}
1568
peah8271d042016-11-22 07:24:52 -08001569void AudioProcessingImpl::MutateConfig(
1570 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1571 rtc::CritScope cs_render(&crit_render_);
1572 rtc::CritScope cs_capture(&crit_capture_);
1573 mutator(&config_);
1574 ApplyConfig(config_);
1575}
1576
1577AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1578 rtc::CritScope cs_render(&crit_render_);
1579 rtc::CritScope cs_capture(&crit_capture_);
1580 return config_;
1581}
1582
peah2ace3f92016-09-10 04:42:27 -07001583bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1584 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001585 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001586 public_submodules_->echo_cancellation->is_enabled(),
1587 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001588 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001589 public_submodules_->noise_suppression->is_enabled(),
1590 capture_nonlocked_.intelligibility_enabled,
1591 capture_nonlocked_.beamformer_enabled,
1592 public_submodules_->gain_control->is_enabled(),
1593 capture_nonlocked_.level_controller_enabled,
1594 public_submodules_->voice_detection->is_enabled(),
1595 public_submodules_->level_estimator->is_enabled(),
1596 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001597}
1598
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001599
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001600void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001601 if (capture_.transient_suppressor_enabled) {
1602 if (!public_submodules_->transient_suppressor.get()) {
1603 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001604 }
peahdf3efa82015-11-28 12:35:15 -08001605 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001606 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1607 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001608 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001609}
1610
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001611void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001612 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001613 if (!private_submodules_->beamformer) {
1614 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001615 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001616 }
peahdf3efa82015-11-28 12:35:15 -08001617 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1618 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001619 }
1620}
1621
ekmeyerson60d9b332015-08-14 10:35:55 -07001622void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001623#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001624 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001625 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001626 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001627 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001628 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001629 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001630 }
peah1bcfce52016-08-26 07:16:04 -07001631#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001632}
1633
peah8271d042016-11-22 07:24:52 -08001634void AudioProcessingImpl::InitializeLowCutFilter() {
1635 if (config_.high_pass_filter.enabled) {
1636 private_submodules_->low_cut_filter.reset(
1637 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1638 } else {
1639 private_submodules_->low_cut_filter.reset();
1640 }
1641}
1642
peahca4cac72016-06-29 15:26:12 -07001643void AudioProcessingImpl::InitializeLevelController() {
1644 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1645}
1646
ivoc9f4a4a02016-10-28 05:39:16 -07001647void AudioProcessingImpl::InitializeResidualEchoDetector() {
1648 private_submodules_->residual_echo_detector->Initialize();
1649}
1650
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001651void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001652 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001653
1654 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001655 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1656 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001657 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001658 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001659 capture_.stream_delay_jumps = 0;
1660 }
1661 if (capture_.aec_system_delay_jumps == -1 &&
1662 echo_cancellation()->stream_has_echo()) {
1663 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001664 }
1665
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001666 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001667 const int diff_stream_delay_ms =
1668 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1669 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1670 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001671 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1672 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001673 if (capture_.stream_delay_jumps == -1) {
1674 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001675 }
peahdf3efa82015-11-28 12:35:15 -08001676 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001677 }
peahdf3efa82015-11-28 12:35:15 -08001678 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001679
1680 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001681 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001682 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001683 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001684 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001685 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1686 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001687 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001688 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001689 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001690 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001691 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1692 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1693 100);
peahdf3efa82015-11-28 12:35:15 -08001694 if (capture_.aec_system_delay_jumps == -1) {
1695 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001696 }
peahdf3efa82015-11-28 12:35:15 -08001697 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001698 }
peahdf3efa82015-11-28 12:35:15 -08001699 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001700 }
1701}
1702
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001703void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001704 // Run in a single-threaded manner.
1705 rtc::CritScope cs_render(&crit_render_);
1706 rtc::CritScope cs_capture(&crit_capture_);
1707
1708 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001709 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001710 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001711 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001712 }
peahdf3efa82015-11-28 12:35:15 -08001713 capture_.stream_delay_jumps = -1;
1714 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001715
peahdf3efa82015-11-28 12:35:15 -08001716 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001717 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1718 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001719 }
peahdf3efa82015-11-28 12:35:15 -08001720 capture_.aec_system_delay_jumps = -1;
1721 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001722}
1723
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001724#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001725int AudioProcessingImpl::WriteMessageToDebugFile(
1726 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08001727 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08001728 rtc::CriticalSection* crit_debug,
1729 ApmDebugDumpThreadState* debug_state) {
1730 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00001731 if (size <= 0) {
1732 return kUnspecifiedError;
1733 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00001734#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07001735// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
1736// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00001737#endif
1738
peahdf3efa82015-11-28 12:35:15 -08001739 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00001740 return kUnspecifiedError;
1741 }
1742
peahdf3efa82015-11-28 12:35:15 -08001743 {
1744 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08001745 rtc::CritScope cs_debug(crit_debug);
1746
tommia6219cc2016-06-15 10:30:14 -07001747 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08001748 // Update the byte counter.
1749 if (*filesize_limit_bytes >= 0) {
1750 *filesize_limit_bytes -=
1751 (sizeof(int32_t) + debug_state->event_str.length());
1752 if (*filesize_limit_bytes < 0) {
1753 // Not enough bytes are left to write this message, so stop logging.
1754 debug_file->CloseFile();
1755 return kNoError;
1756 }
1757 }
peahdf3efa82015-11-28 12:35:15 -08001758 // Write message preceded by its size.
1759 if (!debug_file->Write(&size, sizeof(int32_t))) {
1760 return kFileError;
1761 }
1762 if (!debug_file->Write(debug_state->event_str.data(),
1763 debug_state->event_str.length())) {
1764 return kFileError;
1765 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001766 }
1767
peahdf3efa82015-11-28 12:35:15 -08001768 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00001769
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001770 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001771}
1772
1773int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08001774 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
1775 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
1776 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00001777
Peter Kasting69558702016-01-12 16:26:35 -08001778 msg->set_num_input_channels(static_cast<google::protobuf::int32>(
1779 formats_.api_format.input_stream().num_channels()));
1780 msg->set_num_output_channels(static_cast<google::protobuf::int32>(
1781 formats_.api_format.output_stream().num_channels()));
1782 msg->set_num_reverse_channels(static_cast<google::protobuf::int32>(
1783 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08001784 msg->set_reverse_sample_rate(
1785 formats_.api_format.reverse_input_stream().sample_rate_hz());
1786 msg->set_output_sample_rate(
1787 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07001788 msg->set_reverse_output_sample_rate(
1789 formats_.api_format.reverse_output_stream().sample_rate_hz());
1790 msg->set_num_reverse_output_channels(
1791 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08001792
1793 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001794 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001795 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02001796 return kNoError;
1797}
1798
1799int AudioProcessingImpl::WriteConfigMessage(bool forced) {
1800 audioproc::Config config;
1801
peahdf3efa82015-11-28 12:35:15 -08001802 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001803 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08001804 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001805 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08001806 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001807 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08001808 public_submodules_->echo_cancellation->is_extended_filter_enabled());
1809 config.set_aec_suppression_level(static_cast<int>(
1810 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02001811
peahdf3efa82015-11-28 12:35:15 -08001812 config.set_aecm_enabled(
1813 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001814 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08001815 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
1816 config.set_aecm_routing_mode(static_cast<int>(
1817 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02001818
peahdf3efa82015-11-28 12:35:15 -08001819 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
1820 config.set_agc_mode(
1821 static_cast<int>(public_submodules_->gain_control->mode()));
1822 config.set_agc_limiter_enabled(
1823 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08001824 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02001825
peah8271d042016-11-22 07:24:52 -08001826 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001827
peahdf3efa82015-11-28 12:35:15 -08001828 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
1829 config.set_ns_level(
1830 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02001831
peahdf3efa82015-11-28 12:35:15 -08001832 config.set_transient_suppression_enabled(
1833 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001834 config.set_intelligibility_enhancer_enabled(
1835 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001836
peah7789fe72016-04-15 01:19:44 -07001837 std::string experiments_description =
1838 public_submodules_->echo_cancellation->GetExperimentsDescription();
1839 // TODO(peah): Add semicolon-separated concatenations of experiment
1840 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07001841 if (capture_nonlocked_.level_controller_enabled) {
1842 experiments_description += "LevelController;";
1843 }
peah7789fe72016-04-15 01:19:44 -07001844 config.set_experiments_description(experiments_description);
1845
Minyue13b96ba2015-10-03 00:39:14 +02001846 std::string serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08001847 if (!forced &&
1848 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02001849 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001850 }
1851
peahdf3efa82015-11-28 12:35:15 -08001852 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02001853
peahdf3efa82015-11-28 12:35:15 -08001854 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
1855 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02001856
peahdf3efa82015-11-28 12:35:15 -08001857 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001858 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001859 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00001860 return kNoError;
1861}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001862#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001863
kwiberg83ffe452016-08-29 14:46:07 -07001864AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1865 bool transient_suppressor_enabled,
1866 const std::vector<Point>& array_geometry,
1867 SphericalPointf target_direction)
1868 : aec_system_delay_jumps(-1),
1869 delay_offset_ms(0),
1870 was_stream_delay_set(false),
1871 last_stream_delay_ms(0),
1872 last_aec_system_delay_ms(0),
1873 stream_delay_jumps(-1),
1874 output_will_be_muted(false),
1875 key_pressed(false),
1876 transient_suppressor_enabled(transient_suppressor_enabled),
1877 array_geometry(array_geometry),
1878 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001879 capture_processing_format(kSampleRate16kHz),
kwiberg83ffe452016-08-29 14:46:07 -07001880 split_rate(kSampleRate16kHz) {}
1881
1882AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1883
1884AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1885
1886AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1887
niklase@google.com470e71d2011-07-07 08:21:25 +00001888} // namespace webrtc