blob: a96f8ff8ab656a488422ceb4ed24bbaab7ab286f [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
1313 RETURN_ON_ERR(public_submodules_->echo_control_mobile->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001314 capture_buffer, stream_delay_ms()));
peah253534d2016-03-15 04:32:28 -07001315
ivoc9f4a4a02016-10-28 05:39:16 -07001316
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001317 if (capture_nonlocked_.beamformer_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001318 private_submodules_->beamformer->PostFilter(capture_buffer->split_data_f());
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001319 }
1320
peahde65ddc2016-09-16 15:02:15 -07001321 public_submodules_->voice_detection->ProcessCaptureAudio(capture_buffer);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001322
peahbe615622016-02-13 16:40:47 -08001323 if (constants_.use_experimental_agc &&
peahdf3efa82015-11-28 12:35:15 -08001324 public_submodules_->gain_control->is_enabled() &&
aluebsb2328d12016-01-11 20:32:29 -08001325 (!capture_nonlocked_.beamformer_enabled ||
peahdf3efa82015-11-28 12:35:15 -08001326 private_submodules_->beamformer->is_target_present())) {
1327 private_submodules_->agc_manager->Process(
peahde65ddc2016-09-16 15:02:15 -07001328 capture_buffer->split_bands_const(0)[kBand0To8kHz],
1329 capture_buffer->num_frames_per_band(), capture_nonlocked_.split_rate);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001330 }
peahb8fbb542016-03-15 02:28:08 -07001331 RETURN_ON_ERR(public_submodules_->gain_control->ProcessCaptureAudio(
peahde65ddc2016-09-16 15:02:15 -07001332 capture_buffer, echo_cancellation()->stream_has_echo()));
niklase@google.com470e71d2011-07-07 08:21:25 +00001333
peah2ace3f92016-09-10 04:42:27 -07001334 if (submodule_states_.CaptureMultiBandProcessingActive() &&
1335 SampleRateSupportsMultiBand(
peahde65ddc2016-09-16 15:02:15 -07001336 capture_nonlocked_.capture_processing_format.sample_rate_hz())) {
1337 capture_buffer->MergeFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001338 }
1339
peah9e6a2902017-05-15 07:19:21 -07001340 if (config_.residual_echo_detector.enabled) {
1341 private_submodules_->residual_echo_detector->AnalyzeCaptureAudio(
1342 rtc::ArrayView<const float>(capture_buffer->channels_f()[0],
1343 capture_buffer->num_frames()));
1344 }
1345
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001346 // TODO(aluebs): Investigate if the transient suppression placement should be
1347 // before or after the AGC.
peahdf3efa82015-11-28 12:35:15 -08001348 if (capture_.transient_suppressor_enabled) {
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001349 float voice_probability =
peahdf3efa82015-11-28 12:35:15 -08001350 private_submodules_->agc_manager.get()
1351 ? private_submodules_->agc_manager->voice_probability()
1352 : 1.f;
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001353
peahdf3efa82015-11-28 12:35:15 -08001354 public_submodules_->transient_suppressor->Suppress(
peahde65ddc2016-09-16 15:02:15 -07001355 capture_buffer->channels_f()[0], capture_buffer->num_frames(),
1356 capture_buffer->num_channels(),
1357 capture_buffer->split_bands_const_f(0)[kBand0To8kHz],
1358 capture_buffer->num_frames_per_band(), capture_buffer->keyboard_data(),
1359 capture_buffer->num_keyboard_frames(), voice_probability,
peahdf3efa82015-11-28 12:35:15 -08001360 capture_.key_pressed);
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001361 }
1362
alessiob3ec96df2017-05-22 06:57:06 -07001363 if (capture_nonlocked_.gain_controller2_enabled) {
1364 private_submodules_->gain_controller2->Process(capture_buffer);
1365 }
1366
peahca4cac72016-06-29 15:26:12 -07001367 if (capture_nonlocked_.level_controller_enabled) {
peahde65ddc2016-09-16 15:02:15 -07001368 private_submodules_->level_controller->Process(capture_buffer);
peahca4cac72016-06-29 15:26:12 -07001369 }
1370
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001371 // The level estimator operates on the recombined data.
peahde65ddc2016-09-16 15:02:15 -07001372 public_submodules_->level_estimator->ProcessStream(capture_buffer);
ajm@google.com808e0e02011-08-03 21:08:51 +00001373
peah1b08dc32016-12-20 13:45:58 -08001374 capture_output_rms_.Analyze(rtc::ArrayView<const int16_t>(
1375 capture_buffer->channels_const()[0],
1376 capture_nonlocked_.capture_processing_format.num_frames()));
1377 if (log_rms) {
1378 RmsLevel::Levels levels = capture_output_rms_.AverageAndPeak();
1379 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelAverageRms",
1380 levels.average, 1, RmsLevel::kMinLevelDb, 64);
1381 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.ApmCaptureOutputLevelPeakRms",
1382 levels.peak, 1, RmsLevel::kMinLevelDb, 64);
1383 }
1384
peahdf3efa82015-11-28 12:35:15 -08001385 capture_.was_stream_delay_set = false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001386 return kNoError;
1387}
1388
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001389int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001390 size_t samples_per_channel,
peahde65ddc2016-09-16 15:02:15 -07001391 int sample_rate_hz,
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001392 ChannelLayout layout) {
peah369f8282015-12-17 06:42:29 -08001393 TRACE_EVENT0("webrtc", "AudioProcessing::AnalyzeReverseStream_ChannelLayout");
peahdf3efa82015-11-28 12:35:15 -08001394 rtc::CritScope cs(&crit_render_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001395 const StreamConfig reverse_config = {
peahde65ddc2016-09-16 15:02:15 -07001396 sample_rate_hz, ChannelsFromLayout(layout), LayoutHasKeyboard(layout),
Michael Graczyk86c6d332015-07-23 11:41:39 -07001397 };
1398 if (samples_per_channel != reverse_config.num_frames()) {
1399 return kBadDataLengthError;
1400 }
peahdf3efa82015-11-28 12:35:15 -08001401 return AnalyzeReverseStreamLocked(data, reverse_config, reverse_config);
ekmeyerson60d9b332015-08-14 10:35:55 -07001402}
1403
peahde65ddc2016-09-16 15:02:15 -07001404int AudioProcessingImpl::ProcessReverseStream(const float* const* src,
1405 const StreamConfig& input_config,
1406 const StreamConfig& output_config,
1407 float* const* dest) {
peah369f8282015-12-17 06:42:29 -08001408 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_StreamConfig");
peahdf3efa82015-11-28 12:35:15 -08001409 rtc::CritScope cs(&crit_render_);
peahde65ddc2016-09-16 15:02:15 -07001410 RETURN_ON_ERR(AnalyzeReverseStreamLocked(src, input_config, output_config));
peah2ace3f92016-09-10 04:42:27 -07001411 if (submodule_states_.RenderMultiBandProcessingActive()) {
peahdf3efa82015-11-28 12:35:15 -08001412 render_.render_audio->CopyTo(formats_.api_format.reverse_output_stream(),
1413 dest);
peah2ace3f92016-09-10 04:42:27 -07001414 } else if (formats_.api_format.reverse_input_stream() !=
1415 formats_.api_format.reverse_output_stream()) {
peahde65ddc2016-09-16 15:02:15 -07001416 render_.render_converter->Convert(src, input_config.num_samples(), dest,
1417 output_config.num_samples());
ekmeyerson60d9b332015-08-14 10:35:55 -07001418 } else {
peahde65ddc2016-09-16 15:02:15 -07001419 CopyAudioIfNeeded(src, input_config.num_frames(),
1420 input_config.num_channels(), dest);
ekmeyerson60d9b332015-08-14 10:35:55 -07001421 }
1422
1423 return kNoError;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001424}
1425
peahdf3efa82015-11-28 12:35:15 -08001426int AudioProcessingImpl::AnalyzeReverseStreamLocked(
ekmeyerson60d9b332015-08-14 10:35:55 -07001427 const float* const* src,
peahde65ddc2016-09-16 15:02:15 -07001428 const StreamConfig& input_config,
1429 const StreamConfig& output_config) {
peahdf3efa82015-11-28 12:35:15 -08001430 if (src == nullptr) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001431 return kNullPointerError;
1432 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001433
peahde65ddc2016-09-16 15:02:15 -07001434 if (input_config.num_channels() == 0) {
Michael Graczyk86c6d332015-07-23 11:41:39 -07001435 return kBadNumberChannelsError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001436 }
1437
peahdf3efa82015-11-28 12:35:15 -08001438 ProcessingConfig processing_config = formats_.api_format;
peahde65ddc2016-09-16 15:02:15 -07001439 processing_config.reverse_input_stream() = input_config;
1440 processing_config.reverse_output_stream() = output_config;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001441
peahdf3efa82015-11-28 12:35:15 -08001442 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
peahde65ddc2016-09-16 15:02:15 -07001443 assert(input_config.num_frames() ==
1444 formats_.api_format.reverse_input_stream().num_frames());
Michael Graczyk86c6d332015-07-23 11:41:39 -07001445
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001446#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001447 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001448 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1449 audioproc::ReverseStream* msg =
1450 debug_dump_.render.event_msg->mutable_reverse_stream();
aluebs@webrtc.org59a1b1b2014-08-28 10:43:09 +00001451 const size_t channel_size =
peahdf3efa82015-11-28 12:35:15 -08001452 sizeof(float) * formats_.api_format.reverse_input_stream().num_frames();
Peter Kasting69558702016-01-12 16:26:35 -08001453 for (size_t i = 0;
peahdf3efa82015-11-28 12:35:15 -08001454 i < formats_.api_format.reverse_input_stream().num_channels(); ++i)
ekmeyerson60d9b332015-08-14 10:35:55 -07001455 msg->add_channel(src[i], channel_size);
peahdf3efa82015-11-28 12:35:15 -08001456 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001457 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001458 &crit_debug_, &debug_dump_.render));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001459 }
1460#endif
aleloi868f32f2017-05-23 07:20:05 -07001461 if (aec_dump_) {
1462 const size_t channel_size =
1463 formats_.api_format.reverse_input_stream().num_frames();
1464 const size_t num_channels =
1465 formats_.api_format.reverse_input_stream().num_channels();
1466 aec_dump_->WriteRenderStreamMessage(
1467 FloatAudioFrame(src, num_channels, channel_size));
1468 }
peahdf3efa82015-11-28 12:35:15 -08001469 render_.render_audio->CopyFrom(src,
1470 formats_.api_format.reverse_input_stream());
peahde65ddc2016-09-16 15:02:15 -07001471 return ProcessRenderStreamLocked();
ekmeyerson60d9b332015-08-14 10:35:55 -07001472}
1473
1474int AudioProcessingImpl::ProcessReverseStream(AudioFrame* frame) {
peah369f8282015-12-17 06:42:29 -08001475 TRACE_EVENT0("webrtc", "AudioProcessing::ProcessReverseStream_AudioFrame");
peahdf3efa82015-11-28 12:35:15 -08001476 rtc::CritScope cs(&crit_render_);
peahdf3efa82015-11-28 12:35:15 -08001477 if (frame == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001478 return kNullPointerError;
1479 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001480 // Must be a native rate.
1481 if (frame->sample_rate_hz_ != kSampleRate8kHz &&
1482 frame->sample_rate_hz_ != kSampleRate16kHz &&
aluebs@webrtc.org087da132014-11-17 23:01:23 +00001483 frame->sample_rate_hz_ != kSampleRate32kHz &&
1484 frame->sample_rate_hz_ != kSampleRate48kHz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001485 return kBadSampleRateError;
1486 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001487
Michael Graczyk86c6d332015-07-23 11:41:39 -07001488 if (frame->num_channels_ <= 0) {
1489 return kBadNumberChannelsError;
1490 }
1491
peahdf3efa82015-11-28 12:35:15 -08001492 ProcessingConfig processing_config = formats_.api_format;
ekmeyerson60d9b332015-08-14 10:35:55 -07001493 processing_config.reverse_input_stream().set_sample_rate_hz(
1494 frame->sample_rate_hz_);
1495 processing_config.reverse_input_stream().set_num_channels(
1496 frame->num_channels_);
1497 processing_config.reverse_output_stream().set_sample_rate_hz(
1498 frame->sample_rate_hz_);
1499 processing_config.reverse_output_stream().set_num_channels(
1500 frame->num_channels_);
Michael Graczyk86c6d332015-07-23 11:41:39 -07001501
peahdf3efa82015-11-28 12:35:15 -08001502 RETURN_ON_ERR(MaybeInitializeRender(processing_config));
Michael Graczyk86c6d332015-07-23 11:41:39 -07001503 if (frame->samples_per_channel_ !=
peahdf3efa82015-11-28 12:35:15 -08001504 formats_.api_format.reverse_input_stream().num_frames()) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001505 return kBadDataLengthError;
1506 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001507
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001508#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
tommia6219cc2016-06-15 10:30:14 -07001509 if (debug_dump_.debug_file->is_open()) {
peahdf3efa82015-11-28 12:35:15 -08001510 debug_dump_.render.event_msg->set_type(audioproc::Event::REVERSE_STREAM);
1511 audioproc::ReverseStream* msg =
1512 debug_dump_.render.event_msg->mutable_reverse_stream();
Michael Graczyk86c6d332015-07-23 11:41:39 -07001513 const size_t data_size =
1514 sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001515 msg->set_data(frame->data_, data_size);
peahdf3efa82015-11-28 12:35:15 -08001516 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08001517 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08001518 &crit_debug_, &debug_dump_.render));
niklase@google.com470e71d2011-07-07 08:21:25 +00001519 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001520#endif
aleloi868f32f2017-05-23 07:20:05 -07001521 if (aec_dump_) {
1522 aec_dump_->WriteRenderStreamMessage(*frame);
1523 }
1524
peahdf3efa82015-11-28 12:35:15 -08001525 render_.render_audio->DeinterleaveFrom(frame);
peahde65ddc2016-09-16 15:02:15 -07001526 RETURN_ON_ERR(ProcessRenderStreamLocked());
peah2ace3f92016-09-10 04:42:27 -07001527 render_.render_audio->InterleaveTo(
1528 frame, submodule_states_.RenderMultiBandProcessingActive());
aluebsb0319552016-03-17 20:39:53 -07001529 return kNoError;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001530}
niklase@google.com470e71d2011-07-07 08:21:25 +00001531
peahde65ddc2016-09-16 15:02:15 -07001532int AudioProcessingImpl::ProcessRenderStreamLocked() {
1533 AudioBuffer* render_buffer = render_.render_audio.get(); // For brevity.
peah9e6a2902017-05-15 07:19:21 -07001534
1535 QueueNonbandedRenderAudio(render_buffer);
1536
peah2ace3f92016-09-10 04:42:27 -07001537 if (submodule_states_.RenderMultiBandSubModulesActive() &&
peahde65ddc2016-09-16 15:02:15 -07001538 SampleRateSupportsMultiBand(
1539 formats_.render_processing_format.sample_rate_hz())) {
1540 render_buffer->SplitIntoFrequencyBands();
niklase@google.com470e71d2011-07-07 08:21:25 +00001541 }
1542
peah1bcfce52016-08-26 07:16:04 -07001543#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001544 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001545 public_submodules_->intelligibility_enhancer->ProcessRenderAudio(
Alejandro Luebsef009252016-09-20 14:51:56 -07001546 render_buffer);
ekmeyerson60d9b332015-08-14 10:35:55 -07001547 }
peah1bcfce52016-08-26 07:16:04 -07001548#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001549
peahce4d9152017-05-19 01:28:05 -07001550 if (submodule_states_.RenderMultiBandSubModulesActive()) {
1551 QueueBandedRenderAudio(render_buffer);
1552 }
1553
peahe0eae3c2016-12-14 01:16:23 -08001554 // TODO(peah): Perform the queueing ínside QueueRenderAudiuo().
1555 if (private_submodules_->echo_canceller3) {
peahcf02cf12017-04-05 14:18:07 -07001556 private_submodules_->echo_canceller3->AnalyzeRender(render_buffer);
peahe0eae3c2016-12-14 01:16:23 -08001557 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001558
peah2ace3f92016-09-10 04:42:27 -07001559 if (submodule_states_.RenderMultiBandProcessingActive() &&
peahde65ddc2016-09-16 15:02:15 -07001560 SampleRateSupportsMultiBand(
1561 formats_.render_processing_format.sample_rate_hz())) {
1562 render_buffer->MergeFrequencyBands();
ekmeyerson60d9b332015-08-14 10:35:55 -07001563 }
1564
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001565 return kNoError;
niklase@google.com470e71d2011-07-07 08:21:25 +00001566}
1567
1568int AudioProcessingImpl::set_stream_delay_ms(int delay) {
peahdf3efa82015-11-28 12:35:15 -08001569 rtc::CritScope cs(&crit_capture_);
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001570 Error retval = kNoError;
peahdf3efa82015-11-28 12:35:15 -08001571 capture_.was_stream_delay_set = true;
1572 delay += capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001573
niklase@google.com470e71d2011-07-07 08:21:25 +00001574 if (delay < 0) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001575 delay = 0;
1576 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001577 }
1578
1579 // TODO(ajm): the max is rather arbitrarily chosen; investigate.
1580 if (delay > 500) {
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001581 delay = 500;
1582 retval = kBadStreamParameterWarning;
niklase@google.com470e71d2011-07-07 08:21:25 +00001583 }
1584
peahdf3efa82015-11-28 12:35:15 -08001585 capture_nonlocked_.stream_delay_ms = delay;
andrew@webrtc.org5f23d642012-05-29 21:14:06 +00001586 return retval;
niklase@google.com470e71d2011-07-07 08:21:25 +00001587}
1588
1589int AudioProcessingImpl::stream_delay_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001590 // Used as callback from submodules, hence locking is not allowed.
1591 return capture_nonlocked_.stream_delay_ms;
niklase@google.com470e71d2011-07-07 08:21:25 +00001592}
1593
1594bool AudioProcessingImpl::was_stream_delay_set() const {
peahdf3efa82015-11-28 12:35:15 -08001595 // Used as callback from submodules, hence locking is not allowed.
1596 return capture_.was_stream_delay_set;
niklase@google.com470e71d2011-07-07 08:21:25 +00001597}
1598
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001599void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
peahdf3efa82015-11-28 12:35:15 -08001600 rtc::CritScope cs(&crit_capture_);
1601 capture_.key_pressed = key_pressed;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001602}
1603
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001604void AudioProcessingImpl::set_delay_offset_ms(int offset) {
peahdf3efa82015-11-28 12:35:15 -08001605 rtc::CritScope cs(&crit_capture_);
1606 capture_.delay_offset_ms = offset;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001607}
1608
1609int AudioProcessingImpl::delay_offset_ms() const {
peahdf3efa82015-11-28 12:35:15 -08001610 rtc::CritScope cs(&crit_capture_);
1611 return capture_.delay_offset_ms;
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +00001612}
1613
aleloi868f32f2017-05-23 07:20:05 -07001614void AudioProcessingImpl::AttachAecDump(std::unique_ptr<AecDump> aec_dump) {
1615 RTC_DCHECK(aec_dump);
1616 rtc::CritScope cs_render(&crit_render_);
1617 rtc::CritScope cs_capture(&crit_capture_);
1618
1619 // The previously attached AecDump will be destroyed with the
1620 // 'aec_dump' parameter, which is after locks are released.
1621 aec_dump_.swap(aec_dump);
1622 WriteAecDumpConfigMessage(true);
1623 aec_dump_->WriteInitMessage(ToStreamsConfig(formats_.api_format));
1624}
1625
1626void AudioProcessingImpl::DetachAecDump() {
1627 // The d-tor of a task-queue based AecDump blocks until all pending
1628 // tasks are done. This construction avoids blocking while holding
1629 // the render and capture locks.
1630 std::unique_ptr<AecDump> aec_dump = nullptr;
1631 {
1632 rtc::CritScope cs_render(&crit_render_);
1633 rtc::CritScope cs_capture(&crit_capture_);
1634 aec_dump = std::move(aec_dump_);
1635 }
1636}
1637
niklase@google.com470e71d2011-07-07 08:21:25 +00001638int AudioProcessingImpl::StartDebugRecording(
ivocd66b44d2016-01-15 03:06:36 -08001639 const char filename[AudioProcessing::kMaxFilenameSize],
1640 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001641 // Run in a single-threaded manner.
1642 rtc::CritScope cs_render(&crit_render_);
1643 rtc::CritScope cs_capture(&crit_capture_);
André Susano Pinto664cdaf2015-05-20 11:11:07 +02001644 static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
niklase@google.com470e71d2011-07-07 08:21:25 +00001645
peahdf3efa82015-11-28 12:35:15 -08001646 if (filename == nullptr) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001647 return kNullPointerError;
1648 }
1649
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001650#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001651 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
niklase@google.com470e71d2011-07-07 08:21:25 +00001652 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001653 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001654
tommia6219cc2016-06-15 10:30:14 -07001655 if (!debug_dump_.debug_file->OpenFile(filename, false)) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001656 return kFileError;
1657 }
1658
Minyue13b96ba2015-10-03 00:39:14 +02001659 RETURN_ON_ERR(WriteConfigMessage(true));
1660 RETURN_ON_ERR(WriteInitMessage());
niklase@google.com470e71d2011-07-07 08:21:25 +00001661 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001662#else
1663 return kUnsupportedFunctionError;
1664#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001665}
1666
ivocd66b44d2016-01-15 03:06:36 -08001667int AudioProcessingImpl::StartDebugRecording(FILE* handle,
1668 int64_t max_log_size_bytes) {
peahdf3efa82015-11-28 12:35:15 -08001669 // Run in a single-threaded manner.
1670 rtc::CritScope cs_render(&crit_render_);
1671 rtc::CritScope cs_capture(&crit_capture_);
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001672
peahdf3efa82015-11-28 12:35:15 -08001673 if (handle == nullptr) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001674 return kNullPointerError;
1675 }
1676
1677#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
ivocd66b44d2016-01-15 03:06:36 -08001678 debug_dump_.num_bytes_left_for_log_ = max_log_size_bytes;
1679
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001680 // Stop any ongoing recording.
tommia6219cc2016-06-15 10:30:14 -07001681 debug_dump_.debug_file->CloseFile();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001682
tommia6219cc2016-06-15 10:30:14 -07001683 if (!debug_dump_.debug_file->OpenFromFileHandle(handle)) {
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001684 return kFileError;
1685 }
1686
Minyue13b96ba2015-10-03 00:39:14 +02001687 RETURN_ON_ERR(WriteConfigMessage(true));
1688 RETURN_ON_ERR(WriteInitMessage());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001689 return kNoError;
1690#else
1691 return kUnsupportedFunctionError;
1692#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1693}
1694
peah73a28ee2016-10-12 03:01:49 -07001695int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
1696 return StartDebugRecording(handle, -1);
1697}
1698
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001699int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
1700 rtc::PlatformFile handle) {
peahdf3efa82015-11-28 12:35:15 -08001701 // Run in a single-threaded manner.
1702 rtc::CritScope cs_render(&crit_render_);
1703 rtc::CritScope cs_capture(&crit_capture_);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001704 FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
ivocd66b44d2016-01-15 03:06:36 -08001705 return StartDebugRecording(stream, -1);
xians@webrtc.orge46bc772014-10-10 08:36:56 +00001706}
1707
niklase@google.com470e71d2011-07-07 08:21:25 +00001708int AudioProcessingImpl::StopDebugRecording() {
aleloi868f32f2017-05-23 07:20:05 -07001709 DetachAecDump();
1710
1711#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08001712 // Run in a single-threaded manner.
1713 rtc::CritScope cs_render(&crit_render_);
1714 rtc::CritScope cs_capture(&crit_capture_);
niklase@google.com470e71d2011-07-07 08:21:25 +00001715 // We just return if recording hasn't started.
tommia6219cc2016-06-15 10:30:14 -07001716 debug_dump_.debug_file->CloseFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001717 return kNoError;
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001718#else
1719 return kUnsupportedFunctionError;
1720#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
niklase@google.com470e71d2011-07-07 08:21:25 +00001721}
1722
ivoc4e477a12017-01-15 08:29:46 -08001723AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics() {
1724 residual_echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1725 echo_return_loss.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1726 echo_return_loss_enhancement.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1727 a_nlp.Set(-100.0f, -100.0f, -100.0f, -100.0f);
1728}
1729
1730AudioProcessing::AudioProcessingStatistics::AudioProcessingStatistics(
1731 const AudioProcessingStatistics& other) = default;
1732
1733AudioProcessing::AudioProcessingStatistics::~AudioProcessingStatistics() =
1734 default;
1735
ivoc3e9a5372016-10-28 07:55:33 -07001736// TODO(ivoc): Remove this when GetStatistics() becomes pure virtual.
1737AudioProcessing::AudioProcessingStatistics AudioProcessing::GetStatistics()
1738 const {
1739 return AudioProcessingStatistics();
1740}
1741
1742AudioProcessing::AudioProcessingStatistics AudioProcessingImpl::GetStatistics()
1743 const {
1744 AudioProcessingStatistics stats;
1745 EchoCancellation::Metrics metrics;
ivocd0a151c2016-11-02 09:14:37 -07001746 int success = public_submodules_->echo_cancellation->GetMetrics(&metrics);
1747 if (success == Error::kNoError) {
1748 stats.a_nlp.Set(metrics.a_nlp);
1749 stats.divergent_filter_fraction = metrics.divergent_filter_fraction;
1750 stats.echo_return_loss.Set(metrics.echo_return_loss);
1751 stats.echo_return_loss_enhancement.Set(
1752 metrics.echo_return_loss_enhancement);
1753 stats.residual_echo_return_loss.Set(metrics.residual_echo_return_loss);
1754 }
ivoc9c192b22017-03-16 04:22:14 -07001755 {
1756 rtc::CritScope cs_capture(&crit_capture_);
1757 stats.residual_echo_likelihood =
1758 private_submodules_->residual_echo_detector->echo_likelihood();
1759 stats.residual_echo_likelihood_recent_max =
1760 private_submodules_->residual_echo_detector
1761 ->echo_likelihood_recent_max();
1762 }
ivoc3e9a5372016-10-28 07:55:33 -07001763 public_submodules_->echo_cancellation->GetDelayMetrics(
1764 &stats.delay_median, &stats.delay_standard_deviation,
1765 &stats.fraction_poor_delays);
1766 return stats;
1767}
1768
niklase@google.com470e71d2011-07-07 08:21:25 +00001769EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
peahb624d8c2016-03-05 03:01:14 -08001770 return public_submodules_->echo_cancellation.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001771}
1772
1773EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
peahbb9edbd2016-03-10 12:54:25 -08001774 return public_submodules_->echo_control_mobile.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001775}
1776
1777GainControl* AudioProcessingImpl::gain_control() const {
peahbe615622016-02-13 16:40:47 -08001778 if (constants_.use_experimental_agc) {
1779 return public_submodules_->gain_control_for_experimental_agc.get();
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001780 }
peahbfa97112016-03-10 21:09:04 -08001781 return public_submodules_->gain_control.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001782}
1783
1784HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
peah8271d042016-11-22 07:24:52 -08001785 return high_pass_filter_impl_.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001786}
1787
1788LevelEstimator* AudioProcessingImpl::level_estimator() const {
solenberg949028f2015-12-15 11:39:38 -08001789 return public_submodules_->level_estimator.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001790}
1791
1792NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
solenberg5e465c32015-12-08 13:22:33 -08001793 return public_submodules_->noise_suppression.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001794}
1795
1796VoiceDetection* AudioProcessingImpl::voice_detection() const {
solenberga29386c2015-12-16 03:31:12 -08001797 return public_submodules_->voice_detection.get();
niklase@google.com470e71d2011-07-07 08:21:25 +00001798}
1799
peah8271d042016-11-22 07:24:52 -08001800void AudioProcessingImpl::MutateConfig(
1801 rtc::FunctionView<void(AudioProcessing::Config*)> mutator) {
1802 rtc::CritScope cs_render(&crit_render_);
1803 rtc::CritScope cs_capture(&crit_capture_);
1804 mutator(&config_);
1805 ApplyConfig(config_);
1806}
1807
1808AudioProcessing::Config AudioProcessingImpl::GetConfig() const {
1809 rtc::CritScope cs_render(&crit_render_);
1810 rtc::CritScope cs_capture(&crit_capture_);
1811 return config_;
1812}
1813
peah2ace3f92016-09-10 04:42:27 -07001814bool AudioProcessingImpl::UpdateActiveSubmoduleStates() {
1815 return submodule_states_.Update(
peah8271d042016-11-22 07:24:52 -08001816 config_.high_pass_filter.enabled,
peah2ace3f92016-09-10 04:42:27 -07001817 public_submodules_->echo_cancellation->is_enabled(),
1818 public_submodules_->echo_control_mobile->is_enabled(),
ivoc9f4a4a02016-10-28 05:39:16 -07001819 config_.residual_echo_detector.enabled,
peah2ace3f92016-09-10 04:42:27 -07001820 public_submodules_->noise_suppression->is_enabled(),
1821 capture_nonlocked_.intelligibility_enabled,
1822 capture_nonlocked_.beamformer_enabled,
1823 public_submodules_->gain_control->is_enabled(),
alessiob3ec96df2017-05-22 06:57:06 -07001824 capture_nonlocked_.gain_controller2_enabled,
peah2ace3f92016-09-10 04:42:27 -07001825 capture_nonlocked_.level_controller_enabled,
peahe0eae3c2016-12-14 01:16:23 -08001826 capture_nonlocked_.echo_canceller3_enabled,
peah2ace3f92016-09-10 04:42:27 -07001827 public_submodules_->voice_detection->is_enabled(),
1828 public_submodules_->level_estimator->is_enabled(),
1829 capture_.transient_suppressor_enabled);
ekmeyerson60d9b332015-08-14 10:35:55 -07001830}
1831
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001832
Bjorn Volckeradc46c42015-04-15 11:42:40 +02001833void AudioProcessingImpl::InitializeTransient() {
peahdf3efa82015-11-28 12:35:15 -08001834 if (capture_.transient_suppressor_enabled) {
1835 if (!public_submodules_->transient_suppressor.get()) {
1836 public_submodules_->transient_suppressor.reset(new TransientSuppressor());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001837 }
peahdf3efa82015-11-28 12:35:15 -08001838 public_submodules_->transient_suppressor->Initialize(
peahde65ddc2016-09-16 15:02:15 -07001839 capture_nonlocked_.capture_processing_format.sample_rate_hz(),
1840 capture_nonlocked_.split_rate, num_proc_channels());
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001841 }
pbos@webrtc.org788acd12014-12-15 09:41:24 +00001842}
1843
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001844void AudioProcessingImpl::InitializeBeamformer() {
aluebsb2328d12016-01-11 20:32:29 -08001845 if (capture_nonlocked_.beamformer_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001846 if (!private_submodules_->beamformer) {
1847 private_submodules_->beamformer.reset(new NonlinearBeamformer(
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001848 capture_.array_geometry, 1u, capture_.target_direction));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001849 }
peahdf3efa82015-11-28 12:35:15 -08001850 private_submodules_->beamformer->Initialize(kChunkSizeMs,
1851 capture_nonlocked_.split_rate);
aluebs@webrtc.orgae643ce2014-12-19 19:57:34 +00001852 }
1853}
1854
ekmeyerson60d9b332015-08-14 10:35:55 -07001855void AudioProcessingImpl::InitializeIntelligibility() {
peah1bcfce52016-08-26 07:16:04 -07001856#if WEBRTC_INTELLIGIBILITY_ENHANCER
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07001857 if (capture_nonlocked_.intelligibility_enabled) {
peahdf3efa82015-11-28 12:35:15 -08001858 public_submodules_->intelligibility_enhancer.reset(
Alejandro Luebs18fcbcf2016-02-22 15:57:38 -08001859 new IntelligibilityEnhancer(capture_nonlocked_.split_rate,
Alex Luebs57ae8292016-03-09 16:24:34 +01001860 render_.render_audio->num_channels(),
Alejandro Luebsef009252016-09-20 14:51:56 -07001861 render_.render_audio->num_bands(),
Alex Luebs57ae8292016-03-09 16:24:34 +01001862 NoiseSuppressionImpl::num_noise_bins()));
ekmeyerson60d9b332015-08-14 10:35:55 -07001863 }
peah1bcfce52016-08-26 07:16:04 -07001864#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001865}
1866
peah8271d042016-11-22 07:24:52 -08001867void AudioProcessingImpl::InitializeLowCutFilter() {
1868 if (config_.high_pass_filter.enabled) {
1869 private_submodules_->low_cut_filter.reset(
1870 new LowCutFilter(num_proc_channels(), proc_sample_rate_hz()));
1871 } else {
1872 private_submodules_->low_cut_filter.reset();
1873 }
1874}
alessiob3ec96df2017-05-22 06:57:06 -07001875
peahe0eae3c2016-12-14 01:16:23 -08001876void AudioProcessingImpl::InitializeEchoCanceller3() {
1877 if (capture_nonlocked_.echo_canceller3_enabled) {
1878 private_submodules_->echo_canceller3.reset(
1879 new EchoCanceller3(proc_sample_rate_hz(), true));
1880 } else {
1881 private_submodules_->echo_canceller3.reset();
1882 }
1883}
peah8271d042016-11-22 07:24:52 -08001884
alessiob3ec96df2017-05-22 06:57:06 -07001885void AudioProcessingImpl::InitializeGainController2() {
1886 if (capture_nonlocked_.gain_controller2_enabled) {
1887 private_submodules_->gain_controller2.reset(
1888 new GainController2(proc_sample_rate_hz()));
1889 } else {
1890 private_submodules_->gain_controller2.reset();
1891 }
1892}
1893
peahca4cac72016-06-29 15:26:12 -07001894void AudioProcessingImpl::InitializeLevelController() {
1895 private_submodules_->level_controller->Initialize(proc_sample_rate_hz());
1896}
1897
ivoc9f4a4a02016-10-28 05:39:16 -07001898void AudioProcessingImpl::InitializeResidualEchoDetector() {
1899 private_submodules_->residual_echo_detector->Initialize();
1900}
1901
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001902void AudioProcessingImpl::MaybeUpdateHistograms() {
Bjorn Volckerd92f2672015-07-05 10:46:01 +02001903 static const int kMinDiffDelayMs = 60;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001904
1905 if (echo_cancellation()->is_enabled()) {
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001906 // Activate delay_jumps_ counters if we know echo_cancellation is runnning.
1907 // If a stream has echo we know that the echo_cancellation is in process.
peahdf3efa82015-11-28 12:35:15 -08001908 if (capture_.stream_delay_jumps == -1 &&
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001909 echo_cancellation()->stream_has_echo()) {
peahdf3efa82015-11-28 12:35:15 -08001910 capture_.stream_delay_jumps = 0;
1911 }
1912 if (capture_.aec_system_delay_jumps == -1 &&
1913 echo_cancellation()->stream_has_echo()) {
1914 capture_.aec_system_delay_jumps = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001915 }
1916
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001917 // Detect a jump in platform reported system delay and log the difference.
peahdf3efa82015-11-28 12:35:15 -08001918 const int diff_stream_delay_ms =
1919 capture_nonlocked_.stream_delay_ms - capture_.last_stream_delay_ms;
1920 if (diff_stream_delay_ms > kMinDiffDelayMs &&
1921 capture_.last_stream_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001922 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
1923 diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
peahdf3efa82015-11-28 12:35:15 -08001924 if (capture_.stream_delay_jumps == -1) {
1925 capture_.stream_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001926 }
peahdf3efa82015-11-28 12:35:15 -08001927 capture_.stream_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001928 }
peahdf3efa82015-11-28 12:35:15 -08001929 capture_.last_stream_delay_ms = capture_nonlocked_.stream_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001930
1931 // Detect a jump in AEC system delay and log the difference.
peah20028c42016-03-04 11:50:54 -08001932 const int samples_per_ms =
peahdf3efa82015-11-28 12:35:15 -08001933 rtc::CheckedDivExact(capture_nonlocked_.split_rate, 1000);
peah20028c42016-03-04 11:50:54 -08001934 RTC_DCHECK_LT(0, samples_per_ms);
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001935 const int aec_system_delay_ms =
peah20028c42016-03-04 11:50:54 -08001936 public_submodules_->echo_cancellation->GetSystemDelayInSamples() /
1937 samples_per_ms;
Michael Graczyk86c6d332015-07-23 11:41:39 -07001938 const int diff_aec_system_delay_ms =
peahdf3efa82015-11-28 12:35:15 -08001939 aec_system_delay_ms - capture_.last_aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001940 if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
peahdf3efa82015-11-28 12:35:15 -08001941 capture_.last_aec_system_delay_ms != 0) {
asaperssona2c58e22016-03-07 01:52:59 -08001942 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
1943 diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
1944 100);
peahdf3efa82015-11-28 12:35:15 -08001945 if (capture_.aec_system_delay_jumps == -1) {
1946 capture_.aec_system_delay_jumps = 0; // Activate counter if needed.
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001947 }
peahdf3efa82015-11-28 12:35:15 -08001948 capture_.aec_system_delay_jumps++;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001949 }
peahdf3efa82015-11-28 12:35:15 -08001950 capture_.last_aec_system_delay_ms = aec_system_delay_ms;
Bjorn Volcker1ca324f2015-06-29 14:57:29 +02001951 }
1952}
1953
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001954void AudioProcessingImpl::UpdateHistogramsOnCallEnd() {
peahdf3efa82015-11-28 12:35:15 -08001955 // Run in a single-threaded manner.
1956 rtc::CritScope cs_render(&crit_render_);
1957 rtc::CritScope cs_capture(&crit_capture_);
1958
1959 if (capture_.stream_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001960 RTC_HISTOGRAM_ENUMERATION(
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001961 "WebRTC.Audio.NumOfPlatformReportedStreamDelayJumps",
peahdf3efa82015-11-28 12:35:15 -08001962 capture_.stream_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001963 }
peahdf3efa82015-11-28 12:35:15 -08001964 capture_.stream_delay_jumps = -1;
1965 capture_.last_stream_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001966
peahdf3efa82015-11-28 12:35:15 -08001967 if (capture_.aec_system_delay_jumps > -1) {
asaperssona2c58e22016-03-07 01:52:59 -08001968 RTC_HISTOGRAM_ENUMERATION("WebRTC.Audio.NumOfAecSystemDelayJumps",
1969 capture_.aec_system_delay_jumps, 51);
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001970 }
peahdf3efa82015-11-28 12:35:15 -08001971 capture_.aec_system_delay_jumps = -1;
1972 capture_.last_aec_system_delay_ms = 0;
Bjorn Volcker4e7aa432015-07-07 11:50:05 +02001973}
1974
aleloi868f32f2017-05-23 07:20:05 -07001975void AudioProcessingImpl::WriteAecDumpConfigMessage(bool forced) {
1976 if (!aec_dump_) {
1977 return;
1978 }
1979 std::string experiments_description =
1980 public_submodules_->echo_cancellation->GetExperimentsDescription();
1981 // TODO(peah): Add semicolon-separated concatenations of experiment
1982 // descriptions for other submodules.
1983 if (capture_nonlocked_.level_controller_enabled) {
1984 experiments_description += "LevelController;";
1985 }
1986 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
1987 experiments_description += "AgcClippingLevelExperiment;";
1988 }
1989 if (capture_nonlocked_.echo_canceller3_enabled) {
1990 experiments_description += "EchoCanceller3;";
1991 }
1992
1993 InternalAPMConfig apm_config;
1994
1995 apm_config.aec_enabled = public_submodules_->echo_cancellation->is_enabled();
1996 apm_config.aec_delay_agnostic_enabled =
1997 public_submodules_->echo_cancellation->is_delay_agnostic_enabled();
1998 apm_config.aec_drift_compensation_enabled =
1999 public_submodules_->echo_cancellation->is_drift_compensation_enabled();
2000 apm_config.aec_extended_filter_enabled =
2001 public_submodules_->echo_cancellation->is_extended_filter_enabled();
2002 apm_config.aec_suppression_level = static_cast<int>(
2003 public_submodules_->echo_cancellation->suppression_level());
2004
2005 apm_config.aecm_enabled =
2006 public_submodules_->echo_control_mobile->is_enabled();
2007 apm_config.aecm_comfort_noise_enabled =
2008 public_submodules_->echo_control_mobile->is_comfort_noise_enabled();
2009 apm_config.aecm_routing_mode =
2010 static_cast<int>(public_submodules_->echo_control_mobile->routing_mode());
2011
2012 apm_config.agc_enabled = public_submodules_->gain_control->is_enabled();
2013 apm_config.agc_mode =
2014 static_cast<int>(public_submodules_->gain_control->mode());
2015 apm_config.agc_limiter_enabled =
2016 public_submodules_->gain_control->is_limiter_enabled();
2017 apm_config.noise_robust_agc_enabled = constants_.use_experimental_agc;
2018
2019 apm_config.hpf_enabled = config_.high_pass_filter.enabled;
2020
2021 apm_config.ns_enabled = public_submodules_->noise_suppression->is_enabled();
2022 apm_config.ns_level =
2023 static_cast<int>(public_submodules_->noise_suppression->level());
2024
2025 apm_config.transient_suppression_enabled =
2026 capture_.transient_suppressor_enabled;
2027 apm_config.intelligibility_enhancer_enabled =
2028 capture_nonlocked_.intelligibility_enabled;
2029 apm_config.experiments_description = experiments_description;
2030
2031 if (!forced && apm_config == apm_config_for_aec_dump_) {
2032 return;
2033 }
2034 aec_dump_->WriteConfig(apm_config);
2035 apm_config_for_aec_dump_ = apm_config;
2036}
2037
2038void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2039 const float* const* src) {
2040 RTC_DCHECK(aec_dump_);
2041 WriteAecDumpConfigMessage(false);
2042
2043 const size_t channel_size = formats_.api_format.input_stream().num_frames();
2044 const size_t num_channels = formats_.api_format.input_stream().num_channels();
2045 aec_dump_->AddCaptureStreamInput(
2046 FloatAudioFrame(src, num_channels, channel_size));
2047 RecordAudioProcessingState();
2048}
2049
2050void AudioProcessingImpl::RecordUnprocessedCaptureStream(
2051 const AudioFrame& capture_frame) {
2052 RTC_DCHECK(aec_dump_);
2053 WriteAecDumpConfigMessage(false);
2054
2055 aec_dump_->AddCaptureStreamInput(capture_frame);
2056 RecordAudioProcessingState();
2057}
2058
2059void AudioProcessingImpl::RecordProcessedCaptureStream(
2060 const float* const* processed_capture_stream) {
2061 RTC_DCHECK(aec_dump_);
2062
2063 const size_t channel_size = formats_.api_format.output_stream().num_frames();
2064 const size_t num_channels =
2065 formats_.api_format.output_stream().num_channels();
2066 aec_dump_->AddCaptureStreamOutput(
2067 FloatAudioFrame(processed_capture_stream, num_channels, channel_size));
2068 aec_dump_->WriteCaptureStreamMessage();
2069}
2070
2071void AudioProcessingImpl::RecordProcessedCaptureStream(
2072 const AudioFrame& processed_capture_frame) {
2073 RTC_DCHECK(aec_dump_);
2074
2075 aec_dump_->AddCaptureStreamOutput(processed_capture_frame);
2076 aec_dump_->WriteCaptureStreamMessage();
2077}
2078
2079void AudioProcessingImpl::RecordAudioProcessingState() {
2080 RTC_DCHECK(aec_dump_);
2081 AecDump::AudioProcessingState audio_proc_state;
2082 audio_proc_state.delay = capture_nonlocked_.stream_delay_ms;
2083 audio_proc_state.drift =
2084 public_submodules_->echo_cancellation->stream_drift_samples();
2085 audio_proc_state.level = gain_control()->stream_analog_level();
2086 audio_proc_state.keypress = capture_.key_pressed;
2087 aec_dump_->AddAudioProcessingState(audio_proc_state);
2088}
2089
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00002090#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
peahdf3efa82015-11-28 12:35:15 -08002091int AudioProcessingImpl::WriteMessageToDebugFile(
2092 FileWrapper* debug_file,
ivocd66b44d2016-01-15 03:06:36 -08002093 int64_t* filesize_limit_bytes,
peahdf3efa82015-11-28 12:35:15 -08002094 rtc::CriticalSection* crit_debug,
2095 ApmDebugDumpThreadState* debug_state) {
2096 int32_t size = debug_state->event_msg->ByteSize();
ajm@google.com808e0e02011-08-03 21:08:51 +00002097 if (size <= 0) {
2098 return kUnspecifiedError;
2099 }
andrew@webrtc.org621df672013-10-22 10:27:23 +00002100#if defined(WEBRTC_ARCH_BIG_ENDIAN)
Michael Graczyk86c6d332015-07-23 11:41:39 -07002101// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
2102// pretty safe in assuming little-endian.
ajm@google.com808e0e02011-08-03 21:08:51 +00002103#endif
2104
peahdf3efa82015-11-28 12:35:15 -08002105 if (!debug_state->event_msg->SerializeToString(&debug_state->event_str)) {
ajm@google.com808e0e02011-08-03 21:08:51 +00002106 return kUnspecifiedError;
2107 }
2108
peahdf3efa82015-11-28 12:35:15 -08002109 {
2110 // Ensure atomic writes of the message.
ivocd66b44d2016-01-15 03:06:36 -08002111 rtc::CritScope cs_debug(crit_debug);
2112
tommia6219cc2016-06-15 10:30:14 -07002113 RTC_DCHECK(debug_file->is_open());
ivocd66b44d2016-01-15 03:06:36 -08002114 // Update the byte counter.
2115 if (*filesize_limit_bytes >= 0) {
2116 *filesize_limit_bytes -=
2117 (sizeof(int32_t) + debug_state->event_str.length());
2118 if (*filesize_limit_bytes < 0) {
2119 // Not enough bytes are left to write this message, so stop logging.
2120 debug_file->CloseFile();
2121 return kNoError;
2122 }
2123 }
peahdf3efa82015-11-28 12:35:15 -08002124 // Write message preceded by its size.
2125 if (!debug_file->Write(&size, sizeof(int32_t))) {
2126 return kFileError;
2127 }
2128 if (!debug_file->Write(debug_state->event_str.data(),
2129 debug_state->event_str.length())) {
2130 return kFileError;
2131 }
ajm@google.com808e0e02011-08-03 21:08:51 +00002132 }
2133
peahdf3efa82015-11-28 12:35:15 -08002134 debug_state->event_msg->Clear();
ajm@google.com808e0e02011-08-03 21:08:51 +00002135
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002136 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00002137}
2138
2139int AudioProcessingImpl::WriteInitMessage() {
peahdf3efa82015-11-28 12:35:15 -08002140 debug_dump_.capture.event_msg->set_type(audioproc::Event::INIT);
2141 audioproc::Init* msg = debug_dump_.capture.event_msg->mutable_init();
2142 msg->set_sample_rate(formats_.api_format.input_stream().sample_rate_hz());
ajm@google.com808e0e02011-08-03 21:08:51 +00002143
mbonadei7c2c8432017-04-07 00:59:12 -07002144 msg->set_num_input_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08002145 formats_.api_format.input_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07002146 msg->set_num_output_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08002147 formats_.api_format.output_stream().num_channels()));
mbonadei7c2c8432017-04-07 00:59:12 -07002148 msg->set_num_reverse_channels(static_cast<int32_t>(
Peter Kasting69558702016-01-12 16:26:35 -08002149 formats_.api_format.reverse_input_stream().num_channels()));
peahdf3efa82015-11-28 12:35:15 -08002150 msg->set_reverse_sample_rate(
2151 formats_.api_format.reverse_input_stream().sample_rate_hz());
2152 msg->set_output_sample_rate(
2153 formats_.api_format.output_stream().sample_rate_hz());
peahc7bdf8a2016-04-11 07:05:53 -07002154 msg->set_reverse_output_sample_rate(
2155 formats_.api_format.reverse_output_stream().sample_rate_hz());
2156 msg->set_num_reverse_output_channels(
2157 formats_.api_format.reverse_output_stream().num_channels());
peahdf3efa82015-11-28 12:35:15 -08002158
2159 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08002160 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08002161 &crit_debug_, &debug_dump_.capture));
Minyue13b96ba2015-10-03 00:39:14 +02002162 return kNoError;
2163}
2164
2165int AudioProcessingImpl::WriteConfigMessage(bool forced) {
2166 audioproc::Config config;
2167
peahdf3efa82015-11-28 12:35:15 -08002168 config.set_aec_enabled(public_submodules_->echo_cancellation->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002169 config.set_aec_delay_agnostic_enabled(
peahdf3efa82015-11-28 12:35:15 -08002170 public_submodules_->echo_cancellation->is_delay_agnostic_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002171 config.set_aec_drift_compensation_enabled(
peahdf3efa82015-11-28 12:35:15 -08002172 public_submodules_->echo_cancellation->is_drift_compensation_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002173 config.set_aec_extended_filter_enabled(
peahdf3efa82015-11-28 12:35:15 -08002174 public_submodules_->echo_cancellation->is_extended_filter_enabled());
2175 config.set_aec_suppression_level(static_cast<int>(
2176 public_submodules_->echo_cancellation->suppression_level()));
Minyue13b96ba2015-10-03 00:39:14 +02002177
peahdf3efa82015-11-28 12:35:15 -08002178 config.set_aecm_enabled(
2179 public_submodules_->echo_control_mobile->is_enabled());
Minyue13b96ba2015-10-03 00:39:14 +02002180 config.set_aecm_comfort_noise_enabled(
peahdf3efa82015-11-28 12:35:15 -08002181 public_submodules_->echo_control_mobile->is_comfort_noise_enabled());
2182 config.set_aecm_routing_mode(static_cast<int>(
2183 public_submodules_->echo_control_mobile->routing_mode()));
Minyue13b96ba2015-10-03 00:39:14 +02002184
peahdf3efa82015-11-28 12:35:15 -08002185 config.set_agc_enabled(public_submodules_->gain_control->is_enabled());
2186 config.set_agc_mode(
2187 static_cast<int>(public_submodules_->gain_control->mode()));
2188 config.set_agc_limiter_enabled(
2189 public_submodules_->gain_control->is_limiter_enabled());
peahbe615622016-02-13 16:40:47 -08002190 config.set_noise_robust_agc_enabled(constants_.use_experimental_agc);
Minyue13b96ba2015-10-03 00:39:14 +02002191
peah8271d042016-11-22 07:24:52 -08002192 config.set_hpf_enabled(config_.high_pass_filter.enabled);
Minyue13b96ba2015-10-03 00:39:14 +02002193
peahdf3efa82015-11-28 12:35:15 -08002194 config.set_ns_enabled(public_submodules_->noise_suppression->is_enabled());
2195 config.set_ns_level(
2196 static_cast<int>(public_submodules_->noise_suppression->level()));
Minyue13b96ba2015-10-03 00:39:14 +02002197
peahdf3efa82015-11-28 12:35:15 -08002198 config.set_transient_suppression_enabled(
2199 capture_.transient_suppressor_enabled);
Alejandro Luebsc9b0c262016-05-16 15:32:38 -07002200 config.set_intelligibility_enhancer_enabled(
2201 capture_nonlocked_.intelligibility_enabled);
Minyue13b96ba2015-10-03 00:39:14 +02002202
peah7789fe72016-04-15 01:19:44 -07002203 std::string experiments_description =
2204 public_submodules_->echo_cancellation->GetExperimentsDescription();
2205 // TODO(peah): Add semicolon-separated concatenations of experiment
2206 // descriptions for other submodules.
peahca4cac72016-06-29 15:26:12 -07002207 if (capture_nonlocked_.level_controller_enabled) {
2208 experiments_description += "LevelController;";
2209 }
henrik.lundinbd681b92016-12-05 09:08:42 -08002210 if (constants_.agc_clipped_level_min != kClippedLevelMin) {
2211 experiments_description += "AgcClippingLevelExperiment;";
2212 }
peahe0eae3c2016-12-14 01:16:23 -08002213 if (capture_nonlocked_.echo_canceller3_enabled) {
2214 experiments_description += "EchoCanceller3;";
2215 }
peah7789fe72016-04-15 01:19:44 -07002216 config.set_experiments_description(experiments_description);
2217
mbonadei7c2c8432017-04-07 00:59:12 -07002218 ProtoString serialized_config = config.SerializeAsString();
peahdf3efa82015-11-28 12:35:15 -08002219 if (!forced &&
2220 debug_dump_.capture.last_serialized_config == serialized_config) {
Minyue13b96ba2015-10-03 00:39:14 +02002221 return kNoError;
ajm@google.com808e0e02011-08-03 21:08:51 +00002222 }
2223
peahdf3efa82015-11-28 12:35:15 -08002224 debug_dump_.capture.last_serialized_config = serialized_config;
Minyue13b96ba2015-10-03 00:39:14 +02002225
peahdf3efa82015-11-28 12:35:15 -08002226 debug_dump_.capture.event_msg->set_type(audioproc::Event::CONFIG);
2227 debug_dump_.capture.event_msg->mutable_config()->CopyFrom(config);
Minyue13b96ba2015-10-03 00:39:14 +02002228
peahdf3efa82015-11-28 12:35:15 -08002229 RETURN_ON_ERR(WriteMessageToDebugFile(debug_dump_.debug_file.get(),
ivocd66b44d2016-01-15 03:06:36 -08002230 &debug_dump_.num_bytes_left_for_log_,
peahdf3efa82015-11-28 12:35:15 -08002231 &crit_debug_, &debug_dump_.capture));
ajm@google.com808e0e02011-08-03 21:08:51 +00002232 return kNoError;
2233}
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00002234#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002235
kwiberg83ffe452016-08-29 14:46:07 -07002236AudioProcessingImpl::ApmCaptureState::ApmCaptureState(
2237 bool transient_suppressor_enabled,
2238 const std::vector<Point>& array_geometry,
2239 SphericalPointf target_direction)
2240 : aec_system_delay_jumps(-1),
2241 delay_offset_ms(0),
2242 was_stream_delay_set(false),
2243 last_stream_delay_ms(0),
2244 last_aec_system_delay_ms(0),
2245 stream_delay_jumps(-1),
2246 output_will_be_muted(false),
2247 key_pressed(false),
2248 transient_suppressor_enabled(transient_suppressor_enabled),
2249 array_geometry(array_geometry),
2250 target_direction(target_direction),
peahde65ddc2016-09-16 15:02:15 -07002251 capture_processing_format(kSampleRate16kHz),
peah67995532017-04-10 14:12:41 -07002252 split_rate(kSampleRate16kHz),
2253 previous_agc_level(0),
2254 echo_path_gain_change(false) {}
kwiberg83ffe452016-08-29 14:46:07 -07002255
2256AudioProcessingImpl::ApmCaptureState::~ApmCaptureState() = default;
2257
2258AudioProcessingImpl::ApmRenderState::ApmRenderState() = default;
2259
2260AudioProcessingImpl::ApmRenderState::~ApmRenderState() = default;
2261
niklase@google.com470e71d2011-07-07 08:21:25 +00002262} // namespace webrtc