blob: 922997e5c7cb8bd60312344ad4a0bccebdd83671 [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
peah103ac7e2017-04-12 05:40:55 -070013#include <math.h>
Michael Graczyk86c6d332015-07-23 11:41:39 -070014#include <algorithm>
alessiob3ec96df2017-05-22 06:57:06 -070015#include <string>
niklase@google.com470e71d2011-07-07 08:21:25 +000016
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020017#include "webrtc/base/checks.h"
nisse368f5cf2017-04-05 05:00:33 -070018#include "webrtc/base/logging.h"
xians@webrtc.orge46bc772014-10-10 08:36:56 +000019#include "webrtc/base/platform_file.h"
peah369f8282015-12-17 06:42:29 -080020#include "webrtc/base/trace_event.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070021#include "webrtc/common_audio/audio_converter.h"
Michael Graczykdfa36052015-03-25 16:37:27 -070022#include "webrtc/common_audio/channel_buffer.h"
ekmeyerson60d9b332015-08-14 10:35:55 -070023#include "webrtc/common_audio/include/audio_util.h"
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000024#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
Bjorn Volcker1ca324f2015-06-29 14:57:29 +020025#include "webrtc/modules/audio_processing/aec/aec_core.h"
peahe0eae3c2016-12-14 01:16:23 -080026#include "webrtc/modules/audio_processing/aec3/echo_canceller3.h"
alessiob3ec96df2017-05-22 06:57:06 -070027#include "webrtc/modules/audio_processing/agc2/gain_controller2.h"
pbos@webrtc.org788acd12014-12-15 09:41:24 +000028#include "webrtc/modules/audio_processing/agc/agc_manager_direct.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000029#include "webrtc/modules/audio_processing/audio_buffer.h"
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +000030#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000031#include "webrtc/modules/audio_processing/common.h"
andrew@webrtc.org56e4a052014-02-27 22:23:17 +000032#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000033#include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
peahbe615622016-02-13 16:40:47 -080034#include "webrtc/modules/audio_processing/gain_control_for_experimental_agc.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000035#include "webrtc/modules/audio_processing/gain_control_impl.h"
peah1bcfce52016-08-26 07:16:04 -070036#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -070037#include "webrtc/modules/audio_processing/intelligibility/intelligibility_enhancer.h"
peah1bcfce52016-08-26 07:16:04 -070038#endif
peahca4cac72016-06-29 15:26:12 -070039#include "webrtc/modules/audio_processing/level_controller/level_controller.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000040#include "webrtc/modules/audio_processing/level_estimator_impl.h"
peah8271d042016-11-22 07:24:52 -080041#include "webrtc/modules/audio_processing/low_cut_filter.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000042#include "webrtc/modules/audio_processing/noise_suppression_impl.h"
ivoc9f4a4a02016-10-28 05:39:16 -070043#include "webrtc/modules/audio_processing/residual_echo_detector.h"
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +000044#include "webrtc/modules/audio_processing/transient/transient_suppressor.h"
andrew@webrtc.org78693fe2013-03-01 16:36:19 +000045#include "webrtc/modules/audio_processing/voice_detection_impl.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010046#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010047#include "webrtc/system_wrappers/include/file_wrapper.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010048#include "webrtc/system_wrappers/include/metrics.h"
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000049
50#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
51// Files generated at build-time by the protobuf compiler.
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000052#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000053#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000054#else
kjellander78ddd732016-02-09 08:13:06 -080055#include "webrtc/modules/audio_processing/debug.pb.h"
leozwang@google.comce9bfbb2011-08-03 23:34:31 +000056#endif
andrew@webrtc.org7bf26462011-12-03 00:03:31 +000057#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +000058
peah1bcfce52016-08-26 07:16:04 -070059// Check to verify that the define for the intelligibility enhancer is properly
60// set.
61#if !defined(WEBRTC_INTELLIGIBILITY_ENHANCER) || \
62 (WEBRTC_INTELLIGIBILITY_ENHANCER != 0 && \
63 WEBRTC_INTELLIGIBILITY_ENHANCER != 1)
64#error "Set WEBRTC_INTELLIGIBILITY_ENHANCER to either 0 or 1"
65#endif
66
Michael Graczyk86c6d332015-07-23 11:41:39 -070067#define RETURN_ON_ERR(expr) \
68 do { \
69 int err = (expr); \
70 if (err != kNoError) { \
71 return err; \
72 } \
andrew@webrtc.org60730cf2014-01-07 17:45:09 +000073 } while (0)
74
niklase@google.com470e71d2011-07-07 08:21:25 +000075namespace webrtc {
aluebsdf6416a2016-03-16 18:26:35 -070076
kwibergd59d3bb2016-09-13 07:49:33 -070077constexpr int AudioProcessing::kNativeSampleRatesHz[];
aluebsdf6416a2016-03-16 18:26:35 -070078
Michael Graczyk86c6d332015-07-23 11:41:39 -070079namespace {
80
81static bool LayoutHasKeyboard(AudioProcessing::ChannelLayout layout) {
82 switch (layout) {
83 case AudioProcessing::kMono:
84 case AudioProcessing::kStereo:
85 return false;
86 case AudioProcessing::kMonoAndKeyboard:
87 case AudioProcessing::kStereoAndKeyboard:
88 return true;
89 }
90
kwiberg9e2be5f2016-09-14 05:23:22 -070091 RTC_NOTREACHED();
Michael Graczyk86c6d332015-07-23 11:41:39 -070092 return false;
93}
aluebsdf6416a2016-03-16 18:26:35 -070094
peah2ace3f92016-09-10 04:42:27 -070095bool SampleRateSupportsMultiBand(int sample_rate_hz) {
aluebsdf6416a2016-03-16 18:26:35 -070096 return sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
97 sample_rate_hz == AudioProcessing::kSampleRate48kHz;
98}
99
peah2ace3f92016-09-10 04:42:27 -0700100int FindNativeProcessRateToUse(int minimum_rate, bool band_splitting_required) {
101#ifdef WEBRTC_ARCH_ARM_FAMILY
kwibergd59d3bb2016-09-13 07:49:33 -0700102 constexpr int kMaxSplittingNativeProcessRate =
103 AudioProcessing::kSampleRate32kHz;
peah2ace3f92016-09-10 04:42:27 -0700104#else
kwibergd59d3bb2016-09-13 07:49:33 -0700105 constexpr int kMaxSplittingNativeProcessRate =
106 AudioProcessing::kSampleRate48kHz;
peah2ace3f92016-09-10 04:42:27 -0700107#endif
kwibergd59d3bb2016-09-13 07:49:33 -0700108 static_assert(
109 kMaxSplittingNativeProcessRate <= AudioProcessing::kMaxNativeSampleRateHz,
110 "");
peah2ace3f92016-09-10 04:42:27 -0700111 const int uppermost_native_rate = band_splitting_required
112 ? kMaxSplittingNativeProcessRate
113 : AudioProcessing::kSampleRate48kHz;
114
115 for (auto rate : AudioProcessing::kNativeSampleRatesHz) {
116 if (rate >= uppermost_native_rate) {
117 return uppermost_native_rate;
118 }
119 if (rate >= minimum_rate) {
aluebsdf6416a2016-03-16 18:26:35 -0700120 return rate;
121 }
122 }
peah2ace3f92016-09-10 04:42:27 -0700123 RTC_NOTREACHED();
124 return uppermost_native_rate;
aluebsdf6416a2016-03-16 18:26:35 -0700125}
126
peah9e6a2902017-05-15 07:19:21 -0700127// Maximum lengths that frame of samples being passed from the render side to
128// the capture side can have (does not apply to AEC3).
129static const size_t kMaxAllowedValuesOfSamplesPerBand = 160;
130static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480;
131
peah764e3642016-10-22 05:04:30 -0700132// Maximum number of frames to buffer in the render queue.
133// TODO(peah): Decrease this once we properly handle hugely unbalanced
134// reverse and forward call numbers.
135static const size_t kMaxNumFramesToBuffer = 100;
136
peah8271d042016-11-22 07:24:52 -0800137class HighPassFilterImpl : public HighPassFilter {
138 public:
139 explicit HighPassFilterImpl(AudioProcessingImpl* apm) : apm_(apm) {}
140 ~HighPassFilterImpl() override = default;
141
142 // HighPassFilter implementation.
143 int Enable(bool enable) override {
144 apm_->MutateConfig([enable](AudioProcessing::Config* config) {
145 config->high_pass_filter.enabled = enable;
146 });
147
148 return AudioProcessing::kNoError;
149 }
150
151 bool is_enabled() const override {
152 return apm_->GetConfig().high_pass_filter.enabled;
153 }
154
155 private:
156 AudioProcessingImpl* apm_;
157 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(HighPassFilterImpl);
158};
159
aleloi868f32f2017-05-23 07:20:05 -0700160webrtc::InternalAPMStreamsConfig ToStreamsConfig(
161 const ProcessingConfig& api_format) {
162 webrtc::InternalAPMStreamsConfig result;
163 result.input_sample_rate = api_format.input_stream().sample_rate_hz();
164 result.input_num_channels = api_format.input_stream().num_channels();
165 result.output_num_channels = api_format.output_stream().num_channels();
166 result.render_input_num_channels =
167 api_format.reverse_input_stream().num_channels();
168 result.render_input_sample_rate =
169 api_format.reverse_input_stream().sample_rate_hz();
170 result.output_sample_rate = api_format.output_stream().sample_rate_hz();
171 result.render_output_sample_rate =
172 api_format.reverse_output_stream().sample_rate_hz();
173 result.render_output_num_channels =
174 api_format.reverse_output_stream().num_channels();
175 return result;
176}
Michael Graczyk86c6d332015-07-23 11:41:39 -0700177} // namespace
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000178
179// Throughout webrtc, it's assumed that success is represented by zero.
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +0000180static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000181
peah2ace3f92016-09-10 04:42:27 -0700182AudioProcessingImpl::ApmSubmoduleStates::ApmSubmoduleStates() {}
183
184bool AudioProcessingImpl::ApmSubmoduleStates::Update(
peah8271d042016-11-22 07:24:52 -0800185 bool low_cut_filter_enabled,
peah2ace3f92016-09-10 04:42:27 -0700186 bool echo_canceller_enabled,
187 bool mobile_echo_controller_enabled,
ivoc9f4a4a02016-10-28 05:39:16 -0700188 bool residual_echo_detector_enabled,
peah2ace3f92016-09-10 04:42:27 -0700189 bool noise_suppressor_enabled,
190 bool intelligibility_enhancer_enabled,
191 bool beamformer_enabled,
192 bool adaptive_gain_controller_enabled,
alessiob3ec96df2017-05-22 06:57:06 -0700193 bool gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -0700194 bool level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -0800195 bool echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -0700196 bool voice_activity_detector_enabled,
197 bool level_estimator_enabled,
198 bool transient_suppressor_enabled) {
199 bool changed = false;
peah8271d042016-11-22 07:24:52 -0800200 changed |= (low_cut_filter_enabled != low_cut_filter_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700201 changed |= (echo_canceller_enabled != echo_canceller_enabled_);
202 changed |=
203 (mobile_echo_controller_enabled != mobile_echo_controller_enabled_);
ivoc9f4a4a02016-10-28 05:39:16 -0700204 changed |=
205 (residual_echo_detector_enabled != residual_echo_detector_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700206 changed |= (noise_suppressor_enabled != noise_suppressor_enabled_);
207 changed |=
208 (intelligibility_enhancer_enabled != intelligibility_enhancer_enabled_);
209 changed |= (beamformer_enabled != beamformer_enabled_);
210 changed |=
211 (adaptive_gain_controller_enabled != adaptive_gain_controller_enabled_);
alessiob3ec96df2017-05-22 06:57:06 -0700212 changed |=
213 (gain_controller2_enabled != gain_controller2_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700214 changed |= (level_controller_enabled != level_controller_enabled_);
peahe0eae3c2016-12-14 01:16:23 -0800215 changed |= (echo_canceller3_enabled != echo_canceller3_enabled_);
peah2ace3f92016-09-10 04:42:27 -0700216 changed |= (level_estimator_enabled != level_estimator_enabled_);
217 changed |=
218 (voice_activity_detector_enabled != voice_activity_detector_enabled_);
219 changed |= (transient_suppressor_enabled != transient_suppressor_enabled_);
220 if (changed) {
peah8271d042016-11-22 07:24:52 -0800221 low_cut_filter_enabled_ = low_cut_filter_enabled;
peah2ace3f92016-09-10 04:42:27 -0700222 echo_canceller_enabled_ = echo_canceller_enabled;
223 mobile_echo_controller_enabled_ = mobile_echo_controller_enabled;
ivoc9f4a4a02016-10-28 05:39:16 -0700224 residual_echo_detector_enabled_ = residual_echo_detector_enabled;
peah2ace3f92016-09-10 04:42:27 -0700225 noise_suppressor_enabled_ = noise_suppressor_enabled;
226 intelligibility_enhancer_enabled_ = intelligibility_enhancer_enabled;
227 beamformer_enabled_ = beamformer_enabled;
228 adaptive_gain_controller_enabled_ = adaptive_gain_controller_enabled;
alessiob3ec96df2017-05-22 06:57:06 -0700229 gain_controller2_enabled_ = gain_controller2_enabled;
peah2ace3f92016-09-10 04:42:27 -0700230 level_controller_enabled_ = level_controller_enabled;
peahe0eae3c2016-12-14 01:16:23 -0800231 echo_canceller3_enabled_ = echo_canceller3_enabled;
peah2ace3f92016-09-10 04:42:27 -0700232 level_estimator_enabled_ = level_estimator_enabled;
233 voice_activity_detector_enabled_ = voice_activity_detector_enabled;
234 transient_suppressor_enabled_ = transient_suppressor_enabled;
235 }
236
237 changed |= first_update_;
238 first_update_ = false;
239 return changed;
240}
241
242bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandSubModulesActive()
243 const {
244#if WEBRTC_INTELLIGIBILITY_ENHANCER
245 return CaptureMultiBandProcessingActive() ||
peah52775842017-05-16 06:14:09 -0700246 intelligibility_enhancer_enabled_ || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700247#else
peah52775842017-05-16 06:14:09 -0700248 return CaptureMultiBandProcessingActive() || voice_activity_detector_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700249#endif
250}
251
252bool AudioProcessingImpl::ApmSubmoduleStates::CaptureMultiBandProcessingActive()
253 const {
peah8271d042016-11-22 07:24:52 -0800254 return low_cut_filter_enabled_ || echo_canceller_enabled_ ||
peah2ace3f92016-09-10 04:42:27 -0700255 mobile_echo_controller_enabled_ || noise_suppressor_enabled_ ||
peahe0eae3c2016-12-14 01:16:23 -0800256 beamformer_enabled_ || adaptive_gain_controller_enabled_ ||
257 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700258}
259
peah23ac8b42017-05-23 05:33:56 -0700260bool AudioProcessingImpl::ApmSubmoduleStates::CaptureFullBandProcessingActive()
261 const {
262 return level_controller_enabled_;
263}
264
peah2ace3f92016-09-10 04:42:27 -0700265bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandSubModulesActive()
266 const {
267 return RenderMultiBandProcessingActive() || echo_canceller_enabled_ ||
ivoc20270be2016-11-15 05:24:35 -0800268 mobile_echo_controller_enabled_ || adaptive_gain_controller_enabled_ ||
peah52775842017-05-16 06:14:09 -0700269 echo_canceller3_enabled_;
peah2ace3f92016-09-10 04:42:27 -0700270}
271
272bool AudioProcessingImpl::ApmSubmoduleStates::RenderMultiBandProcessingActive()
273 const {
274#if WEBRTC_INTELLIGIBILITY_ENHANCER
275 return intelligibility_enhancer_enabled_;
276#else
277 return false;
278#endif
279}
280
solenberg5e465c32015-12-08 13:22:33 -0800281struct AudioProcessingImpl::ApmPublicSubmodules {
peahbfa97112016-03-10 21:09:04 -0800282 ApmPublicSubmodules() {}
solenberg5e465c32015-12-08 13:22:33 -0800283 // Accessed externally of APM without any lock acquired.
peahb624d8c2016-03-05 03:01:14 -0800284 std::unique_ptr<EchoCancellationImpl> echo_cancellation;
peahbb9edbd2016-03-10 12:54:25 -0800285 std::unique_ptr<EchoControlMobileImpl> echo_control_mobile;
peahbfa97112016-03-10 21:09:04 -0800286 std::unique_ptr<GainControlImpl> gain_control;
kwiberg88788ad2016-02-19 07:04:49 -0800287 std::unique_ptr<LevelEstimatorImpl> level_estimator;
288 std::unique_ptr<NoiseSuppressionImpl> noise_suppression;
289 std::unique_ptr<VoiceDetectionImpl> voice_detection;
290 std::unique_ptr<GainControlForExperimentalAgc>
peahbe615622016-02-13 16:40:47 -0800291 gain_control_for_experimental_agc;
solenberg5e465c32015-12-08 13:22:33 -0800292
293 // Accessed internally from both render and capture.
kwiberg88788ad2016-02-19 07:04:49 -0800294 std::unique_ptr<TransientSuppressor> transient_suppressor;
peah1bcfce52016-08-26 07:16:04 -0700295#if WEBRTC_INTELLIGIBILITY_ENHANCER
kwiberg88788ad2016-02-19 07:04:49 -0800296 std::unique_ptr<IntelligibilityEnhancer> intelligibility_enhancer;
peah1bcfce52016-08-26 07:16:04 -0700297#endif
solenberg5e465c32015-12-08 13:22:33 -0800298};
299
300struct AudioProcessingImpl::ApmPrivateSubmodules {
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700301 explicit ApmPrivateSubmodules(NonlinearBeamformer* beamformer)
solenberg5e465c32015-12-08 13:22:33 -0800302 : beamformer(beamformer) {}
303 // Accessed internally from capture or during initialization
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700304 std::unique_ptr<NonlinearBeamformer> beamformer;
kwiberg88788ad2016-02-19 07:04:49 -0800305 std::unique_ptr<AgcManagerDirect> agc_manager;
alessiob3ec96df2017-05-22 06:57:06 -0700306 std::unique_ptr<GainController2> gain_controller2;
peah8271d042016-11-22 07:24:52 -0800307 std::unique_ptr<LowCutFilter> low_cut_filter;
peahca4cac72016-06-29 15:26:12 -0700308 std::unique_ptr<LevelController> level_controller;
ivoc9f4a4a02016-10-28 05:39:16 -0700309 std::unique_ptr<ResidualEchoDetector> residual_echo_detector;
peahe0eae3c2016-12-14 01:16:23 -0800310 std::unique_ptr<EchoCanceller3> echo_canceller3;
solenberg5e465c32015-12-08 13:22:33 -0800311};
312
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000313AudioProcessing* AudioProcessing::Create() {
peah88ac8532016-09-12 16:47:25 -0700314 webrtc::Config config;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000315 return Create(config, nullptr);
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000316}
317
peah88ac8532016-09-12 16:47:25 -0700318AudioProcessing* AudioProcessing::Create(const webrtc::Config& config) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000319 return Create(config, nullptr);
320}
321
peah88ac8532016-09-12 16:47:25 -0700322AudioProcessing* AudioProcessing::Create(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700323 NonlinearBeamformer* beamformer) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000324 AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer);
niklase@google.com470e71d2011-07-07 08:21:25 +0000325 if (apm->Initialize() != kNoError) {
326 delete apm;
peahdf3efa82015-11-28 12:35:15 -0800327 apm = nullptr;
niklase@google.com470e71d2011-07-07 08:21:25 +0000328 }
329
330 return apm;
331}
332
peah88ac8532016-09-12 16:47:25 -0700333AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config)
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000334 : AudioProcessingImpl(config, nullptr) {}
335
peah88ac8532016-09-12 16:47:25 -0700336AudioProcessingImpl::AudioProcessingImpl(const webrtc::Config& config,
Alejandro Luebsf4022ff2016-07-01 17:19:09 -0700337 NonlinearBeamformer* beamformer)
peah8271d042016-11-22 07:24:52 -0800338 : high_pass_filter_impl_(new HighPassFilterImpl(this)),
339 public_submodules_(new ApmPublicSubmodules()),
peahdf3efa82015-11-28 12:35:15 -0800340 private_submodules_(new ApmPrivateSubmodules(beamformer)),
341 constants_(config.Get<ExperimentalAgc>().startup_min_volume,
henrik.lundinbd681b92016-12-05 09:08:42 -0800342 config.Get<ExperimentalAgc>().clipped_level_min,
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000343#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700344 false),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000345#else
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700346 config.Get<ExperimentalAgc>().enabled),
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000347#endif
andrew1c7075f2015-06-24 18:14:14 -0700348#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
aluebs2a346882016-01-11 18:04:30 -0800349 capture_(false,
andrew1c7075f2015-06-24 18:14:14 -0700350#else
aluebs2a346882016-01-11 18:04:30 -0800351 capture_(config.Get<ExperimentalNs>().enabled,
andrew1c7075f2015-06-24 18:14:14 -0700352#endif
aluebs2a346882016-01-11 18:04:30 -0800353 config.Get<Beamforming>().array_geometry,
aluebsb2328d12016-01-11 20:32:29 -0800354 config.Get<Beamforming>().target_direction),
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700355 capture_nonlocked_(config.Get<Beamforming>().enabled,
peah88ac8532016-09-12 16:47:25 -0700356 config.Get<Intelligibility>().enabled) {
peahdf3efa82015-11-28 12:35:15 -0800357 {
358 rtc::CritScope cs_render(&crit_render_);
359 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000360
peahb624d8c2016-03-05 03:01:14 -0800361 public_submodules_->echo_cancellation.reset(
peahb58a1582016-03-15 09:34:24 -0700362 new EchoCancellationImpl(&crit_render_, &crit_capture_));
peahbb9edbd2016-03-10 12:54:25 -0800363 public_submodules_->echo_control_mobile.reset(
peah253534d2016-03-15 04:32:28 -0700364 new EchoControlMobileImpl(&crit_render_, &crit_capture_));
peahbfa97112016-03-10 21:09:04 -0800365 public_submodules_->gain_control.reset(
peahb8fbb542016-03-15 02:28:08 -0700366 new GainControlImpl(&crit_capture_, &crit_capture_));
solenberg949028f2015-12-15 11:39:38 -0800367 public_submodules_->level_estimator.reset(
368 new LevelEstimatorImpl(&crit_capture_));
solenberg5e465c32015-12-08 13:22:33 -0800369 public_submodules_->noise_suppression.reset(
370 new NoiseSuppressionImpl(&crit_capture_));
solenberga29386c2015-12-16 03:31:12 -0800371 public_submodules_->voice_detection.reset(
372 new VoiceDetectionImpl(&crit_capture_));
peahbe615622016-02-13 16:40:47 -0800373 public_submodules_->gain_control_for_experimental_agc.reset(
peahbfa97112016-03-10 21:09:04 -0800374 new GainControlForExperimentalAgc(
375 public_submodules_->gain_control.get(), &crit_capture_));
ivoc9f4a4a02016-10-28 05:39:16 -0700376 private_submodules_->residual_echo_detector.reset(
377 new ResidualEchoDetector());
peahca4cac72016-06-29 15:26:12 -0700378
peahc19f3122016-10-07 14:54:10 -0700379 // TODO(peah): Move this creation to happen only when the level controller
380 // is enabled.
peahca4cac72016-06-29 15:26:12 -0700381 private_submodules_->level_controller.reset(new LevelController());
peahdf3efa82015-11-28 12:35:15 -0800382 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000383
andrew@webrtc.orge84978f2014-01-25 02:09:06 +0000384 SetExtraOptions(config);
niklase@google.com470e71d2011-07-07 08:21:25 +0000385}
386
387AudioProcessingImpl::~AudioProcessingImpl() {
peahdf3efa82015-11-28 12:35:15 -0800388 // Depends on gain_control_ and
peahbe615622016-02-13 16:40:47 -0800389 // public_submodules_->gain_control_for_experimental_agc.
peahdf3efa82015-11-28 12:35:15 -0800390 private_submodules_->agc_manager.reset();
391 // Depends on gain_control_.
peahbe615622016-02-13 16:40:47 -0800392 public_submodules_->gain_control_for_experimental_agc.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000393
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000394#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700395 debug_dump_.debug_file->CloseFile();
peahdf3efa82015-11-28 12:35:15 -0800396#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000397}
398
niklase@google.com470e71d2011-07-07 08:21:25 +0000399int AudioProcessingImpl::Initialize() {
peahdf3efa82015-11-28 12:35:15 -0800400 // Run in a single-threaded manner during initialization.
401 rtc::CritScope cs_render(&crit_render_);
402 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000403 return InitializeLocked();
404}
405
peahde65ddc2016-09-16 15:02:15 -0700406int AudioProcessingImpl::Initialize(int capture_input_sample_rate_hz,
407 int capture_output_sample_rate_hz,
408 int render_input_sample_rate_hz,
409 ChannelLayout capture_input_layout,
410 ChannelLayout capture_output_layout,
411 ChannelLayout render_input_layout) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700412 const ProcessingConfig processing_config = {
peahde65ddc2016-09-16 15:02:15 -0700413 {{capture_input_sample_rate_hz, ChannelsFromLayout(capture_input_layout),
414 LayoutHasKeyboard(capture_input_layout)},
415 {capture_output_sample_rate_hz,
416 ChannelsFromLayout(capture_output_layout),
417 LayoutHasKeyboard(capture_output_layout)},
418 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
419 LayoutHasKeyboard(render_input_layout)},
420 {render_input_sample_rate_hz, ChannelsFromLayout(render_input_layout),
421 LayoutHasKeyboard(render_input_layout)}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700422
423 return Initialize(processing_config);
424}
425
426int AudioProcessingImpl::Initialize(const ProcessingConfig& processing_config) {
peahdf3efa82015-11-28 12:35:15 -0800427 // Run in a single-threaded manner during initialization.
428 rtc::CritScope cs_render(&crit_render_);
429 rtc::CritScope cs_capture(&crit_capture_);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700430 return InitializeLocked(processing_config);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000431}
432
peahdf3efa82015-11-28 12:35:15 -0800433int AudioProcessingImpl::MaybeInitializeRender(
peah81b9bfe2015-11-27 02:47:28 -0800434 const ProcessingConfig& processing_config) {
peah2ace3f92016-09-10 04:42:27 -0700435 return MaybeInitialize(processing_config, false);
peah81b9bfe2015-11-27 02:47:28 -0800436}
437
peahdf3efa82015-11-28 12:35:15 -0800438int AudioProcessingImpl::MaybeInitializeCapture(
peah2ace3f92016-09-10 04:42:27 -0700439 const ProcessingConfig& processing_config,
440 bool force_initialization) {
441 return MaybeInitialize(processing_config, force_initialization);
peah81b9bfe2015-11-27 02:47:28 -0800442}
443
kwiberg83ffe452016-08-29 14:46:07 -0700444#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
445
446AudioProcessingImpl::ApmDebugDumpThreadState::ApmDebugDumpThreadState()
447 : event_msg(new audioproc::Event()) {}
448
449AudioProcessingImpl::ApmDebugDumpThreadState::~ApmDebugDumpThreadState() {}
450
451AudioProcessingImpl::ApmDebugDumpState::ApmDebugDumpState()
452 : debug_file(FileWrapper::Create()) {}
453
454AudioProcessingImpl::ApmDebugDumpState::~ApmDebugDumpState() {}
455
456#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
457
peah192164e2015-11-17 02:16:45 -0800458// Calls InitializeLocked() if any of the audio parameters have changed from
peahdf3efa82015-11-28 12:35:15 -0800459// their current values (needs to be called while holding the crit_render_lock).
460int AudioProcessingImpl::MaybeInitialize(
peah2ace3f92016-09-10 04:42:27 -0700461 const ProcessingConfig& processing_config,
462 bool force_initialization) {
peahdf3efa82015-11-28 12:35:15 -0800463 // Called from both threads. Thread check is therefore not possible.
peah2ace3f92016-09-10 04:42:27 -0700464 if (processing_config == formats_.api_format && !force_initialization) {
peah192164e2015-11-17 02:16:45 -0800465 return kNoError;
466 }
peahdf3efa82015-11-28 12:35:15 -0800467
468 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -0800469 return InitializeLocked(processing_config);
470}
471
niklase@google.com470e71d2011-07-07 08:21:25 +0000472int AudioProcessingImpl::InitializeLocked() {
peah522d71b2017-02-23 05:16:26 -0800473 const int capture_audiobuffer_num_channels =
474 capture_nonlocked_.beamformer_enabled
475 ? formats_.api_format.input_stream().num_channels()
476 : formats_.api_format.output_stream().num_channels();
477
peahde65ddc2016-09-16 15:02:15 -0700478 const int render_audiobuffer_num_output_frames =
peahdf3efa82015-11-28 12:35:15 -0800479 formats_.api_format.reverse_output_stream().num_frames() == 0
peahde65ddc2016-09-16 15:02:15 -0700480 ? formats_.render_processing_format.num_frames()
peahdf3efa82015-11-28 12:35:15 -0800481 : formats_.api_format.reverse_output_stream().num_frames();
482 if (formats_.api_format.reverse_input_stream().num_channels() > 0) {
483 render_.render_audio.reset(new AudioBuffer(
484 formats_.api_format.reverse_input_stream().num_frames(),
485 formats_.api_format.reverse_input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700486 formats_.render_processing_format.num_frames(),
487 formats_.render_processing_format.num_channels(),
488 render_audiobuffer_num_output_frames));
peah2ace3f92016-09-10 04:42:27 -0700489 if (formats_.api_format.reverse_input_stream() !=
490 formats_.api_format.reverse_output_stream()) {
kwibergc2b785d2016-02-24 05:22:32 -0800491 render_.render_converter = AudioConverter::Create(
peahdf3efa82015-11-28 12:35:15 -0800492 formats_.api_format.reverse_input_stream().num_channels(),
493 formats_.api_format.reverse_input_stream().num_frames(),
494 formats_.api_format.reverse_output_stream().num_channels(),
kwibergc2b785d2016-02-24 05:22:32 -0800495 formats_.api_format.reverse_output_stream().num_frames());
ekmeyerson60d9b332015-08-14 10:35:55 -0700496 } else {
peahdf3efa82015-11-28 12:35:15 -0800497 render_.render_converter.reset(nullptr);
ekmeyerson60d9b332015-08-14 10:35:55 -0700498 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700499 } else {
peahdf3efa82015-11-28 12:35:15 -0800500 render_.render_audio.reset(nullptr);
501 render_.render_converter.reset(nullptr);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700502 }
peahce4d9152017-05-19 01:28:05 -0700503
peahdf3efa82015-11-28 12:35:15 -0800504 capture_.capture_audio.reset(
505 new AudioBuffer(formats_.api_format.input_stream().num_frames(),
506 formats_.api_format.input_stream().num_channels(),
peahde65ddc2016-09-16 15:02:15 -0700507 capture_nonlocked_.capture_processing_format.num_frames(),
508 capture_audiobuffer_num_channels,
peahdf3efa82015-11-28 12:35:15 -0800509 formats_.api_format.output_stream().num_frames()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000510
peahde65ddc2016-09-16 15:02:15 -0700511 public_submodules_->echo_cancellation->Initialize(
512 proc_sample_rate_hz(), num_reverse_channels(), num_output_channels(),
513 num_proc_channels());
peah764e3642016-10-22 05:04:30 -0700514 AllocateRenderQueue();
515
ivoc3e9a5372016-10-28 07:55:33 -0700516 int success = public_submodules_->echo_cancellation->enable_metrics(true);
517 RTC_DCHECK_EQ(0, success);
518 success = public_submodules_->echo_cancellation->enable_delay_logging(true);
519 RTC_DCHECK_EQ(0, success);
peahde65ddc2016-09-16 15:02:15 -0700520 public_submodules_->echo_control_mobile->Initialize(
521 proc_split_sample_rate_hz(), num_reverse_channels(),
522 num_output_channels());
peah135259a2016-10-28 03:12:11 -0700523
524 public_submodules_->gain_control->Initialize(num_proc_channels(),
525 proc_sample_rate_hz());
peahde65ddc2016-09-16 15:02:15 -0700526 if (constants_.use_experimental_agc) {
527 if (!private_submodules_->agc_manager.get()) {
528 private_submodules_->agc_manager.reset(new AgcManagerDirect(
529 public_submodules_->gain_control.get(),
530 public_submodules_->gain_control_for_experimental_agc.get(),
henrik.lundinbd681b92016-12-05 09:08:42 -0800531 constants_.agc_startup_min_volume, constants_.agc_clipped_level_min));
peahde65ddc2016-09-16 15:02:15 -0700532 }
533 private_submodules_->agc_manager->Initialize();
534 private_submodules_->agc_manager->SetCaptureMuted(
535 capture_.output_will_be_muted);
peah135259a2016-10-28 03:12:11 -0700536 public_submodules_->gain_control_for_experimental_agc->Initialize();
peahde65ddc2016-09-16 15:02:15 -0700537 }
Bjorn Volckeradc46c42015-04-15 11:42:40 +0200538 InitializeTransient();
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +0000539 InitializeBeamformer();
peah1bcfce52016-08-26 07:16:04 -0700540#if WEBRTC_INTELLIGIBILITY_ENHANCER
ekmeyerson60d9b332015-08-14 10:35:55 -0700541 InitializeIntelligibility();
peah1bcfce52016-08-26 07:16:04 -0700542#endif
peah8271d042016-11-22 07:24:52 -0800543 InitializeLowCutFilter();
peahde65ddc2016-09-16 15:02:15 -0700544 public_submodules_->noise_suppression->Initialize(num_proc_channels(),
545 proc_sample_rate_hz());
546 public_submodules_->voice_detection->Initialize(proc_split_sample_rate_hz());
547 public_submodules_->level_estimator->Initialize();
peahca4cac72016-06-29 15:26:12 -0700548 InitializeLevelController();
ivoc9f4a4a02016-10-28 05:39:16 -0700549 InitializeResidualEchoDetector();
peahe0eae3c2016-12-14 01:16:23 -0800550 InitializeEchoCanceller3();
alessiob3ec96df2017-05-22 06:57:06 -0700551 InitializeGainController2();
solenberg70f99032015-12-08 11:07:32 -0800552
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000553#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700554 if (debug_dump_.debug_file->is_open()) {
ajm@google.com808e0e02011-08-03 21:08:51 +0000555 int err = WriteInitMessage();
556 if (err != kNoError) {
557 return err;
558 }
559 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +0000560#endif
aleloi868f32f2017-05-23 07:20:05 -0700561 if (aec_dump_) {
562 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
563 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000564 return kNoError;
565}
566
Michael Graczyk86c6d332015-07-23 11:41:39 -0700567int AudioProcessingImpl::InitializeLocked(const ProcessingConfig& config) {
568 for (const auto& stream : config.streams) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700569 if (stream.num_channels() > 0 && stream.sample_rate_hz() <= 0) {
570 return kBadSampleRateError;
571 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000572 }
Michael Graczyk86c6d332015-07-23 11:41:39 -0700573
Peter Kasting69558702016-01-12 16:26:35 -0800574 const size_t num_in_channels = config.input_stream().num_channels();
575 const size_t num_out_channels = config.output_stream().num_channels();
Michael Graczyk86c6d332015-07-23 11:41:39 -0700576
577 // Need at least one input channel.
578 // Need either one output channel or as many outputs as there are inputs.
579 if (num_in_channels == 0 ||
580 !(num_out_channels == 1 || num_out_channels == num_in_channels)) {
Michael Graczykc2047542015-07-22 21:06:11 -0700581 return kBadNumberChannelsError;
582 }
583
aluebsb2328d12016-01-11 20:32:29 -0800584 if (capture_nonlocked_.beamformer_enabled &&
Peter Kasting69558702016-01-12 16:26:35 -0800585 num_in_channels != capture_.array_geometry.size()) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700586 return kBadNumberChannelsError;
587 }
588
peahdf3efa82015-11-28 12:35:15 -0800589 formats_.api_format = config;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000590
peahde65ddc2016-09-16 15:02:15 -0700591 int capture_processing_rate = FindNativeProcessRateToUse(
peah423d2362016-04-09 16:06:52 -0700592 std::min(formats_.api_format.input_stream().sample_rate_hz(),
peah2ace3f92016-09-10 04:42:27 -0700593 formats_.api_format.output_stream().sample_rate_hz()),
594 submodule_states_.CaptureMultiBandSubModulesActive() ||
595 submodule_states_.RenderMultiBandSubModulesActive());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000596
peahde65ddc2016-09-16 15:02:15 -0700597 capture_nonlocked_.capture_processing_format =
598 StreamConfig(capture_processing_rate);
peah2ace3f92016-09-10 04:42:27 -0700599
peah2ce640f2017-04-07 03:57:48 -0700600 int render_processing_rate;
601 if (!config_.echo_canceller3.enabled) {
602 render_processing_rate = FindNativeProcessRateToUse(
603 std::min(formats_.api_format.reverse_input_stream().sample_rate_hz(),
604 formats_.api_format.reverse_output_stream().sample_rate_hz()),
605 submodule_states_.CaptureMultiBandSubModulesActive() ||
606 submodule_states_.RenderMultiBandSubModulesActive());
607 } else {
608 render_processing_rate = capture_processing_rate;
609 }
610
aluebseb3603b2016-04-20 15:27:58 -0700611 // TODO(aluebs): Remove this restriction once we figure out why the 3-band
612 // splitting filter degrades the AEC performance.
peahcf02cf12017-04-05 14:18:07 -0700613 if (render_processing_rate > kSampleRate32kHz &&
614 !config_.echo_canceller3.enabled) {
peahde65ddc2016-09-16 15:02:15 -0700615 render_processing_rate = submodule_states_.RenderMultiBandProcessingActive()
616 ? kSampleRate32kHz
617 : kSampleRate16kHz;
aluebseb3603b2016-04-20 15:27:58 -0700618 }
peah2ce640f2017-04-07 03:57:48 -0700619
peahde65ddc2016-09-16 15:02:15 -0700620 // If the forward sample rate is 8 kHz, the render stream is also processed
aluebseb3603b2016-04-20 15:27:58 -0700621 // at this rate.
peahde65ddc2016-09-16 15:02:15 -0700622 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
623 kSampleRate8kHz) {
624 render_processing_rate = kSampleRate8kHz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000625 } else {
peahde65ddc2016-09-16 15:02:15 -0700626 render_processing_rate =
627 std::max(render_processing_rate, static_cast<int>(kSampleRate16kHz));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000628 }
629
peahde65ddc2016-09-16 15:02:15 -0700630 // Always downmix the render stream to mono for analysis. This has been
andrew@webrtc.org30be8272014-09-24 20:06:23 +0000631 // demonstrated to work well for AEC in most practical scenarios.
peahce4d9152017-05-19 01:28:05 -0700632 if (submodule_states_.RenderMultiBandSubModulesActive()) {
633 formats_.render_processing_format = StreamConfig(render_processing_rate, 1);
634 } else {
635 formats_.render_processing_format = StreamConfig(
636 formats_.api_format.reverse_input_stream().sample_rate_hz(),
637 formats_.api_format.reverse_input_stream().num_channels());
638 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000639
peahde65ddc2016-09-16 15:02:15 -0700640 if (capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
641 kSampleRate32kHz ||
642 capture_nonlocked_.capture_processing_format.sample_rate_hz() ==
643 kSampleRate48kHz) {
peahdf3efa82015-11-28 12:35:15 -0800644 capture_nonlocked_.split_rate = kSampleRate16kHz;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000645 } else {
peahdf3efa82015-11-28 12:35:15 -0800646 capture_nonlocked_.split_rate =
peahde65ddc2016-09-16 15:02:15 -0700647 capture_nonlocked_.capture_processing_format.sample_rate_hz();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000648 }
649
650 return InitializeLocked();
651}
652
peah88ac8532016-09-12 16:47:25 -0700653void AudioProcessingImpl::ApplyConfig(const AudioProcessing::Config& config) {
peahc19f3122016-10-07 14:54:10 -0700654 config_ = config;
peah88ac8532016-09-12 16:47:25 -0700655
peahc19f3122016-10-07 14:54:10 -0700656 bool config_ok = LevelController::Validate(config_.level_controller);
peah88ac8532016-09-12 16:47:25 -0700657 if (!config_ok) {
658 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
659 << "level_controller: "
peahc19f3122016-10-07 14:54:10 -0700660 << LevelController::ToString(config_.level_controller)
peah88ac8532016-09-12 16:47:25 -0700661 << std::endl
662 << "Reverting to default parameter set";
peahc19f3122016-10-07 14:54:10 -0700663 config_.level_controller = AudioProcessing::Config::LevelController();
peah88ac8532016-09-12 16:47:25 -0700664 }
665
666 // Run in a single-threaded manner when applying the settings.
667 rtc::CritScope cs_render(&crit_render_);
668 rtc::CritScope cs_capture(&crit_capture_);
669
peahc19f3122016-10-07 14:54:10 -0700670 // TODO(peah): Replace the use of capture_nonlocked_.level_controller_enabled
671 // with the value in config_ everywhere in the code.
672 if (capture_nonlocked_.level_controller_enabled !=
673 config_.level_controller.enabled) {
peah88ac8532016-09-12 16:47:25 -0700674 capture_nonlocked_.level_controller_enabled =
peahc19f3122016-10-07 14:54:10 -0700675 config_.level_controller.enabled;
676 // TODO(peah): Remove the conditional initialization to always initialize
677 // the level controller regardless of whether it is enabled or not.
678 InitializeLevelController();
peah88ac8532016-09-12 16:47:25 -0700679 }
peahc19f3122016-10-07 14:54:10 -0700680 LOG(LS_INFO) << "Level controller activated: "
681 << capture_nonlocked_.level_controller_enabled;
682
683 private_submodules_->level_controller->ApplyConfig(config_.level_controller);
peah8271d042016-11-22 07:24:52 -0800684
685 InitializeLowCutFilter();
686
687 LOG(LS_INFO) << "Highpass filter activated: "
688 << config_.high_pass_filter.enabled;
peahe0eae3c2016-12-14 01:16:23 -0800689
690 config_ok = EchoCanceller3::Validate(config_.echo_canceller3);
691 if (!config_ok) {
692 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
693 << "echo canceller 3: "
694 << EchoCanceller3::ToString(config_.echo_canceller3)
695 << std::endl
696 << "Reverting to default parameter set";
697 config_.echo_canceller3 = AudioProcessing::Config::EchoCanceller3();
698 }
699
700 if (config.echo_canceller3.enabled !=
701 capture_nonlocked_.echo_canceller3_enabled) {
702 capture_nonlocked_.echo_canceller3_enabled =
703 config_.echo_canceller3.enabled;
704 InitializeEchoCanceller3();
705 LOG(LS_INFO) << "Echo canceller 3 activated: "
706 << capture_nonlocked_.echo_canceller3_enabled;
707 }
alessiob3ec96df2017-05-22 06:57:06 -0700708
709 config_ok = GainController2::Validate(config_.gain_controller2);
710 if (!config_ok) {
711 LOG(LS_ERROR) << "AudioProcessing module config error" << std::endl
712 << "gain_controller2: "
713 << GainController2::ToString(config_.gain_controller2)
714 << std::endl
715 << "Reverting to default parameter set";
716 config_.gain_controller2 = AudioProcessing::Config::GainController2();
717 }
718
719 if (config.gain_controller2.enabled !=
720 capture_nonlocked_.gain_controller2_enabled) {
721 capture_nonlocked_.gain_controller2_enabled =
722 config_.gain_controller2.enabled;
723 InitializeGainController2();
724 LOG(LS_INFO) << "Gain controller 2 activated: "
725 << capture_nonlocked_.gain_controller2_enabled;
726 }
peah88ac8532016-09-12 16:47:25 -0700727}
728
729void AudioProcessingImpl::SetExtraOptions(const webrtc::Config& config) {
peahdf3efa82015-11-28 12:35:15 -0800730 // Run in a single-threaded manner when setting the extra options.
731 rtc::CritScope cs_render(&crit_render_);
732 rtc::CritScope cs_capture(&crit_capture_);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000733
peahb624d8c2016-03-05 03:01:14 -0800734 public_submodules_->echo_cancellation->SetExtraOptions(config);
735
peahdf3efa82015-11-28 12:35:15 -0800736 if (capture_.transient_suppressor_enabled !=
737 config.Get<ExperimentalNs>().enabled) {
738 capture_.transient_suppressor_enabled =
739 config.Get<ExperimentalNs>().enabled;
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000740 InitializeTransient();
741 }
aluebs2a346882016-01-11 18:04:30 -0800742
peah1bcfce52016-08-26 07:16:04 -0700743#if WEBRTC_INTELLIGIBILITY_ENHANCER
alessiob3ec96df2017-05-22 06:57:06 -0700744 if (capture_nonlocked_.intelligibility_enabled !=
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700745 config.Get<Intelligibility>().enabled) {
746 capture_nonlocked_.intelligibility_enabled =
747 config.Get<Intelligibility>().enabled;
748 InitializeIntelligibility();
749 }
peah1bcfce52016-08-26 07:16:04 -0700750#endif
Alejandro Luebsc9b0c262016-05-16 15:32:38 -0700751
aluebs2a346882016-01-11 18:04:30 -0800752#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
aluebsb2328d12016-01-11 20:32:29 -0800753 if (capture_nonlocked_.beamformer_enabled !=
754 config.Get<Beamforming>().enabled) {
755 capture_nonlocked_.beamformer_enabled = config.Get<Beamforming>().enabled;
aluebs2a346882016-01-11 18:04:30 -0800756 if (config.Get<Beamforming>().array_geometry.size() > 1) {
757 capture_.array_geometry = config.Get<Beamforming>().array_geometry;
758 }
759 capture_.target_direction = config.Get<Beamforming>().target_direction;
760 InitializeBeamformer();
761 }
762#endif // WEBRTC_ANDROID_PLATFORM_BUILD
andrew@webrtc.org61e596f2013-07-25 18:28:29 +0000763}
764
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000765int AudioProcessingImpl::proc_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800766 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700767 return capture_nonlocked_.capture_processing_format.sample_rate_hz();
niklase@google.com470e71d2011-07-07 08:21:25 +0000768}
769
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000770int AudioProcessingImpl::proc_split_sample_rate_hz() const {
peahdf3efa82015-11-28 12:35:15 -0800771 // Used as callback from submodules, hence locking is not allowed.
772 return capture_nonlocked_.split_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000773}
774
Peter Kasting69558702016-01-12 16:26:35 -0800775size_t AudioProcessingImpl::num_reverse_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800776 // Used as callback from submodules, hence locking is not allowed.
peahde65ddc2016-09-16 15:02:15 -0700777 return formats_.render_processing_format.num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000778}
779
Peter Kasting69558702016-01-12 16:26:35 -0800780size_t AudioProcessingImpl::num_input_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800781 // Used as callback from submodules, hence locking is not allowed.
782 return formats_.api_format.input_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000783}
784
Peter Kasting69558702016-01-12 16:26:35 -0800785size_t AudioProcessingImpl::num_proc_channels() const {
aluebsb2328d12016-01-11 20:32:29 -0800786 // Used as callback from submodules, hence locking is not allowed.
peahedddac52017-05-16 01:08:58 -0700787 return (capture_nonlocked_.beamformer_enabled ||
788 capture_nonlocked_.echo_canceller3_enabled)
789 ? 1
790 : num_output_channels();
aluebsb2328d12016-01-11 20:32:29 -0800791}
792
Peter Kasting69558702016-01-12 16:26:35 -0800793size_t AudioProcessingImpl::num_output_channels() const {
peahdf3efa82015-11-28 12:35:15 -0800794 // Used as callback from submodules, hence locking is not allowed.
795 return formats_.api_format.output_stream().num_channels();
niklase@google.com470e71d2011-07-07 08:21:25 +0000796}
797
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000798void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
peahdf3efa82015-11-28 12:35:15 -0800799 rtc::CritScope cs(&crit_capture_);
800 capture_.output_will_be_muted = muted;
801 if (private_submodules_->agc_manager.get()) {
802 private_submodules_->agc_manager->SetCaptureMuted(
803 capture_.output_will_be_muted);
pbos@webrtc.org788acd12014-12-15 09:41:24 +0000804 }
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000805}
806
andrew@webrtc.org17342e52014-02-12 22:28:31 +0000807
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000808int AudioProcessingImpl::ProcessStream(const float* const* src,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700809 size_t samples_per_channel,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000810 int input_sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000811 ChannelLayout input_layout,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000812 int output_sample_rate_hz,
813 ChannelLayout output_layout,
814 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800815 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -0800816 StreamConfig input_stream;
817 StreamConfig output_stream;
818 {
819 // Access the formats_.api_format.input_stream beneath the capture lock.
820 // The lock must be released as it is later required in the call
821 // to ProcessStream(,,,);
822 rtc::CritScope cs(&crit_capture_);
823 input_stream = formats_.api_format.input_stream();
824 output_stream = formats_.api_format.output_stream();
825 }
826
Michael Graczyk86c6d332015-07-23 11:41:39 -0700827 input_stream.set_sample_rate_hz(input_sample_rate_hz);
828 input_stream.set_num_channels(ChannelsFromLayout(input_layout));
829 input_stream.set_has_keyboard(LayoutHasKeyboard(input_layout));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700830 output_stream.set_sample_rate_hz(output_sample_rate_hz);
831 output_stream.set_num_channels(ChannelsFromLayout(output_layout));
832 output_stream.set_has_keyboard(LayoutHasKeyboard(output_layout));
833
834 if (samples_per_channel != input_stream.num_frames()) {
835 return kBadDataLengthError;
836 }
837 return ProcessStream(src, input_stream, output_stream, dest);
838}
839
840int AudioProcessingImpl::ProcessStream(const float* const* src,
841 const StreamConfig& input_config,
842 const StreamConfig& output_config,
843 float* const* dest) {
peah369f8282015-12-17 06:42:29 -0800844 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -0800845 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -0700846 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -0800847 {
848 // Acquire the capture lock in order to safely call the function
849 // that retrieves the render side data. This function accesses apm
850 // getters that need the capture lock held when being called.
851 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -0700852 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -0800853
854 if (!src || !dest) {
855 return kNullPointerError;
856 }
857
858 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -0700859 reinitialization_required = UpdateActiveSubmoduleStates();
niklase@google.com470e71d2011-07-07 08:21:25 +0000860 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000861
Michael Graczyk86c6d332015-07-23 11:41:39 -0700862 processing_config.input_stream() = input_config;
863 processing_config.output_stream() = output_config;
864
peahdf3efa82015-11-28 12:35:15 -0800865 {
866 // Do conditional reinitialization.
867 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -0700868 RETURN_ON_ERR(
869 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -0800870 }
871 rtc::CritScope cs_capture(&crit_capture_);
kwiberg9e2be5f2016-09-14 05:23:22 -0700872 RTC_DCHECK_EQ(processing_config.input_stream().num_frames(),
873 formats_.api_format.input_stream().num_frames());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000874
875#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700876 if (debug_dump_.debug_file->is_open()) {
Minyue13b96ba2015-10-03 00:39:14 +0200877 RETURN_ON_ERR(WriteConfigMessage(false));
878
peahdf3efa82015-11-28 12:35:15 -0800879 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
880 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000881 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800882 sizeof(float) * formats_.api_format.input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800883 for (size_t i = 0; i < formats_.api_format.input_stream().num_channels();
884 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000885 msg->add_input_channel(src[i], channel_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000886 }
887#endif
888
aleloi868f32f2017-05-23 07:20:05 -0700889 if (aec_dump_) {
890 RecordUnprocessedCaptureStream(src);
891 }
892
peahdf3efa82015-11-28 12:35:15 -0800893 capture_.capture_audio->CopyFrom(src, formats_.api_format.input_stream());
peahde65ddc2016-09-16 15:02:15 -0700894 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peahdf3efa82015-11-28 12:35:15 -0800895 capture_.capture_audio->CopyTo(formats_.api_format.output_stream(), dest);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000896
897#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -0700898 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -0800899 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +0000900 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -0800901 sizeof(float) * formats_.api_format.output_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -0800902 for (size_t i = 0; i < formats_.api_format.output_stream().num_channels();
903 ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000904 msg->add_output_channel(dest[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -0800905 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -0800906 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -0800907 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000908 }
909#endif
aleloi868f32f2017-05-23 07:20:05 -0700910 if (aec_dump_) {
911 RecordProcessedCaptureStream(dest);
912 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000913 return kNoError;
914}
915
peah9e6a2902017-05-15 07:19:21 -0700916void AudioProcessingImpl::QueueBandedRenderAudio(AudioBuffer* audio) {
peah764e3642016-10-22 05:04:30 -0700917 EchoCancellationImpl::PackRenderAudioBuffer(audio, num_output_channels(),
918 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700919 &aec_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700920
kwibergaf476c72016-11-28 15:21:39 -0800921 RTC_DCHECK_GE(160, audio->num_frames_per_band());
peah764e3642016-10-22 05:04:30 -0700922
923 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700924 if (!aec_render_signal_queue_->Insert(&aec_render_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -0700925 // The data queue is full and needs to be emptied.
926 EmptyQueuedRenderAudio();
927
928 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700929 bool result = aec_render_signal_queue_->Insert(&aec_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700930 RTC_DCHECK(result);
931 }
932
933 EchoControlMobileImpl::PackRenderAudioBuffer(audio, num_output_channels(),
934 num_reverse_channels(),
peah701d6282016-10-25 05:42:20 -0700935 &aecm_render_queue_buffer_);
peaha0624602016-10-25 04:45:24 -0700936
937 // Insert the samples into the queue.
peah701d6282016-10-25 05:42:20 -0700938 if (!aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -0700939 // The data queue is full and needs to be emptied.
940 EmptyQueuedRenderAudio();
941
942 // Retry the insert (should always work).
peah701d6282016-10-25 05:42:20 -0700943 bool result = aecm_render_signal_queue_->Insert(&aecm_render_queue_buffer_);
peah764e3642016-10-22 05:04:30 -0700944 RTC_DCHECK(result);
945 }
peah701d6282016-10-25 05:42:20 -0700946
947 if (!constants_.use_experimental_agc) {
948 GainControlImpl::PackRenderAudioBuffer(audio, &agc_render_queue_buffer_);
949 // Insert the samples into the queue.
950 if (!agc_render_signal_queue_->Insert(&agc_render_queue_buffer_)) {
951 // The data queue is full and needs to be emptied.
952 EmptyQueuedRenderAudio();
953
954 // Retry the insert (should always work).
955 bool result = agc_render_signal_queue_->Insert(&agc_render_queue_buffer_);
956 RTC_DCHECK(result);
957 }
958 }
peah9e6a2902017-05-15 07:19:21 -0700959}
ivoc9f4a4a02016-10-28 05:39:16 -0700960
peah9e6a2902017-05-15 07:19:21 -0700961void AudioProcessingImpl::QueueNonbandedRenderAudio(AudioBuffer* audio) {
ivoc9f4a4a02016-10-28 05:39:16 -0700962 ResidualEchoDetector::PackRenderAudioBuffer(audio, &red_render_queue_buffer_);
963
964 // Insert the samples into the queue.
965 if (!red_render_signal_queue_->Insert(&red_render_queue_buffer_)) {
966 // The data queue is full and needs to be emptied.
967 EmptyQueuedRenderAudio();
968
969 // Retry the insert (should always work).
970 bool result = red_render_signal_queue_->Insert(&red_render_queue_buffer_);
971 RTC_DCHECK(result);
972 }
peah764e3642016-10-22 05:04:30 -0700973}
974
975void AudioProcessingImpl::AllocateRenderQueue() {
peah701d6282016-10-25 05:42:20 -0700976 const size_t new_aec_render_queue_element_max_size =
peah764e3642016-10-22 05:04:30 -0700977 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700978 kMaxAllowedValuesOfSamplesPerBand *
peah764e3642016-10-22 05:04:30 -0700979 EchoCancellationImpl::NumCancellersRequired(
980 num_output_channels(), num_reverse_channels()));
981
peah701d6282016-10-25 05:42:20 -0700982 const size_t new_aecm_render_queue_element_max_size =
peaha0624602016-10-25 04:45:24 -0700983 std::max(static_cast<size_t>(1),
peah9e6a2902017-05-15 07:19:21 -0700984 kMaxAllowedValuesOfSamplesPerBand *
peaha0624602016-10-25 04:45:24 -0700985 EchoControlMobileImpl::NumCancellersRequired(
986 num_output_channels(), num_reverse_channels()));
peah764e3642016-10-22 05:04:30 -0700987
peah701d6282016-10-25 05:42:20 -0700988 const size_t new_agc_render_queue_element_max_size =
peah9e6a2902017-05-15 07:19:21 -0700989 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerBand);
peah701d6282016-10-25 05:42:20 -0700990
ivoc9f4a4a02016-10-28 05:39:16 -0700991 const size_t new_red_render_queue_element_max_size =
992 std::max(static_cast<size_t>(1), kMaxAllowedValuesOfSamplesPerFrame);
993
peaha0624602016-10-25 04:45:24 -0700994 // Reallocate the queues if the queue item sizes are too small to fit the
995 // data to put in the queues.
peah701d6282016-10-25 05:42:20 -0700996 if (aec_render_queue_element_max_size_ <
997 new_aec_render_queue_element_max_size) {
998 aec_render_queue_element_max_size_ = new_aec_render_queue_element_max_size;
peah764e3642016-10-22 05:04:30 -0700999
peaha0624602016-10-25 04:45:24 -07001000 std::vector<float> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001001 aec_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001002
peah701d6282016-10-25 05:42:20 -07001003 aec_render_signal_queue_.reset(
peah764e3642016-10-22 05:04:30 -07001004 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1005 kMaxNumFramesToBuffer, template_queue_element,
peaha0624602016-10-25 04:45:24 -07001006 RenderQueueItemVerifier<float>(
peah701d6282016-10-25 05:42:20 -07001007 aec_render_queue_element_max_size_)));
peah764e3642016-10-22 05:04:30 -07001008
peah701d6282016-10-25 05:42:20 -07001009 aec_render_queue_buffer_.resize(aec_render_queue_element_max_size_);
1010 aec_capture_queue_buffer_.resize(aec_render_queue_element_max_size_);
peah764e3642016-10-22 05:04:30 -07001011 } else {
peah701d6282016-10-25 05:42:20 -07001012 aec_render_signal_queue_->Clear();
peaha0624602016-10-25 04:45:24 -07001013 }
1014
peah701d6282016-10-25 05:42:20 -07001015 if (aecm_render_queue_element_max_size_ <
1016 new_aecm_render_queue_element_max_size) {
1017 aecm_render_queue_element_max_size_ =
1018 new_aecm_render_queue_element_max_size;
peaha0624602016-10-25 04:45:24 -07001019
1020 std::vector<int16_t> template_queue_element(
peah701d6282016-10-25 05:42:20 -07001021 aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001022
peah701d6282016-10-25 05:42:20 -07001023 aecm_render_signal_queue_.reset(
peaha0624602016-10-25 04:45:24 -07001024 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1025 kMaxNumFramesToBuffer, template_queue_element,
1026 RenderQueueItemVerifier<int16_t>(
peah701d6282016-10-25 05:42:20 -07001027 aecm_render_queue_element_max_size_)));
peaha0624602016-10-25 04:45:24 -07001028
peah701d6282016-10-25 05:42:20 -07001029 aecm_render_queue_buffer_.resize(aecm_render_queue_element_max_size_);
1030 aecm_capture_queue_buffer_.resize(aecm_render_queue_element_max_size_);
peaha0624602016-10-25 04:45:24 -07001031 } else {
peah701d6282016-10-25 05:42:20 -07001032 aecm_render_signal_queue_->Clear();
1033 }
1034
1035 if (agc_render_queue_element_max_size_ <
1036 new_agc_render_queue_element_max_size) {
1037 agc_render_queue_element_max_size_ = new_agc_render_queue_element_max_size;
1038
1039 std::vector<int16_t> template_queue_element(
1040 agc_render_queue_element_max_size_);
1041
1042 agc_render_signal_queue_.reset(
1043 new SwapQueue<std::vector<int16_t>, RenderQueueItemVerifier<int16_t>>(
1044 kMaxNumFramesToBuffer, template_queue_element,
1045 RenderQueueItemVerifier<int16_t>(
1046 agc_render_queue_element_max_size_)));
1047
1048 agc_render_queue_buffer_.resize(agc_render_queue_element_max_size_);
1049 agc_capture_queue_buffer_.resize(agc_render_queue_element_max_size_);
1050 } else {
1051 agc_render_signal_queue_->Clear();
peah764e3642016-10-22 05:04:30 -07001052 }
ivoc9f4a4a02016-10-28 05:39:16 -07001053
1054 if (red_render_queue_element_max_size_ <
1055 new_red_render_queue_element_max_size) {
1056 red_render_queue_element_max_size_ = new_red_render_queue_element_max_size;
1057
1058 std::vector<float> template_queue_element(
1059 red_render_queue_element_max_size_);
1060
1061 red_render_signal_queue_.reset(
1062 new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
1063 kMaxNumFramesToBuffer, template_queue_element,
1064 RenderQueueItemVerifier<float>(
1065 red_render_queue_element_max_size_)));
1066
1067 red_render_queue_buffer_.resize(red_render_queue_element_max_size_);
1068 red_capture_queue_buffer_.resize(red_render_queue_element_max_size_);
1069 } else {
1070 red_render_signal_queue_->Clear();
1071 }
peah764e3642016-10-22 05:04:30 -07001072}
1073
1074void AudioProcessingImpl::EmptyQueuedRenderAudio() {
1075 rtc::CritScope cs_capture(&crit_capture_);
peah701d6282016-10-25 05:42:20 -07001076 while (aec_render_signal_queue_->Remove(&aec_capture_queue_buffer_)) {
peah764e3642016-10-22 05:04:30 -07001077 public_submodules_->echo_cancellation->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001078 aec_capture_queue_buffer_);
peaha0624602016-10-25 04:45:24 -07001079 }
1080
peah701d6282016-10-25 05:42:20 -07001081 while (aecm_render_signal_queue_->Remove(&aecm_capture_queue_buffer_)) {
peaha0624602016-10-25 04:45:24 -07001082 public_submodules_->echo_control_mobile->ProcessRenderAudio(
peah701d6282016-10-25 05:42:20 -07001083 aecm_capture_queue_buffer_);
1084 }
1085
1086 while (agc_render_signal_queue_->Remove(&agc_capture_queue_buffer_)) {
1087 public_submodules_->gain_control->ProcessRenderAudio(
1088 agc_capture_queue_buffer_);
peah764e3642016-10-22 05:04:30 -07001089 }
ivoc9f4a4a02016-10-28 05:39:16 -07001090
1091 while (red_render_signal_queue_->Remove(&red_capture_queue_buffer_)) {
1092 private_submodules_->residual_echo_detector->AnalyzeRenderAudio(
1093 red_capture_queue_buffer_);
1094 }
peah764e3642016-10-22 05:04:30 -07001095}
1096
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001097int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001098 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001099 {
1100 // Acquire the capture lock in order to safely call the function
1101 // that retrieves the render side data. This function accesses apm
1102 // getters that need the capture lock held when being called.
1103 // The lock needs to be released as
1104 // public_submodules_->echo_control_mobile->is_enabled() aquires this lock
1105 // as well.
1106 rtc::CritScope cs_capture(&crit_capture_);
peah764e3642016-10-22 05:04:30 -07001107 EmptyQueuedRenderAudio();
peahdf3efa82015-11-28 12:35:15 -08001108 }
peahfa6228e2015-11-16 16:27:42 -08001109
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001110 if (!frame) {
1111 return kNullPointerError;
1112 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001113 // Must be a native rate.
1114 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1115 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001116 frame->sample_rate_hz_ != kSampleRate32kHz &&
1117 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001118 return kBadSampleRateError;
1119 }
peah192164e2015-11-17 02:16:45 -08001120
peahdf3efa82015-11-28 12:35:15 -08001121 ProcessingConfig processing_config;
peah2ace3f92016-09-10 04:42:27 -07001122 bool reinitialization_required = false;
peahdf3efa82015-11-28 12:35:15 -08001123 {
1124 // Aquire lock for the access of api_format.
1125 // The lock is released immediately due to the conditional
1126 // reinitialization.
1127 rtc::CritScope cs_capture(&crit_capture_);
1128 // TODO(ajm): The input and output rates and channels are currently
1129 // constrained to be identical in the int16 interface.
1130 processing_config = formats_.api_format;
peah2ace3f92016-09-10 04:42:27 -07001131
1132 reinitialization_required = UpdateActiveSubmoduleStates();
peahdf3efa82015-11-28 12:35:15 -08001133 }
Michael Graczyk86c6d332015-07-23 11:41:39 -07001134 processing_config.input_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1135 processing_config.input_stream().set_num_channels(frame->num_channels_);
1136 processing_config.output_stream().set_sample_rate_hz(frame->sample_rate_hz_);
1137 processing_config.output_stream().set_num_channels(frame->num_channels_);
1138
peahdf3efa82015-11-28 12:35:15 -08001139 {
1140 // Do conditional reinitialization.
1141 rtc::CritScope cs_render(&crit_render_);
peah2ace3f92016-09-10 04:42:27 -07001142 RETURN_ON_ERR(
1143 MaybeInitializeCapture(processing_config, reinitialization_required));
peahdf3efa82015-11-28 12:35:15 -08001144 }
1145 rtc::CritScope cs_capture(&crit_capture_);
peah192164e2015-11-17 02:16:45 -08001146 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001147 formats_.api_format.input_stream().num_frames()) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001148 return kBadDataLengthError;
1149 }
1150
aleloi868f32f2017-05-23 07:20:05 -07001151 if (aec_dump_) {
1152 RecordUnprocessedCaptureStream(*frame);
1153 }
1154
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001155#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001156 if (debug_dump_.debug_file->is_open()) {
peah644fa962016-08-18 06:48:33 -07001157 RETURN_ON_ERR(WriteConfigMessage(false));
1158
peahdf3efa82015-11-28 12:35:15 -08001159 debug_dump_.capture.event_msg->set_type(audioproc::Event::STREAM);
1160 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001161 const size_t data_size =
1162 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001163 msg->set_input_data(frame->data_, data_size);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001164 }
1165#endif
1166
peahdf3efa82015-11-28 12:35:15 -08001167 capture_.capture_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001168 RETURN_ON_ERR(ProcessCaptureStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001169 capture_.capture_audio->InterleaveTo(
peah23ac8b42017-05-23 05:33:56 -07001170 frame, submodule_states_.CaptureMultiBandProcessingActive() ||
1171 submodule_states_.CaptureFullBandProcessingActive());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001172
aleloi868f32f2017-05-23 07:20:05 -07001173 if (aec_dump_) {
1174 RecordProcessedCaptureStream(*frame);
1175 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001176#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001177 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001178 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001179 const size_t data_size =
1180 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001181 msg->set_output_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001182 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001183 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001184 &crit_debug_, &debug_dump_.capture));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001185 }
1186#endif
1187
1188 return kNoError;
1189}
1190
peahde65ddc2016-09-16 15:02:15 -07001191int AudioProcessingImpl::ProcessCaptureStreamLocked() {
peahb58a1582016-03-15 09:34:24 -07001192 // Ensure that not both the AEC and AECM are active at the same time.
1193 // TODO(peah): Simplify once the public API Enable functions for these
1194 // are moved to APM.
1195 RTC_DCHECK(!(public_submodules_->echo_cancellation->is_enabled() &&
1196 public_submodules_->echo_control_mobile->is_enabled()));
1197
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001198#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001199 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001200 audioproc::Stream* msg = debug_dump_.capture.event_msg->mutable_stream();
1201 msg->set_delay(capture_nonlocked_.stream_delay_ms);
1202 msg->set_drift(
1203 public_submodules_->echo_cancellation->stream_drift_samples());
bjornv@webrtc.org63da1dd2015-02-06 19:44:21 +00001204 msg->set_level(gain_control()->stream_analog_level());
peahdf3efa82015-11-28 12:35:15 -08001205 msg->set_keypress(capture_.key_pressed);
niklase@google.com470e71d2011-07-07 08:21:25 +00001206 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001207#endif
niklase@google.com470e71d2011-07-07 08:21:25 +00001208
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001209 MaybeUpdateHistograms();
1210
peahde65ddc2016-09-16 15:02:15 -07001211 AudioBuffer* capture_buffer = capture_.capture_audio.get(); // For brevity.
ekmeyerson60d9b332015-08-14 10:35:55 -07001212
peah1b08dc32016-12-20 13:45:58 -08001213 capture_input_rms_.Analyze(rtc::ArrayView<const int16_t>(
henrik.lundin290d43a2016-11-29 08:09:09 -08001214 capture_buffer->channels_const()[0],
1215 capture_nonlocked_.capture_processing_format.num_frames()));
peah1b08dc32016-12-20 13:45:58 -08001216 const bool log_rms = ++capture_rms_interval_counter_ >= 1000;
1217 if (log_rms) {
1218 capture_rms_interval_counter_ = 0;
1219 RmsLevel::Levels levels = capture_input_rms_.AverageAndPeak();
henrik.lundin45bb5132016-12-06 04:28:04 -08001220 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelAverageRms",
1221 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1222 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureInputLevelPeakRms",
1223 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
henrik.lundin290d43a2016-11-29 08:09:09 -08001224 }
1225
peahe0eae3c2016-12-14 01:16:23 -08001226 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001227 const int new_agc_level = gain_control()->stream_analog_level();
1228 capture_.echo_path_gain_change =
peah103ac7e2017-04-12 05:40:55 -07001229 abs(capture_.previous_agc_level - new_agc_level) > 5;
peah67995532017-04-10 14:12:41 -07001230 capture_.previous_agc_level = new_agc_level;
peahe0eae3c2016-12-14 01:16:23 -08001231 private_submodules_->echo_canceller3->AnalyzeCapture(capture_buffer);
1232 }
1233
peahbe615622016-02-13 16:40:47 -08001234 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001235 public_submodules_->gain_control->is_enabled()) {
1236 private_submodules_->agc_manager->AnalyzePreProcess(
peahde65ddc2016-09-16 15:02:15 -07001237 capture_buffer->channels()[0], capture_buffer->num_channels(),
1238 capture_nonlocked_.capture_processing_format.num_frames());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001239 }
1240
peah2ace3f92016-09-10 04:42:27 -07001241 if (submodule_states_.CaptureMultiBandSubModulesActive() &&
1242 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001243 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1244 capture_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001245 }
1246
peah522d71b2017-02-23 05:16:26 -08001247 if (private_submodules_->echo_canceller3) {
1248 // Force down-mixing of the number of channels after the detection of
1249 // capture signal saturation.
1250 // TODO(peah): Look into ensuring that this kind of tampering with the
1251 // AudioBuffer functionality should not be needed.
1252 capture_buffer->set_num_channels(1);
1253 }
1254
aluebsb2328d12016-01-11 20:32:29 -08001255 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001256 private_submodules_->beamformer->AnalyzeChunk(
1257 *capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001258 // Discards all channels by the leftmost one.
peahde65ddc2016-09-16 15:02:15 -07001259 capture_buffer->set_num_channels(1);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001260 }
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001261
peahe0eae3c2016-12-14 01:16:23 -08001262 // TODO(peah): Move the AEC3 low-cut filter to this place.
1263 if (private_submodules_->low_cut_filter &&
1264 !private_submodules_->echo_canceller3) {
peah8271d042016-11-22 07:24:52 -08001265 private_submodules_->low_cut_filter->Process(capture_buffer);
1266 }
peahde65ddc2016-09-16 15:02:15 -07001267 RETURN_ON_ERR(
1268 public_submodules_->gain_control->AnalyzeCaptureAudio(capture_buffer));
1269 public_submodules_->noise_suppression->AnalyzeCaptureAudio(capture_buffer);
peahb58a1582016-03-15 09:34:24 -07001270
1271 // Ensure that the stream delay was set before the call to the
1272 // AEC ProcessCaptureAudio function.
1273 if (public_submodules_->echo_cancellation->is_enabled() &&
1274 !was_stream_delay_set()) {
1275 return AudioProcessing::kStreamParameterNotSetError;
1276 }
1277
peahe0eae3c2016-12-14 01:16:23 -08001278 if (private_submodules_->echo_canceller3) {
peah67995532017-04-10 14:12:41 -07001279 private_submodules_->echo_canceller3->ProcessCapture(
1280 capture_buffer, capture_.echo_path_gain_change);
peah61202ac2017-02-06 03:39:42 -08001281 } else {
1282 RETURN_ON_ERR(public_submodules_->echo_cancellation->ProcessCaptureAudio(
1283 capture_buffer, stream_delay_ms()));
peahe0eae3c2016-12-14 01:16:23 -08001284 }
1285
peahdf3efa82015-11-28 12:35:15 -08001286 if (public_submodules_->echo_control_mobile->is_enabled() &&
1287 public_submodules_->noise_suppression->is_enabled()) {
peahde65ddc2016-09-16 15:02:15 -07001288 capture_buffer->CopyLowPassToReference();
niklase@google.com470e71d2011-07-07 08:21:25 +00001289 }
peahde65ddc2016-09-16 15:02:15 -07001290 public_submodules_->noise_suppression->ProcessCaptureAudio(capture_buffer);
peah1bcfce52016-08-26 07:16:04 -07001291#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001292 if (capture_nonlocked_.intelligibility_enabled) {
aluebsc466bad2016-02-10 12:03:00 -08001293 RTC_DCHECK(public_submodules_->noise_suppression->is_enabled());
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001294 int gain_db = public_submodules_->gain_control->is_enabled() ?
1295 public_submodules_->gain_control->compression_gain_db() :
1296 0;
Alejandro Luebs50411102016-06-30 15:35:41 -07001297 float gain = std::pow(10.f, gain_db / 20.f);
1298 gain *= capture_nonlocked_.level_controller_enabled ?
1299 private_submodules_->level_controller->GetLastGain() :
1300 1.f;
aluebsc466bad2016-02-10 12:03:00 -08001301 public_submodules_->intelligibility_enhancer->SetCaptureNoiseEstimate(
Alejandro Luebs50411102016-06-30 15:35:41 -07001302 public_submodules_->noise_suppression->NoiseEstimate(), gain);
aluebsc466bad2016-02-10 12:03:00 -08001303 }
peah1bcfce52016-08-26 07:16:04 -07001304#endif
peah253534d2016-03-15 04:32:28 -07001305
1306 // Ensure that the stream delay was set before the call to the
1307 // AECM ProcessCaptureAudio function.
1308 if (public_submodules_->echo_control_mobile->is_enabled() &&
1309 !was_stream_delay_set()) {
1310 return AudioProcessing::kStreamParameterNotSetError;
1311 }
1312
Per Ã…hgren46537a32017-06-07 10:08:10 +02001313 if (!(private_submodules_->echo_canceller3 ||
1314 public_submodules_->echo_cancellation->is_enabled())) {
1315 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
1316 capture_buffer, stream_delay_ms()));
1317 }
ivoc9f4a4a02016-10-28 05:39:16 -07001318
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001319 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001320 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001321 }
1322
peahde65ddc2016-09-16 15:02:15 -07001323 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001324
peahbe615622016-02-13 16:40:47 -08001325 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001326 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001327 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001328 private_submodules_->beamformer->is_target_present())) {
1329 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001330 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1331 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001332 }
peahb8fbb542016-03-15 02:28:08 -07001333 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001334 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001335
peah2ace3f92016-09-10 04:42:27 -07001336 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1337 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001338 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1339 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001340 }
1341
peah9e6a2902017-05-15 07:19:21 -07001342 if (config_.residual_echo_detector.enabled) {
1343 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1344 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1345 capture_buffer->num_frames()));
1346 }
1347
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001348 // TODO(aluebs): Investigate if the transient suppression placement should be
1349 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001350 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001351 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001352 private_submodules_->agc_manager.get()
1353 ? private_submodules_->agc_manager->voice_probability()
1354 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001355
peahdf3efa82015-11-28 12:35:15 -08001356 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001357 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1358 capture_buffer->num_channels(),
1359 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1360 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1361 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001362 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001363 }
1364
alessiob3ec96df2017-05-22 06:57:06 -07001365 if (capture_nonlocked_.gain_controller2_enabled) {
1366 private_submodules_->gain_controller2->Process(capture_buffer);
1367 }
1368
peahca4cac72016-06-29 15:26:12 -07001369 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001370 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001371 }
1372
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001373 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001374 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001375
peah1b08dc32016-12-20 13:45:58 -08001376 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1377 capture_buffer->channels_const()[0],
1378 capture_nonlocked_.capture_processing_format.num_frames()));
1379 if (log_rms) {
1380 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1381 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1382 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1383 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1384 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1385 }
1386
peahdf3efa82015-11-28 12:35:15 -08001387 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001388 return kNoError;
1389}
1390
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001391int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001392 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001393 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001394 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001395 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001396 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001397 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001398 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001399 };
1400 if (samples_per_channel != reverse_config.num_frames()) {
1401 return kBadDataLengthError;
1402 }
peahdf3efa82015-11-28 12:35:15 -08001403 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001404}
1405
peahde65ddc2016-09-16 15:02:15 -07001406int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1407 const StreamConfig& input_config,
1408 const StreamConfig& output_config,
1409 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001410 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001411 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001412 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001413 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001414 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1415 dest);
peah2ace3f92016-09-10 04:42:27 -07001416 } else if (formats_.api_format.reverse_input_stream() !=
1417 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001418 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1419 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001420 } else {
peahde65ddc2016-09-16 15:02:15 -07001421 CopyAudioIfNeeded(src, input_config.num_frames(),
1422 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001423 }
1424
1425 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001426}
1427
peahdf3efa82015-11-28 12:35:15 -08001428int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001429 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001430 const StreamConfig& input_config,
1431 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001432 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001433 return kNullPointerError;
1434 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001435
peahde65ddc2016-09-16 15:02:15 -07001436 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001437 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001438 }
1439
peahdf3efa82015-11-28 12:35:15 -08001440 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001441 processing_config.reverse_input_stream() = input_config;
1442 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001443
peahdf3efa82015-11-28 12:35:15 -08001444 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001445 assert(input_config.num_frames() ==
1446 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001447
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001448#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001449 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001450 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1451 audioproc::ReverseStream* msg =
1452 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001453 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001454 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001455 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001456 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001457 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001458 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001459 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001460 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001461 }
1462#endif
aleloi868f32f2017-05-23 07:20:05 -07001463 if (aec_dump_) {
1464 const size_t channel_size =
1465 formats_.api_format.reverse_input_stream().num_frames();
1466 const size_t num_channels =
1467 formats_.api_format.reverse_input_stream().num_channels();
1468 aec_dump_->WriteRenderStreamMessage(
1469 FloatAudioFrame(src, num_channels, channel_size));
1470 }
peahdf3efa82015-11-28 12:35:15 -08001471 render_.render_audio->CopyFrom(src,
1472 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001473 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001474}
1475
1476int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001477 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001478 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001479 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001480 return kNullPointerError;
1481 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001482 // Must be a native rate.
1483 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1484 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001485 frame->sample_rate_hz_ != kSampleRate32kHz &&
1486 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001487 return kBadSampleRateError;
1488 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001489
Michael Graczyk86c6d332015-07-23 11:41:39 -07001490 if (frame->num_channels_ <= 0) {
1491 return kBadNumberChannelsError;
1492 }
1493
peahdf3efa82015-11-28 12:35:15 -08001494 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001495 processing_config.reverse_input_stream().set_sample_rate_hz(
1496 frame->sample_rate_hz_);
1497 processing_config.reverse_input_stream().set_num_channels(
1498 frame->num_channels_);
1499 processing_config.reverse_output_stream().set_sample_rate_hz(
1500 frame->sample_rate_hz_);
1501 processing_config.reverse_output_stream().set_num_channels(
1502 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001503
peahdf3efa82015-11-28 12:35:15 -08001504 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001505 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001506 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001507 return kBadDataLengthError;
1508 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001509
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001510#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001511 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001512 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1513 audioproc::ReverseStream* msg =
1514 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001515 const size_t data_size =
1516 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001517 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001518 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001519 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001520 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001521 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001522#endif
aleloi868f32f2017-05-23 07:20:05 -07001523 if (aec_dump_) {
1524 aec_dump_->WriteRenderStreamMessage(*frame);
1525 }
1526
peahdf3efa82015-11-28 12:35:15 -08001527 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001528 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001529 render_.render_audio->InterleaveTo(
1530 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001531 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001532}
niklase@google.com470e71d2011-07-07 08:21:25 +00001533
peahde65ddc2016-09-16 15:02:15 -07001534int AudioProcessingImpl::ProcessRenderStreamLocked() {
1535 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001536
1537 QueueNonbandedRenderAudio(render_buffer);
1538
peah2ace3f92016-09-10 04:42:27 -07001539 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001540 SampleRateSupportsMultiBand(
1541 formats_.render_processing_format.sample_rate_hz())) {
1542 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001543 }
1544
peah1bcfce52016-08-26 07:16:04 -07001545#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001546 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001547 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001548 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001549 }
peah1bcfce52016-08-26 07:16:04 -07001550#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001551
peahce4d9152017-05-19 01:28:05 -07001552 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1553 QueueBandedRenderAudio(render_buffer);
1554 }
1555
peahe0eae3c2016-12-14 01:16:23 -08001556 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1557 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001558 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001559 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001560
peah2ace3f92016-09-10 04:42:27 -07001561 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001562 SampleRateSupportsMultiBand(
1563 formats_.render_processing_format.sample_rate_hz())) {
1564 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001565 }
1566
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001567 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001568}
1569
1570int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001571 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001572 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001573 capture_.was_stream_delay_set = true;
1574 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001575
niklase@google.com470e71d2011-07-07 08:21:25 +00001576 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001577 delay = 0;
1578 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001579 }
1580
1581 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1582 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001583 delay = 500;
1584 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001585 }
1586
peahdf3efa82015-11-28 12:35:15 -08001587 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001588 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001589}
1590
1591int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001592 // Used as callback from submodules, hence locking is not allowed.
1593 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001594}
1595
1596bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001597 // Used as callback from submodules, hence locking is not allowed.
1598 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001599}
1600
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001601void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001602 rtc::CritScope cs(&crit_capture_);
1603 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001604}
1605
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001606void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001607 rtc::CritScope cs(&crit_capture_);
1608 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001609}
1610
1611int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001612 rtc::CritScope cs(&crit_capture_);
1613 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001614}
1615
aleloi868f32f2017-05-23 07:20:05 -07001616void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1617 RTC_DCHECK(aec_dump);
1618 rtc::CritScope cs_render(&crit_render_);
1619 rtc::CritScope cs_capture(&crit_capture_);
1620
1621 // The previously attached AecDump will be destroyed with the
1622 // 'aec_dump' parameter, which is after locks are released.
1623 aec_dump_.swap(aec_dump);
1624 WriteAecDumpConfigMessage(true);
1625 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1626}
1627
1628void AudioProcessingImpl::DetachAecDump() {
1629 // The d-tor of a task-queue based AecDump blocks until all pending
1630 // tasks are done. This construction avoids blocking while holding
1631 // the render and capture locks.
1632 std::unique_ptr<AecDump> aec_dump = nullptr;
1633 {
1634 rtc::CritScope cs_render(&crit_render_);
1635 rtc::CritScope cs_capture(&crit_capture_);
1636 aec_dump = std::move(aec_dump_);
1637 }
1638}
1639
niklase@google.com470e71d2011-07-07 08:21:25 +00001640int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001641 const char filename[AudioProcessing::kMaxFilenameSize],
1642 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001643 // Run in a single-threaded manner.
1644 rtc::CritScope cs_render(&crit_render_);
1645 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001646 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001647
peahdf3efa82015-11-28 12:35:15 -08001648 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001649 return kNullPointerError;
1650 }
1651
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001652#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001653 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001654 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001655 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001656
tommia6219cc2016-06-15 10:30:14 -07001657 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001658 return kFileError;
1659 }
1660
Minyue13b96ba2015-10-03 00:39:14 +02001661 RETURN_ON_ERR(WriteConfigMessage(true));
1662 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001663 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001664#else
1665 return kUnsupportedFunctionError;
1666#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001667}
1668
ivocd66b44d2016-01-15 03:06:36 -08001669int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1670 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001671 // Run in a single-threaded manner.
1672 rtc::CritScope cs_render(&crit_render_);
1673 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001674
peahdf3efa82015-11-28 12:35:15 -08001675 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001676 return kNullPointerError;
1677 }
1678
1679#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001680 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1681
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001682 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001683 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001684
tommia6219cc2016-06-15 10:30:14 -07001685 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001686 return kFileError;
1687 }
1688
Minyue13b96ba2015-10-03 00:39:14 +02001689 RETURN_ON_ERR(WriteConfigMessage(true));
1690 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001691 return kNoError;
1692#else
1693 return kUnsupportedFunctionError;
1694#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1695}
1696
peah73a28ee2016-10-12 03:01:49 -07001697int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1698 return StartDebugRecording(handle, -1);
1699}
1700
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001701int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1702 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001703 // Run in a single-threaded manner.
1704 rtc::CritScope cs_render(&crit_render_);
1705 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001706 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001707 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001708}
1709
niklase@google.com470e71d2011-07-07 08:21:25 +00001710int AudioProcessingImpl::StopDebugRecording() {
aleloi868f32f2017-05-23 07:20:05 -07001711 DetachAecDump();
1712
1713#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001714 // Run in a single-threaded manner.
1715 rtc::CritScope cs_render(&crit_render_);
1716 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001717 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001718 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001719 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001720#else
1721 return kUnsupportedFunctionError;
1722#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001723}
1724
ivoc4e477a12017-01-15 08:29:46 -08001725AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1726 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1727 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1728 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1729 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1730}
1731
1732AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1733 const AudioProcessingStatistics& other) = default;
1734
1735AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1736 default;
1737
ivoc3e9a5372016-10-28 07:55:33 -07001738// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1739AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1740 const {
1741 return AudioProcessingStatistics();
1742}
1743
1744AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1745 const {
1746 AudioProcessingStatistics stats;
1747 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001748 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1749 if (success == Error::kNoError) {
1750 stats.a_nlp.Set(metrics.a_nlp);
1751 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1752 stats.echo_return_loss.Set(metrics.echo_return_loss);
1753 stats.echo_return_loss_enhancement.Set(
1754 metrics.echo_return_loss_enhancement);
1755 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1756 }
ivoc9c192b22017-03-16 04:22:14 -07001757 {
1758 rtc::CritScope cs_capture(&crit_capture_);
1759 stats.residual_echo_likelihood =
1760 private_submodules_->residual_echo_detector->echo_likelihood();
1761 stats.residual_echo_likelihood_recent_max =
1762 private_submodules_->residual_echo_detector
1763 ->echo_likelihood_recent_max();
1764 }
ivoc3e9a5372016-10-28 07:55:33 -07001765 public_submodules_->echo_cancellation->GetDelayMetrics(
1766 &stats.delay_median, &stats.delay_standard_deviation,
1767 &stats.fraction_poor_delays);
1768 return stats;
1769}
1770
niklase@google.com470e71d2011-07-07 08:21:25 +00001771EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001772 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001773}
1774
1775EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001776 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001777}
1778
1779GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001780 if (constants_.use_experimental_agc) {
1781 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001782 }
peahbfa97112016-03-10 21:09:04 -08001783 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001784}
1785
1786HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001787 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001788}
1789
1790LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001791 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001792}
1793
1794NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001795 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001796}
1797
1798VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001799 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001800}
1801
peah8271d042016-11-22 07:24:52 -08001802void AudioProcessingImpl::MutateConfig(
1803 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1804 rtc::CritScope cs_render(&crit_render_);
1805 rtc::CritScope cs_capture(&crit_capture_);
1806 mutator(&config_);
1807 ApplyConfig(config_);
1808}
1809
1810AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1811 rtc::CritScope cs_render(&crit_render_);
1812 rtc::CritScope cs_capture(&crit_capture_);
1813 return config_;
1814}
1815
peah2ace3f92016-09-10 04:42:27 -07001816bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1817 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001818 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001819 public_submodules_->echo_cancellation->is_enabled(),
1820 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001821 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001822 public_submodules_->noise_suppression->is_enabled(),
1823 capture_nonlocked_.intelligibility_enabled,
1824 capture_nonlocked_.beamformer_enabled,
1825 public_submodules_->gain_control->is_enabled(),
alessiob3ec96df2017-05-22 06:57:06 -07001826 capture_nonlocked_.gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -07001827 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001828 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001829 public_submodules_->voice_detection->is_enabled(),
1830 public_submodules_->level_estimator->is_enabled(),
1831 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001832}
1833
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001834
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001835void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001836 if (capture_.transient_suppressor_enabled) {
1837 if (!public_submodules_->transient_suppressor.get()) {
1838 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001839 }
peahdf3efa82015-11-28 12:35:15 -08001840 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001841 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1842 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001843 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001844}
1845
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001846void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001847 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001848 if (!private_submodules_->beamformer) {
1849 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001850 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001851 }
peahdf3efa82015-11-28 12:35:15 -08001852 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1853 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001854 }
1855}
1856
ekmeyerson60d9b332015-08-14 10:35:55 -07001857void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001858#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001859 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001860 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001861 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001862 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001863 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001864 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001865 }
peah1bcfce52016-08-26 07:16:04 -07001866#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001867}
1868
peah8271d042016-11-22 07:24:52 -08001869void AudioProcessingImpl::InitializeLowCutFilter() {
1870 if (config_.high_pass_filter.enabled) {
1871 private_submodules_->low_cut_filter.reset(
1872 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1873 } else {
1874 private_submodules_->low_cut_filter.reset();
1875 }
1876}
alessiob3ec96df2017-05-22 06:57:06 -07001877
peahe0eae3c2016-12-14 01:16:23 -08001878void AudioProcessingImpl::InitializeEchoCanceller3() {
1879 if (capture_nonlocked_.echo_canceller3_enabled) {
1880 private_submodules_->echo_canceller3.reset(
1881 new EchoCanceller3(proc_sample_rate_hz(), true));
1882 } else {
1883 private_submodules_->echo_canceller3.reset();
1884 }
1885}
peah8271d042016-11-22 07:24:52 -08001886
alessiob3ec96df2017-05-22 06:57:06 -07001887void AudioProcessingImpl::InitializeGainController2() {
1888 if (capture_nonlocked_.gain_controller2_enabled) {
1889 private_submodules_->gain_controller2.reset(
1890 new GainController2(proc_sample_rate_hz()));
1891 } else {
1892 private_submodules_->gain_controller2.reset();
1893 }
1894}
1895
peahca4cac72016-06-29 15:26:12 -07001896void AudioProcessingImpl::InitializeLevelController() {
1897 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1898}
1899
ivoc9f4a4a02016-10-28 05:39:16 -07001900void AudioProcessingImpl::InitializeResidualEchoDetector() {
1901 private_submodules_->residual_echo_detector->Initialize();
1902}
1903
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001904void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001905 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001906
1907 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001908 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1909 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001910 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001911 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001912 capture_.stream_delay_jumps = 0;
1913 }
1914 if (capture_.aec_system_delay_jumps == -1 &&
1915 echo_cancellation()->stream_has_echo()) {
1916 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001917 }
1918
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001919 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001920 const int diff_stream_delay_ms =
1921 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1922 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1923 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001924 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1925 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001926 if (capture_.stream_delay_jumps == -1) {
1927 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001928 }
peahdf3efa82015-11-28 12:35:15 -08001929 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001930 }
peahdf3efa82015-11-28 12:35:15 -08001931 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001932
1933 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001934 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001935 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001936 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001937 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001938 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1939 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001940 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001941 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001942 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001943 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001944 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1945 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1946 100);
peahdf3efa82015-11-28 12:35:15 -08001947 if (capture_.aec_system_delay_jumps == -1) {
1948 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001949 }
peahdf3efa82015-11-28 12:35:15 -08001950 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001951 }
peahdf3efa82015-11-28 12:35:15 -08001952 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001953 }
1954}
1955
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001956void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001957 // Run in a single-threaded manner.
1958 rtc::CritScope cs_render(&crit_render_);
1959 rtc::CritScope cs_capture(&crit_capture_);
1960
1961 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001962 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001963 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001964 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001965 }
peahdf3efa82015-11-28 12:35:15 -08001966 capture_.stream_delay_jumps = -1;
1967 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001968
peahdf3efa82015-11-28 12:35:15 -08001969 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001970 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1971 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001972 }
peahdf3efa82015-11-28 12:35:15 -08001973 capture_.aec_system_delay_jumps = -1;
1974 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001975}
1976
aleloi868f32f2017-05-23 07:20:05 -07001977void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1978 if (!aec_dump_) {
1979 return;
1980 }
1981 std::string experiments_description =
1982 public_submodules_->echo_cancellation->GetExperimentsDescription();
1983 // TODO(peah): Add semicolon-separated concatenations of experiment
1984 // descriptions for other submodules.
1985 if (capture_nonlocked_.level_controller_enabled) {
1986 experiments_description += "LevelController;";
1987 }
1988 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1989 experiments_description += "AgcClippingLevelExperiment;";
1990 }
1991 if (capture_nonlocked_.echo_canceller3_enabled) {
1992 experiments_description += "EchoCanceller3;";
1993 }
1994
1995 InternalAPMConfig apm_config;
1996
1997 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1998 apm_config.aec_delay_agnostic_enabled =
1999 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
2000 apm_config.aec_drift_compensation_enabled =
2001 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
2002 apm_config.aec_extended_filter_enabled =
2003 public_submodules_->echo_cancellation->is_extended_filter_enabled();
2004 apm_config.aec_suppression_level = static_cast<int>(
2005 public_submodules_->echo_cancellation->suppression_level());
2006
2007 apm_config.aecm_enabled =
2008 public_submodules_->echo_control_mobile->is_enabled();
2009 apm_config.aecm_comfort_noise_enabled =
2010 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
2011 apm_config.aecm_routing_mode =
2012 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
2013
2014 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2015 apm_config.agc_mode =
2016 static_cast<int>(public_submodules_->gain_control->mode());
2017 apm_config.agc_limiter_enabled =
2018 public_submodules_->gain_control->is_limiter_enabled();
2019 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2020
2021 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2022
2023 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2024 apm_config.ns_level =
2025 static_cast<int>(public_submodules_->noise_suppression->level());
2026
2027 apm_config.transient_suppression_enabled =
2028 capture_.transient_suppressor_enabled;
2029 apm_config.intelligibility_enhancer_enabled =
2030 capture_nonlocked_.intelligibility_enabled;
2031 apm_config.experiments_description = experiments_description;
2032
2033 if (!forced && apm_config == apm_config_for_aec_dump_) {
2034 return;
2035 }
2036 aec_dump_->WriteConfig(apm_config);
2037 apm_config_for_aec_dump_ = apm_config;
2038}
2039
2040void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2041 const float* const* src) {
2042 RTC_DCHECK(aec_dump_);
2043 WriteAecDumpConfigMessage(false);
2044
2045 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2046 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2047 aec_dump_->AddCaptureStreamInput(
2048 FloatAudioFrame(src, num_channels, channel_size));
2049 RecordAudioProcessingState();
2050}
2051
2052void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2053 const AudioFrame& capture_frame) {
2054 RTC_DCHECK(aec_dump_);
2055 WriteAecDumpConfigMessage(false);
2056
2057 aec_dump_->AddCaptureStreamInput(capture_frame);
2058 RecordAudioProcessingState();
2059}
2060
2061void AudioProcessingImpl::RecordProcessedCaptureStream(
2062 const float* const* processed_capture_stream) {
2063 RTC_DCHECK(aec_dump_);
2064
2065 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2066 const size_t num_channels =
2067 formats_.api_format.output_stream().num_channels();
2068 aec_dump_->AddCaptureStreamOutput(
2069 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
2070 aec_dump_->WriteCaptureStreamMessage();
2071}
2072
2073void AudioProcessingImpl::RecordProcessedCaptureStream(
2074 const AudioFrame& processed_capture_frame) {
2075 RTC_DCHECK(aec_dump_);
2076
2077 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2078 aec_dump_->WriteCaptureStreamMessage();
2079}
2080
2081void AudioProcessingImpl::RecordAudioProcessingState() {
2082 RTC_DCHECK(aec_dump_);
2083 AecDump::AudioProcessingState audio_proc_state;
2084 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2085 audio_proc_state.drift =
2086 public_submodules_->echo_cancellation->stream_drift_samples();
2087 audio_proc_state.level = gain_control()->stream_analog_level();
2088 audio_proc_state.keypress = capture_.key_pressed;
2089 aec_dump_->AddAudioProcessingState(audio_proc_state);
2090}
2091
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00002092#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08002093int AudioProcessingImpl::WriteMessageToDebugFile(
2094 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08002095 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08002096 rtc::CriticalSection* crit_debug,
2097 ApmDebugDumpThreadState* debug_state) {
2098 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00002099 if (size <= 0) {
2100 return kUnspecifiedError;
2101 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00002102#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07002103// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
2104// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00002105#endif
2106
peahdf3efa82015-11-28 12:35:15 -08002107 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00002108 return kUnspecifiedError;
2109 }
2110
peahdf3efa82015-11-28 12:35:15 -08002111 {
2112 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08002113 rtc::CritScope cs_debug(crit_debug);
2114
tommia6219cc2016-06-15 10:30:14 -07002115 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08002116 // Update the byte counter.
2117 if (*filesize_limit_bytes >= 0) {
2118 *filesize_limit_bytes -=
2119 (sizeof(int32_t) + debug_state->event_str.length());
2120 if (*filesize_limit_bytes < 0) {
2121 // Not enough bytes are left to write this message, so stop logging.
2122 debug_file->CloseFile();
2123 return kNoError;
2124 }
2125 }
peahdf3efa82015-11-28 12:35:15 -08002126 // Write message preceded by its size.
2127 if (!debug_file->Write(&size, sizeof(int32_t))) {
2128 return kFileError;
2129 }
2130 if (!debug_file->Write(debug_state->event_str.data(),
2131 debug_state->event_str.length())) {
2132 return kFileError;
2133 }
ajm@google.com808e0e02011-08-03 21:08:51 +00002134 }
2135
peahdf3efa82015-11-28 12:35:15 -08002136 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00002137
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002138 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00002139}
2140
2141int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08002142 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
2143 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
2144 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00002145
mbonadei7c2c8432017-04-07 00:59:12 -07002146 msg->set_num_input_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08002147 formats_.api_format.input_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07002148 msg->set_num_output_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08002149 formats_.api_format.output_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07002150 msg->set_num_reverse_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08002151 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08002152 msg->set_reverse_sample_rate(
2153 formats_.api_format.reverse_input_stream().sample_rate_hz());
2154 msg->set_output_sample_rate(
2155 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07002156 msg->set_reverse_output_sample_rate(
2157 formats_.api_format.reverse_output_stream().sample_rate_hz());
2158 msg->set_num_reverse_output_channels(
2159 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08002160
2161 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08002162 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08002163 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02002164 return kNoError;
2165}
2166
2167int AudioProcessingImpl::WriteConfigMessage(bool forced) {
2168 audioproc::Config config;
2169
peahdf3efa82015-11-28 12:35:15 -08002170 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002171 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08002172 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002173 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08002174 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002175 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08002176 public_submodules_->echo_cancellation->is_extended_filter_enabled());
2177 config.set_aec_suppression_level(static_cast<int>(
2178 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02002179
peahdf3efa82015-11-28 12:35:15 -08002180 config.set_aecm_enabled(
2181 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002182 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08002183 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
2184 config.set_aecm_routing_mode(static_cast<int>(
2185 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02002186
peahdf3efa82015-11-28 12:35:15 -08002187 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
2188 config.set_agc_mode(
2189 static_cast<int>(public_submodules_->gain_control->mode()));
2190 config.set_agc_limiter_enabled(
2191 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08002192 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02002193
peah8271d042016-11-22 07:24:52 -08002194 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02002195
peahdf3efa82015-11-28 12:35:15 -08002196 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
2197 config.set_ns_level(
2198 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02002199
peahdf3efa82015-11-28 12:35:15 -08002200 config.set_transient_suppression_enabled(
2201 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07002202 config.set_intelligibility_enhancer_enabled(
2203 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02002204
peah7789fe72016-04-15 01:19:44 -07002205 std::string experiments_description =
2206 public_submodules_->echo_cancellation->GetExperimentsDescription();
2207 // TODO(peah): Add semicolon-separated concatenations of experiment
2208 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07002209 if (capture_nonlocked_.level_controller_enabled) {
2210 experiments_description += "LevelController;";
2211 }
henrik.lundinbd681b92016-12-05 09:08:42 -08002212 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2213 experiments_description += "AgcClippingLevelExperiment;";
2214 }
peahe0eae3c2016-12-14 01:16:23 -08002215 if (capture_nonlocked_.echo_canceller3_enabled) {
2216 experiments_description += "EchoCanceller3;";
2217 }
peah7789fe72016-04-15 01:19:44 -07002218 config.set_experiments_description(experiments_description);
2219
mbonadei7c2c8432017-04-07 00:59:12 -07002220 ProtoString serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08002221 if (!forced &&
2222 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02002223 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00002224 }
2225
peahdf3efa82015-11-28 12:35:15 -08002226 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02002227
peahdf3efa82015-11-28 12:35:15 -08002228 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
2229 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02002230
peahdf3efa82015-11-28 12:35:15 -08002231 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08002232 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08002233 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00002234 return kNoError;
2235}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00002236#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002237
kwiberg83ffe452016-08-29 14:46:07 -07002238AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2239 bool transient_suppressor_enabled,
2240 const std::vector<Point>& array_geometry,
2241 SphericalPointf target_direction)
2242 : aec_system_delay_jumps(-1),
2243 delay_offset_ms(0),
2244 was_stream_delay_set(false),
2245 last_stream_delay_ms(0),
2246 last_aec_system_delay_ms(0),
2247 stream_delay_jumps(-1),
2248 output_will_be_muted(false),
2249 key_pressed(false),
2250 transient_suppressor_enabled(transient_suppressor_enabled),
2251 array_geometry(array_geometry),
2252 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002253 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002254 split_rate(kSampleRate16kHz),
2255 previous_agc_level(0),
2256 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002257
2258AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2259
2260AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2261
2262AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2263
niklase@google.com470e71d2011-07-07 08:21:25 +00002264} // namespace webrtc