blob: c7d325c69bfe45baff9e6ab7d16604327d9ef543 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
andrew@webrtc.org293d22b2012-01-30 22:04:26 +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 */
Jonas Olssona4d87372019-07-05 19:08:33 +020010#include "modules/audio_processing/include/audio_processing.h"
11
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000012#include <math.h>
ajm@google.com59e41402011-07-28 17:34:04 +000013#include <stdio.h>
kwiberg62eaacf2016-02-17 06:39:05 -080014
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000015#include <algorithm>
Oleh Prypin708eccc2019-03-27 09:38:52 +010016#include <cmath>
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000017#include <limits>
kwiberg62eaacf2016-02-17 06:39:05 -080018#include <memory>
Sam Zackrissone277bde2019-10-25 10:07:54 +020019#include <numeric>
bjornv@webrtc.org3e102492013-02-14 15:29:09 +000020#include <queue>
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000021
Sam Zackrisson6558fa52019-08-26 10:12:41 +020022#include "absl/flags/flag.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "common_audio/include/audio_util.h"
24#include "common_audio/resampler/include/push_resampler.h"
25#include "common_audio/resampler/push_sinc_resampler.h"
26#include "common_audio/signal_processing/include/signal_processing_library.h"
27#include "modules/audio_processing/aec_dump/aec_dump_factory.h"
28#include "modules/audio_processing/audio_processing_impl.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "modules/audio_processing/common.h"
Sam Zackrisson0beac582017-09-25 12:04:02 +020030#include "modules/audio_processing/include/mock_audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "modules/audio_processing/test/protobuf_utils.h"
32#include "modules/audio_processing/test/test_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/arraysize.h"
34#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "rtc_base/fake_clock.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/gtest_prod_util.h"
37#include "rtc_base/ignore_wundef.h"
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +010038#include "rtc_base/numerics/safe_conversions.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010039#include "rtc_base/numerics/safe_minmax.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/protobuf_utils.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/ref_counted_object.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020042#include "rtc_base/strings/string_builder.h"
Alessio Bazzicac054e782018-04-16 12:10:09 +020043#include "rtc_base/swap_queue.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020044#include "rtc_base/system/arch.h"
Danil Chapovalov07122bc2019-03-26 14:37:01 +010045#include "rtc_base/task_queue_for_test.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/thread.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "test/gtest.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "test/testsupport/file_utils.h"
kwiberg77eab702016-09-28 17:42:01 -070049
50RTC_PUSH_IGNORING_WUNDEF()
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000051#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000052#include "external/webrtc/webrtc/modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000053#else
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000055#endif
kwiberg77eab702016-09-28 17:42:01 -070056RTC_POP_IGNORING_WUNDEF()
niklase@google.com470e71d2011-07-07 08:21:25 +000057
Sam Zackrisson6558fa52019-08-26 10:12:41 +020058ABSL_FLAG(bool,
59 write_apm_ref_data,
60 false,
61 "Write ApmTest.Process results to file, instead of comparing results "
62 "to the existing reference data file.");
63
andrew@webrtc.org27c69802014-02-18 20:24:56 +000064namespace webrtc {
niklase@google.com470e71d2011-07-07 08:21:25 +000065namespace {
andrew@webrtc.org17e40642014-03-04 20:58:13 +000066
ekmeyerson60d9b332015-08-14 10:35:55 -070067// TODO(ekmeyerson): Switch to using StreamConfig and ProcessingConfig where
68// applicable.
69
mbonadei7c2c8432017-04-07 00:59:12 -070070const int32_t kChannels[] = {1, 2};
Alejandro Luebs47748742015-05-22 12:00:21 -070071const int kSampleRates[] = {8000, 16000, 32000, 48000};
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +000072
aluebseb3603b2016-04-20 15:27:58 -070073#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
74// Android doesn't support 48kHz.
75const int kProcessSampleRates[] = {8000, 16000, 32000};
76#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Alejandro Luebs47748742015-05-22 12:00:21 -070077const int kProcessSampleRates[] = {8000, 16000, 32000, 48000};
aluebseb3603b2016-04-20 15:27:58 -070078#endif
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000079
ekmeyerson60d9b332015-08-14 10:35:55 -070080enum StreamDirection { kForward = 0, kReverse };
81
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000082void ConvertToFloat(const int16_t* int_data, ChannelBuffer<float>* cb) {
Jonas Olssona4d87372019-07-05 19:08:33 +020083 ChannelBuffer<int16_t> cb_int(cb->num_frames(), cb->num_channels());
84 Deinterleave(int_data, cb->num_frames(), cb->num_channels(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000085 cb_int.channels());
Peter Kasting69558702016-01-12 16:26:35 -080086 for (size_t i = 0; i < cb->num_channels(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +020087 S16ToFloat(cb_int.channels()[i], cb->num_frames(), cb->channels()[i]);
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000088 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000089}
andrew@webrtc.org17e40642014-03-04 20:58:13 +000090
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000091void ConvertToFloat(const AudioFrame& frame, ChannelBuffer<float>* cb) {
yujo36b1a5f2017-06-12 12:45:32 -070092 ConvertToFloat(frame.data(), cb);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000093}
94
andrew@webrtc.org103657b2014-04-24 18:28:56 +000095// Number of channels including the keyboard channel.
Peter Kasting69558702016-01-12 16:26:35 -080096size_t TotalChannelsFromLayout(AudioProcessing::ChannelLayout layout) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +000097 switch (layout) {
98 case AudioProcessing::kMono:
99 return 1;
100 case AudioProcessing::kMonoAndKeyboard:
101 case AudioProcessing::kStereo:
102 return 2;
103 case AudioProcessing::kStereoAndKeyboard:
104 return 3;
105 }
kwiberg9e2be5f2016-09-14 05:23:22 -0700106 RTC_NOTREACHED();
pkasting25702cb2016-01-08 13:50:27 -0800107 return 0;
andrew@webrtc.org103657b2014-04-24 18:28:56 +0000108}
109
Jonas Olssona4d87372019-07-05 19:08:33 +0200110void MixStereoToMono(const float* stereo,
111 float* mono,
pkasting25702cb2016-01-08 13:50:27 -0800112 size_t samples_per_channel) {
113 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000114 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) / 2;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000115}
116
Jonas Olssona4d87372019-07-05 19:08:33 +0200117void MixStereoToMono(const int16_t* stereo,
118 int16_t* mono,
pkasting25702cb2016-01-08 13:50:27 -0800119 size_t samples_per_channel) {
120 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000121 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) >> 1;
122}
123
pkasting25702cb2016-01-08 13:50:27 -0800124void CopyLeftToRightChannel(int16_t* stereo, size_t samples_per_channel) {
125 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000126 stereo[i * 2 + 1] = stereo[i * 2];
127 }
128}
129
yujo36b1a5f2017-06-12 12:45:32 -0700130void VerifyChannelsAreEqual(const int16_t* stereo, size_t samples_per_channel) {
pkasting25702cb2016-01-08 13:50:27 -0800131 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000132 EXPECT_EQ(stereo[i * 2 + 1], stereo[i * 2]);
133 }
134}
135
136void SetFrameTo(AudioFrame* frame, int16_t value) {
yujo36b1a5f2017-06-12 12:45:32 -0700137 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700138 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
139 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700140 frame_data[i] = value;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000141 }
142}
143
144void SetFrameTo(AudioFrame* frame, int16_t left, int16_t right) {
Peter Kasting69558702016-01-12 16:26:35 -0800145 ASSERT_EQ(2u, frame->num_channels_);
yujo36b1a5f2017-06-12 12:45:32 -0700146 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700147 for (size_t i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
yujo36b1a5f2017-06-12 12:45:32 -0700148 frame_data[i] = left;
149 frame_data[i + 1] = right;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000150 }
151}
152
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000153void ScaleFrame(AudioFrame* frame, float scale) {
yujo36b1a5f2017-06-12 12:45:32 -0700154 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700155 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
156 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700157 frame_data[i] = FloatS16ToS16(frame_data[i] * scale);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000158 }
159}
160
andrew@webrtc.org81865342012-10-27 00:28:27 +0000161bool FrameDataAreEqual(const AudioFrame& frame1, const AudioFrame& frame2) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000162 if (frame1.samples_per_channel_ != frame2.samples_per_channel_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000163 return false;
164 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000165 if (frame1.num_channels_ != frame2.num_channels_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000166 return false;
167 }
yujo36b1a5f2017-06-12 12:45:32 -0700168 if (memcmp(frame1.data(), frame2.data(),
andrew@webrtc.org81865342012-10-27 00:28:27 +0000169 frame1.samples_per_channel_ * frame1.num_channels_ *
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000170 sizeof(int16_t))) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000171 return false;
172 }
173 return true;
174}
175
Sam Zackrissone277bde2019-10-25 10:07:54 +0200176rtc::ArrayView<int16_t> GetMutableFrameData(AudioFrame* frame) {
177 int16_t* ptr = frame->mutable_data();
178 const size_t len = frame->samples_per_channel() * frame->num_channels();
179 return rtc::ArrayView<int16_t>(ptr, len);
180}
181
182rtc::ArrayView<const int16_t> GetFrameData(const AudioFrame& frame) {
183 const int16_t* ptr = frame.data();
184 const size_t len = frame.samples_per_channel() * frame.num_channels();
185 return rtc::ArrayView<const int16_t>(ptr, len);
186}
187
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000188void EnableAllAPComponents(AudioProcessing* ap) {
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200189 AudioProcessing::Config apm_config = ap->GetConfig();
190 apm_config.echo_canceller.enabled = true;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000191#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200192 apm_config.echo_canceller.mobile_mode = true;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100193
194 apm_config.gain_controller1.enabled = true;
195 apm_config.gain_controller1.mode =
196 AudioProcessing::Config::GainController1::kAdaptiveDigital;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000197#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200198 apm_config.echo_canceller.mobile_mode = false;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000199
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100200 apm_config.gain_controller1.enabled = true;
201 apm_config.gain_controller1.mode =
202 AudioProcessing::Config::GainController1::kAdaptiveAnalog;
203 apm_config.gain_controller1.analog_level_minimum = 0;
204 apm_config.gain_controller1.analog_level_maximum = 255;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000205#endif
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000206
saza0bad15f2019-10-16 11:46:11 +0200207 apm_config.noise_suppression.enabled = true;
208
peah8271d042016-11-22 07:24:52 -0800209 apm_config.high_pass_filter.enabled = true;
Sam Zackrisson11b87032018-12-18 17:13:58 +0100210 apm_config.level_estimation.enabled = true;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200211 apm_config.voice_detection.enabled = true;
peah8271d042016-11-22 07:24:52 -0800212 ap->ApplyConfig(apm_config);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000213}
214
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000215// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000216template <class T>
217T AbsValue(T a) {
Jonas Olssona4d87372019-07-05 19:08:33 +0200218 return a > 0 ? a : -a;
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000219}
220
221int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800222 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700223 const int16_t* frame_data = frame.data();
224 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800225 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700226 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000227 }
228
229 return max_data;
230}
231
Alex Loiko890988c2017-08-31 10:25:48 +0200232void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700233 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000234 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000235 ASSERT_TRUE(file != NULL);
236
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100237 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000238 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800239 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000240 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000241
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000242 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000243 ASSERT_EQ(static_cast<size_t>(size),
Jonas Olssona4d87372019-07-05 19:08:33 +0200244 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000245 fclose(file);
246}
247
Alex Loiko890988c2017-08-31 10:25:48 +0200248std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200249 rtc::StringBuilder ss;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000250 // Resource files are all stereo.
251 ss << name << sample_rate_hz / 1000 << "_stereo";
252 return test::ResourcePath(ss.str(), "pcm");
253}
254
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000255// Temporary filenames unique to this process. Used to be able to run these
256// tests in parallel as each process needs to be running in isolation they can't
257// have competing filenames.
258std::map<std::string, std::string> temp_filenames;
259
Alex Loiko890988c2017-08-31 10:25:48 +0200260std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000261 int input_rate,
262 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700263 int reverse_input_rate,
264 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800265 size_t num_input_channels,
266 size_t num_output_channels,
267 size_t num_reverse_input_channels,
268 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700269 StreamDirection file_direction) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200270 rtc::StringBuilder ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700271 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
272 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000273 if (num_output_channels == 1) {
274 ss << "mono";
275 } else if (num_output_channels == 2) {
276 ss << "stereo";
277 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700278 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000279 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700280 ss << output_rate / 1000;
281 if (num_reverse_output_channels == 1) {
282 ss << "_rmono";
283 } else if (num_reverse_output_channels == 2) {
284 ss << "_rstereo";
285 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700286 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700287 }
288 ss << reverse_output_rate / 1000;
289 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000290
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000291 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700292 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000293 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
294 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000295}
296
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000297void ClearTempFiles() {
298 for (auto& kv : temp_filenames)
299 remove(kv.second.c_str());
300}
301
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200302// Only remove "out" files. Keep "ref" files.
303void ClearTempOutFiles() {
304 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
305 const std::string& filename = it->first;
306 if (filename.substr(0, 3).compare("out") == 0) {
307 remove(it->second.c_str());
308 temp_filenames.erase(it++);
309 } else {
310 it++;
311 }
312 }
313}
314
Alex Loiko890988c2017-08-31 10:25:48 +0200315void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000316 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000317 ASSERT_TRUE(file != NULL);
318 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000319 fclose(file);
320}
321
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000322// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
323// stereo) file, converts to deinterleaved float (optionally downmixing) and
324// returns the result in |cb|. Returns false if the file ended (or on error) and
325// true otherwise.
326//
327// |int_data| and |float_data| are just temporary space that must be
328// sufficiently large to hold the 10 ms chunk.
Jonas Olssona4d87372019-07-05 19:08:33 +0200329bool ReadChunk(FILE* file,
330 int16_t* int_data,
331 float* float_data,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000332 ChannelBuffer<float>* cb) {
333 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000334 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000335 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
336 if (read_count != frame_size) {
337 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700338 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000339 return false; // This is expected.
340 }
341
342 S16ToFloat(int_data, frame_size, float_data);
343 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000344 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000345 } else {
Jonas Olssona4d87372019-07-05 19:08:33 +0200346 Deinterleave(float_data, cb->num_frames(), 2, cb->channels());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000347 }
348
349 return true;
350}
351
niklase@google.com470e71d2011-07-07 08:21:25 +0000352class ApmTest : public ::testing::Test {
353 protected:
354 ApmTest();
355 virtual void SetUp();
356 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000357
Mirko Bonadei71061bc2019-06-04 09:01:51 +0200358 static void SetUpTestSuite() {}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000359
Mirko Bonadei71061bc2019-06-04 09:01:51 +0200360 static void TearDownTestSuite() { ClearTempFiles(); }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000361
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000362 // Used to select between int and float interface tests.
Jonas Olssona4d87372019-07-05 19:08:33 +0200363 enum Format { kIntFormat, kFloatFormat };
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000364
365 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000366 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000367 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800368 size_t num_input_channels,
369 size_t num_output_channels,
370 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000371 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000372 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000373 void EnableAllComponents();
374 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000375 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000376 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
Jonas Olssona4d87372019-07-05 19:08:33 +0200377 void ReadFrameWithRewind(FILE* file,
378 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000379 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000380 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
Jonas Olssona4d87372019-07-05 19:08:33 +0200381 void ProcessDelayVerificationTest(int delay_ms,
382 int system_delay_ms,
383 int delay_min,
384 int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700385 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800386 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700387 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800388 void TestChangingForwardChannels(size_t num_in_channels,
389 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700390 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800391 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700392 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000393 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
394 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000395 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000396 int ProcessStreamChooser(Format format);
397 int AnalyzeReverseStreamChooser(Format format);
398 void ProcessDebugDump(const std::string& in_filename,
399 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800400 Format format,
401 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000402 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000403
404 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000405 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800406 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000407 AudioFrame* frame_;
408 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800409 std::unique_ptr<ChannelBuffer<float> > float_cb_;
410 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000411 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800412 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000413 FILE* far_file_;
414 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000415 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000416};
417
418ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000419 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000420#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +0200421 ref_filename_(
422 test::ResourcePath("audio_processing/output_data_fixed", "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000423#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +0200424 ref_filename_(
425 test::ResourcePath("audio_processing/output_data_float", "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000426#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000427 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000428 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000429 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000430 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000431 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000432 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000433 out_file_(NULL) {
434 Config config;
435 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100436 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000437}
niklase@google.com470e71d2011-07-07 08:21:25 +0000438
439void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000440 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000441
442 frame_ = new AudioFrame();
443 revframe_ = new AudioFrame();
444
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000445 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000446}
447
448void ApmTest::TearDown() {
449 if (frame_) {
450 delete frame_;
451 }
452 frame_ = NULL;
453
454 if (revframe_) {
455 delete revframe_;
456 }
457 revframe_ = NULL;
458
459 if (far_file_) {
460 ASSERT_EQ(0, fclose(far_file_));
461 }
462 far_file_ = NULL;
463
464 if (near_file_) {
465 ASSERT_EQ(0, fclose(near_file_));
466 }
467 near_file_ = NULL;
468
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000469 if (out_file_) {
470 ASSERT_EQ(0, fclose(out_file_));
471 }
472 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000473}
474
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000475void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000476 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700477 ap->Initialize(
478 {{{frame_->sample_rate_hz_, frame_->num_channels_},
479 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700480 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700481 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000482}
483
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000484void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000485 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000486 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800487 size_t num_input_channels,
488 size_t num_output_channels,
489 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000490 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000491 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000492 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000493 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000494
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000495 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
496 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000497 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000498
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000499 if (far_file_) {
500 ASSERT_EQ(0, fclose(far_file_));
501 }
502 std::string filename = ResourceFilePath("far", sample_rate_hz);
503 far_file_ = fopen(filename.c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200504 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000505
506 if (near_file_) {
507 ASSERT_EQ(0, fclose(near_file_));
508 }
509 filename = ResourceFilePath("near", sample_rate_hz);
510 near_file_ = fopen(filename.c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200511 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000512
513 if (open_output_file) {
514 if (out_file_) {
515 ASSERT_EQ(0, fclose(out_file_));
516 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700517 filename = OutputFilePath(
518 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
519 reverse_sample_rate_hz, num_input_channels, num_output_channels,
520 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000521 out_file_ = fopen(filename.c_str(), "wb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200522 ASSERT_TRUE(out_file_ != NULL)
523 << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000524 }
525}
526
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000527void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000528 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000529}
530
Jonas Olssona4d87372019-07-05 19:08:33 +0200531bool ApmTest::ReadFrame(FILE* file,
532 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000533 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000534 // The files always contain stereo audio.
535 size_t frame_size = frame->samples_per_channel_ * 2;
Jonas Olssona4d87372019-07-05 19:08:33 +0200536 size_t read_count =
537 fread(frame->mutable_data(), sizeof(int16_t), frame_size, file);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000538 if (read_count != frame_size) {
539 // Check that the file really ended.
540 EXPECT_NE(0, feof(file));
541 return false; // This is expected.
542 }
543
544 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700545 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000546 frame->samples_per_channel_);
547 }
548
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000549 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000550 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000551 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000552 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000553}
554
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000555bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
556 return ReadFrame(file, frame, NULL);
557}
558
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000559// If the end of the file has been reached, rewind it and attempt to read the
560// frame again.
Jonas Olssona4d87372019-07-05 19:08:33 +0200561void ApmTest::ReadFrameWithRewind(FILE* file,
562 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000563 ChannelBuffer<float>* cb) {
564 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000565 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000566 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000567 }
568}
569
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000570void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
571 ReadFrameWithRewind(file, frame, NULL);
572}
573
andrew@webrtc.org81865342012-10-27 00:28:27 +0000574void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
575 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
Sam Zackrisson41478c72019-10-15 10:10:26 +0200576 apm_->set_stream_analog_level(127);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000577 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000578}
579
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000580int ApmTest::ProcessStreamChooser(Format format) {
581 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000582 return apm_->ProcessStream(frame_);
583 }
Jonas Olssona4d87372019-07-05 19:08:33 +0200584 return apm_->ProcessStream(
585 float_cb_->channels(), frame_->samples_per_channel_,
586 frame_->sample_rate_hz_, LayoutFromChannels(frame_->num_channels_),
587 output_sample_rate_hz_, LayoutFromChannels(num_output_channels_),
588 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000589}
590
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000591int ApmTest::AnalyzeReverseStreamChooser(Format format) {
592 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700593 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000594 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000595 return apm_->AnalyzeReverseStream(
Jonas Olssona4d87372019-07-05 19:08:33 +0200596 revfloat_cb_->channels(), revframe_->samples_per_channel_,
597 revframe_->sample_rate_hz_, LayoutFromChannels(revframe_->num_channels_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000598}
599
Jonas Olssona4d87372019-07-05 19:08:33 +0200600void ApmTest::ProcessDelayVerificationTest(int delay_ms,
601 int system_delay_ms,
602 int delay_min,
603 int delay_max) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000604 // The |revframe_| and |frame_| should include the proper frame information,
605 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000606 AudioFrame tmp_frame;
607 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000608 bool causal = true;
609
610 tmp_frame.CopyFrom(*revframe_);
611 SetFrameTo(&tmp_frame, 0);
612
613 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
614 // Initialize the |frame_queue| with empty frames.
615 int frame_delay = delay_ms / 10;
616 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000617 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000618 frame->CopyFrom(tmp_frame);
619 frame_queue.push(frame);
620 frame_delay++;
621 causal = false;
622 }
623 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000624 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000625 frame->CopyFrom(tmp_frame);
626 frame_queue.push(frame);
627 frame_delay--;
628 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000629 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
630 // need enough frames with audio to have reliable estimates, but as few as
631 // possible to keep processing time down. 4.5 seconds seemed to be a good
632 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000633 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000634 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000635 frame->CopyFrom(tmp_frame);
636 // Use the near end recording, since that has more speech in it.
637 ASSERT_TRUE(ReadFrame(near_file_, frame));
638 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000639 AudioFrame* reverse_frame = frame;
640 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000641 if (!causal) {
642 reverse_frame = frame_queue.front();
643 // When we call ProcessStream() the frame is modified, so we can't use the
644 // pointer directly when things are non-causal. Use an intermediate frame
645 // and copy the data.
646 process_frame = &tmp_frame;
647 process_frame->CopyFrom(*frame);
648 }
aluebsb0319552016-03-17 20:39:53 -0700649 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000650 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
651 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
652 frame = frame_queue.front();
653 frame_queue.pop();
654 delete frame;
655
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000656 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000657 // Discard the first delay metrics to avoid convergence effects.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200658 static_cast<void>(apm_->GetStatistics(true /* has_remote_tracks */));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000659 }
660 }
661
662 rewind(near_file_);
663 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000664 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000665 frame_queue.pop();
666 delete frame;
667 }
668 // Calculate expected delay estimate and acceptable regions. Further,
669 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700670 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700671 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700672 const int expected_median =
673 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
674 const int expected_median_high = rtc::SafeClamp<int>(
675 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700676 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700677 const int expected_median_low = rtc::SafeClamp<int>(
678 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700679 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000680 // Verify delay metrics.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200681 AudioProcessingStats stats =
682 apm_->GetStatistics(true /* has_remote_tracks */);
683 ASSERT_TRUE(stats.delay_median_ms.has_value());
684 int32_t median = *stats.delay_median_ms;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000685 EXPECT_GE(expected_median_high, median);
686 EXPECT_LE(expected_median_low, median);
687}
688
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000689void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000690 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000691 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000692
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000693 // -- Missing AGC level --
Sam Zackrisson41478c72019-10-15 10:10:26 +0200694 AudioProcessing::Config apm_config = apm_->GetConfig();
695 apm_config.gain_controller1.enabled = true;
696 apm_->ApplyConfig(apm_config);
Jonas Olssona4d87372019-07-05 19:08:33 +0200697 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000698
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000699 // Resets after successful ProcessStream().
Sam Zackrisson41478c72019-10-15 10:10:26 +0200700 apm_->set_stream_analog_level(127);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000701 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Jonas Olssona4d87372019-07-05 19:08:33 +0200702 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000703
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000704 // Other stream parameters set correctly.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200705 apm_config.echo_canceller.enabled = true;
706 apm_config.echo_canceller.mobile_mode = false;
707 apm_->ApplyConfig(apm_config);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000708 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
Jonas Olssona4d87372019-07-05 19:08:33 +0200709 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
Sam Zackrisson41478c72019-10-15 10:10:26 +0200710 apm_config.gain_controller1.enabled = false;
711 apm_->ApplyConfig(apm_config);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000712
713 // -- Missing delay --
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000714 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100715 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000716
717 // Resets after successful ProcessStream().
718 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000719 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100720 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000721
722 // Other stream parameters set correctly.
Sam Zackrisson41478c72019-10-15 10:10:26 +0200723 apm_config.gain_controller1.enabled = true;
724 apm_->ApplyConfig(apm_config);
725 apm_->set_stream_analog_level(127);
Per Åhgren200feba2019-03-06 04:16:46 +0100726 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Sam Zackrisson41478c72019-10-15 10:10:26 +0200727 apm_config.gain_controller1.enabled = false;
728 apm_->ApplyConfig(apm_config);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000729
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000730 // -- No stream parameters --
Jonas Olssona4d87372019-07-05 19:08:33 +0200731 EXPECT_EQ(apm_->kNoError, AnalyzeReverseStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100732 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000733
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000734 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000735 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
Sam Zackrisson41478c72019-10-15 10:10:26 +0200736 apm_->set_stream_analog_level(127);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000737 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000738}
739
740TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000741 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000742}
743
744TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000745 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000746}
747
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000748TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
749 EXPECT_EQ(0, apm_->delay_offset_ms());
750 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
751 EXPECT_EQ(50, apm_->stream_delay_ms());
752}
753
754TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
755 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000756 apm_->set_delay_offset_ms(100);
757 EXPECT_EQ(100, apm_->delay_offset_ms());
758 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000759 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000760 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
761 EXPECT_EQ(200, apm_->stream_delay_ms());
762
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000763 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000764 apm_->set_delay_offset_ms(-50);
765 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000766 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
767 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000768 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
769 EXPECT_EQ(50, apm_->stream_delay_ms());
770}
771
Michael Graczyk86c6d332015-07-23 11:41:39 -0700772void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800773 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700774 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000775 frame_->num_channels_ = num_channels;
776 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700777 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000778}
779
Michael Graczyk86c6d332015-07-23 11:41:39 -0700780void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800781 size_t num_in_channels,
782 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700783 AudioProcessing::Error expected_return) {
784 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
785 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
786
787 EXPECT_EQ(expected_return,
788 apm_->ProcessStream(float_cb_->channels(), input_stream,
789 output_stream, float_cb_->channels()));
790}
791
792void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800793 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700794 AudioProcessing::Error expected_return) {
795 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700796 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
797 {output_sample_rate_hz_, apm_->num_output_channels()},
798 {frame_->sample_rate_hz_, num_rev_channels},
799 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700800
ekmeyerson60d9b332015-08-14 10:35:55 -0700801 EXPECT_EQ(
802 expected_return,
803 apm_->ProcessReverseStream(
804 float_cb_->channels(), processing_config.reverse_input_stream(),
805 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700806}
807
808TEST_F(ApmTest, ChannelsInt16Interface) {
809 // Testing number of invalid and valid channels.
810 Init(16000, 16000, 16000, 4, 4, 4, false);
811
812 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
813
Peter Kasting69558702016-01-12 16:26:35 -0800814 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700815 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000816 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000817 }
818}
819
Michael Graczyk86c6d332015-07-23 11:41:39 -0700820TEST_F(ApmTest, Channels) {
821 // Testing number of invalid and valid channels.
822 Init(16000, 16000, 16000, 4, 4, 4, false);
823
824 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
825 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
826
Peter Kasting69558702016-01-12 16:26:35 -0800827 for (size_t i = 1; i < 4; ++i) {
828 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700829 // Output channels much be one or match input channels.
830 if (j == 1 || i == j) {
831 TestChangingForwardChannels(i, j, kNoErr);
832 TestChangingReverseChannels(i, kNoErr);
833
834 EXPECT_EQ(i, apm_->num_input_channels());
835 EXPECT_EQ(j, apm_->num_output_channels());
836 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800837 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700838 } else {
839 TestChangingForwardChannels(i, j,
840 AudioProcessing::kBadNumberChannelsError);
841 }
842 }
843 }
844}
845
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000846TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000847 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000848 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000849 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000850 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700851 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800852 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000853 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000854 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000855 }
856}
857
Sam Zackrissone277bde2019-10-25 10:07:54 +0200858// This test repeatedly reconfigures the pre-amplifier in APM, processes a
859// number of frames, and checks that output signal has the right level.
860TEST_F(ApmTest, PreAmplifier) {
861 // Fill the audio frame with a sawtooth pattern.
862 rtc::ArrayView<int16_t> frame_data = GetMutableFrameData(frame_);
863 const size_t samples_per_channel = frame_->samples_per_channel();
864 for (size_t i = 0; i < samples_per_channel; i++) {
865 for (size_t ch = 0; ch < frame_->num_channels(); ++ch) {
866 frame_data[i + ch * samples_per_channel] = 10000 * ((i % 3) - 1);
867 }
868 }
869 // Cache the frame in tmp_frame.
870 AudioFrame tmp_frame;
871 tmp_frame.CopyFrom(*frame_);
872
873 auto compute_power = [](const AudioFrame& frame) {
874 rtc::ArrayView<const int16_t> data = GetFrameData(frame);
875 return std::accumulate(data.begin(), data.end(), 0.0f,
876 [](float a, float b) { return a + b * b; }) /
877 data.size() / 32768 / 32768;
878 };
879
880 const float input_power = compute_power(tmp_frame);
881 // Double-check that the input data is large compared to the error kEpsilon.
882 constexpr float kEpsilon = 1e-4f;
883 RTC_DCHECK_GE(input_power, 10 * kEpsilon);
884
885 // 1. Enable pre-amp with 0 dB gain.
886 AudioProcessing::Config config = apm_->GetConfig();
887 config.pre_amplifier.enabled = true;
888 config.pre_amplifier.fixed_gain_factor = 1.0f;
889 apm_->ApplyConfig(config);
890
891 for (int i = 0; i < 20; ++i) {
892 frame_->CopyFrom(tmp_frame);
893 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kIntFormat));
894 }
895 float output_power = compute_power(*frame_);
896 EXPECT_NEAR(output_power, input_power, kEpsilon);
897 config = apm_->GetConfig();
898 EXPECT_EQ(config.pre_amplifier.fixed_gain_factor, 1.0f);
899
900 // 2. Change pre-amp gain via ApplyConfig.
901 config.pre_amplifier.fixed_gain_factor = 2.0f;
902 apm_->ApplyConfig(config);
903
904 for (int i = 0; i < 20; ++i) {
905 frame_->CopyFrom(tmp_frame);
906 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kIntFormat));
907 }
908 output_power = compute_power(*frame_);
909 EXPECT_NEAR(output_power, 4 * input_power, kEpsilon);
910 config = apm_->GetConfig();
911 EXPECT_EQ(config.pre_amplifier.fixed_gain_factor, 2.0f);
912
913 // 3. Change pre-amp gain via a RuntimeSetting.
914 apm_->SetRuntimeSetting(
915 AudioProcessing::RuntimeSetting::CreateCapturePreGain(1.5f));
916
917 for (int i = 0; i < 20; ++i) {
918 frame_->CopyFrom(tmp_frame);
919 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kIntFormat));
920 }
921 output_power = compute_power(*frame_);
922 EXPECT_NEAR(output_power, 2.25 * input_power, kEpsilon);
923 config = apm_->GetConfig();
924 EXPECT_EQ(config.pre_amplifier.fixed_gain_factor, 1.5f);
925}
926
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000927TEST_F(ApmTest, GainControl) {
Sam Zackrisson41478c72019-10-15 10:10:26 +0200928 AudioProcessing::Config config = apm_->GetConfig();
929 config.gain_controller1.enabled = false;
930 apm_->ApplyConfig(config);
931 config.gain_controller1.enabled = true;
932 apm_->ApplyConfig(config);
933
niklase@google.com470e71d2011-07-07 08:21:25 +0000934 // Testing gain modes
Sam Zackrisson41478c72019-10-15 10:10:26 +0200935 for (auto mode :
936 {AudioProcessing::Config::GainController1::kAdaptiveDigital,
937 AudioProcessing::Config::GainController1::kFixedDigital,
938 AudioProcessing::Config::GainController1::kAdaptiveAnalog}) {
939 config.gain_controller1.mode = mode;
940 apm_->ApplyConfig(config);
941 apm_->set_stream_analog_level(100);
942 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kFloatFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000943 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000944
Sam Zackrisson41478c72019-10-15 10:10:26 +0200945 // Testing target levels
946 for (int target_level_dbfs : {0, 15, 31}) {
947 config.gain_controller1.target_level_dbfs = target_level_dbfs;
948 apm_->ApplyConfig(config);
949 apm_->set_stream_analog_level(100);
950 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kFloatFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000951 }
952
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100953 // Testing compression gains
Sam Zackrisson41478c72019-10-15 10:10:26 +0200954 for (int compression_gain_db : {0, 10, 90}) {
955 config.gain_controller1.compression_gain_db = compression_gain_db;
956 apm_->ApplyConfig(config);
957 apm_->set_stream_analog_level(100);
958 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kFloatFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000959 }
960
961 // Testing limiter off/on
Sam Zackrisson41478c72019-10-15 10:10:26 +0200962 for (bool enable : {false, true}) {
963 config.gain_controller1.enable_limiter = enable;
964 apm_->ApplyConfig(config);
965 apm_->set_stream_analog_level(100);
966 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kFloatFormat));
967 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000968
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100969 // Testing level limits
Sam Zackrisson41478c72019-10-15 10:10:26 +0200970 std::array<int, 4> kMinLevels = {0, 0, 255, 65000};
971 std::array<int, 4> kMaxLevels = {255, 1024, 65535, 65535};
972 for (size_t i = 0; i < kMinLevels.size(); ++i) {
973 int min_level = kMinLevels[i];
974 int max_level = kMaxLevels[i];
975 config.gain_controller1.analog_level_minimum = min_level;
976 config.gain_controller1.analog_level_maximum = max_level;
977 apm_->ApplyConfig(config);
978 apm_->set_stream_analog_level((min_level + max_level) / 2);
979 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(kFloatFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000980 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000981}
982
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100983#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
984TEST_F(ApmTest, GainControlDiesOnTooLowTargetLevelDbfs) {
Sam Zackrisson41478c72019-10-15 10:10:26 +0200985 auto config = apm_->GetConfig();
986 config.gain_controller1.target_level_dbfs = -1;
987 EXPECT_DEATH(apm_->ApplyConfig(config), "");
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100988}
989
990TEST_F(ApmTest, GainControlDiesOnTooHighTargetLevelDbfs) {
Sam Zackrisson41478c72019-10-15 10:10:26 +0200991 auto config = apm_->GetConfig();
992 config.gain_controller1.target_level_dbfs = 32;
993 EXPECT_DEATH(apm_->ApplyConfig(config), "");
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100994}
995
996TEST_F(ApmTest, GainControlDiesOnTooLowCompressionGainDb) {
Sam Zackrisson41478c72019-10-15 10:10:26 +0200997 auto config = apm_->GetConfig();
998 config.gain_controller1.compression_gain_db = -1;
999 EXPECT_DEATH(apm_->ApplyConfig(config), "");
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001000}
1001
1002TEST_F(ApmTest, GainControlDiesOnTooHighCompressionGainDb) {
Sam Zackrisson41478c72019-10-15 10:10:26 +02001003 auto config = apm_->GetConfig();
1004 config.gain_controller1.compression_gain_db = 91;
1005 EXPECT_DEATH(apm_->ApplyConfig(config), "");
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001006}
1007
1008TEST_F(ApmTest, GainControlDiesOnTooLowAnalogLevelLowerLimit) {
Sam Zackrisson41478c72019-10-15 10:10:26 +02001009 auto config = apm_->GetConfig();
1010 config.gain_controller1.analog_level_minimum = -1;
1011 EXPECT_DEATH(apm_->ApplyConfig(config), "");
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001012}
1013
1014TEST_F(ApmTest, GainControlDiesOnTooHighAnalogLevelUpperLimit) {
Sam Zackrisson41478c72019-10-15 10:10:26 +02001015 auto config = apm_->GetConfig();
1016 config.gain_controller1.analog_level_maximum = 65536;
1017 EXPECT_DEATH(apm_->ApplyConfig(config), "");
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001018}
1019
1020TEST_F(ApmTest, GainControlDiesOnInvertedAnalogLevelLimits) {
Sam Zackrisson41478c72019-10-15 10:10:26 +02001021 auto config = apm_->GetConfig();
1022 config.gain_controller1.analog_level_minimum = 512;
1023 config.gain_controller1.analog_level_maximum = 255;
1024 EXPECT_DEATH(apm_->ApplyConfig(config), "");
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001025}
1026
1027TEST_F(ApmTest, ApmDiesOnTooLowAnalogLevel) {
Sam Zackrisson41478c72019-10-15 10:10:26 +02001028 auto config = apm_->GetConfig();
1029 config.gain_controller1.analog_level_minimum = 255;
1030 config.gain_controller1.analog_level_maximum = 512;
1031 apm_->ApplyConfig(config);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001032 EXPECT_DEATH(apm_->set_stream_analog_level(254), "");
1033}
1034
1035TEST_F(ApmTest, ApmDiesOnTooHighAnalogLevel) {
Sam Zackrisson41478c72019-10-15 10:10:26 +02001036 auto config = apm_->GetConfig();
1037 config.gain_controller1.analog_level_minimum = 255;
1038 config.gain_controller1.analog_level_maximum = 512;
1039 apm_->ApplyConfig(config);
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001040 EXPECT_DEATH(apm_->set_stream_analog_level(513), "");
1041}
1042#endif
1043
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001044void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001045 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
Sam Zackrisson41478c72019-10-15 10:10:26 +02001046 auto config = apm_->GetConfig();
1047 config.gain_controller1.enabled = true;
1048 config.gain_controller1.mode =
1049 AudioProcessing::Config::GainController1::kAdaptiveAnalog;
1050 apm_->ApplyConfig(config);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001051
1052 int out_analog_level = 0;
1053 for (int i = 0; i < 2000; ++i) {
1054 ReadFrameWithRewind(near_file_, frame_);
1055 // Ensure the audio is at a low level, so the AGC will try to increase it.
1056 ScaleFrame(frame_, 0.25);
1057
1058 // Always pass in the same volume.
Sam Zackrisson41478c72019-10-15 10:10:26 +02001059 apm_->set_stream_analog_level(100);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001060 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
Sam Zackrisson41478c72019-10-15 10:10:26 +02001061 out_analog_level = apm_->recommended_stream_analog_level();
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001062 }
1063
1064 // Ensure the AGC is still able to reach the maximum.
1065 EXPECT_EQ(255, out_analog_level);
1066}
1067
1068// Verifies that despite volume slider quantization, the AGC can continue to
1069// increase its volume.
1070TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -08001071 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001072 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
1073 }
1074}
1075
1076void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001077 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
Sam Zackrisson41478c72019-10-15 10:10:26 +02001078 auto config = apm_->GetConfig();
1079 config.gain_controller1.enabled = true;
1080 config.gain_controller1.mode =
1081 AudioProcessing::Config::GainController1::kAdaptiveAnalog;
1082 apm_->ApplyConfig(config);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001083
1084 int out_analog_level = 100;
1085 for (int i = 0; i < 1000; ++i) {
1086 ReadFrameWithRewind(near_file_, frame_);
1087 // Ensure the audio is at a low level, so the AGC will try to increase it.
1088 ScaleFrame(frame_, 0.25);
1089
Sam Zackrisson41478c72019-10-15 10:10:26 +02001090 apm_->set_stream_analog_level(out_analog_level);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001091 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
Sam Zackrisson41478c72019-10-15 10:10:26 +02001092 out_analog_level = apm_->recommended_stream_analog_level();
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001093 }
1094
1095 // Ensure the volume was raised.
1096 EXPECT_GT(out_analog_level, 100);
1097 int highest_level_reached = out_analog_level;
1098 // Simulate a user manual volume change.
1099 out_analog_level = 100;
1100
1101 for (int i = 0; i < 300; ++i) {
1102 ReadFrameWithRewind(near_file_, frame_);
1103 ScaleFrame(frame_, 0.25);
1104
Sam Zackrisson41478c72019-10-15 10:10:26 +02001105 apm_->set_stream_analog_level(out_analog_level);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001106 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
Sam Zackrisson41478c72019-10-15 10:10:26 +02001107 out_analog_level = apm_->recommended_stream_analog_level();
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001108 // Check that AGC respected the manually adjusted volume.
1109 EXPECT_LT(out_analog_level, highest_level_reached);
1110 }
1111 // Check that the volume was still raised.
1112 EXPECT_GT(out_analog_level, 100);
1113}
1114
1115TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001116 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001117 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1118 }
1119}
1120
niklase@google.com470e71d2011-07-07 08:21:25 +00001121TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001122 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001123 AudioProcessing::Config apm_config;
1124 apm_config.high_pass_filter.enabled = true;
1125 apm_->ApplyConfig(apm_config);
1126 apm_config.high_pass_filter.enabled = false;
1127 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001128}
1129
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001130TEST_F(ApmTest, AllProcessingDisabledByDefault) {
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001131 AudioProcessing::Config config = apm_->GetConfig();
1132 EXPECT_FALSE(config.echo_canceller.enabled);
1133 EXPECT_FALSE(config.high_pass_filter.enabled);
Sam Zackrisson41478c72019-10-15 10:10:26 +02001134 EXPECT_FALSE(config.gain_controller1.enabled);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001135 EXPECT_FALSE(config.level_estimation.enabled);
saza0bad15f2019-10-16 11:46:11 +02001136 EXPECT_FALSE(config.noise_suppression.enabled);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001137 EXPECT_FALSE(config.voice_detection.enabled);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001138}
1139
1140TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001141 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001142 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001143 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001144 AudioFrame frame_copy;
1145 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001146 for (int j = 0; j < 1000; j++) {
1147 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1148 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001149 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1150 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001151 }
1152 }
1153}
1154
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001155TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1156 // Test that ProcessStream copies input to output even with no processing.
Per Åhgrenc8626b62019-08-23 15:49:51 +02001157 const size_t kSamples = 160;
1158 const int sample_rate = 16000;
Jonas Olssona4d87372019-07-05 19:08:33 +02001159 const float src[kSamples] = {-1.0f, 0.0f, 1.0f};
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001160 float dest[kSamples] = {};
1161
1162 auto src_channels = &src[0];
1163 auto dest_channels = &dest[0];
1164
Ivo Creusen62337e52018-01-09 14:17:33 +01001165 apm_.reset(AudioProcessingBuilder().Create());
Jonas Olssona4d87372019-07-05 19:08:33 +02001166 EXPECT_NOERR(apm_->ProcessStream(&src_channels, kSamples, sample_rate,
1167 LayoutFromChannels(1), sample_rate,
1168 LayoutFromChannels(1), &dest_channels));
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001169
1170 for (size_t i = 0; i < kSamples; ++i) {
1171 EXPECT_EQ(src[i], dest[i]);
1172 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001173
1174 // Same for ProcessReverseStream.
1175 float rev_dest[kSamples] = {};
1176 auto rev_dest_channels = &rev_dest[0];
1177
1178 StreamConfig input_stream = {sample_rate, 1};
1179 StreamConfig output_stream = {sample_rate, 1};
1180 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1181 output_stream, &rev_dest_channels));
1182
1183 for (size_t i = 0; i < kSamples; ++i) {
1184 EXPECT_EQ(src[i], rev_dest[i]);
1185 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001186}
1187
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001188TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1189 EnableAllComponents();
1190
pkasting25702cb2016-01-08 13:50:27 -08001191 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001192 Init(kProcessSampleRates[i], kProcessSampleRates[i], kProcessSampleRates[i],
1193 2, 2, 2, false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001194 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001195 ASSERT_EQ(0, feof(far_file_));
1196 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001197 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001198 CopyLeftToRightChannel(revframe_->mutable_data(),
1199 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001200
aluebsb0319552016-03-17 20:39:53 -07001201 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001202
yujo36b1a5f2017-06-12 12:45:32 -07001203 CopyLeftToRightChannel(frame_->mutable_data(),
1204 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001205 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1206
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001207 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
Sam Zackrisson41478c72019-10-15 10:10:26 +02001208 apm_->set_stream_analog_level(analog_level);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001209 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
Sam Zackrisson41478c72019-10-15 10:10:26 +02001210 analog_level = apm_->recommended_stream_analog_level();
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001211
yujo36b1a5f2017-06-12 12:45:32 -07001212 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001213 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001214 rewind(far_file_);
1215 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001216 }
1217}
1218
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001219TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001220 // Verify the filter is not active through undistorted audio when:
1221 // 1. No components are enabled...
1222 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001223 AudioFrame frame_copy;
1224 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001225 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1226 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1227 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1228
1229 // 2. Only the level estimator is enabled...
saza6787f232019-10-11 19:31:07 +02001230 auto apm_config = apm_->GetConfig();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001231 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001232 frame_copy.CopyFrom(*frame_);
saza6787f232019-10-11 19:31:07 +02001233 apm_config.level_estimation.enabled = true;
1234 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001235 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1236 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1237 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
saza6787f232019-10-11 19:31:07 +02001238 apm_config.level_estimation.enabled = false;
1239 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001240
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001241 // 3. Only GetStatistics-reporting VAD is enabled...
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001242 SetFrameTo(frame_, 1000);
1243 frame_copy.CopyFrom(*frame_);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001244 apm_config.voice_detection.enabled = true;
1245 apm_->ApplyConfig(apm_config);
1246 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1247 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1248 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1249 apm_config.voice_detection.enabled = false;
1250 apm_->ApplyConfig(apm_config);
1251
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001252 // 4. Both the VAD and the level estimator are enabled...
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001253 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001254 frame_copy.CopyFrom(*frame_);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001255 apm_config.voice_detection.enabled = true;
saza6787f232019-10-11 19:31:07 +02001256 apm_config.level_estimation.enabled = true;
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001257 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001258 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1259 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1260 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001261 apm_config.voice_detection.enabled = false;
saza6787f232019-10-11 19:31:07 +02001262 apm_config.level_estimation.enabled = false;
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001263 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001264
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001265 // Check the test is valid. We should have distortion from the filter
1266 // when AEC is enabled (which won't affect the audio).
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001267 apm_config.echo_canceller.enabled = true;
1268 apm_config.echo_canceller.mobile_mode = false;
1269 apm_->ApplyConfig(apm_config);
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001270 frame_->samples_per_channel_ = 320;
1271 frame_->num_channels_ = 2;
1272 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001273 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001274 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001275 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001276 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1277 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1278}
1279
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001280#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1281void ApmTest::ProcessDebugDump(const std::string& in_filename,
1282 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001283 Format format,
1284 int max_size_bytes) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001285 TaskQueueForTest worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001286 FILE* in_file = fopen(in_filename.c_str(), "rb");
1287 ASSERT_TRUE(in_file != NULL);
1288 audioproc::Event event_msg;
1289 bool first_init = true;
1290
1291 while (ReadMessageFromFile(in_file, &event_msg)) {
1292 if (event_msg.type() == audioproc::Event::INIT) {
1293 const audioproc::Init msg = event_msg.init();
1294 int reverse_sample_rate = msg.sample_rate();
1295 if (msg.has_reverse_sample_rate()) {
1296 reverse_sample_rate = msg.reverse_sample_rate();
1297 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001298 int output_sample_rate = msg.sample_rate();
1299 if (msg.has_output_sample_rate()) {
1300 output_sample_rate = msg.output_sample_rate();
1301 }
1302
Jonas Olssona4d87372019-07-05 19:08:33 +02001303 Init(msg.sample_rate(), output_sample_rate, reverse_sample_rate,
1304 msg.num_input_channels(), msg.num_output_channels(),
1305 msg.num_reverse_channels(), false);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001306 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001307 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001308 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001309 auto aec_dump =
1310 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1311 EXPECT_TRUE(aec_dump);
1312 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001313 first_init = false;
1314 }
1315
1316 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1317 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1318
1319 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001320 ASSERT_EQ(revframe_->num_channels_,
1321 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001322 for (int i = 0; i < msg.channel_size(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001323 memcpy(revfloat_cb_->channels()[i], msg.channel(i).data(),
1324 msg.channel(i).size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001325 }
1326 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001327 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001328 if (format == kFloatFormat) {
1329 // We're using an int16 input file; convert to float.
1330 ConvertToFloat(*revframe_, revfloat_cb_.get());
1331 }
1332 }
1333 AnalyzeReverseStreamChooser(format);
1334
1335 } else if (event_msg.type() == audioproc::Event::STREAM) {
1336 const audioproc::Stream msg = event_msg.stream();
1337 // ProcessStream could have changed this for the output frame.
1338 frame_->num_channels_ = apm_->num_input_channels();
1339
Sam Zackrisson41478c72019-10-15 10:10:26 +02001340 apm_->set_stream_analog_level(msg.level());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001341 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001342 if (msg.has_keypress()) {
1343 apm_->set_stream_key_pressed(msg.keypress());
1344 } else {
1345 apm_->set_stream_key_pressed(true);
1346 }
1347
1348 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001349 ASSERT_EQ(frame_->num_channels_,
1350 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001351 for (int i = 0; i < msg.input_channel_size(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001352 memcpy(float_cb_->channels()[i], msg.input_channel(i).data(),
1353 msg.input_channel(i).size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001354 }
1355 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001356 memcpy(frame_->mutable_data(), msg.input_data().data(),
1357 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001358 if (format == kFloatFormat) {
1359 // We're using an int16 input file; convert to float.
1360 ConvertToFloat(*frame_, float_cb_.get());
1361 }
1362 }
1363 ProcessStreamChooser(format);
1364 }
1365 }
aleloif4dd1912017-06-15 01:55:38 -07001366 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001367 fclose(in_file);
1368}
1369
1370void ApmTest::VerifyDebugDumpTest(Format format) {
Minyue Li656d6092018-08-10 15:38:52 +02001371 rtc::ScopedFakeClock fake_clock;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001372 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001373 std::string format_string;
1374 switch (format) {
1375 case kIntFormat:
1376 format_string = "_int";
1377 break;
1378 case kFloatFormat:
1379 format_string = "_float";
1380 break;
1381 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001382 const std::string ref_filename = test::TempFilename(
1383 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1384 const std::string out_filename = test::TempFilename(
1385 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001386 const std::string limited_filename = test::TempFilename(
1387 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1388 const size_t logging_limit_bytes = 100000;
1389 // We expect at least this many bytes in the created logfile.
1390 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001391 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001392 ProcessDebugDump(in_filename, ref_filename, format, -1);
1393 ProcessDebugDump(ref_filename, out_filename, format, -1);
1394 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001395
1396 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1397 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001398 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001399 ASSERT_TRUE(ref_file != NULL);
1400 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001401 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001402 std::unique_ptr<uint8_t[]> ref_bytes;
1403 std::unique_ptr<uint8_t[]> out_bytes;
1404 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001405
1406 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1407 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001408 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001409 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001410 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001411 while (ref_size > 0 && out_size > 0) {
1412 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001413 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001414 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001415 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001416 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001417 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001418 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1419 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001420 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001421 }
1422 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001423 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1424 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001425 EXPECT_NE(0, feof(ref_file));
1426 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001427 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001428 ASSERT_EQ(0, fclose(ref_file));
1429 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001430 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001431 remove(ref_filename.c_str());
1432 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001433 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001434}
1435
pbosc7a65692016-05-06 12:50:04 -07001436TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001437 VerifyDebugDumpTest(kIntFormat);
1438}
1439
pbosc7a65692016-05-06 12:50:04 -07001440TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001441 VerifyDebugDumpTest(kFloatFormat);
1442}
1443#endif
1444
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001445// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001446TEST_F(ApmTest, DebugDump) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001447 TaskQueueForTest worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001448 const std::string filename =
1449 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001450 {
1451 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1452 EXPECT_FALSE(aec_dump);
1453 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001454
1455#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1456 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001457 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001458
aleloif4dd1912017-06-15 01:55:38 -07001459 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1460 EXPECT_TRUE(aec_dump);
1461 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001462 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001463 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001464 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001465
1466 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001467 FILE* fid = fopen(filename.c_str(), "r");
1468 ASSERT_TRUE(fid != NULL);
1469
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001470 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001471 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001472 ASSERT_EQ(0, remove(filename.c_str()));
1473#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001474 // Verify the file has NOT been written.
1475 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1476#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1477}
1478
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001479// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001480TEST_F(ApmTest, DebugDumpFromFileHandle) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001481 TaskQueueForTest worker_queue("ApmTest_worker_queue");
aleloif4dd1912017-06-15 01:55:38 -07001482
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001483 const std::string filename =
1484 test::TempFilename(test::OutputPath(), "debug_aec");
Niels Möllere8e4dc42019-06-11 14:04:16 +02001485 FileWrapper f = FileWrapper::OpenWriteOnly(filename.c_str());
1486 ASSERT_TRUE(f.is_open());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001487
1488#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1489 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001490 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001491
Niels Möllere8e4dc42019-06-11 14:04:16 +02001492 auto aec_dump = AecDumpFactory::Create(std::move(f), -1, &worker_queue);
aleloif4dd1912017-06-15 01:55:38 -07001493 EXPECT_TRUE(aec_dump);
1494 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001495 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001496 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001497 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001498
1499 // Verify the file has been written.
Niels Möllere8e4dc42019-06-11 14:04:16 +02001500 FILE* fid = fopen(filename.c_str(), "r");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001501 ASSERT_TRUE(fid != NULL);
1502
1503 // Clean it up.
1504 ASSERT_EQ(0, fclose(fid));
1505 ASSERT_EQ(0, remove(filename.c_str()));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001506#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1507}
1508
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001509// TODO(andrew): Add a test to process a few frames with different combinations
1510// of enabled components.
1511
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001512TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001513 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001514 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001515
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001516 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001517 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001518 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001519 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08001520 for (size_t i = 0; i < arraysize(kChannels); i++) {
1521 for (size_t j = 0; j < arraysize(kChannels); j++) {
1522 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001523 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001524 test->set_num_reverse_channels(kChannels[i]);
1525 test->set_num_input_channels(kChannels[j]);
1526 test->set_num_output_channels(kChannels[j]);
1527 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001528 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001529 }
1530 }
1531 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001532#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1533 // To test the extended filter mode.
1534 audioproc::Test* test = ref_data.add_test();
1535 test->set_num_reverse_channels(2);
1536 test->set_num_input_channels(2);
1537 test->set_num_output_channels(2);
1538 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
1539 test->set_use_aec_extended_filter(true);
1540#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001541 }
1542
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001543 for (int i = 0; i < ref_data.test_size(); i++) {
1544 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001545
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001546 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001547 // TODO(ajm): We no longer allow different input and output channels. Skip
1548 // these tests for now, but they should be removed from the set.
1549 if (test->num_input_channels() != test->num_output_channels())
1550 continue;
1551
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001552 Config config;
1553 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02001554 config.Set<ExtendedFilter>(
1555 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01001556 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001557
1558 EnableAllComponents();
1559
Jonas Olssona4d87372019-07-05 19:08:33 +02001560 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08001561 static_cast<size_t>(test->num_input_channels()),
1562 static_cast<size_t>(test->num_output_channels()),
Jonas Olssona4d87372019-07-05 19:08:33 +02001563 static_cast<size_t>(test->num_reverse_channels()), true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001564
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001565 int frame_count = 0;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001566 int has_voice_count = 0;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001567 int analog_level = 127;
1568 int analog_level_average = 0;
1569 int max_output_average = 0;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001570 float rms_dbfs_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07001571#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +02001572 int stats_index = 0;
minyue58530ed2016-05-24 05:50:12 -07001573#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001574
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001575 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07001576 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001577
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001578 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1579
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001580 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
Sam Zackrisson41478c72019-10-15 10:10:26 +02001581 apm_->set_stream_analog_level(analog_level);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001582
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001583 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001584
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001585 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08001586 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
1587 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001588
1589 max_output_average += MaxAudioFrame(*frame_);
1590
Sam Zackrisson41478c72019-10-15 10:10:26 +02001591 analog_level = apm_->recommended_stream_analog_level();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001592 analog_level_average += analog_level;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001593 AudioProcessingStats stats =
1594 apm_->GetStatistics(/*has_remote_tracks=*/false);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001595 EXPECT_TRUE(stats.voice_detected);
1596 EXPECT_TRUE(stats.output_rms_dbfs);
1597 has_voice_count += *stats.voice_detected ? 1 : 0;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001598 rms_dbfs_average += *stats.output_rms_dbfs;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001599
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001600 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
Jonas Olssona4d87372019-07-05 19:08:33 +02001601 size_t write_count =
1602 fwrite(frame_->data(), sizeof(int16_t), frame_size, out_file_);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001603 ASSERT_EQ(frame_size, write_count);
1604
1605 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08001606 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001607 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07001608
1609#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1610 const int kStatsAggregationFrameNum = 100; // 1 second.
1611 if (frame_count % kStatsAggregationFrameNum == 0) {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001612 // Get echo and delay metrics.
1613 AudioProcessingStats stats =
1614 apm_->GetStatistics(true /* has_remote_tracks */);
minyue58530ed2016-05-24 05:50:12 -07001615
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001616 // Echo metrics.
1617 const float echo_return_loss = stats.echo_return_loss.value_or(-1.0f);
1618 const float echo_return_loss_enhancement =
1619 stats.echo_return_loss_enhancement.value_or(-1.0f);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001620 const float residual_echo_likelihood =
1621 stats.residual_echo_likelihood.value_or(-1.0f);
1622 const float residual_echo_likelihood_recent_max =
1623 stats.residual_echo_likelihood_recent_max.value_or(-1.0f);
1624
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001625 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
minyue58530ed2016-05-24 05:50:12 -07001626 const audioproc::Test::EchoMetrics& reference =
1627 test->echo_metrics(stats_index);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001628 constexpr float kEpsilon = 0.01;
1629 EXPECT_NEAR(echo_return_loss, reference.echo_return_loss(), kEpsilon);
1630 EXPECT_NEAR(echo_return_loss_enhancement,
1631 reference.echo_return_loss_enhancement(), kEpsilon);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001632 EXPECT_NEAR(residual_echo_likelihood,
1633 reference.residual_echo_likelihood(), kEpsilon);
1634 EXPECT_NEAR(residual_echo_likelihood_recent_max,
1635 reference.residual_echo_likelihood_recent_max(),
1636 kEpsilon);
minyue58530ed2016-05-24 05:50:12 -07001637 ++stats_index;
1638 } else {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001639 audioproc::Test::EchoMetrics* message_echo = test->add_echo_metrics();
1640 message_echo->set_echo_return_loss(echo_return_loss);
1641 message_echo->set_echo_return_loss_enhancement(
1642 echo_return_loss_enhancement);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001643 message_echo->set_residual_echo_likelihood(residual_echo_likelihood);
1644 message_echo->set_residual_echo_likelihood_recent_max(
1645 residual_echo_likelihood_recent_max);
minyue58530ed2016-05-24 05:50:12 -07001646 }
1647 }
1648#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001649 }
1650 max_output_average /= frame_count;
1651 analog_level_average /= frame_count;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001652 rms_dbfs_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001653
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001654 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001655 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001656 // When running the test on a N7 we get a {2, 6} difference of
1657 // |has_voice_count| and |max_output_average| is up to 18 higher.
1658 // All numbers being consistently higher on N7 compare to ref_data.
1659 // TODO(bjornv): If we start getting more of these offsets on Android we
1660 // should consider a different approach. Either using one slack for all,
1661 // or generate a separate android reference.
Kári Tristan Helgason640106e2018-09-06 15:29:45 +02001662#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001663 const int kHasVoiceCountOffset = 3;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001664 const int kHasVoiceCountNear = 8;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001665 const int kMaxOutputAverageOffset = 9;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001666 const int kMaxOutputAverageNear = 26;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001667#else
1668 const int kHasVoiceCountOffset = 0;
1669 const int kHasVoiceCountNear = kIntNear;
1670 const int kMaxOutputAverageOffset = 0;
1671 const int kMaxOutputAverageNear = kIntNear;
1672#endif
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001673 EXPECT_NEAR(test->has_voice_count(),
Jonas Olssona4d87372019-07-05 19:08:33 +02001674 has_voice_count - kHasVoiceCountOffset, kHasVoiceCountNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001675
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001676 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001677 EXPECT_NEAR(test->max_output_average(),
1678 max_output_average - kMaxOutputAverageOffset,
1679 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00001680#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001681 const double kFloatNear = 0.0005;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001682 EXPECT_NEAR(test->rms_dbfs_average(), rms_dbfs_average, kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001683#endif
1684 } else {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001685 test->set_has_voice_count(has_voice_count);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001686
1687 test->set_analog_level_average(analog_level_average);
1688 test->set_max_output_average(max_output_average);
1689
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00001690#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Sam Zackrisson11b87032018-12-18 17:13:58 +01001691 test->set_rms_dbfs_average(rms_dbfs_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001692#endif
1693 }
1694
1695 rewind(far_file_);
1696 rewind(near_file_);
1697 }
1698
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001699 if (absl::GetFlag(FLAGS_write_apm_ref_data)) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001700 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001701 }
1702}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001703
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001704TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
1705 struct ChannelFormat {
1706 AudioProcessing::ChannelLayout in_layout;
1707 AudioProcessing::ChannelLayout out_layout;
1708 };
1709 ChannelFormat cf[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001710 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
1711 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
1712 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001713 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001714
Ivo Creusen62337e52018-01-09 14:17:33 +01001715 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001716 // Enable one component just to ensure some processing takes place.
saza0bad15f2019-10-16 11:46:11 +02001717 AudioProcessing::Config config;
1718 config.noise_suppression.enabled = true;
1719 ap->ApplyConfig(config);
pkasting25702cb2016-01-08 13:50:27 -08001720 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001721 const int in_rate = 44100;
1722 const int out_rate = 48000;
1723 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
1724 TotalChannelsFromLayout(cf[i].in_layout));
1725 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
1726 ChannelsFromLayout(cf[i].out_layout));
1727
1728 // Run over a few chunks.
1729 for (int j = 0; j < 10; ++j) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001730 EXPECT_NOERR(ap->ProcessStream(in_cb.channels(), in_cb.num_frames(),
1731 in_rate, cf[i].in_layout, out_rate,
1732 cf[i].out_layout, out_cb.channels()));
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001733 }
1734 }
1735}
1736
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001737// Compares the reference and test arrays over a region around the expected
1738// delay. Finds the highest SNR in that region and adds the variance and squared
1739// error results to the supplied accumulators.
1740void UpdateBestSNR(const float* ref,
1741 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08001742 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001743 int expected_delay,
1744 double* variance_acc,
1745 double* sq_error_acc) {
1746 double best_snr = std::numeric_limits<double>::min();
1747 double best_variance = 0;
1748 double best_sq_error = 0;
1749 // Search over a region of eight samples around the expected delay.
1750 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
1751 ++delay) {
1752 double sq_error = 0;
1753 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08001754 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001755 double error = test[i + delay] - ref[i];
1756 sq_error += error * error;
1757 variance += ref[i] * ref[i];
1758 }
1759
1760 if (sq_error == 0) {
1761 *variance_acc += variance;
1762 return;
1763 }
1764 double snr = variance / sq_error;
1765 if (snr > best_snr) {
1766 best_snr = snr;
1767 best_variance = variance;
1768 best_sq_error = sq_error;
1769 }
1770 }
1771
1772 *variance_acc += best_variance;
1773 *sq_error_acc += best_sq_error;
1774}
1775
1776// Used to test a multitude of sample rate and channel combinations. It works
1777// by first producing a set of reference files (in SetUpTestCase) that are
1778// assumed to be correct, as the used parameters are verified by other tests
1779// in this collection. Primarily the reference files are all produced at
1780// "native" rates which do not involve any resampling.
1781
1782// Each test pass produces an output file with a particular format. The output
1783// is matched against the reference file closest to its internal processing
1784// format. If necessary the output is resampled back to its process format.
1785// Due to the resampling distortion, we don't expect identical results, but
1786// enforce SNR thresholds which vary depending on the format. 0 is a special
1787// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02001788typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001789class AudioProcessingTest
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001790 : public ::testing::TestWithParam<AudioProcessingTestData> {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001791 public:
1792 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02001793 : input_rate_(std::get<0>(GetParam())),
1794 output_rate_(std::get<1>(GetParam())),
1795 reverse_input_rate_(std::get<2>(GetParam())),
1796 reverse_output_rate_(std::get<3>(GetParam())),
1797 expected_snr_(std::get<4>(GetParam())),
1798 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001799
1800 virtual ~AudioProcessingTest() {}
1801
Mirko Bonadei71061bc2019-06-04 09:01:51 +02001802 static void SetUpTestSuite() {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001803 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07001804 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08001805 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08001806 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
1807 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
1808 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001809 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07001810 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
1811 kNativeRates[i], kNumChannels[j], kNumChannels[j],
1812 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001813 }
1814 }
1815 }
1816 }
1817
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02001818 void TearDown() {
1819 // Remove "out" files after each test.
1820 ClearTempOutFiles();
1821 }
1822
Mirko Bonadei71061bc2019-06-04 09:01:51 +02001823 static void TearDownTestSuite() { ClearTempFiles(); }
ekmeyerson60d9b332015-08-14 10:35:55 -07001824
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001825 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07001826 // to a file specified with |output_file_prefix|. Both forward and reverse
1827 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001828 static void ProcessFormat(int input_rate,
1829 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07001830 int reverse_input_rate,
1831 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001832 size_t num_input_channels,
1833 size_t num_output_channels,
1834 size_t num_reverse_input_channels,
1835 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02001836 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001837 Config config;
1838 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001839 std::unique_ptr<AudioProcessing> ap(
1840 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001841 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001842
ekmeyerson60d9b332015-08-14 10:35:55 -07001843 ProcessingConfig processing_config = {
1844 {{input_rate, num_input_channels},
1845 {output_rate, num_output_channels},
1846 {reverse_input_rate, num_reverse_input_channels},
1847 {reverse_output_rate, num_reverse_output_channels}}};
1848 ap->Initialize(processing_config);
1849
1850 FILE* far_file =
1851 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001852 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +02001853 FILE* out_file = fopen(
1854 OutputFilePath(
1855 output_file_prefix, input_rate, output_rate, reverse_input_rate,
1856 reverse_output_rate, num_input_channels, num_output_channels,
1857 num_reverse_input_channels, num_reverse_output_channels, kForward)
1858 .c_str(),
1859 "wb");
1860 FILE* rev_out_file = fopen(
1861 OutputFilePath(
1862 output_file_prefix, input_rate, output_rate, reverse_input_rate,
1863 reverse_output_rate, num_input_channels, num_output_channels,
1864 num_reverse_input_channels, num_reverse_output_channels, kReverse)
1865 .c_str(),
1866 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001867 ASSERT_TRUE(far_file != NULL);
1868 ASSERT_TRUE(near_file != NULL);
1869 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07001870 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001871
1872 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
1873 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07001874 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
1875 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001876 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
1877 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07001878 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
1879 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001880
1881 // Temporary buffers.
1882 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07001883 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
1884 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08001885 std::unique_ptr<float[]> float_data(new float[max_length]);
1886 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001887
1888 int analog_level = 127;
1889 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
1890 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07001891 EXPECT_NOERR(ap->ProcessReverseStream(
1892 rev_cb.channels(), processing_config.reverse_input_stream(),
1893 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001894
1895 EXPECT_NOERR(ap->set_stream_delay_ms(0));
Sam Zackrisson41478c72019-10-15 10:10:26 +02001896 ap->set_stream_analog_level(analog_level);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001897
1898 EXPECT_NOERR(ap->ProcessStream(
Jonas Olssona4d87372019-07-05 19:08:33 +02001899 fwd_cb.channels(), fwd_cb.num_frames(), input_rate,
1900 LayoutFromChannels(num_input_channels), output_rate,
1901 LayoutFromChannels(num_output_channels), out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001902
ekmeyerson60d9b332015-08-14 10:35:55 -07001903 // Dump forward output to file.
1904 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001905 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08001906 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07001907
Jonas Olssona4d87372019-07-05 19:08:33 +02001908 ASSERT_EQ(out_length, fwrite(float_data.get(), sizeof(float_data[0]),
1909 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001910
ekmeyerson60d9b332015-08-14 10:35:55 -07001911 // Dump reverse output to file.
1912 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
1913 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08001914 size_t rev_out_length =
1915 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07001916
Jonas Olssona4d87372019-07-05 19:08:33 +02001917 ASSERT_EQ(rev_out_length, fwrite(float_data.get(), sizeof(float_data[0]),
1918 rev_out_length, rev_out_file));
ekmeyerson60d9b332015-08-14 10:35:55 -07001919
Sam Zackrisson41478c72019-10-15 10:10:26 +02001920 analog_level = ap->recommended_stream_analog_level();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001921 }
1922 fclose(far_file);
1923 fclose(near_file);
1924 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07001925 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001926 }
1927
1928 protected:
1929 int input_rate_;
1930 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07001931 int reverse_input_rate_;
1932 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001933 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07001934 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001935};
1936
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00001937TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001938 struct ChannelFormat {
1939 int num_input;
1940 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07001941 int num_reverse_input;
1942 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001943 };
1944 ChannelFormat cf[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001945 {1, 1, 1, 1}, {1, 1, 2, 1}, {2, 1, 1, 1},
1946 {2, 1, 2, 1}, {2, 2, 1, 1}, {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001947 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001948
pkasting25702cb2016-01-08 13:50:27 -08001949 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07001950 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
1951 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
1952 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07001953
ekmeyerson60d9b332015-08-14 10:35:55 -07001954 // Verify output for both directions.
1955 std::vector<StreamDirection> stream_directions;
1956 stream_directions.push_back(kForward);
1957 stream_directions.push_back(kReverse);
1958 for (StreamDirection file_direction : stream_directions) {
1959 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
1960 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
1961 const int out_num =
1962 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
1963 const double expected_snr =
1964 file_direction ? expected_reverse_snr_ : expected_snr_;
1965
1966 const int min_ref_rate = std::min(in_rate, out_rate);
1967 int ref_rate;
1968
1969 if (min_ref_rate > 32000) {
1970 ref_rate = 48000;
1971 } else if (min_ref_rate > 16000) {
1972 ref_rate = 32000;
1973 } else if (min_ref_rate > 8000) {
1974 ref_rate = 16000;
1975 } else {
1976 ref_rate = 8000;
1977 }
aluebs776593b2016-03-15 14:04:58 -07001978#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08001979 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07001980 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08001981 }
1982#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001983 FILE* out_file = fopen(
1984 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
1985 reverse_output_rate_, cf[i].num_input,
1986 cf[i].num_output, cf[i].num_reverse_input,
Jonas Olssona4d87372019-07-05 19:08:33 +02001987 cf[i].num_reverse_output, file_direction)
1988 .c_str(),
ekmeyerson60d9b332015-08-14 10:35:55 -07001989 "rb");
1990 // The reference files always have matching input and output channels.
Jonas Olssona4d87372019-07-05 19:08:33 +02001991 FILE* ref_file =
1992 fopen(OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
1993 cf[i].num_output, cf[i].num_output,
1994 cf[i].num_reverse_output,
1995 cf[i].num_reverse_output, file_direction)
1996 .c_str(),
1997 "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07001998 ASSERT_TRUE(out_file != NULL);
1999 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002000
pkasting25702cb2016-01-08 13:50:27 -08002001 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2002 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002003 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002004 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002005 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002006 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002007 // Data from the resampled output, in case the reference and output rates
2008 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002009 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002010
ekmeyerson60d9b332015-08-14 10:35:55 -07002011 PushResampler<float> resampler;
2012 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002013
ekmeyerson60d9b332015-08-14 10:35:55 -07002014 // Compute the resampling delay of the output relative to the reference,
2015 // to find the region over which we should search for the best SNR.
2016 float expected_delay_sec = 0;
2017 if (in_rate != ref_rate) {
2018 // Input resampling delay.
2019 expected_delay_sec +=
2020 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2021 }
2022 if (out_rate != ref_rate) {
2023 // Output resampling delay.
2024 expected_delay_sec +=
2025 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2026 // Delay of converting the output back to its processing rate for
2027 // testing.
2028 expected_delay_sec +=
2029 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2030 }
2031 int expected_delay =
Oleh Prypin708eccc2019-03-27 09:38:52 +01002032 std::floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002033
ekmeyerson60d9b332015-08-14 10:35:55 -07002034 double variance = 0;
2035 double sq_error = 0;
2036 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2037 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2038 float* out_ptr = out_data.get();
2039 if (out_rate != ref_rate) {
2040 // Resample the output back to its internal processing rate if
2041 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002042 ASSERT_EQ(ref_length,
2043 static_cast<size_t>(resampler.Resample(
2044 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002045 out_ptr = cmp_data.get();
2046 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002047
ekmeyerson60d9b332015-08-14 10:35:55 -07002048 // Update the |sq_error| and |variance| accumulators with the highest
2049 // SNR of reference vs output.
2050 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2051 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002052 }
2053
ekmeyerson60d9b332015-08-14 10:35:55 -07002054 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2055 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2056 << cf[i].num_input << ", " << cf[i].num_output << ", "
2057 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2058 << ", " << file_direction << "): ";
2059 if (sq_error > 0) {
2060 double snr = 10 * log10(variance / sq_error);
2061 EXPECT_GE(snr, expected_snr);
2062 EXPECT_NE(0, expected_snr);
2063 std::cout << "SNR=" << snr << " dB" << std::endl;
2064 } else {
aluebs776593b2016-03-15 14:04:58 -07002065 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002066 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002067
ekmeyerson60d9b332015-08-14 10:35:55 -07002068 fclose(out_file);
2069 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002070 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002071 }
2072}
2073
2074#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002075INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002076 CommonFormats,
2077 AudioProcessingTest,
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002078 ::testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2079 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2080 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2081 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2082 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2083 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2084 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2085 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2086 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2087 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2088 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2089 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002090
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002091 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2092 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2093 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2094 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2095 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2096 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2097 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2098 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2099 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2100 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2101 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2102 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002103
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002104 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2105 std::make_tuple(32000, 48000, 32000, 48000, 32, 30),
2106 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2107 std::make_tuple(32000, 44100, 48000, 44100, 19, 20),
2108 std::make_tuple(32000, 44100, 32000, 44100, 19, 15),
2109 std::make_tuple(32000, 44100, 16000, 44100, 19, 15),
2110 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2111 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2112 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2113 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2114 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2115 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002116
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002117 std::make_tuple(16000, 48000, 48000, 48000, 24, 0),
2118 std::make_tuple(16000, 48000, 32000, 48000, 24, 30),
2119 std::make_tuple(16000, 48000, 16000, 48000, 24, 20),
2120 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2121 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2122 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2123 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2124 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2125 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2126 std::make_tuple(16000, 16000, 48000, 16000, 39, 20),
2127 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2128 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002129
2130#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002131INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002132 CommonFormats,
2133 AudioProcessingTest,
Per Åhgren0aefbf02019-08-23 21:29:17 +02002134 ::testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 19, 0),
2135 std::make_tuple(48000, 48000, 32000, 48000, 19, 30),
2136 std::make_tuple(48000, 48000, 16000, 48000, 19, 20),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002137 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2138 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2139 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
Per Åhgren0aefbf02019-08-23 21:29:17 +02002140 std::make_tuple(48000, 32000, 48000, 32000, 19, 35),
2141 std::make_tuple(48000, 32000, 32000, 32000, 19, 0),
2142 std::make_tuple(48000, 32000, 16000, 32000, 19, 20),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002143 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2144 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2145 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002146
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002147 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2148 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2149 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2150 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2151 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2152 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
Per Åhgren0aefbf02019-08-23 21:29:17 +02002153 std::make_tuple(44100, 32000, 48000, 32000, 18, 35),
2154 std::make_tuple(44100, 32000, 32000, 32000, 18, 0),
2155 std::make_tuple(44100, 32000, 16000, 32000, 18, 20),
2156 std::make_tuple(44100, 16000, 48000, 16000, 19, 20),
2157 std::make_tuple(44100, 16000, 32000, 16000, 19, 20),
2158 std::make_tuple(44100, 16000, 16000, 16000, 19, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002159
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002160 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2161 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2162 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2163 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2164 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2165 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2166 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2167 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2168 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2169 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2170 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2171 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002172
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002173 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2174 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2175 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2176 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2177 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2178 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2179 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2180 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2181 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2182 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2183 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2184 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002185#endif
2186
Per Åhgren3e8bf282019-08-29 23:38:40 +02002187// Produces a scoped trace debug output.
2188std::string ProduceDebugText(int render_input_sample_rate_hz,
2189 int render_output_sample_rate_hz,
2190 int capture_input_sample_rate_hz,
2191 int capture_output_sample_rate_hz,
2192 size_t render_input_num_channels,
2193 size_t render_output_num_channels,
2194 size_t capture_input_num_channels,
2195 size_t capture_output_num_channels) {
2196 rtc::StringBuilder ss;
2197 ss << "Sample rates:"
2198 << "\n"
2199 << " Render input: " << render_input_sample_rate_hz << " Hz"
2200 << "\n"
2201 << " Render output: " << render_output_sample_rate_hz << " Hz"
2202 << "\n"
2203 << " Capture input: " << capture_input_sample_rate_hz << " Hz"
2204 << "\n"
2205 << " Capture output: " << capture_output_sample_rate_hz << " Hz"
2206 << "\n"
2207 << "Number of channels:"
2208 << "\n"
2209 << " Render input: " << render_input_num_channels << "\n"
2210 << " Render output: " << render_output_num_channels << "\n"
2211 << " Capture input: " << capture_input_num_channels << "\n"
2212 << " Capture output: " << capture_output_num_channels;
2213 return ss.Release();
2214}
2215
2216// Validates that running the audio processing module using various combinations
2217// of sample rates and number of channels works as intended.
2218void RunApmRateAndChannelTest(
2219 rtc::ArrayView<const int> sample_rates_hz,
2220 rtc::ArrayView<const int> render_channel_counts,
2221 rtc::ArrayView<const int> capture_channel_counts) {
2222 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2223 webrtc::AudioProcessing::Config apm_config;
2224 apm_config.echo_canceller.enabled = true;
2225 apm->ApplyConfig(apm_config);
2226
2227 StreamConfig render_input_stream_config;
2228 StreamConfig render_output_stream_config;
2229 StreamConfig capture_input_stream_config;
2230 StreamConfig capture_output_stream_config;
2231
2232 std::vector<float> render_input_frame_channels;
2233 std::vector<float*> render_input_frame;
2234 std::vector<float> render_output_frame_channels;
2235 std::vector<float*> render_output_frame;
2236 std::vector<float> capture_input_frame_channels;
2237 std::vector<float*> capture_input_frame;
2238 std::vector<float> capture_output_frame_channels;
2239 std::vector<float*> capture_output_frame;
2240
2241 for (auto render_input_sample_rate_hz : sample_rates_hz) {
2242 for (auto render_output_sample_rate_hz : sample_rates_hz) {
2243 for (auto capture_input_sample_rate_hz : sample_rates_hz) {
2244 for (auto capture_output_sample_rate_hz : sample_rates_hz) {
2245 for (size_t render_input_num_channels : render_channel_counts) {
2246 for (size_t capture_input_num_channels : capture_channel_counts) {
2247 size_t render_output_num_channels = render_input_num_channels;
2248 size_t capture_output_num_channels = capture_input_num_channels;
2249 auto populate_audio_frame = [](int sample_rate_hz,
2250 size_t num_channels,
2251 StreamConfig* cfg,
2252 std::vector<float>* channels_data,
2253 std::vector<float*>* frame_data) {
2254 cfg->set_sample_rate_hz(sample_rate_hz);
2255 cfg->set_num_channels(num_channels);
2256 cfg->set_has_keyboard(false);
2257
2258 size_t max_frame_size = ceil(sample_rate_hz / 100.f);
2259 channels_data->resize(num_channels * max_frame_size);
2260 std::fill(channels_data->begin(), channels_data->end(), 0.5f);
2261 frame_data->resize(num_channels);
2262 for (size_t channel = 0; channel < num_channels; ++channel) {
2263 (*frame_data)[channel] =
2264 &(*channels_data)[channel * max_frame_size];
2265 }
2266 };
2267
2268 populate_audio_frame(
2269 render_input_sample_rate_hz, render_input_num_channels,
2270 &render_input_stream_config, &render_input_frame_channels,
2271 &render_input_frame);
2272 populate_audio_frame(
2273 render_output_sample_rate_hz, render_output_num_channels,
2274 &render_output_stream_config, &render_output_frame_channels,
2275 &render_output_frame);
2276 populate_audio_frame(
2277 capture_input_sample_rate_hz, capture_input_num_channels,
2278 &capture_input_stream_config, &capture_input_frame_channels,
2279 &capture_input_frame);
2280 populate_audio_frame(
2281 capture_output_sample_rate_hz, capture_output_num_channels,
2282 &capture_output_stream_config, &capture_output_frame_channels,
2283 &capture_output_frame);
2284
2285 for (size_t frame = 0; frame < 2; ++frame) {
2286 SCOPED_TRACE(ProduceDebugText(
2287 render_input_sample_rate_hz, render_output_sample_rate_hz,
2288 capture_input_sample_rate_hz, capture_output_sample_rate_hz,
2289 render_input_num_channels, render_output_num_channels,
2290 render_input_num_channels, capture_output_num_channels));
2291
2292 int result = apm->ProcessReverseStream(
2293 &render_input_frame[0], render_input_stream_config,
2294 render_output_stream_config, &render_output_frame[0]);
2295 EXPECT_EQ(result, AudioProcessing::kNoError);
2296 result = apm->ProcessStream(
2297 &capture_input_frame[0], capture_input_stream_config,
2298 capture_output_stream_config, &capture_output_frame[0]);
2299 EXPECT_EQ(result, AudioProcessing::kNoError);
2300 }
2301 }
2302 }
2303 }
2304 }
2305 }
2306 }
2307}
2308
niklase@google.com470e71d2011-07-07 08:21:25 +00002309} // namespace
peahc19f3122016-10-07 14:54:10 -07002310
Alessio Bazzicac054e782018-04-16 12:10:09 +02002311TEST(RuntimeSettingTest, TestDefaultCtor) {
2312 auto s = AudioProcessing::RuntimeSetting();
2313 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2314}
2315
2316TEST(RuntimeSettingTest, TestCapturePreGain) {
2317 using Type = AudioProcessing::RuntimeSetting::Type;
2318 {
2319 auto s = AudioProcessing::RuntimeSetting::CreateCapturePreGain(1.25f);
2320 EXPECT_EQ(Type::kCapturePreGain, s.type());
2321 float v;
2322 s.GetFloat(&v);
2323 EXPECT_EQ(1.25f, v);
2324 }
2325
2326#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2327 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2328#endif
2329}
2330
Per Åhgren6ee75fd2019-04-26 11:33:37 +02002331TEST(RuntimeSettingTest, TestCaptureFixedPostGain) {
2332 using Type = AudioProcessing::RuntimeSetting::Type;
2333 {
2334 auto s = AudioProcessing::RuntimeSetting::CreateCaptureFixedPostGain(1.25f);
2335 EXPECT_EQ(Type::kCaptureFixedPostGain, s.type());
2336 float v;
2337 s.GetFloat(&v);
2338 EXPECT_EQ(1.25f, v);
2339 }
2340
2341#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2342 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2343#endif
2344}
2345
Alessio Bazzicac054e782018-04-16 12:10:09 +02002346TEST(RuntimeSettingTest, TestUsageWithSwapQueue) {
2347 SwapQueue<AudioProcessing::RuntimeSetting> q(1);
2348 auto s = AudioProcessing::RuntimeSetting();
2349 ASSERT_TRUE(q.Insert(&s));
2350 ASSERT_TRUE(q.Remove(&s));
2351 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2352}
2353
Sam Zackrisson0beac582017-09-25 12:04:02 +02002354TEST(ApmConfiguration, EnablePostProcessing) {
2355 // Verify that apm uses a capture post processing module if one is provided.
Sam Zackrisson0beac582017-09-25 12:04:02 +02002356 auto mock_post_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002357 new ::testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002358 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002359 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002360 rtc::scoped_refptr<AudioProcessing> apm =
2361 AudioProcessingBuilder()
2362 .SetCapturePostProcessing(std::move(mock_post_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002363 .Create();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002364
2365 AudioFrame audio;
2366 audio.num_channels_ = 1;
2367 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2368
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002369 EXPECT_CALL(*mock_post_processor_ptr, Process(::testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002370 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002371}
2372
Alex Loiko5825aa62017-12-18 16:02:40 +01002373TEST(ApmConfiguration, EnablePreProcessing) {
2374 // Verify that apm uses a capture post processing module if one is provided.
Alex Loiko5825aa62017-12-18 16:02:40 +01002375 auto mock_pre_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002376 new ::testing::NiceMock<test::MockCustomProcessing>();
Alex Loiko5825aa62017-12-18 16:02:40 +01002377 auto mock_pre_processor =
2378 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002379 rtc::scoped_refptr<AudioProcessing> apm =
2380 AudioProcessingBuilder()
2381 .SetRenderPreProcessing(std::move(mock_pre_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002382 .Create();
Alex Loiko5825aa62017-12-18 16:02:40 +01002383
2384 AudioFrame audio;
2385 audio.num_channels_ = 1;
2386 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2387
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002388 EXPECT_CALL(*mock_pre_processor_ptr, Process(::testing::_)).Times(1);
Alex Loiko5825aa62017-12-18 16:02:40 +01002389 apm->ProcessReverseStream(&audio);
2390}
2391
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002392TEST(ApmConfiguration, EnableCaptureAnalyzer) {
2393 // Verify that apm uses a capture analyzer if one is provided.
2394 auto mock_capture_analyzer_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002395 new ::testing::NiceMock<test::MockCustomAudioAnalyzer>();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002396 auto mock_capture_analyzer =
2397 std::unique_ptr<CustomAudioAnalyzer>(mock_capture_analyzer_ptr);
2398 rtc::scoped_refptr<AudioProcessing> apm =
2399 AudioProcessingBuilder()
2400 .SetCaptureAnalyzer(std::move(mock_capture_analyzer))
2401 .Create();
2402
2403 AudioFrame audio;
2404 audio.num_channels_ = 1;
2405 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2406
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002407 EXPECT_CALL(*mock_capture_analyzer_ptr, Analyze(::testing::_)).Times(1);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002408 apm->ProcessStream(&audio);
2409}
2410
Alex Loiko73ec0192018-05-15 10:52:28 +02002411TEST(ApmConfiguration, PreProcessingReceivesRuntimeSettings) {
2412 auto mock_pre_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002413 new ::testing::NiceMock<test::MockCustomProcessing>();
Alex Loiko73ec0192018-05-15 10:52:28 +02002414 auto mock_pre_processor =
2415 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
2416 rtc::scoped_refptr<AudioProcessing> apm =
2417 AudioProcessingBuilder()
2418 .SetRenderPreProcessing(std::move(mock_pre_processor))
2419 .Create();
2420 apm->SetRuntimeSetting(
2421 AudioProcessing::RuntimeSetting::CreateCustomRenderSetting(0));
2422
2423 // RuntimeSettings forwarded during 'Process*Stream' calls.
2424 // Therefore we have to make one such call.
2425 AudioFrame audio;
2426 audio.num_channels_ = 1;
2427 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2428
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002429 EXPECT_CALL(*mock_pre_processor_ptr, SetRuntimeSetting(::testing::_))
2430 .Times(1);
Alex Loiko73ec0192018-05-15 10:52:28 +02002431 apm->ProcessReverseStream(&audio);
2432}
2433
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002434class MyEchoControlFactory : public EchoControlFactory {
2435 public:
2436 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2437 auto ec = new test::MockEchoControl();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002438 EXPECT_CALL(*ec, AnalyzeRender(::testing::_)).Times(1);
2439 EXPECT_CALL(*ec, AnalyzeCapture(::testing::_)).Times(2);
2440 EXPECT_CALL(*ec, ProcessCapture(::testing::_, ::testing::_)).Times(2);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002441 return std::unique_ptr<EchoControl>(ec);
2442 }
Per Åhgrence202a02019-09-02 17:01:19 +02002443
2444 std::unique_ptr<EchoControl> Create(int sample_rate_hz,
2445 size_t num_render_channels,
2446 size_t num_capture_channels) {
2447 return Create(sample_rate_hz);
2448 }
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002449};
2450
2451TEST(ApmConfiguration, EchoControlInjection) {
2452 // Verify that apm uses an injected echo controller if one is provided.
2453 webrtc::Config webrtc_config;
2454 std::unique_ptr<EchoControlFactory> echo_control_factory(
2455 new MyEchoControlFactory());
2456
Alex Loiko5825aa62017-12-18 16:02:40 +01002457 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002458 AudioProcessingBuilder()
2459 .SetEchoControlFactory(std::move(echo_control_factory))
2460 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002461
2462 AudioFrame audio;
2463 audio.num_channels_ = 1;
2464 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2465 apm->ProcessStream(&audio);
2466 apm->ProcessReverseStream(&audio);
2467 apm->ProcessStream(&audio);
2468}
Ivo Creusenae026092017-11-20 13:07:16 +01002469
Per Åhgren8607f842019-04-12 22:02:26 +02002470std::unique_ptr<AudioProcessing> CreateApm(bool mobile_aec) {
Ivo Creusenae026092017-11-20 13:07:16 +01002471 Config old_config;
Ivo Creusen62337e52018-01-09 14:17:33 +01002472 std::unique_ptr<AudioProcessing> apm(
2473 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002474 if (!apm) {
2475 return apm;
2476 }
2477
2478 ProcessingConfig processing_config = {
2479 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2480
2481 if (apm->Initialize(processing_config) != 0) {
2482 return nullptr;
2483 }
2484
2485 // Disable all components except for an AEC and the residual echo detector.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002486 AudioProcessing::Config apm_config;
2487 apm_config.residual_echo_detector.enabled = true;
2488 apm_config.high_pass_filter.enabled = false;
Sam Zackrisson41478c72019-10-15 10:10:26 +02002489 apm_config.gain_controller1.enabled = false;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002490 apm_config.gain_controller2.enabled = false;
2491 apm_config.echo_canceller.enabled = true;
Per Åhgren8607f842019-04-12 22:02:26 +02002492 apm_config.echo_canceller.mobile_mode = mobile_aec;
saza0bad15f2019-10-16 11:46:11 +02002493 apm_config.noise_suppression.enabled = false;
2494 apm_config.level_estimation.enabled = false;
2495 apm_config.voice_detection.enabled = false;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002496 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002497 return apm;
2498}
2499
2500#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
2501#define MAYBE_ApmStatistics DISABLED_ApmStatistics
2502#else
2503#define MAYBE_ApmStatistics ApmStatistics
2504#endif
2505
Per Åhgren8607f842019-04-12 22:02:26 +02002506TEST(MAYBE_ApmStatistics, AECEnabledTest) {
2507 // Set up APM with AEC3 and process some audio.
2508 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
Ivo Creusenae026092017-11-20 13:07:16 +01002509 ASSERT_TRUE(apm);
Per Åhgren200feba2019-03-06 04:16:46 +01002510 AudioProcessing::Config apm_config;
2511 apm_config.echo_canceller.enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002512 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002513
2514 // Set up an audioframe.
2515 AudioFrame frame;
2516 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002517 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002518
2519 // Fill the audio frame with a sawtooth pattern.
2520 int16_t* ptr = frame.mutable_data();
2521 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2522 ptr[i] = 10000 * ((i % 3) - 1);
2523 }
2524
2525 // Do some processing.
2526 for (int i = 0; i < 200; i++) {
2527 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2528 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2529 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2530 }
2531
2532 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002533 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002534 // We expect all statistics to be set and have a sensible value.
2535 ASSERT_TRUE(stats.residual_echo_likelihood);
2536 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2537 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2538 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
2539 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2540 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2541 ASSERT_TRUE(stats.echo_return_loss);
2542 EXPECT_NE(*stats.echo_return_loss, -100.0);
2543 ASSERT_TRUE(stats.echo_return_loss_enhancement);
2544 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
Ivo Creusenae026092017-11-20 13:07:16 +01002545
2546 // If there are no receive streams, we expect the stats not to be set. The
2547 // 'false' argument signals to APM that no receive streams are currently
2548 // active. In that situation the statistics would get stuck at their last
2549 // calculated value (AEC and echo detection need at least one stream in each
2550 // direction), so to avoid that, they should not be set by APM.
2551 stats = apm->GetStatistics(false);
2552 EXPECT_FALSE(stats.residual_echo_likelihood);
2553 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2554 EXPECT_FALSE(stats.echo_return_loss);
2555 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002556}
2557
2558TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
2559 // Set up APM with AECM and process some audio.
Per Åhgren8607f842019-04-12 22:02:26 +02002560 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002561 ASSERT_TRUE(apm);
2562
2563 // Set up an audioframe.
2564 AudioFrame frame;
2565 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002566 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002567
2568 // Fill the audio frame with a sawtooth pattern.
2569 int16_t* ptr = frame.mutable_data();
2570 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2571 ptr[i] = 10000 * ((i % 3) - 1);
2572 }
2573
2574 // Do some processing.
2575 for (int i = 0; i < 200; i++) {
2576 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2577 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2578 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2579 }
2580
2581 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002582 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002583 // We expect only the residual echo detector statistics to be set and have a
2584 // sensible value.
2585 EXPECT_TRUE(stats.residual_echo_likelihood);
2586 if (stats.residual_echo_likelihood) {
2587 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2588 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2589 }
2590 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
2591 if (stats.residual_echo_likelihood_recent_max) {
2592 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2593 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2594 }
2595 EXPECT_FALSE(stats.echo_return_loss);
2596 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002597
2598 // If there are no receive streams, we expect the stats not to be set.
2599 stats = apm->GetStatistics(false);
2600 EXPECT_FALSE(stats.residual_echo_likelihood);
2601 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2602 EXPECT_FALSE(stats.echo_return_loss);
2603 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002604}
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002605
2606TEST(ApmStatistics, ReportOutputRmsDbfs) {
2607 ProcessingConfig processing_config = {
2608 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2609 AudioProcessing::Config config;
2610
2611 // Set up an audioframe.
2612 AudioFrame frame;
2613 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002614 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002615
2616 // Fill the audio frame with a sawtooth pattern.
2617 int16_t* ptr = frame.mutable_data();
2618 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2619 ptr[i] = 10000 * ((i % 3) - 1);
2620 }
2621
2622 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2623 apm->Initialize(processing_config);
2624
2625 // If not enabled, no metric should be reported.
2626 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2627 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2628
2629 // If enabled, metrics should be reported.
2630 config.level_estimation.enabled = true;
2631 apm->ApplyConfig(config);
2632 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2633 auto stats = apm->GetStatistics(false);
2634 EXPECT_TRUE(stats.output_rms_dbfs);
2635 EXPECT_GE(*stats.output_rms_dbfs, 0);
2636
2637 // If re-disabled, the value is again not reported.
2638 config.level_estimation.enabled = false;
2639 apm->ApplyConfig(config);
2640 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2641 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2642}
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002643
2644TEST(ApmStatistics, ReportHasVoice) {
2645 ProcessingConfig processing_config = {
2646 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2647 AudioProcessing::Config config;
2648
2649 // Set up an audioframe.
2650 AudioFrame frame;
2651 frame.num_channels_ = 1;
2652 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
2653
2654 // Fill the audio frame with a sawtooth pattern.
2655 int16_t* ptr = frame.mutable_data();
2656 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2657 ptr[i] = 10000 * ((i % 3) - 1);
2658 }
2659
2660 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2661 apm->Initialize(processing_config);
2662
2663 // If not enabled, no metric should be reported.
2664 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2665 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2666
2667 // If enabled, metrics should be reported.
2668 config.voice_detection.enabled = true;
2669 apm->ApplyConfig(config);
2670 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2671 auto stats = apm->GetStatistics(false);
2672 EXPECT_TRUE(stats.voice_detected);
2673
2674 // If re-disabled, the value is again not reported.
2675 config.voice_detection.enabled = false;
2676 apm->ApplyConfig(config);
2677 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2678 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2679}
Per Åhgren3e8bf282019-08-29 23:38:40 +02002680
2681TEST(ApmConfiguration, HandlingOfRateAndChannelCombinations) {
2682 std::array<int, 3> sample_rates_hz = {16000, 32000, 48000};
2683 std::array<int, 2> render_channel_counts = {1, 7};
2684 std::array<int, 2> capture_channel_counts = {1, 7};
2685 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2686 capture_channel_counts);
2687}
2688
2689TEST(ApmConfiguration, HandlingOfChannelCombinations) {
2690 std::array<int, 1> sample_rates_hz = {48000};
2691 std::array<int, 8> render_channel_counts = {1, 2, 3, 4, 5, 6, 7, 8};
2692 std::array<int, 8> capture_channel_counts = {1, 2, 3, 4, 5, 6, 7, 8};
2693 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2694 capture_channel_counts);
2695}
2696
2697TEST(ApmConfiguration, HandlingOfRateCombinations) {
2698 std::array<int, 9> sample_rates_hz = {8000, 11025, 16000, 22050, 32000,
2699 48000, 96000, 192000, 384000};
2700 std::array<int, 1> render_channel_counts = {2};
2701 std::array<int, 1> capture_channel_counts = {2};
2702 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2703 capture_channel_counts);
2704}
2705
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002706} // namespace webrtc