blob: ce71461b2ee41e5bd24016a27237651dcd965eab [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org40654032012-01-30 20:51:15 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000011#include "webrtc/modules/audio_processing/audio_processing_impl.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Michael Graczyk86c6d332015-07-23 11:41:39 -070013#include <algorithm>
niklase@google.com470e71d2011-07-07 08:21:25 +000014
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020015#include "webrtc/base/checks.h"
xians@webrtc.orge46bc772014-10-10 08:36:56 +000016#include "webrtc/base/platform_file.h"
peah369f8282015-12-17 06:42:29 -080017#include "webrtc/base/trace_event.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070018#include "webrtc/common_audio/audio_converter.h"
Michael Graczykdfa36052015-03-25 16:37:27 -070019#include "webrtc/common_audio/channel_buffer.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070020#include "webrtc/common_audio/include/audio_util.h"
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000021#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020022#include "webrtc/modules/audio_processing/aec/aec_core.h"
peahe0eae3c2016-12-14 01:16:23 -080023#include "webrtc/modules/audio_processing/aec3/echo_canceller3.h"
pbos@webrtc.org788acd12014-12-15 09:41:24 +000024#include "webrtc/modules/audio_processing/agc/agc_manager_direct.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000025#include "webrtc/modules/audio_processing/audio_buffer.h"
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +000026#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000027#include "webrtc/modules/audio_processing/common.h"
andrew@webrtc.org56e4a052014-02-27 22:23:17 +000028#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000029#include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
peahbe615622016-02-13 16:40:47 -080030#include "webrtc/modules/audio_processing/gain_control_for_experimental_agc.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000031#include "webrtc/modules/audio_processing/gain_control_impl.h"
peah1bcfce52016-08-26 07:16:04 -070032#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -070033#include "webrtc/modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070034#endif
peahca4cac72016-06-29 15:26:12 -070035#include "webrtc/modules/audio_processing/level_controller/level_controller.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000036#include "webrtc/modules/audio_processing/level_estimator_impl.h"
peah8271d042016-11-22 07:24:52 -080037#include "webrtc/modules/audio_processing/low_cut_filter.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000038#include "webrtc/modules/audio_processing/noise_suppression_impl.h"
ivoc9f4a4a02016-10-28 05:39:16 -070039#include "webrtc/modules/audio_processing/residual_echo_detector.h"
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +000040#include "webrtc/modules/audio_processing/transient/transient_suppressor.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000041#include "webrtc/modules/audio_processing/voice_detection_impl.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010042#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/file_wrapper.h"
44#include "webrtc/system_wrappers/include/logging.h"
45#include "webrtc/system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000046
47#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
48// Files generated at build-time by the protobuf compiler.
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000049#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000050#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000051#else
kjellander78ddd732016-02-09 08:13:06 -080052#include "webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000053#endif
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000054#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +000055
peah1bcfce52016-08-26 07:16:04 -070056// Check to verify that the define for the intelligibility enhancer is properly
57// set.
58#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
59 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
60 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
61#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
62#endif
63
Michael Graczyk86c6d332015-07-23 11:41:39 -070064#define RETURN_ON_ERR(expr) \
65 do { \
66 int err = (expr); \
67 if (err != kNoError) { \
68 return err; \
69 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000070 } while (0)
71
niklase@google.com470e71d2011-07-07 08:21:25 +000072namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070073
kwibergd59d3bb2016-09-13 07:49:33 -070074constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070075
Michael Graczyk86c6d332015-07-23 11:41:39 -070076namespace {
77
78static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
79 switch (layout) {
80 case AudioProcessing::kMono:
81 case AudioProcessing::kStereo:
82 return false;
83 case AudioProcessing::kMonoAndKeyboard:
84 case AudioProcessing::kStereoAndKeyboard:
85 return true;
86 }
87
kwiberg9e2be5f2016-09-14 05:23:22 -070088 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070089 return false;
90}
aluebsdf6416a2016-03-16 18:26:35 -070091
peah2ace3f92016-09-10 04:42:27 -070092bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070093 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
94 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
95}
96
peah2ace3f92016-09-10 04:42:27 -070097int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
98#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -070099 constexpr int kMaxSplittingNativeProcessRate =
100 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -0700101#else
kwibergd59d3bb2016-09-13 07:49:33 -0700102 constexpr int kMaxSplittingNativeProcessRate =
103 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700104#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700105 static_assert(
106 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
107 "");
peah2ace3f92016-09-10 04:42:27 -0700108 const int uppermost_native_rate = band_splitting_required
109 ? kMaxSplittingNativeProcessRate
110 : AudioProcessing::kSampleRate48kHz;
111
112 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
113 if (rate >= uppermost_native_rate) {
114 return uppermost_native_rate;
115 }
116 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700117 return rate;
118 }
119 }
peah2ace3f92016-09-10 04:42:27 -0700120 RTC_NOTREACHED();
121 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700122}
123
peah764e3642016-10-22 05:04:30 -0700124// Maximum length that a frame of samples can have.
125static const size_t kMaxAllowedValuesOfSamplesPerFrame = 160;
126// Maximum number of frames to buffer in the render queue.
127// TODO(peah): Decrease this once we properly handle hugely unbalanced
128// reverse and forward call numbers.
129static const size_t kMaxNumFramesToBuffer = 100;
130
peah8271d042016-11-22 07:24:52 -0800131class HighPassFilterImpl : public HighPassFilter {
132 public:
133 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
134 ~HighPassFilterImpl() override = default;
135
136 // HighPassFilter implementation.
137 int Enable(bool enable) override {
138 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
139 config->high_pass_filter.enabled = enable;
140 });
141
142 return AudioProcessing::kNoError;
143 }
144
145 bool is_enabled() const override {
146 return apm_->GetConfig().high_pass_filter.enabled;
147 }
148
149 private:
150 AudioProcessingImpl* apm_;
151 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
152};
153
Michael Graczyk86c6d332015-07-23 11:41:39 -0700154} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000155
156// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000157static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000158
peah2ace3f92016-09-10 04:42:27 -0700159AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates() {}
160
161bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800162 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700163 bool echo_canceller_enabled,
164 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700165 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700166 bool noise_suppressor_enabled,
167 bool intelligibility_enhancer_enabled,
168 bool beamformer_enabled,
169 bool adaptive_gain_controller_enabled,
170 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800171 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700172 bool voice_activity_detector_enabled,
173 bool level_estimator_enabled,
174 bool transient_suppressor_enabled) {
175 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800176 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700177 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
178 changed |=
179 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700180 changed |=
181 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700182 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
183 changed |=
184 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
185 changed |= (beamformer_enabled != beamformer_enabled_);
186 changed |=
187 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
188 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800189 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700190 changed |= (level_estimator_enabled != level_estimator_enabled_);
191 changed |=
192 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
193 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
194 if (changed) {
peah8271d042016-11-22 07:24:52 -0800195 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700196 echo_canceller_enabled_ = echo_canceller_enabled;
197 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700198 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700199 noise_suppressor_enabled_ = noise_suppressor_enabled;
200 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
201 beamformer_enabled_ = beamformer_enabled;
202 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
203 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800204 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700205 level_estimator_enabled_ = level_estimator_enabled;
206 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
207 transient_suppressor_enabled_ = transient_suppressor_enabled;
208 }
209
210 changed |= first_update_;
211 first_update_ = false;
212 return changed;
213}
214
215bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
216 const {
217#if WEBRTC_INTELLIGIBILITY_ENHANCER
218 return CaptureMultiBandProcessingActive() ||
ivoc20270be2016-11-15 05:24:35 -0800219 intelligibility_enhancer_enabled_ ||
220 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700221#else
ivoc20270be2016-11-15 05:24:35 -0800222 return CaptureMultiBandProcessingActive() ||
223 voice_activity_detector_enabled_ || residual_echo_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700224#endif
225}
226
227bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
228 const {
peah8271d042016-11-22 07:24:52 -0800229 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700230 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800231 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
232 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700233}
234
235bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
236 const {
237 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800238 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800239 residual_echo_detector_enabled_ || echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700240}
241
242bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
243 const {
244#if WEBRTC_INTELLIGIBILITY_ENHANCER
245 return intelligibility_enhancer_enabled_;
246#else
247 return false;
248#endif
249}
250
solenberg5e465c32015-12-08 13:22:33 -0800251struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800252 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800253 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800254 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800255 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800256 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800257 std::unique_ptr<LevelEstimatorImpl> level_estimator;
258 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
259 std::unique_ptr<VoiceDetectionImpl> voice_detection;
260 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800261 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800262
263 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800264 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700265#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800266 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700267#endif
solenberg5e465c32015-12-08 13:22:33 -0800268};
269
270struct AudioProcessingImpl::ApmPrivateSubmodules {
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700271 explicit ApmPrivateSubmodules(NonlinearBeamformer* beamformer)
solenberg5e465c32015-12-08 13:22:33 -0800272 : beamformer(beamformer) {}
273 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700274 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800275 std::unique_ptr<AgcManagerDirect> agc_manager;
peah8271d042016-11-22 07:24:52 -0800276 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700277 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700278 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
peahe0eae3c2016-12-14 01:16:23 -0800279 std::unique_ptr<EchoCanceller3> echo_canceller3;
solenberg5e465c32015-12-08 13:22:33 -0800280};
281
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000282AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700283 webrtc::Config config;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000284 return Create(config, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000285}
286
peah88ac8532016-09-12 16:47:25 -0700287AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000288 return Create(config, nullptr);
289}
290
peah88ac8532016-09-12 16:47:25 -0700291AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700292 NonlinearBeamformer* beamformer) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000293 AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000294 if (apm->Initialize() != kNoError) {
295 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800296 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000297 }
298
299 return apm;
300}
301
peah88ac8532016-09-12 16:47:25 -0700302AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000303 : AudioProcessingImpl(config, nullptr) {}
304
peah88ac8532016-09-12 16:47:25 -0700305AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700306 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800307 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
308 public_submodules_(new ApmPublicSubmodules()),
peahdf3efa82015-11-28 12:35:15 -0800309 private_submodules_(new ApmPrivateSubmodules(beamformer)),
310 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800311 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000312#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700313 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000314#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700315 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000316#endif
andrew1c7075f2015-06-24 18:14:14 -0700317#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800318 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700319#else
aluebs2a346882016-01-11 18:04:30 -0800320 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700321#endif
aluebs2a346882016-01-11 18:04:30 -0800322 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800323 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700324 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700325 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800326 {
327 rtc::CritScope cs_render(&crit_render_);
328 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000329
peahb624d8c2016-03-05 03:01:14 -0800330 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700331 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800332 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700333 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800334 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700335 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800336 public_submodules_->level_estimator.reset(
337 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800338 public_submodules_->noise_suppression.reset(
339 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800340 public_submodules_->voice_detection.reset(
341 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800342 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800343 new GainControlForExperimentalAgc(
344 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700345 private_submodules_->residual_echo_detector.reset(
346 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700347
peahc19f3122016-10-07 14:54:10 -0700348 // TODO(peah): Move this creation to happen only when the level controller
349 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700350 private_submodules_->level_controller.reset(new LevelController());
peahdf3efa82015-11-28 12:35:15 -0800351 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000352
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000353 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000354}
355
356AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800357 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800358 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800359 private_submodules_->agc_manager.reset();
360 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800361 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000362
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000363#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700364 debug_dump_.debug_file->CloseFile();
peahdf3efa82015-11-28 12:35:15 -0800365#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000366}
367
niklase@google.com470e71d2011-07-07 08:21:25 +0000368int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800369 // Run in a single-threaded manner during initialization.
370 rtc::CritScope cs_render(&crit_render_);
371 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000372 return InitializeLocked();
373}
374
peahde65ddc2016-09-16 15:02:15 -0700375int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
376 int capture_output_sample_rate_hz,
377 int render_input_sample_rate_hz,
378 ChannelLayout capture_input_layout,
379 ChannelLayout capture_output_layout,
380 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700381 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700382 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
383 LayoutHasKeyboard(capture_input_layout)},
384 {capture_output_sample_rate_hz,
385 ChannelsFromLayout(capture_output_layout),
386 LayoutHasKeyboard(capture_output_layout)},
387 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
388 LayoutHasKeyboard(render_input_layout)},
389 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
390 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700391
392 return Initialize(processing_config);
393}
394
395int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800396 // Run in a single-threaded manner during initialization.
397 rtc::CritScope cs_render(&crit_render_);
398 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700399 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000400}
401
peahdf3efa82015-11-28 12:35:15 -0800402int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800403 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700404 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800405}
406
peahdf3efa82015-11-28 12:35:15 -0800407int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700408 const ProcessingConfig& processing_config,
409 bool force_initialization) {
410 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800411}
412
kwiberg83ffe452016-08-29 14:46:07 -0700413#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
414
415AudioProcessingImpl::ApmDebugDumpThreadState::ApmDebugDumpThreadState()
416 : event_msg(new audioproc::Event()) {}
417
418AudioProcessingImpl::ApmDebugDumpThreadState::~ApmDebugDumpThreadState() {}
419
420AudioProcessingImpl::ApmDebugDumpState::ApmDebugDumpState()
421 : debug_file(FileWrapper::Create()) {}
422
423AudioProcessingImpl::ApmDebugDumpState::~ApmDebugDumpState() {}
424
425#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
426
peah192164e2015-11-17 02:16:45 -0800427// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800428// their current values (needs to be called while holding the crit_render_lock).
429int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700430 const ProcessingConfig& processing_config,
431 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800432 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700433 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800434 return kNoError;
435 }
peahdf3efa82015-11-28 12:35:15 -0800436
437 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800438 return InitializeLocked(processing_config);
439}
440
niklase@google.com470e71d2011-07-07 08:21:25 +0000441int AudioProcessingImpl::InitializeLocked() {
peahe0eae3c2016-12-14 01:16:23 -0800442 int capture_audiobuffer_num_channels;
443 if (private_submodules_->echo_canceller3) {
444 // TODO(peah): Ensure that the echo canceller can operate on more than one
445 // microphone channel.
446 RTC_DCHECK(!capture_nonlocked_.beamformer_enabled);
447 capture_audiobuffer_num_channels = 1;
448 } else {
449 capture_audiobuffer_num_channels =
450 capture_nonlocked_.beamformer_enabled
451 ? formats_.api_format.input_stream().num_channels()
452 : formats_.api_format.output_stream().num_channels();
453 }
peahde65ddc2016-09-16 15:02:15 -0700454 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800455 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700456 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800457 : formats_.api_format.reverse_output_stream().num_frames();
458 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
459 render_.render_audio.reset(new AudioBuffer(
460 formats_.api_format.reverse_input_stream().num_frames(),
461 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700462 formats_.render_processing_format.num_frames(),
463 formats_.render_processing_format.num_channels(),
464 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700465 if (formats_.api_format.reverse_input_stream() !=
466 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800467 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800468 formats_.api_format.reverse_input_stream().num_channels(),
469 formats_.api_format.reverse_input_stream().num_frames(),
470 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800471 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700472 } else {
peahdf3efa82015-11-28 12:35:15 -0800473 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700474 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700475 } else {
peahdf3efa82015-11-28 12:35:15 -0800476 render_.render_audio.reset(nullptr);
477 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700478 }
peahdf3efa82015-11-28 12:35:15 -0800479 capture_.capture_audio.reset(
480 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
481 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700482 capture_nonlocked_.capture_processing_format.num_frames(),
483 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800484 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000485
peahde65ddc2016-09-16 15:02:15 -0700486 public_submodules_->echo_cancellation->Initialize(
487 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
488 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700489 AllocateRenderQueue();
490
ivoc3e9a5372016-10-28 07:55:33 -0700491 int success = public_submodules_->echo_cancellation->enable_metrics(true);
492 RTC_DCHECK_EQ(0, success);
493 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
494 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700495 public_submodules_->echo_control_mobile->Initialize(
496 proc_split_sample_rate_hz(), num_reverse_channels(),
497 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700498
499 public_submodules_->gain_control->Initialize(num_proc_channels(),
500 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700501 if (constants_.use_experimental_agc) {
502 if (!private_submodules_->agc_manager.get()) {
503 private_submodules_->agc_manager.reset(new AgcManagerDirect(
504 public_submodules_->gain_control.get(),
505 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800506 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700507 }
508 private_submodules_->agc_manager->Initialize();
509 private_submodules_->agc_manager->SetCaptureMuted(
510 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700511 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700512 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200513 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000514 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700515#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700516 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700517#endif
peah8271d042016-11-22 07:24:52 -0800518 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700519 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
520 proc_sample_rate_hz());
521 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
522 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700523 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700524 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800525 InitializeEchoCanceller3();
solenberg70f99032015-12-08 11:07:32 -0800526
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000527#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700528 if (debug_dump_.debug_file->is_open()) {
ajm@google.com808e0e02011-08-03 21:08:51 +0000529 int err = WriteInitMessage();
530 if (err != kNoError) {
531 return err;
532 }
533 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000534#endif
ajm@google.com808e0e02011-08-03 21:08:51 +0000535
niklase@google.com470e71d2011-07-07 08:21:25 +0000536 return kNoError;
537}
538
Michael Graczyk86c6d332015-07-23 11:41:39 -0700539int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
540 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700541 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
542 return kBadSampleRateError;
543 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000544 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700545
Peter Kasting69558702016-01-12 16:26:35 -0800546 const size_t num_in_channels = config.input_stream().num_channels();
547 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700548
549 // Need at least one input channel.
550 // Need either one output channel or as many outputs as there are inputs.
551 if (num_in_channels == 0 ||
552 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700553 return kBadNumberChannelsError;
554 }
555
aluebsb2328d12016-01-11 20:32:29 -0800556 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800557 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700558 return kBadNumberChannelsError;
559 }
560
peahdf3efa82015-11-28 12:35:15 -0800561 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000562
peahde65ddc2016-09-16 15:02:15 -0700563 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700564 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700565 formats_.api_format.output_stream().sample_rate_hz()),
566 submodule_states_.CaptureMultiBandSubModulesActive() ||
567 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000568
peahde65ddc2016-09-16 15:02:15 -0700569 capture_nonlocked_.capture_processing_format =
570 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700571
peahde65ddc2016-09-16 15:02:15 -0700572 int render_processing_rate = FindNativeProcessRateToUse(
peah2ace3f92016-09-10 04:42:27 -0700573 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
574 formats_.api_format.reverse_output_stream().sample_rate_hz()),
575 submodule_states_.CaptureMultiBandSubModulesActive() ||
576 submodule_states_.RenderMultiBandSubModulesActive());
aluebseb3603b2016-04-20 15:27:58 -0700577 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
578 // splitting filter degrades the AEC performance.
peahe0eae3c2016-12-14 01:16:23 -0800579 // TODO(peah): Verify that the band splitting is needed for the AEC3.
580 if (render_processing_rate > kSampleRate32kHz &&
581 !capture_nonlocked_.echo_canceller3_enabled) {
peahde65ddc2016-09-16 15:02:15 -0700582 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
583 ? kSampleRate32kHz
584 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700585 }
peahde65ddc2016-09-16 15:02:15 -0700586 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700587 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700588 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
589 kSampleRate8kHz) {
590 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000591 } else {
peahde65ddc2016-09-16 15:02:15 -0700592 render_processing_rate =
593 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000594 }
595
peahde65ddc2016-09-16 15:02:15 -0700596 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000597 // demonstrated to work well for AEC in most practical scenarios.
peahde65ddc2016-09-16 15:02:15 -0700598 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000599
peahde65ddc2016-09-16 15:02:15 -0700600 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
601 kSampleRate32kHz ||
602 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
603 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800604 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000605 } else {
peahdf3efa82015-11-28 12:35:15 -0800606 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700607 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000608 }
609
610 return InitializeLocked();
611}
612
peah88ac8532016-09-12 16:47:25 -0700613void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700614 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700615
peahc19f3122016-10-07 14:54:10 -0700616 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700617 if (!config_ok) {
618 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
619 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700620 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700621 << std::endl
622 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700623 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700624 }
625
626 // Run in a single-threaded manner when applying the settings.
627 rtc::CritScope cs_render(&crit_render_);
628 rtc::CritScope cs_capture(&crit_capture_);
629
peahc19f3122016-10-07 14:54:10 -0700630 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
631 // with the value in config_ everywhere in the code.
632 if (capture_nonlocked_.level_controller_enabled !=
633 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700634 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700635 config_.level_controller.enabled;
636 // TODO(peah): Remove the conditional initialization to always initialize
637 // the level controller regardless of whether it is enabled or not.
638 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700639 }
peahc19f3122016-10-07 14:54:10 -0700640 LOG(LS_INFO) << "Level controller activated: "
641 << capture_nonlocked_.level_controller_enabled;
642
643 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800644
645 InitializeLowCutFilter();
646
647 LOG(LS_INFO) << "Highpass filter activated: "
648 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800649
650 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
651 if (!config_ok) {
652 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
653 << "echo canceller 3: "
654 << EchoCanceller3::ToString(config_.echo_canceller3)
655 << std::endl
656 << "Reverting to default parameter set";
657 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
658 }
659
660 if (config.echo_canceller3.enabled !=
661 capture_nonlocked_.echo_canceller3_enabled) {
662 capture_nonlocked_.echo_canceller3_enabled =
663 config_.echo_canceller3.enabled;
664 InitializeEchoCanceller3();
665 LOG(LS_INFO) << "Echo canceller 3 activated: "
666 << capture_nonlocked_.echo_canceller3_enabled;
667 }
peah88ac8532016-09-12 16:47:25 -0700668}
669
670void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800671 // Run in a single-threaded manner when setting the extra options.
672 rtc::CritScope cs_render(&crit_render_);
673 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000674
peahb624d8c2016-03-05 03:01:14 -0800675 public_submodules_->echo_cancellation->SetExtraOptions(config);
676
peahdf3efa82015-11-28 12:35:15 -0800677 if (capture_.transient_suppressor_enabled !=
678 config.Get<ExperimentalNs>().enabled) {
679 capture_.transient_suppressor_enabled =
680 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000681 InitializeTransient();
682 }
aluebs2a346882016-01-11 18:04:30 -0800683
peah1bcfce52016-08-26 07:16:04 -0700684#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700685 if(capture_nonlocked_.intelligibility_enabled !=
686 config.Get<Intelligibility>().enabled) {
687 capture_nonlocked_.intelligibility_enabled =
688 config.Get<Intelligibility>().enabled;
689 InitializeIntelligibility();
690 }
peah1bcfce52016-08-26 07:16:04 -0700691#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700692
aluebs2a346882016-01-11 18:04:30 -0800693#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800694 if (capture_nonlocked_.beamformer_enabled !=
695 config.Get<Beamforming>().enabled) {
696 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800697 if (config.Get<Beamforming>().array_geometry.size() > 1) {
698 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
699 }
700 capture_.target_direction = config.Get<Beamforming>().target_direction;
701 InitializeBeamformer();
702 }
703#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000704}
705
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000706int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800707 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700708 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000709}
710
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000711int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800712 // Used as callback from submodules, hence locking is not allowed.
713 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000714}
715
Peter Kasting69558702016-01-12 16:26:35 -0800716size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800717 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700718 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000719}
720
Peter Kasting69558702016-01-12 16:26:35 -0800721size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800722 // Used as callback from submodules, hence locking is not allowed.
723 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000724}
725
Peter Kasting69558702016-01-12 16:26:35 -0800726size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800727 // Used as callback from submodules, hence locking is not allowed.
728 return capture_nonlocked_.beamformer_enabled ? 1 : num_output_channels();
729}
730
Peter Kasting69558702016-01-12 16:26:35 -0800731size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800732 // Used as callback from submodules, hence locking is not allowed.
733 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000734}
735
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000736void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800737 rtc::CritScope cs(&crit_capture_);
738 capture_.output_will_be_muted = muted;
739 if (private_submodules_->agc_manager.get()) {
740 private_submodules_->agc_manager->SetCaptureMuted(
741 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000742 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000743}
744
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000745
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000746int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700747 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000748 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000749 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000750 int output_sample_rate_hz,
751 ChannelLayout output_layout,
752 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800753 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800754 StreamConfig input_stream;
755 StreamConfig output_stream;
756 {
757 // Access the formats_.api_format.input_stream beneath the capture lock.
758 // The lock must be released as it is later required in the call
759 // to ProcessStream(,,,);
760 rtc::CritScope cs(&crit_capture_);
761 input_stream = formats_.api_format.input_stream();
762 output_stream = formats_.api_format.output_stream();
763 }
764
Michael Graczyk86c6d332015-07-23 11:41:39 -0700765 input_stream.set_sample_rate_hz(input_sample_rate_hz);
766 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
767 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700768 output_stream.set_sample_rate_hz(output_sample_rate_hz);
769 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
770 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
771
772 if (samples_per_channel != input_stream.num_frames()) {
773 return kBadDataLengthError;
774 }
775 return ProcessStream(src, input_stream, output_stream, dest);
776}
777
778int AudioProcessingImpl::ProcessStream(const float* const* src,
779 const StreamConfig& input_config,
780 const StreamConfig& output_config,
781 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800782 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800783 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700784 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800785 {
786 // Acquire the capture lock in order to safely call the function
787 // that retrieves the render side data. This function accesses apm
788 // getters that need the capture lock held when being called.
789 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700790 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800791
792 if (!src || !dest) {
793 return kNullPointerError;
794 }
795
796 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700797 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000798 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000799
Michael Graczyk86c6d332015-07-23 11:41:39 -0700800 processing_config.input_stream() = input_config;
801 processing_config.output_stream() = output_config;
802
peahdf3efa82015-11-28 12:35:15 -0800803 {
804 // Do conditional reinitialization.
805 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700806 RETURN_ON_ERR(
807 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800808 }
809 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700810 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
811 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000812
813#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700814 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200815 RETURN_ON_ERR(WriteConfigMessage(false));
816
peahdf3efa82015-11-28 12:35:15 -0800817 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
818 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000819 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800820 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800821 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
822 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000823 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000824 }
825#endif
826
peahdf3efa82015-11-28 12:35:15 -0800827 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700828 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800829 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000830
831#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700832 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800833 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000834 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800835 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800836 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
837 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000838 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800839 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800840 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800841 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000842 }
843#endif
844
845 return kNoError;
846}
847
peah701d6282016-10-25 05:42:20 -0700848void AudioProcessingImpl::QueueRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700849 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
850 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700851 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700852
kwibergaf476c72016-11-28 15:21:39 -0800853 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700854
855 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700856 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700857 // The data queue is full and needs to be emptied.
858 EmptyQueuedRenderAudio();
859
860 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700861 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700862 RTC_DCHECK(result);
863 }
864
865 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
866 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700867 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700868
869 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700870 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700871 // The data queue is full and needs to be emptied.
872 EmptyQueuedRenderAudio();
873
874 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700875 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700876 RTC_DCHECK(result);
877 }
peah701d6282016-10-25 05:42:20 -0700878
879 if (!constants_.use_experimental_agc) {
880 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
881 // Insert the samples into the queue.
882 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
883 // The data queue is full and needs to be emptied.
884 EmptyQueuedRenderAudio();
885
886 // Retry the insert (should always work).
887 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
888 RTC_DCHECK(result);
889 }
890 }
ivoc9f4a4a02016-10-28 05:39:16 -0700891
892 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
893
894 // Insert the samples into the queue.
895 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
896 // The data queue is full and needs to be emptied.
897 EmptyQueuedRenderAudio();
898
899 // Retry the insert (should always work).
900 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
901 RTC_DCHECK(result);
902 }
peah764e3642016-10-22 05:04:30 -0700903}
904
905void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700906 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700907 std::max(static_cast<size_t>(1),
908 kMaxAllowedValuesOfSamplesPerFrame *
909 EchoCancellationImpl::NumCancellersRequired(
910 num_output_channels(), num_reverse_channels()));
911
peah701d6282016-10-25 05:42:20 -0700912 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700913 std::max(static_cast<size_t>(1),
914 kMaxAllowedValuesOfSamplesPerFrame *
915 EchoControlMobileImpl::NumCancellersRequired(
916 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700917
peah701d6282016-10-25 05:42:20 -0700918 const size_t new_agc_render_queue_element_max_size =
919 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
920
ivoc9f4a4a02016-10-28 05:39:16 -0700921 const size_t new_red_render_queue_element_max_size =
922 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
923
peaha0624602016-10-25 04:45:24 -0700924 // Reallocate the queues if the queue item sizes are too small to fit the
925 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700926 if (aec_render_queue_element_max_size_ <
927 new_aec_render_queue_element_max_size) {
928 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700929
peaha0624602016-10-25 04:45:24 -0700930 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700931 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700932
peah701d6282016-10-25 05:42:20 -0700933 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -0700934 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
935 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -0700936 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -0700937 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -0700938
peah701d6282016-10-25 05:42:20 -0700939 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
940 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -0700941 } else {
peah701d6282016-10-25 05:42:20 -0700942 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -0700943 }
944
peah701d6282016-10-25 05:42:20 -0700945 if (aecm_render_queue_element_max_size_ <
946 new_aecm_render_queue_element_max_size) {
947 aecm_render_queue_element_max_size_ =
948 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -0700949
950 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -0700951 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700952
peah701d6282016-10-25 05:42:20 -0700953 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -0700954 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
955 kMaxNumFramesToBuffer, template_queue_element,
956 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -0700957 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -0700958
peah701d6282016-10-25 05:42:20 -0700959 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
960 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -0700961 } else {
peah701d6282016-10-25 05:42:20 -0700962 aecm_render_signal_queue_->Clear();
963 }
964
965 if (agc_render_queue_element_max_size_ <
966 new_agc_render_queue_element_max_size) {
967 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
968
969 std::vector<int16_t> template_queue_element(
970 agc_render_queue_element_max_size_);
971
972 agc_render_signal_queue_.reset(
973 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
974 kMaxNumFramesToBuffer, template_queue_element,
975 RenderQueueItemVerifier<int16_t>(
976 agc_render_queue_element_max_size_)));
977
978 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
979 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
980 } else {
981 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -0700982 }
ivoc9f4a4a02016-10-28 05:39:16 -0700983
984 if (red_render_queue_element_max_size_ <
985 new_red_render_queue_element_max_size) {
986 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
987
988 std::vector<float> template_queue_element(
989 red_render_queue_element_max_size_);
990
991 red_render_signal_queue_.reset(
992 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
993 kMaxNumFramesToBuffer, template_queue_element,
994 RenderQueueItemVerifier<float>(
995 red_render_queue_element_max_size_)));
996
997 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
998 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
999 } else {
1000 red_render_signal_queue_->Clear();
1001 }
peah764e3642016-10-22 05:04:30 -07001002}
1003
1004void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1005 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001006 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001007 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001008 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001009 }
1010
peah701d6282016-10-25 05:42:20 -07001011 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001012 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001013 aecm_capture_queue_buffer_);
1014 }
1015
1016 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1017 public_submodules_->gain_control->ProcessRenderAudio(
1018 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001019 }
ivoc9f4a4a02016-10-28 05:39:16 -07001020
1021 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1022 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1023 red_capture_queue_buffer_);
1024 }
peah764e3642016-10-22 05:04:30 -07001025}
1026
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001027int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001028 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001029 {
1030 // Acquire the capture lock in order to safely call the function
1031 // that retrieves the render side data. This function accesses apm
1032 // getters that need the capture lock held when being called.
1033 // The lock needs to be released as
1034 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1035 // as well.
1036 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001037 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001038 }
peahfa6228e2015-11-16 16:27:42 -08001039
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001040 if (!frame) {
1041 return kNullPointerError;
1042 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001043 // Must be a native rate.
1044 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1045 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001046 frame->sample_rate_hz_ != kSampleRate32kHz &&
1047 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001048 return kBadSampleRateError;
1049 }
peah192164e2015-11-17 02:16:45 -08001050
peahdf3efa82015-11-28 12:35:15 -08001051 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001052 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001053 {
1054 // Aquire lock for the access of api_format.
1055 // The lock is released immediately due to the conditional
1056 // reinitialization.
1057 rtc::CritScope cs_capture(&crit_capture_);
1058 // TODO(ajm): The input and output rates and channels are currently
1059 // constrained to be identical in the int16 interface.
1060 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001061
1062 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001063 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001064 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1065 processing_config.input_stream().set_num_channels(frame->num_channels_);
1066 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1067 processing_config.output_stream().set_num_channels(frame->num_channels_);
1068
peahdf3efa82015-11-28 12:35:15 -08001069 {
1070 // Do conditional reinitialization.
1071 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001072 RETURN_ON_ERR(
1073 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001074 }
1075 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001076 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001077 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001078 return kBadDataLengthError;
1079 }
1080
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001081#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001082 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001083 RETURN_ON_ERR(WriteConfigMessage(false));
1084
peahdf3efa82015-11-28 12:35:15 -08001085 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1086 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001087 const size_t data_size =
1088 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001089 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001090 }
1091#endif
1092
peahdf3efa82015-11-28 12:35:15 -08001093 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001094 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001095 capture_.capture_audio->InterleaveTo(
1096 frame, submodule_states_.CaptureMultiBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001097
1098#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001099 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001100 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001101 const size_t data_size =
1102 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001103 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001104 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001105 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001106 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001107 }
1108#endif
1109
1110 return kNoError;
1111}
1112
peahde65ddc2016-09-16 15:02:15 -07001113int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001114 // Ensure that not both the AEC and AECM are active at the same time.
1115 // TODO(peah): Simplify once the public API Enable functions for these
1116 // are moved to APM.
1117 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1118 public_submodules_->echo_control_mobile->is_enabled()));
1119
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001120#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001121 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001122 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1123 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1124 msg->set_drift(
1125 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001126 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001127 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001128 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001129#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001130
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001131 MaybeUpdateHistograms();
1132
peahde65ddc2016-09-16 15:02:15 -07001133 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001134
henrik.lundin290d43a2016-11-29 08:09:09 -08001135 rms_.Analyze(rtc::ArrayView<const int16_t>(
1136 capture_buffer->channels_const()[0],
1137 capture_nonlocked_.capture_processing_format.num_frames()));
1138 if (++rms_interval_counter_ >= 1000) {
1139 rms_interval_counter_ = 0;
1140 RmsLevel::Levels levels = rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001141 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1142 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1143 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1144 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001145 }
1146
peahe0eae3c2016-12-14 01:16:23 -08001147 if (private_submodules_->echo_canceller3) {
1148 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1149 }
1150
peahbe615622016-02-13 16:40:47 -08001151 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001152 public_submodules_->gain_control->is_enabled()) {
1153 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001154 capture_buffer->channels()[0], capture_buffer->num_channels(),
1155 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001156 }
1157
peah2ace3f92016-09-10 04:42:27 -07001158 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1159 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001160 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1161 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001162 }
1163
aluebsb2328d12016-01-11 20:32:29 -08001164 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001165 private_submodules_->beamformer->AnalyzeChunk(
1166 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001167 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001168 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001169 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001170
peahe0eae3c2016-12-14 01:16:23 -08001171 // TODO(peah): Move the AEC3 low-cut filter to this place.
1172 if (private_submodules_->low_cut_filter &&
1173 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001174 private_submodules_->low_cut_filter->Process(capture_buffer);
1175 }
peahde65ddc2016-09-16 15:02:15 -07001176 RETURN_ON_ERR(
1177 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1178 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001179
1180 // Ensure that the stream delay was set before the call to the
1181 // AEC ProcessCaptureAudio function.
1182 if (public_submodules_->echo_cancellation->is_enabled() &&
1183 !was_stream_delay_set()) {
1184 return AudioProcessing::kStreamParameterNotSetError;
1185 }
1186
peahe0eae3c2016-12-14 01:16:23 -08001187 if (private_submodules_->echo_canceller3) {
1188 private_submodules_->echo_canceller3->ProcessCapture(capture_buffer, false);
1189 }
1190
peahb58a1582016-03-15 09:34:24 -07001191 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001192 capture_buffer, stream_delay_ms()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001193
peahdf3efa82015-11-28 12:35:15 -08001194 if (public_submodules_->echo_control_mobile->is_enabled() &&
1195 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001196 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001197 }
peahde65ddc2016-09-16 15:02:15 -07001198 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001199#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001200 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001201 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001202 int gain_db = public_submodules_->gain_control->is_enabled() ?
1203 public_submodules_->gain_control->compression_gain_db() :
1204 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001205 float gain = std::pow(10.f, gain_db / 20.f);
1206 gain *= capture_nonlocked_.level_controller_enabled ?
1207 private_submodules_->level_controller->GetLastGain() :
1208 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001209 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001210 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001211 }
peah1bcfce52016-08-26 07:16:04 -07001212#endif
peah253534d2016-03-15 04:32:28 -07001213
1214 // Ensure that the stream delay was set before the call to the
1215 // AECM ProcessCaptureAudio function.
1216 if (public_submodules_->echo_control_mobile->is_enabled() &&
1217 !was_stream_delay_set()) {
1218 return AudioProcessing::kStreamParameterNotSetError;
1219 }
1220
1221 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001222 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001223
ivoc9f4a4a02016-10-28 05:39:16 -07001224 if (config_.residual_echo_detector.enabled) {
1225 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1226 rtc::ArrayView<const float>(
1227 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1228 capture_buffer->num_frames_per_band()));
1229 }
1230
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001231 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001232 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001233 }
1234
peahde65ddc2016-09-16 15:02:15 -07001235 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001236
peahbe615622016-02-13 16:40:47 -08001237 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001238 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001239 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001240 private_submodules_->beamformer->is_target_present())) {
1241 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001242 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1243 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001244 }
peahb8fbb542016-03-15 02:28:08 -07001245 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001246 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001247
peah2ace3f92016-09-10 04:42:27 -07001248 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1249 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001250 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1251 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001252 }
1253
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001254 // TODO(aluebs): Investigate if the transient suppression placement should be
1255 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001256 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001257 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001258 private_submodules_->agc_manager.get()
1259 ? private_submodules_->agc_manager->voice_probability()
1260 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001261
peahdf3efa82015-11-28 12:35:15 -08001262 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001263 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1264 capture_buffer->num_channels(),
1265 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1266 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1267 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001268 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001269 }
1270
peahca4cac72016-06-29 15:26:12 -07001271 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001272 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001273 }
1274
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001275 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001276 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001277
peahdf3efa82015-11-28 12:35:15 -08001278 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001279 return kNoError;
1280}
1281
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001282int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001283 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001284 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001285 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001286 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001287 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001288 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001289 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001290 };
1291 if (samples_per_channel != reverse_config.num_frames()) {
1292 return kBadDataLengthError;
1293 }
peahdf3efa82015-11-28 12:35:15 -08001294 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001295}
1296
peahde65ddc2016-09-16 15:02:15 -07001297int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1298 const StreamConfig& input_config,
1299 const StreamConfig& output_config,
1300 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001301 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001302 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001303 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001304 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001305 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1306 dest);
peah2ace3f92016-09-10 04:42:27 -07001307 } else if (formats_.api_format.reverse_input_stream() !=
1308 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001309 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1310 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001311 } else {
peahde65ddc2016-09-16 15:02:15 -07001312 CopyAudioIfNeeded(src, input_config.num_frames(),
1313 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001314 }
1315
1316 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001317}
1318
peahdf3efa82015-11-28 12:35:15 -08001319int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001320 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001321 const StreamConfig& input_config,
1322 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001323 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001324 return kNullPointerError;
1325 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001326
peahde65ddc2016-09-16 15:02:15 -07001327 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001328 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001329 }
1330
peahdf3efa82015-11-28 12:35:15 -08001331 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001332 processing_config.reverse_input_stream() = input_config;
1333 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001334
peahdf3efa82015-11-28 12:35:15 -08001335 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001336 assert(input_config.num_frames() ==
1337 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001338
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001339#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001340 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001341 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1342 audioproc::ReverseStream* msg =
1343 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001344 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001345 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001346 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001347 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001348 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001349 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001350 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001351 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001352 }
1353#endif
1354
peahdf3efa82015-11-28 12:35:15 -08001355 render_.render_audio->CopyFrom(src,
1356 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001357 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001358}
1359
1360int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001361 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001362 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001363 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001364 return kNullPointerError;
1365 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001366 // Must be a native rate.
1367 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1368 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001369 frame->sample_rate_hz_ != kSampleRate32kHz &&
1370 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001371 return kBadSampleRateError;
1372 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001373
Michael Graczyk86c6d332015-07-23 11:41:39 -07001374 if (frame->num_channels_ <= 0) {
1375 return kBadNumberChannelsError;
1376 }
1377
peahdf3efa82015-11-28 12:35:15 -08001378 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001379 processing_config.reverse_input_stream().set_sample_rate_hz(
1380 frame->sample_rate_hz_);
1381 processing_config.reverse_input_stream().set_num_channels(
1382 frame->num_channels_);
1383 processing_config.reverse_output_stream().set_sample_rate_hz(
1384 frame->sample_rate_hz_);
1385 processing_config.reverse_output_stream().set_num_channels(
1386 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001387
peahdf3efa82015-11-28 12:35:15 -08001388 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001389 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001390 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001391 return kBadDataLengthError;
1392 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001393
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001394#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001395 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001396 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1397 audioproc::ReverseStream* msg =
1398 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001399 const size_t data_size =
1400 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001401 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001402 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001403 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001404 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001405 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001406#endif
peahdf3efa82015-11-28 12:35:15 -08001407 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001408 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001409 render_.render_audio->InterleaveTo(
1410 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001411 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001412}
niklase@google.com470e71d2011-07-07 08:21:25 +00001413
peahde65ddc2016-09-16 15:02:15 -07001414int AudioProcessingImpl::ProcessRenderStreamLocked() {
1415 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah2ace3f92016-09-10 04:42:27 -07001416 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001417 SampleRateSupportsMultiBand(
1418 formats_.render_processing_format.sample_rate_hz())) {
1419 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001420 }
1421
peah1bcfce52016-08-26 07:16:04 -07001422#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001423 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001424 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001425 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001426 }
peah1bcfce52016-08-26 07:16:04 -07001427#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001428
peah764e3642016-10-22 05:04:30 -07001429 QueueRenderAudio(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001430 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1431 if (private_submodules_->echo_canceller3) {
1432 if (!private_submodules_->echo_canceller3->AnalyzeRender(render_buffer)) {
1433 // TODO(peah): Lock and empty render queue, and try again.
1434 }
1435 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001436
peah2ace3f92016-09-10 04:42:27 -07001437 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001438 SampleRateSupportsMultiBand(
1439 formats_.render_processing_format.sample_rate_hz())) {
1440 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001441 }
1442
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001443 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001444}
1445
1446int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001447 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001448 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001449 capture_.was_stream_delay_set = true;
1450 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001451
niklase@google.com470e71d2011-07-07 08:21:25 +00001452 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001453 delay = 0;
1454 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001455 }
1456
1457 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1458 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001459 delay = 500;
1460 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001461 }
1462
peahdf3efa82015-11-28 12:35:15 -08001463 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001464 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001465}
1466
1467int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001468 // Used as callback from submodules, hence locking is not allowed.
1469 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001470}
1471
1472bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001473 // Used as callback from submodules, hence locking is not allowed.
1474 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001475}
1476
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001477void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001478 rtc::CritScope cs(&crit_capture_);
1479 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001480}
1481
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001482void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001483 rtc::CritScope cs(&crit_capture_);
1484 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001485}
1486
1487int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001488 rtc::CritScope cs(&crit_capture_);
1489 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001490}
1491
niklase@google.com470e71d2011-07-07 08:21:25 +00001492int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001493 const char filename[AudioProcessing::kMaxFilenameSize],
1494 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001495 // Run in a single-threaded manner.
1496 rtc::CritScope cs_render(&crit_render_);
1497 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001498 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001499
peahdf3efa82015-11-28 12:35:15 -08001500 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001501 return kNullPointerError;
1502 }
1503
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001504#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001505 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001506 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001507 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001508
tommia6219cc2016-06-15 10:30:14 -07001509 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001510 return kFileError;
1511 }
1512
Minyue13b96ba2015-10-03 00:39:14 +02001513 RETURN_ON_ERR(WriteConfigMessage(true));
1514 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001515 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001516#else
1517 return kUnsupportedFunctionError;
1518#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001519}
1520
ivocd66b44d2016-01-15 03:06:36 -08001521int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1522 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001523 // Run in a single-threaded manner.
1524 rtc::CritScope cs_render(&crit_render_);
1525 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001526
peahdf3efa82015-11-28 12:35:15 -08001527 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001528 return kNullPointerError;
1529 }
1530
1531#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001532 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1533
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001534 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001535 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001536
tommia6219cc2016-06-15 10:30:14 -07001537 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001538 return kFileError;
1539 }
1540
Minyue13b96ba2015-10-03 00:39:14 +02001541 RETURN_ON_ERR(WriteConfigMessage(true));
1542 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001543 return kNoError;
1544#else
1545 return kUnsupportedFunctionError;
1546#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1547}
1548
peah73a28ee2016-10-12 03:01:49 -07001549int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1550 return StartDebugRecording(handle, -1);
1551}
1552
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001553int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1554 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001555 // Run in a single-threaded manner.
1556 rtc::CritScope cs_render(&crit_render_);
1557 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001558 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001559 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001560}
1561
niklase@google.com470e71d2011-07-07 08:21:25 +00001562int AudioProcessingImpl::StopDebugRecording() {
peahdf3efa82015-11-28 12:35:15 -08001563 // Run in a single-threaded manner.
1564 rtc::CritScope cs_render(&crit_render_);
1565 rtc::CritScope cs_capture(&crit_capture_);
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001566
1567#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001568 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001569 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001570 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001571#else
1572 return kUnsupportedFunctionError;
1573#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001574}
1575
ivoc3e9a5372016-10-28 07:55:33 -07001576// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1577AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1578 const {
1579 return AudioProcessingStatistics();
1580}
1581
1582AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1583 const {
1584 AudioProcessingStatistics stats;
1585 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001586 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1587 if (success == Error::kNoError) {
1588 stats.a_nlp.Set(metrics.a_nlp);
1589 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1590 stats.echo_return_loss.Set(metrics.echo_return_loss);
1591 stats.echo_return_loss_enhancement.Set(
1592 metrics.echo_return_loss_enhancement);
1593 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1594 }
ivoc87d1a782016-11-14 07:55:03 -08001595 stats.residual_echo_likelihood =
1596 private_submodules_->residual_echo_detector->echo_likelihood();
ivoc3e9a5372016-10-28 07:55:33 -07001597 public_submodules_->echo_cancellation->GetDelayMetrics(
1598 &stats.delay_median, &stats.delay_standard_deviation,
1599 &stats.fraction_poor_delays);
1600 return stats;
1601}
1602
niklase@google.com470e71d2011-07-07 08:21:25 +00001603EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001604 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001605}
1606
1607EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001608 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001609}
1610
1611GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001612 if (constants_.use_experimental_agc) {
1613 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001614 }
peahbfa97112016-03-10 21:09:04 -08001615 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001616}
1617
1618HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001619 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001620}
1621
1622LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001623 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001624}
1625
1626NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001627 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001628}
1629
1630VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001631 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001632}
1633
peah8271d042016-11-22 07:24:52 -08001634void AudioProcessingImpl::MutateConfig(
1635 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1636 rtc::CritScope cs_render(&crit_render_);
1637 rtc::CritScope cs_capture(&crit_capture_);
1638 mutator(&config_);
1639 ApplyConfig(config_);
1640}
1641
1642AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1643 rtc::CritScope cs_render(&crit_render_);
1644 rtc::CritScope cs_capture(&crit_capture_);
1645 return config_;
1646}
1647
peah2ace3f92016-09-10 04:42:27 -07001648bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1649 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001650 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001651 public_submodules_->echo_cancellation->is_enabled(),
1652 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001653 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001654 public_submodules_->noise_suppression->is_enabled(),
1655 capture_nonlocked_.intelligibility_enabled,
1656 capture_nonlocked_.beamformer_enabled,
1657 public_submodules_->gain_control->is_enabled(),
1658 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001659 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001660 public_submodules_->voice_detection->is_enabled(),
1661 public_submodules_->level_estimator->is_enabled(),
1662 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001663}
1664
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001665
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001666void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001667 if (capture_.transient_suppressor_enabled) {
1668 if (!public_submodules_->transient_suppressor.get()) {
1669 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001670 }
peahdf3efa82015-11-28 12:35:15 -08001671 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001672 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1673 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001674 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001675}
1676
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001677void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001678 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001679 if (!private_submodules_->beamformer) {
1680 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001681 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001682 }
peahdf3efa82015-11-28 12:35:15 -08001683 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1684 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001685 }
1686}
1687
ekmeyerson60d9b332015-08-14 10:35:55 -07001688void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001689#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001690 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001691 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001692 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001693 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001694 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001695 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001696 }
peah1bcfce52016-08-26 07:16:04 -07001697#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001698}
1699
peah8271d042016-11-22 07:24:52 -08001700void AudioProcessingImpl::InitializeLowCutFilter() {
1701 if (config_.high_pass_filter.enabled) {
1702 private_submodules_->low_cut_filter.reset(
1703 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1704 } else {
1705 private_submodules_->low_cut_filter.reset();
1706 }
1707}
peahe0eae3c2016-12-14 01:16:23 -08001708void AudioProcessingImpl::InitializeEchoCanceller3() {
1709 if (capture_nonlocked_.echo_canceller3_enabled) {
1710 private_submodules_->echo_canceller3.reset(
1711 new EchoCanceller3(proc_sample_rate_hz(), true));
1712 } else {
1713 private_submodules_->echo_canceller3.reset();
1714 }
1715}
peah8271d042016-11-22 07:24:52 -08001716
peahca4cac72016-06-29 15:26:12 -07001717void AudioProcessingImpl::InitializeLevelController() {
1718 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1719}
1720
ivoc9f4a4a02016-10-28 05:39:16 -07001721void AudioProcessingImpl::InitializeResidualEchoDetector() {
1722 private_submodules_->residual_echo_detector->Initialize();
1723}
1724
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001725void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001726 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001727
1728 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001729 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1730 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001731 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001732 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001733 capture_.stream_delay_jumps = 0;
1734 }
1735 if (capture_.aec_system_delay_jumps == -1 &&
1736 echo_cancellation()->stream_has_echo()) {
1737 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001738 }
1739
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001740 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001741 const int diff_stream_delay_ms =
1742 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1743 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1744 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001745 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1746 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001747 if (capture_.stream_delay_jumps == -1) {
1748 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001749 }
peahdf3efa82015-11-28 12:35:15 -08001750 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001751 }
peahdf3efa82015-11-28 12:35:15 -08001752 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001753
1754 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001755 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001756 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001757 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001758 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001759 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1760 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001761 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001762 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001763 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001764 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001765 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1766 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1767 100);
peahdf3efa82015-11-28 12:35:15 -08001768 if (capture_.aec_system_delay_jumps == -1) {
1769 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001770 }
peahdf3efa82015-11-28 12:35:15 -08001771 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001772 }
peahdf3efa82015-11-28 12:35:15 -08001773 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001774 }
1775}
1776
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001777void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001778 // Run in a single-threaded manner.
1779 rtc::CritScope cs_render(&crit_render_);
1780 rtc::CritScope cs_capture(&crit_capture_);
1781
1782 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001783 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001784 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001785 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001786 }
peahdf3efa82015-11-28 12:35:15 -08001787 capture_.stream_delay_jumps = -1;
1788 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001789
peahdf3efa82015-11-28 12:35:15 -08001790 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001791 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1792 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001793 }
peahdf3efa82015-11-28 12:35:15 -08001794 capture_.aec_system_delay_jumps = -1;
1795 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001796}
1797
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001798#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001799int AudioProcessingImpl::WriteMessageToDebugFile(
1800 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08001801 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08001802 rtc::CriticalSection* crit_debug,
1803 ApmDebugDumpThreadState* debug_state) {
1804 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00001805 if (size <= 0) {
1806 return kUnspecifiedError;
1807 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00001808#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07001809// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
1810// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00001811#endif
1812
peahdf3efa82015-11-28 12:35:15 -08001813 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00001814 return kUnspecifiedError;
1815 }
1816
peahdf3efa82015-11-28 12:35:15 -08001817 {
1818 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08001819 rtc::CritScope cs_debug(crit_debug);
1820
tommia6219cc2016-06-15 10:30:14 -07001821 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08001822 // Update the byte counter.
1823 if (*filesize_limit_bytes >= 0) {
1824 *filesize_limit_bytes -=
1825 (sizeof(int32_t) + debug_state->event_str.length());
1826 if (*filesize_limit_bytes < 0) {
1827 // Not enough bytes are left to write this message, so stop logging.
1828 debug_file->CloseFile();
1829 return kNoError;
1830 }
1831 }
peahdf3efa82015-11-28 12:35:15 -08001832 // Write message preceded by its size.
1833 if (!debug_file->Write(&size, sizeof(int32_t))) {
1834 return kFileError;
1835 }
1836 if (!debug_file->Write(debug_state->event_str.data(),
1837 debug_state->event_str.length())) {
1838 return kFileError;
1839 }
ajm@google.com808e0e02011-08-03 21:08:51 +00001840 }
1841
peahdf3efa82015-11-28 12:35:15 -08001842 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00001843
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001844 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001845}
1846
1847int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08001848 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
1849 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
1850 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00001851
Peter Kasting69558702016-01-12 16:26:35 -08001852 msg->set_num_input_channels(static_cast<google::protobuf::int32>(
1853 formats_.api_format.input_stream().num_channels()));
1854 msg->set_num_output_channels(static_cast<google::protobuf::int32>(
1855 formats_.api_format.output_stream().num_channels()));
1856 msg->set_num_reverse_channels(static_cast<google::protobuf::int32>(
1857 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08001858 msg->set_reverse_sample_rate(
1859 formats_.api_format.reverse_input_stream().sample_rate_hz());
1860 msg->set_output_sample_rate(
1861 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07001862 msg->set_reverse_output_sample_rate(
1863 formats_.api_format.reverse_output_stream().sample_rate_hz());
1864 msg->set_num_reverse_output_channels(
1865 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08001866
1867 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001868 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001869 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02001870 return kNoError;
1871}
1872
1873int AudioProcessingImpl::WriteConfigMessage(bool forced) {
1874 audioproc::Config config;
1875
peahdf3efa82015-11-28 12:35:15 -08001876 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001877 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08001878 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001879 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08001880 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001881 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08001882 public_submodules_->echo_cancellation->is_extended_filter_enabled());
1883 config.set_aec_suppression_level(static_cast<int>(
1884 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02001885
peahdf3efa82015-11-28 12:35:15 -08001886 config.set_aecm_enabled(
1887 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02001888 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08001889 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
1890 config.set_aecm_routing_mode(static_cast<int>(
1891 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02001892
peahdf3efa82015-11-28 12:35:15 -08001893 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
1894 config.set_agc_mode(
1895 static_cast<int>(public_submodules_->gain_control->mode()));
1896 config.set_agc_limiter_enabled(
1897 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08001898 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02001899
peah8271d042016-11-22 07:24:52 -08001900 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001901
peahdf3efa82015-11-28 12:35:15 -08001902 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
1903 config.set_ns_level(
1904 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02001905
peahdf3efa82015-11-28 12:35:15 -08001906 config.set_transient_suppression_enabled(
1907 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001908 config.set_intelligibility_enhancer_enabled(
1909 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02001910
peah7789fe72016-04-15 01:19:44 -07001911 std::string experiments_description =
1912 public_submodules_->echo_cancellation->GetExperimentsDescription();
1913 // TODO(peah): Add semicolon-separated concatenations of experiment
1914 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07001915 if (capture_nonlocked_.level_controller_enabled) {
1916 experiments_description += "LevelController;";
1917 }
henrik.lundinbd681b92016-12-05 09:08:42 -08001918 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1919 experiments_description += "AgcClippingLevelExperiment;";
1920 }
peahe0eae3c2016-12-14 01:16:23 -08001921 if (capture_nonlocked_.echo_canceller3_enabled) {
1922 experiments_description += "EchoCanceller3;";
1923 }
peah7789fe72016-04-15 01:19:44 -07001924 config.set_experiments_description(experiments_description);
1925
Minyue13b96ba2015-10-03 00:39:14 +02001926 std::string serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08001927 if (!forced &&
1928 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02001929 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00001930 }
1931
peahdf3efa82015-11-28 12:35:15 -08001932 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02001933
peahdf3efa82015-11-28 12:35:15 -08001934 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
1935 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02001936
peahdf3efa82015-11-28 12:35:15 -08001937 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001938 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001939 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00001940 return kNoError;
1941}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001942#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001943
kwiberg83ffe452016-08-29 14:46:07 -07001944AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
1945 bool transient_suppressor_enabled,
1946 const std::vector<Point>& array_geometry,
1947 SphericalPointf target_direction)
1948 : aec_system_delay_jumps(-1),
1949 delay_offset_ms(0),
1950 was_stream_delay_set(false),
1951 last_stream_delay_ms(0),
1952 last_aec_system_delay_ms(0),
1953 stream_delay_jumps(-1),
1954 output_will_be_muted(false),
1955 key_pressed(false),
1956 transient_suppressor_enabled(transient_suppressor_enabled),
1957 array_geometry(array_geometry),
1958 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07001959 capture_processing_format(kSampleRate16kHz),
kwiberg83ffe452016-08-29 14:46:07 -07001960 split_rate(kSampleRate16kHz) {}
1961
1962AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
1963
1964AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
1965
1966AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
1967
niklase@google.com470e71d2011-07-07 08:21:25 +00001968} // namespace webrtc