blob: caa7bab50acafb2e4b874bb573961b7c8380da59 [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>
bjornv@webrtc.org3e102492013-02-14 15:29:09 +000019#include <queue>
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000020
Sam Zackrisson6558fa52019-08-26 10:12:41 +020021#include "absl/flags/flag.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "common_audio/include/audio_util.h"
23#include "common_audio/resampler/include/push_resampler.h"
24#include "common_audio/resampler/push_sinc_resampler.h"
25#include "common_audio/signal_processing/include/signal_processing_library.h"
26#include "modules/audio_processing/aec_dump/aec_dump_factory.h"
27#include "modules/audio_processing/audio_processing_impl.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/common.h"
Sam Zackrisson0beac582017-09-25 12:04:02 +020029#include "modules/audio_processing/include/mock_audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "modules/audio_processing/test/protobuf_utils.h"
31#include "modules/audio_processing/test/test_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/arraysize.h"
33#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/fake_clock.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/gtest_prod_util.h"
36#include "rtc_base/ignore_wundef.h"
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +010037#include "rtc_base/numerics/safe_conversions.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010038#include "rtc_base/numerics/safe_minmax.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/protobuf_utils.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "rtc_base/ref_counted_object.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020041#include "rtc_base/strings/string_builder.h"
Alessio Bazzicac054e782018-04-16 12:10:09 +020042#include "rtc_base/swap_queue.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020043#include "rtc_base/system/arch.h"
Danil Chapovalov07122bc2019-03-26 14:37:01 +010044#include "rtc_base/task_queue_for_test.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/thread.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "test/gtest.h"
Steve Anton10542f22019-01-11 09:11:00 -080047#include "test/testsupport/file_utils.h"
kwiberg77eab702016-09-28 17:42:01 -070048
49RTC_PUSH_IGNORING_WUNDEF()
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000050#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000051#include "external/webrtc/webrtc/modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000052#else
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#include "modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000054#endif
kwiberg77eab702016-09-28 17:42:01 -070055RTC_POP_IGNORING_WUNDEF()
niklase@google.com470e71d2011-07-07 08:21:25 +000056
Sam Zackrisson6558fa52019-08-26 10:12:41 +020057ABSL_FLAG(bool,
58 write_apm_ref_data,
59 false,
60 "Write ApmTest.Process results to file, instead of comparing results "
61 "to the existing reference data file.");
62
andrew@webrtc.org27c69802014-02-18 20:24:56 +000063namespace webrtc {
niklase@google.com470e71d2011-07-07 08:21:25 +000064namespace {
andrew@webrtc.org17e40642014-03-04 20:58:13 +000065
ekmeyerson60d9b332015-08-14 10:35:55 -070066// TODO(ekmeyerson): Switch to using StreamConfig and ProcessingConfig where
67// applicable.
68
mbonadei7c2c8432017-04-07 00:59:12 -070069const int32_t kChannels[] = {1, 2};
Alejandro Luebs47748742015-05-22 12:00:21 -070070const int kSampleRates[] = {8000, 16000, 32000, 48000};
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +000071
aluebseb3603b2016-04-20 15:27:58 -070072#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
73// Android doesn't support 48kHz.
74const int kProcessSampleRates[] = {8000, 16000, 32000};
75#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Alejandro Luebs47748742015-05-22 12:00:21 -070076const int kProcessSampleRates[] = {8000, 16000, 32000, 48000};
aluebseb3603b2016-04-20 15:27:58 -070077#endif
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000078
ekmeyerson60d9b332015-08-14 10:35:55 -070079enum StreamDirection { kForward = 0, kReverse };
80
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000081void ConvertToFloat(const int16_t* int_data, ChannelBuffer<float>* cb) {
Jonas Olssona4d87372019-07-05 19:08:33 +020082 ChannelBuffer<int16_t> cb_int(cb->num_frames(), cb->num_channels());
83 Deinterleave(int_data, cb->num_frames(), cb->num_channels(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000084 cb_int.channels());
Peter Kasting69558702016-01-12 16:26:35 -080085 for (size_t i = 0; i < cb->num_channels(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +020086 S16ToFloat(cb_int.channels()[i], cb->num_frames(), cb->channels()[i]);
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000087 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000088}
andrew@webrtc.org17e40642014-03-04 20:58:13 +000089
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000090void ConvertToFloat(const AudioFrame& frame, ChannelBuffer<float>* cb) {
yujo36b1a5f2017-06-12 12:45:32 -070091 ConvertToFloat(frame.data(), cb);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000092}
93
andrew@webrtc.org103657b2014-04-24 18:28:56 +000094// Number of channels including the keyboard channel.
Peter Kasting69558702016-01-12 16:26:35 -080095size_t TotalChannelsFromLayout(AudioProcessing::ChannelLayout layout) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +000096 switch (layout) {
97 case AudioProcessing::kMono:
98 return 1;
99 case AudioProcessing::kMonoAndKeyboard:
100 case AudioProcessing::kStereo:
101 return 2;
102 case AudioProcessing::kStereoAndKeyboard:
103 return 3;
104 }
kwiberg9e2be5f2016-09-14 05:23:22 -0700105 RTC_NOTREACHED();
pkasting25702cb2016-01-08 13:50:27 -0800106 return 0;
andrew@webrtc.org103657b2014-04-24 18:28:56 +0000107}
108
Jonas Olssona4d87372019-07-05 19:08:33 +0200109void MixStereoToMono(const float* stereo,
110 float* mono,
pkasting25702cb2016-01-08 13:50:27 -0800111 size_t samples_per_channel) {
112 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000113 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) / 2;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000114}
115
Jonas Olssona4d87372019-07-05 19:08:33 +0200116void MixStereoToMono(const int16_t* stereo,
117 int16_t* mono,
pkasting25702cb2016-01-08 13:50:27 -0800118 size_t samples_per_channel) {
119 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000120 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) >> 1;
121}
122
pkasting25702cb2016-01-08 13:50:27 -0800123void CopyLeftToRightChannel(int16_t* stereo, size_t samples_per_channel) {
124 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000125 stereo[i * 2 + 1] = stereo[i * 2];
126 }
127}
128
yujo36b1a5f2017-06-12 12:45:32 -0700129void VerifyChannelsAreEqual(const int16_t* stereo, size_t samples_per_channel) {
pkasting25702cb2016-01-08 13:50:27 -0800130 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000131 EXPECT_EQ(stereo[i * 2 + 1], stereo[i * 2]);
132 }
133}
134
135void SetFrameTo(AudioFrame* frame, int16_t value) {
yujo36b1a5f2017-06-12 12:45:32 -0700136 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700137 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
138 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700139 frame_data[i] = value;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000140 }
141}
142
143void SetFrameTo(AudioFrame* frame, int16_t left, int16_t right) {
Peter Kasting69558702016-01-12 16:26:35 -0800144 ASSERT_EQ(2u, frame->num_channels_);
yujo36b1a5f2017-06-12 12:45:32 -0700145 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700146 for (size_t i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
yujo36b1a5f2017-06-12 12:45:32 -0700147 frame_data[i] = left;
148 frame_data[i + 1] = right;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000149 }
150}
151
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000152void ScaleFrame(AudioFrame* frame, float scale) {
yujo36b1a5f2017-06-12 12:45:32 -0700153 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700154 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
155 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700156 frame_data[i] = FloatS16ToS16(frame_data[i] * scale);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000157 }
158}
159
andrew@webrtc.org81865342012-10-27 00:28:27 +0000160bool FrameDataAreEqual(const AudioFrame& frame1, const AudioFrame& frame2) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000161 if (frame1.samples_per_channel_ != frame2.samples_per_channel_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000162 return false;
163 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000164 if (frame1.num_channels_ != frame2.num_channels_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000165 return false;
166 }
yujo36b1a5f2017-06-12 12:45:32 -0700167 if (memcmp(frame1.data(), frame2.data(),
andrew@webrtc.org81865342012-10-27 00:28:27 +0000168 frame1.samples_per_channel_ * frame1.num_channels_ *
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000169 sizeof(int16_t))) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000170 return false;
171 }
172 return true;
173}
174
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000175void EnableAllAPComponents(AudioProcessing* ap) {
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200176 AudioProcessing::Config apm_config = ap->GetConfig();
177 apm_config.echo_canceller.enabled = true;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000178#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200179 apm_config.echo_canceller.mobile_mode = true;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100180
181 apm_config.gain_controller1.enabled = true;
182 apm_config.gain_controller1.mode =
183 AudioProcessing::Config::GainController1::kAdaptiveDigital;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000184#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200185 apm_config.echo_canceller.mobile_mode = false;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000186
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100187 apm_config.gain_controller1.enabled = true;
188 apm_config.gain_controller1.mode =
189 AudioProcessing::Config::GainController1::kAdaptiveAnalog;
190 apm_config.gain_controller1.analog_level_minimum = 0;
191 apm_config.gain_controller1.analog_level_maximum = 255;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000192#endif
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000193
peah8271d042016-11-22 07:24:52 -0800194 apm_config.high_pass_filter.enabled = true;
Sam Zackrisson11b87032018-12-18 17:13:58 +0100195 apm_config.level_estimation.enabled = true;
Sam Zackrisson0824c6f2019-10-07 14:03:56 +0200196 apm_config.voice_detection.enabled = true;
peah8271d042016-11-22 07:24:52 -0800197 ap->ApplyConfig(apm_config);
198
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000199 EXPECT_NOERR(ap->noise_suppression()->Enable(true));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000200}
201
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000202// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000203template <class T>
204T AbsValue(T a) {
Jonas Olssona4d87372019-07-05 19:08:33 +0200205 return a > 0 ? a : -a;
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000206}
207
208int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800209 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700210 const int16_t* frame_data = frame.data();
211 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800212 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700213 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000214 }
215
216 return max_data;
217}
218
Alex Loiko890988c2017-08-31 10:25:48 +0200219void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700220 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000221 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000222 ASSERT_TRUE(file != NULL);
223
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100224 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000225 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800226 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000227 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000228
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000229 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000230 ASSERT_EQ(static_cast<size_t>(size),
Jonas Olssona4d87372019-07-05 19:08:33 +0200231 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000232 fclose(file);
233}
234
Alex Loiko890988c2017-08-31 10:25:48 +0200235std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200236 rtc::StringBuilder ss;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000237 // Resource files are all stereo.
238 ss << name << sample_rate_hz / 1000 << "_stereo";
239 return test::ResourcePath(ss.str(), "pcm");
240}
241
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000242// Temporary filenames unique to this process. Used to be able to run these
243// tests in parallel as each process needs to be running in isolation they can't
244// have competing filenames.
245std::map<std::string, std::string> temp_filenames;
246
Alex Loiko890988c2017-08-31 10:25:48 +0200247std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000248 int input_rate,
249 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700250 int reverse_input_rate,
251 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800252 size_t num_input_channels,
253 size_t num_output_channels,
254 size_t num_reverse_input_channels,
255 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700256 StreamDirection file_direction) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200257 rtc::StringBuilder ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700258 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
259 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000260 if (num_output_channels == 1) {
261 ss << "mono";
262 } else if (num_output_channels == 2) {
263 ss << "stereo";
264 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700265 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000266 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700267 ss << output_rate / 1000;
268 if (num_reverse_output_channels == 1) {
269 ss << "_rmono";
270 } else if (num_reverse_output_channels == 2) {
271 ss << "_rstereo";
272 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700273 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700274 }
275 ss << reverse_output_rate / 1000;
276 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000277
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000278 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700279 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000280 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
281 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000282}
283
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000284void ClearTempFiles() {
285 for (auto& kv : temp_filenames)
286 remove(kv.second.c_str());
287}
288
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200289// Only remove "out" files. Keep "ref" files.
290void ClearTempOutFiles() {
291 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
292 const std::string& filename = it->first;
293 if (filename.substr(0, 3).compare("out") == 0) {
294 remove(it->second.c_str());
295 temp_filenames.erase(it++);
296 } else {
297 it++;
298 }
299 }
300}
301
Alex Loiko890988c2017-08-31 10:25:48 +0200302void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000303 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000304 ASSERT_TRUE(file != NULL);
305 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000306 fclose(file);
307}
308
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000309// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
310// stereo) file, converts to deinterleaved float (optionally downmixing) and
311// returns the result in |cb|. Returns false if the file ended (or on error) and
312// true otherwise.
313//
314// |int_data| and |float_data| are just temporary space that must be
315// sufficiently large to hold the 10 ms chunk.
Jonas Olssona4d87372019-07-05 19:08:33 +0200316bool ReadChunk(FILE* file,
317 int16_t* int_data,
318 float* float_data,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000319 ChannelBuffer<float>* cb) {
320 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000321 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000322 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
323 if (read_count != frame_size) {
324 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700325 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000326 return false; // This is expected.
327 }
328
329 S16ToFloat(int_data, frame_size, float_data);
330 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000331 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000332 } else {
Jonas Olssona4d87372019-07-05 19:08:33 +0200333 Deinterleave(float_data, cb->num_frames(), 2, cb->channels());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000334 }
335
336 return true;
337}
338
niklase@google.com470e71d2011-07-07 08:21:25 +0000339class ApmTest : public ::testing::Test {
340 protected:
341 ApmTest();
342 virtual void SetUp();
343 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000344
Mirko Bonadei71061bc2019-06-04 09:01:51 +0200345 static void SetUpTestSuite() {}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000346
Mirko Bonadei71061bc2019-06-04 09:01:51 +0200347 static void TearDownTestSuite() { ClearTempFiles(); }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000348
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000349 // Used to select between int and float interface tests.
Jonas Olssona4d87372019-07-05 19:08:33 +0200350 enum Format { kIntFormat, kFloatFormat };
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000351
352 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000353 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000354 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800355 size_t num_input_channels,
356 size_t num_output_channels,
357 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000358 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000359 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000360 void EnableAllComponents();
361 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000362 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000363 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
Jonas Olssona4d87372019-07-05 19:08:33 +0200364 void ReadFrameWithRewind(FILE* file,
365 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000366 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000367 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
Jonas Olssona4d87372019-07-05 19:08:33 +0200368 void ProcessDelayVerificationTest(int delay_ms,
369 int system_delay_ms,
370 int delay_min,
371 int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700372 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800373 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700374 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800375 void TestChangingForwardChannels(size_t num_in_channels,
376 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700377 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800378 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700379 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000380 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
381 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000382 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000383 int ProcessStreamChooser(Format format);
384 int AnalyzeReverseStreamChooser(Format format);
385 void ProcessDebugDump(const std::string& in_filename,
386 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800387 Format format,
388 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000389 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000390
391 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000392 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800393 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000394 AudioFrame* frame_;
395 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800396 std::unique_ptr<ChannelBuffer<float> > float_cb_;
397 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000398 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800399 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000400 FILE* far_file_;
401 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000402 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000403};
404
405ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000406 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000407#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +0200408 ref_filename_(
409 test::ResourcePath("audio_processing/output_data_fixed", "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000410#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +0200411 ref_filename_(
412 test::ResourcePath("audio_processing/output_data_float", "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000413#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000414 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000415 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000416 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000417 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000418 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000419 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000420 out_file_(NULL) {
421 Config config;
422 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100423 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000424}
niklase@google.com470e71d2011-07-07 08:21:25 +0000425
426void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000427 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000428
429 frame_ = new AudioFrame();
430 revframe_ = new AudioFrame();
431
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000432 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000433}
434
435void ApmTest::TearDown() {
436 if (frame_) {
437 delete frame_;
438 }
439 frame_ = NULL;
440
441 if (revframe_) {
442 delete revframe_;
443 }
444 revframe_ = NULL;
445
446 if (far_file_) {
447 ASSERT_EQ(0, fclose(far_file_));
448 }
449 far_file_ = NULL;
450
451 if (near_file_) {
452 ASSERT_EQ(0, fclose(near_file_));
453 }
454 near_file_ = NULL;
455
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000456 if (out_file_) {
457 ASSERT_EQ(0, fclose(out_file_));
458 }
459 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000460}
461
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000462void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000463 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700464 ap->Initialize(
465 {{{frame_->sample_rate_hz_, frame_->num_channels_},
466 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700467 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700468 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000469}
470
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000471void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000472 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000473 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800474 size_t num_input_channels,
475 size_t num_output_channels,
476 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000477 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000478 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000479 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000480 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000481
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000482 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
483 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000484 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000485
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000486 if (far_file_) {
487 ASSERT_EQ(0, fclose(far_file_));
488 }
489 std::string filename = ResourceFilePath("far", sample_rate_hz);
490 far_file_ = fopen(filename.c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200491 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000492
493 if (near_file_) {
494 ASSERT_EQ(0, fclose(near_file_));
495 }
496 filename = ResourceFilePath("near", sample_rate_hz);
497 near_file_ = fopen(filename.c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200498 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000499
500 if (open_output_file) {
501 if (out_file_) {
502 ASSERT_EQ(0, fclose(out_file_));
503 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700504 filename = OutputFilePath(
505 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
506 reverse_sample_rate_hz, num_input_channels, num_output_channels,
507 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000508 out_file_ = fopen(filename.c_str(), "wb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200509 ASSERT_TRUE(out_file_ != NULL)
510 << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000511 }
512}
513
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000514void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000515 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000516}
517
Jonas Olssona4d87372019-07-05 19:08:33 +0200518bool ApmTest::ReadFrame(FILE* file,
519 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000520 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000521 // The files always contain stereo audio.
522 size_t frame_size = frame->samples_per_channel_ * 2;
Jonas Olssona4d87372019-07-05 19:08:33 +0200523 size_t read_count =
524 fread(frame->mutable_data(), sizeof(int16_t), frame_size, file);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000525 if (read_count != frame_size) {
526 // Check that the file really ended.
527 EXPECT_NE(0, feof(file));
528 return false; // This is expected.
529 }
530
531 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700532 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000533 frame->samples_per_channel_);
534 }
535
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000536 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000537 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000538 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000539 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000540}
541
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000542bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
543 return ReadFrame(file, frame, NULL);
544}
545
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000546// If the end of the file has been reached, rewind it and attempt to read the
547// frame again.
Jonas Olssona4d87372019-07-05 19:08:33 +0200548void ApmTest::ReadFrameWithRewind(FILE* file,
549 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000550 ChannelBuffer<float>* cb) {
551 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000552 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000553 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000554 }
555}
556
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000557void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
558 ReadFrameWithRewind(file, frame, NULL);
559}
560
andrew@webrtc.org81865342012-10-27 00:28:27 +0000561void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
562 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
Jonas Olssona4d87372019-07-05 19:08:33 +0200563 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000564 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000565}
566
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000567int ApmTest::ProcessStreamChooser(Format format) {
568 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000569 return apm_->ProcessStream(frame_);
570 }
Jonas Olssona4d87372019-07-05 19:08:33 +0200571 return apm_->ProcessStream(
572 float_cb_->channels(), frame_->samples_per_channel_,
573 frame_->sample_rate_hz_, LayoutFromChannels(frame_->num_channels_),
574 output_sample_rate_hz_, LayoutFromChannels(num_output_channels_),
575 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000576}
577
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000578int ApmTest::AnalyzeReverseStreamChooser(Format format) {
579 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700580 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000581 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000582 return apm_->AnalyzeReverseStream(
Jonas Olssona4d87372019-07-05 19:08:33 +0200583 revfloat_cb_->channels(), revframe_->samples_per_channel_,
584 revframe_->sample_rate_hz_, LayoutFromChannels(revframe_->num_channels_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000585}
586
Jonas Olssona4d87372019-07-05 19:08:33 +0200587void ApmTest::ProcessDelayVerificationTest(int delay_ms,
588 int system_delay_ms,
589 int delay_min,
590 int delay_max) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000591 // The |revframe_| and |frame_| should include the proper frame information,
592 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000593 AudioFrame tmp_frame;
594 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000595 bool causal = true;
596
597 tmp_frame.CopyFrom(*revframe_);
598 SetFrameTo(&tmp_frame, 0);
599
600 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
601 // Initialize the |frame_queue| with empty frames.
602 int frame_delay = delay_ms / 10;
603 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000604 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000605 frame->CopyFrom(tmp_frame);
606 frame_queue.push(frame);
607 frame_delay++;
608 causal = false;
609 }
610 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000611 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000612 frame->CopyFrom(tmp_frame);
613 frame_queue.push(frame);
614 frame_delay--;
615 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000616 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
617 // need enough frames with audio to have reliable estimates, but as few as
618 // possible to keep processing time down. 4.5 seconds seemed to be a good
619 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000620 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000621 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000622 frame->CopyFrom(tmp_frame);
623 // Use the near end recording, since that has more speech in it.
624 ASSERT_TRUE(ReadFrame(near_file_, frame));
625 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000626 AudioFrame* reverse_frame = frame;
627 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000628 if (!causal) {
629 reverse_frame = frame_queue.front();
630 // When we call ProcessStream() the frame is modified, so we can't use the
631 // pointer directly when things are non-causal. Use an intermediate frame
632 // and copy the data.
633 process_frame = &tmp_frame;
634 process_frame->CopyFrom(*frame);
635 }
aluebsb0319552016-03-17 20:39:53 -0700636 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000637 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
638 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
639 frame = frame_queue.front();
640 frame_queue.pop();
641 delete frame;
642
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000643 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000644 // Discard the first delay metrics to avoid convergence effects.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200645 static_cast<void>(apm_->GetStatistics(true /* has_remote_tracks */));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000646 }
647 }
648
649 rewind(near_file_);
650 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000651 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000652 frame_queue.pop();
653 delete frame;
654 }
655 // Calculate expected delay estimate and acceptable regions. Further,
656 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700657 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700658 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700659 const int expected_median =
660 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
661 const int expected_median_high = rtc::SafeClamp<int>(
662 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700663 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700664 const int expected_median_low = rtc::SafeClamp<int>(
665 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700666 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000667 // Verify delay metrics.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200668 AudioProcessingStats stats =
669 apm_->GetStatistics(true /* has_remote_tracks */);
670 ASSERT_TRUE(stats.delay_median_ms.has_value());
671 int32_t median = *stats.delay_median_ms;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000672 EXPECT_GE(expected_median_high, median);
673 EXPECT_LE(expected_median_low, median);
674}
675
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000676void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000677 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000678 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000679
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000680 // -- Missing AGC level --
niklase@google.com470e71d2011-07-07 08:21:25 +0000681 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
Jonas Olssona4d87372019-07-05 19:08:33 +0200682 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000683
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000684 // Resets after successful ProcessStream().
Jonas Olssona4d87372019-07-05 19:08:33 +0200685 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000686 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Jonas Olssona4d87372019-07-05 19:08:33 +0200687 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000688
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000689 // Other stream parameters set correctly.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200690 AudioProcessing::Config apm_config = apm_->GetConfig();
691 apm_config.echo_canceller.enabled = true;
692 apm_config.echo_canceller.mobile_mode = false;
693 apm_->ApplyConfig(apm_config);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000694 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
Jonas Olssona4d87372019-07-05 19:08:33 +0200695 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000696 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000697
698 // -- Missing delay --
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000699 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100700 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000701
702 // Resets after successful ProcessStream().
703 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000704 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100705 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000706
707 // Other stream parameters set correctly.
708 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
Jonas Olssona4d87372019-07-05 19:08:33 +0200709 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
Per Åhgren200feba2019-03-06 04:16:46 +0100710 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000711 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
712
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000713 // -- No stream parameters --
Jonas Olssona4d87372019-07-05 19:08:33 +0200714 EXPECT_EQ(apm_->kNoError, AnalyzeReverseStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100715 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000716
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000717 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000718 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
Jonas Olssona4d87372019-07-05 19:08:33 +0200719 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000720 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000721}
722
723TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000724 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000725}
726
727TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000728 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000729}
730
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000731TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
732 EXPECT_EQ(0, apm_->delay_offset_ms());
733 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
734 EXPECT_EQ(50, apm_->stream_delay_ms());
735}
736
737TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
738 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000739 apm_->set_delay_offset_ms(100);
740 EXPECT_EQ(100, apm_->delay_offset_ms());
741 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000742 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000743 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
744 EXPECT_EQ(200, apm_->stream_delay_ms());
745
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000746 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000747 apm_->set_delay_offset_ms(-50);
748 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000749 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
750 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000751 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
752 EXPECT_EQ(50, apm_->stream_delay_ms());
753}
754
Michael Graczyk86c6d332015-07-23 11:41:39 -0700755void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800756 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700757 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000758 frame_->num_channels_ = num_channels;
759 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700760 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000761}
762
Michael Graczyk86c6d332015-07-23 11:41:39 -0700763void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800764 size_t num_in_channels,
765 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700766 AudioProcessing::Error expected_return) {
767 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
768 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
769
770 EXPECT_EQ(expected_return,
771 apm_->ProcessStream(float_cb_->channels(), input_stream,
772 output_stream, float_cb_->channels()));
773}
774
775void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800776 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700777 AudioProcessing::Error expected_return) {
778 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700779 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
780 {output_sample_rate_hz_, apm_->num_output_channels()},
781 {frame_->sample_rate_hz_, num_rev_channels},
782 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700783
ekmeyerson60d9b332015-08-14 10:35:55 -0700784 EXPECT_EQ(
785 expected_return,
786 apm_->ProcessReverseStream(
787 float_cb_->channels(), processing_config.reverse_input_stream(),
788 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700789}
790
791TEST_F(ApmTest, ChannelsInt16Interface) {
792 // Testing number of invalid and valid channels.
793 Init(16000, 16000, 16000, 4, 4, 4, false);
794
795 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
796
Peter Kasting69558702016-01-12 16:26:35 -0800797 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700798 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000799 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000800 }
801}
802
Michael Graczyk86c6d332015-07-23 11:41:39 -0700803TEST_F(ApmTest, Channels) {
804 // Testing number of invalid and valid channels.
805 Init(16000, 16000, 16000, 4, 4, 4, false);
806
807 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
808 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
809
Peter Kasting69558702016-01-12 16:26:35 -0800810 for (size_t i = 1; i < 4; ++i) {
811 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700812 // Output channels much be one or match input channels.
813 if (j == 1 || i == j) {
814 TestChangingForwardChannels(i, j, kNoErr);
815 TestChangingReverseChannels(i, kNoErr);
816
817 EXPECT_EQ(i, apm_->num_input_channels());
818 EXPECT_EQ(j, apm_->num_output_channels());
819 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800820 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700821 } else {
822 TestChangingForwardChannels(i, j,
823 AudioProcessing::kBadNumberChannelsError);
824 }
825 }
826 }
827}
828
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000829TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000830 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000831 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000832 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000833 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700834 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800835 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000836 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000837 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000838 }
839}
840
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000841TEST_F(ApmTest, GainControl) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000842 // Testing gain modes
niklase@google.com470e71d2011-07-07 08:21:25 +0000843 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200844 apm_->gain_control()->set_mode(apm_->gain_control()->mode()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000845
Jonas Olssona4d87372019-07-05 19:08:33 +0200846 GainControl::Mode mode[] = {GainControl::kAdaptiveAnalog,
847 GainControl::kAdaptiveDigital,
848 GainControl::kFixedDigital};
pkasting25702cb2016-01-08 13:50:27 -0800849 for (size_t i = 0; i < arraysize(mode); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +0200850 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_mode(mode[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +0000851 EXPECT_EQ(mode[i], apm_->gain_control()->mode());
852 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100853 // Testing target levels
Jonas Olssona4d87372019-07-05 19:08:33 +0200854 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_target_level_dbfs(
855 apm_->gain_control()->target_level_dbfs()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000856
857 int level_dbfs[] = {0, 6, 31};
pkasting25702cb2016-01-08 13:50:27 -0800858 for (size_t i = 0; i < arraysize(level_dbfs); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000859 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200860 apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +0000861 EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
862 }
863
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100864 // Testing compression gains
Jonas Olssona4d87372019-07-05 19:08:33 +0200865 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_compression_gain_db(
866 apm_->gain_control()->compression_gain_db()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000867
868 int gain_db[] = {0, 10, 90};
pkasting25702cb2016-01-08 13:50:27 -0800869 for (size_t i = 0; i < arraysize(gain_db); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000870 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200871 apm_->gain_control()->set_compression_gain_db(gain_db[i]));
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100872 ProcessStreamChooser(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000873 EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
874 }
875
876 // Testing limiter off/on
877 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
878 EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
879 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
880 EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
881
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100882 // Testing level limits
Jonas Olssona4d87372019-07-05 19:08:33 +0200883 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_analog_level_limits(
884 apm_->gain_control()->analog_level_minimum(),
885 apm_->gain_control()->analog_level_maximum()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000886
887 int min_level[] = {0, 255, 1024};
pkasting25702cb2016-01-08 13:50:27 -0800888 for (size_t i = 0; i < arraysize(min_level); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +0200889 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_analog_level_limits(
890 min_level[i], 1024));
niklase@google.com470e71d2011-07-07 08:21:25 +0000891 EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
892 }
893
894 int max_level[] = {0, 1024, 65535};
pkasting25702cb2016-01-08 13:50:27 -0800895 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000896 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200897 apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +0000898 EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
899 }
900
901 // TODO(ajm): stream_is_saturated() and stream_analog_level()
902
903 // Turn AGC off
904 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
905 EXPECT_FALSE(apm_->gain_control()->is_enabled());
906}
907
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100908#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
909TEST_F(ApmTest, GainControlDiesOnTooLowTargetLevelDbfs) {
910 EXPECT_DEATH(apm_->gain_control()->set_target_level_dbfs(-1), "");
911}
912
913TEST_F(ApmTest, GainControlDiesOnTooHighTargetLevelDbfs) {
914 EXPECT_DEATH(apm_->gain_control()->set_target_level_dbfs(32), "");
915}
916
917TEST_F(ApmTest, GainControlDiesOnTooLowCompressionGainDb) {
918 EXPECT_DEATH(apm_->gain_control()->set_compression_gain_db(-1), "");
919}
920
921TEST_F(ApmTest, GainControlDiesOnTooHighCompressionGainDb) {
922 EXPECT_DEATH(apm_->gain_control()->set_compression_gain_db(91), "");
923}
924
925TEST_F(ApmTest, GainControlDiesOnTooLowAnalogLevelLowerLimit) {
926 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(-1, 512), "");
927}
928
929TEST_F(ApmTest, GainControlDiesOnTooHighAnalogLevelUpperLimit) {
930 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(512, 65536), "");
931}
932
933TEST_F(ApmTest, GainControlDiesOnInvertedAnalogLevelLimits) {
934 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(512, 255), "");
935}
936
937TEST_F(ApmTest, ApmDiesOnTooLowAnalogLevel) {
938 apm_->gain_control()->set_analog_level_limits(255, 512);
939 EXPECT_DEATH(apm_->set_stream_analog_level(254), "");
940}
941
942TEST_F(ApmTest, ApmDiesOnTooHighAnalogLevel) {
943 apm_->gain_control()->set_analog_level_limits(255, 512);
944 EXPECT_DEATH(apm_->set_stream_analog_level(513), "");
945}
946#endif
947
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000948void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000949 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000950 EXPECT_EQ(apm_->kNoError,
951 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
952 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
953
954 int out_analog_level = 0;
955 for (int i = 0; i < 2000; ++i) {
956 ReadFrameWithRewind(near_file_, frame_);
957 // Ensure the audio is at a low level, so the AGC will try to increase it.
958 ScaleFrame(frame_, 0.25);
959
960 // Always pass in the same volume.
961 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200962 apm_->gain_control()->set_stream_analog_level(100));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000963 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
964 out_analog_level = apm_->gain_control()->stream_analog_level();
965 }
966
967 // Ensure the AGC is still able to reach the maximum.
968 EXPECT_EQ(255, out_analog_level);
969}
970
971// Verifies that despite volume slider quantization, the AGC can continue to
972// increase its volume.
973TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -0800974 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000975 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
976 }
977}
978
979void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000980 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000981 EXPECT_EQ(apm_->kNoError,
982 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
983 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
984
985 int out_analog_level = 100;
986 for (int i = 0; i < 1000; ++i) {
987 ReadFrameWithRewind(near_file_, frame_);
988 // Ensure the audio is at a low level, so the AGC will try to increase it.
989 ScaleFrame(frame_, 0.25);
990
991 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200992 apm_->gain_control()->set_stream_analog_level(out_analog_level));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000993 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
994 out_analog_level = apm_->gain_control()->stream_analog_level();
995 }
996
997 // Ensure the volume was raised.
998 EXPECT_GT(out_analog_level, 100);
999 int highest_level_reached = out_analog_level;
1000 // Simulate a user manual volume change.
1001 out_analog_level = 100;
1002
1003 for (int i = 0; i < 300; ++i) {
1004 ReadFrameWithRewind(near_file_, frame_);
1005 ScaleFrame(frame_, 0.25);
1006
1007 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +02001008 apm_->gain_control()->set_stream_analog_level(out_analog_level));
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001009 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1010 out_analog_level = apm_->gain_control()->stream_analog_level();
1011 // Check that AGC respected the manually adjusted volume.
1012 EXPECT_LT(out_analog_level, highest_level_reached);
1013 }
1014 // Check that the volume was still raised.
1015 EXPECT_GT(out_analog_level, 100);
1016}
1017
1018TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001019 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001020 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1021 }
1022}
1023
niklase@google.com470e71d2011-07-07 08:21:25 +00001024TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001025 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001026 NoiseSuppression::Level level[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001027 NoiseSuppression::kLow, NoiseSuppression::kModerate,
1028 NoiseSuppression::kHigh, NoiseSuppression::kVeryHigh};
pkasting25702cb2016-01-08 13:50:27 -08001029 for (size_t i = 0; i < arraysize(level); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001030 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->set_level(level[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +00001031 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1032 }
1033
andrew@webrtc.org648af742012-02-08 01:57:29 +00001034 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001035 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1036 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1037 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1038 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1039}
1040
1041TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001042 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001043 AudioProcessing::Config apm_config;
1044 apm_config.high_pass_filter.enabled = true;
1045 apm_->ApplyConfig(apm_config);
1046 apm_config.high_pass_filter.enabled = false;
1047 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001048}
1049
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001050TEST_F(ApmTest, AllProcessingDisabledByDefault) {
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001051 AudioProcessing::Config config = apm_->GetConfig();
1052 EXPECT_FALSE(config.echo_canceller.enabled);
1053 EXPECT_FALSE(config.high_pass_filter.enabled);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001054 EXPECT_FALSE(config.level_estimation.enabled);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001055 EXPECT_FALSE(config.voice_detection.enabled);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001056 EXPECT_FALSE(apm_->gain_control()->is_enabled());
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001057 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001058}
1059
1060TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001061 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001062 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001063 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001064 AudioFrame frame_copy;
1065 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001066 for (int j = 0; j < 1000; j++) {
1067 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1068 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001069 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1070 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001071 }
1072 }
1073}
1074
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001075TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1076 // Test that ProcessStream copies input to output even with no processing.
Per Åhgrenc8626b62019-08-23 15:49:51 +02001077 const size_t kSamples = 160;
1078 const int sample_rate = 16000;
Jonas Olssona4d87372019-07-05 19:08:33 +02001079 const float src[kSamples] = {-1.0f, 0.0f, 1.0f};
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001080 float dest[kSamples] = {};
1081
1082 auto src_channels = &src[0];
1083 auto dest_channels = &dest[0];
1084
Ivo Creusen62337e52018-01-09 14:17:33 +01001085 apm_.reset(AudioProcessingBuilder().Create());
Jonas Olssona4d87372019-07-05 19:08:33 +02001086 EXPECT_NOERR(apm_->ProcessStream(&src_channels, kSamples, sample_rate,
1087 LayoutFromChannels(1), sample_rate,
1088 LayoutFromChannels(1), &dest_channels));
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001089
1090 for (size_t i = 0; i < kSamples; ++i) {
1091 EXPECT_EQ(src[i], dest[i]);
1092 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001093
1094 // Same for ProcessReverseStream.
1095 float rev_dest[kSamples] = {};
1096 auto rev_dest_channels = &rev_dest[0];
1097
1098 StreamConfig input_stream = {sample_rate, 1};
1099 StreamConfig output_stream = {sample_rate, 1};
1100 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1101 output_stream, &rev_dest_channels));
1102
1103 for (size_t i = 0; i < kSamples; ++i) {
1104 EXPECT_EQ(src[i], rev_dest[i]);
1105 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001106}
1107
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001108TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1109 EnableAllComponents();
1110
pkasting25702cb2016-01-08 13:50:27 -08001111 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001112 Init(kProcessSampleRates[i], kProcessSampleRates[i], kProcessSampleRates[i],
1113 2, 2, 2, false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001114 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001115 ASSERT_EQ(0, feof(far_file_));
1116 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001117 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001118 CopyLeftToRightChannel(revframe_->mutable_data(),
1119 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001120
aluebsb0319552016-03-17 20:39:53 -07001121 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001122
yujo36b1a5f2017-06-12 12:45:32 -07001123 CopyLeftToRightChannel(frame_->mutable_data(),
1124 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001125 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1126
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001127 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001128 ASSERT_EQ(kNoErr,
Jonas Olssona4d87372019-07-05 19:08:33 +02001129 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001130 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001131 analog_level = apm_->gain_control()->stream_analog_level();
1132
yujo36b1a5f2017-06-12 12:45:32 -07001133 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001134 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001135 rewind(far_file_);
1136 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001137 }
1138}
1139
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001140TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001141 // Verify the filter is not active through undistorted audio when:
1142 // 1. No components are enabled...
1143 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001144 AudioFrame frame_copy;
1145 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001146 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1147 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1148 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1149
1150 // 2. Only the level estimator is enabled...
saza6787f232019-10-11 19:31:07 +02001151 auto apm_config = apm_->GetConfig();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001152 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001153 frame_copy.CopyFrom(*frame_);
saza6787f232019-10-11 19:31:07 +02001154 apm_config.level_estimation.enabled = true;
1155 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001156 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1157 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1158 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
saza6787f232019-10-11 19:31:07 +02001159 apm_config.level_estimation.enabled = false;
1160 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001161
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001162 // 3. Only GetStatistics-reporting VAD is enabled...
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001163 SetFrameTo(frame_, 1000);
1164 frame_copy.CopyFrom(*frame_);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001165 apm_config.voice_detection.enabled = true;
1166 apm_->ApplyConfig(apm_config);
1167 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1168 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1169 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1170 apm_config.voice_detection.enabled = false;
1171 apm_->ApplyConfig(apm_config);
1172
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001173 // 4. Both the VAD and the level estimator are enabled...
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001174 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001175 frame_copy.CopyFrom(*frame_);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001176 apm_config.voice_detection.enabled = true;
saza6787f232019-10-11 19:31:07 +02001177 apm_config.level_estimation.enabled = true;
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001178 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001179 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1180 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1181 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001182 apm_config.voice_detection.enabled = false;
saza6787f232019-10-11 19:31:07 +02001183 apm_config.level_estimation.enabled = false;
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001184 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001185
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001186 // Check the test is valid. We should have distortion from the filter
1187 // when AEC is enabled (which won't affect the audio).
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001188 apm_config.echo_canceller.enabled = true;
1189 apm_config.echo_canceller.mobile_mode = false;
1190 apm_->ApplyConfig(apm_config);
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001191 frame_->samples_per_channel_ = 320;
1192 frame_->num_channels_ = 2;
1193 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001194 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001195 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001196 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001197 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1198 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1199}
1200
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001201#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1202void ApmTest::ProcessDebugDump(const std::string& in_filename,
1203 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001204 Format format,
1205 int max_size_bytes) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001206 TaskQueueForTest worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001207 FILE* in_file = fopen(in_filename.c_str(), "rb");
1208 ASSERT_TRUE(in_file != NULL);
1209 audioproc::Event event_msg;
1210 bool first_init = true;
1211
1212 while (ReadMessageFromFile(in_file, &event_msg)) {
1213 if (event_msg.type() == audioproc::Event::INIT) {
1214 const audioproc::Init msg = event_msg.init();
1215 int reverse_sample_rate = msg.sample_rate();
1216 if (msg.has_reverse_sample_rate()) {
1217 reverse_sample_rate = msg.reverse_sample_rate();
1218 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001219 int output_sample_rate = msg.sample_rate();
1220 if (msg.has_output_sample_rate()) {
1221 output_sample_rate = msg.output_sample_rate();
1222 }
1223
Jonas Olssona4d87372019-07-05 19:08:33 +02001224 Init(msg.sample_rate(), output_sample_rate, reverse_sample_rate,
1225 msg.num_input_channels(), msg.num_output_channels(),
1226 msg.num_reverse_channels(), false);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001227 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001228 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001229 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001230 auto aec_dump =
1231 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1232 EXPECT_TRUE(aec_dump);
1233 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001234 first_init = false;
1235 }
1236
1237 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1238 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1239
1240 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001241 ASSERT_EQ(revframe_->num_channels_,
1242 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001243 for (int i = 0; i < msg.channel_size(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001244 memcpy(revfloat_cb_->channels()[i], msg.channel(i).data(),
1245 msg.channel(i).size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001246 }
1247 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001248 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001249 if (format == kFloatFormat) {
1250 // We're using an int16 input file; convert to float.
1251 ConvertToFloat(*revframe_, revfloat_cb_.get());
1252 }
1253 }
1254 AnalyzeReverseStreamChooser(format);
1255
1256 } else if (event_msg.type() == audioproc::Event::STREAM) {
1257 const audioproc::Stream msg = event_msg.stream();
1258 // ProcessStream could have changed this for the output frame.
1259 frame_->num_channels_ = apm_->num_input_channels();
1260
1261 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1262 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001263 if (msg.has_keypress()) {
1264 apm_->set_stream_key_pressed(msg.keypress());
1265 } else {
1266 apm_->set_stream_key_pressed(true);
1267 }
1268
1269 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001270 ASSERT_EQ(frame_->num_channels_,
1271 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001272 for (int i = 0; i < msg.input_channel_size(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001273 memcpy(float_cb_->channels()[i], msg.input_channel(i).data(),
1274 msg.input_channel(i).size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001275 }
1276 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001277 memcpy(frame_->mutable_data(), msg.input_data().data(),
1278 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001279 if (format == kFloatFormat) {
1280 // We're using an int16 input file; convert to float.
1281 ConvertToFloat(*frame_, float_cb_.get());
1282 }
1283 }
1284 ProcessStreamChooser(format);
1285 }
1286 }
aleloif4dd1912017-06-15 01:55:38 -07001287 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001288 fclose(in_file);
1289}
1290
1291void ApmTest::VerifyDebugDumpTest(Format format) {
Minyue Li656d6092018-08-10 15:38:52 +02001292 rtc::ScopedFakeClock fake_clock;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001293 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001294 std::string format_string;
1295 switch (format) {
1296 case kIntFormat:
1297 format_string = "_int";
1298 break;
1299 case kFloatFormat:
1300 format_string = "_float";
1301 break;
1302 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001303 const std::string ref_filename = test::TempFilename(
1304 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1305 const std::string out_filename = test::TempFilename(
1306 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001307 const std::string limited_filename = test::TempFilename(
1308 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1309 const size_t logging_limit_bytes = 100000;
1310 // We expect at least this many bytes in the created logfile.
1311 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001312 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001313 ProcessDebugDump(in_filename, ref_filename, format, -1);
1314 ProcessDebugDump(ref_filename, out_filename, format, -1);
1315 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001316
1317 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1318 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001319 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001320 ASSERT_TRUE(ref_file != NULL);
1321 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001322 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001323 std::unique_ptr<uint8_t[]> ref_bytes;
1324 std::unique_ptr<uint8_t[]> out_bytes;
1325 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001326
1327 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1328 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001329 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001330 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001331 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001332 while (ref_size > 0 && out_size > 0) {
1333 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001334 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001335 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001336 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001337 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001338 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001339 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1340 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001341 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001342 }
1343 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001344 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1345 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001346 EXPECT_NE(0, feof(ref_file));
1347 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001348 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001349 ASSERT_EQ(0, fclose(ref_file));
1350 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001351 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001352 remove(ref_filename.c_str());
1353 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001354 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001355}
1356
pbosc7a65692016-05-06 12:50:04 -07001357TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001358 VerifyDebugDumpTest(kIntFormat);
1359}
1360
pbosc7a65692016-05-06 12:50:04 -07001361TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001362 VerifyDebugDumpTest(kFloatFormat);
1363}
1364#endif
1365
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001366// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001367TEST_F(ApmTest, DebugDump) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001368 TaskQueueForTest worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001369 const std::string filename =
1370 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001371 {
1372 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1373 EXPECT_FALSE(aec_dump);
1374 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001375
1376#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1377 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001378 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001379
aleloif4dd1912017-06-15 01:55:38 -07001380 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1381 EXPECT_TRUE(aec_dump);
1382 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001383 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001384 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001385 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001386
1387 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001388 FILE* fid = fopen(filename.c_str(), "r");
1389 ASSERT_TRUE(fid != NULL);
1390
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001391 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001392 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001393 ASSERT_EQ(0, remove(filename.c_str()));
1394#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001395 // Verify the file has NOT been written.
1396 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1397#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1398}
1399
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001400// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001401TEST_F(ApmTest, DebugDumpFromFileHandle) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001402 TaskQueueForTest worker_queue("ApmTest_worker_queue");
aleloif4dd1912017-06-15 01:55:38 -07001403
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001404 const std::string filename =
1405 test::TempFilename(test::OutputPath(), "debug_aec");
Niels Möllere8e4dc42019-06-11 14:04:16 +02001406 FileWrapper f = FileWrapper::OpenWriteOnly(filename.c_str());
1407 ASSERT_TRUE(f.is_open());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001408
1409#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1410 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001411 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001412
Niels Möllere8e4dc42019-06-11 14:04:16 +02001413 auto aec_dump = AecDumpFactory::Create(std::move(f), -1, &worker_queue);
aleloif4dd1912017-06-15 01:55:38 -07001414 EXPECT_TRUE(aec_dump);
1415 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001416 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001417 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001418 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001419
1420 // Verify the file has been written.
Niels Möllere8e4dc42019-06-11 14:04:16 +02001421 FILE* fid = fopen(filename.c_str(), "r");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001422 ASSERT_TRUE(fid != NULL);
1423
1424 // Clean it up.
1425 ASSERT_EQ(0, fclose(fid));
1426 ASSERT_EQ(0, remove(filename.c_str()));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001427#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1428}
1429
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001430// TODO(andrew): Add a test to process a few frames with different combinations
1431// of enabled components.
1432
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001433TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001434 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001435 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001436
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001437 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001438 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001439 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001440 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08001441 for (size_t i = 0; i < arraysize(kChannels); i++) {
1442 for (size_t j = 0; j < arraysize(kChannels); j++) {
1443 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001444 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001445 test->set_num_reverse_channels(kChannels[i]);
1446 test->set_num_input_channels(kChannels[j]);
1447 test->set_num_output_channels(kChannels[j]);
1448 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001449 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001450 }
1451 }
1452 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001453#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1454 // To test the extended filter mode.
1455 audioproc::Test* test = ref_data.add_test();
1456 test->set_num_reverse_channels(2);
1457 test->set_num_input_channels(2);
1458 test->set_num_output_channels(2);
1459 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
1460 test->set_use_aec_extended_filter(true);
1461#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001462 }
1463
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001464 for (int i = 0; i < ref_data.test_size(); i++) {
1465 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001466
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001467 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001468 // TODO(ajm): We no longer allow different input and output channels. Skip
1469 // these tests for now, but they should be removed from the set.
1470 if (test->num_input_channels() != test->num_output_channels())
1471 continue;
1472
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001473 Config config;
1474 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02001475 config.Set<ExtendedFilter>(
1476 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01001477 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001478
1479 EnableAllComponents();
1480
Jonas Olssona4d87372019-07-05 19:08:33 +02001481 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08001482 static_cast<size_t>(test->num_input_channels()),
1483 static_cast<size_t>(test->num_output_channels()),
Jonas Olssona4d87372019-07-05 19:08:33 +02001484 static_cast<size_t>(test->num_reverse_channels()), true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001485
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001486 int frame_count = 0;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001487 int has_voice_count = 0;
1488 int is_saturated_count = 0;
1489 int analog_level = 127;
1490 int analog_level_average = 0;
1491 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001492 float ns_speech_prob_average = 0.0f;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001493 float rms_dbfs_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07001494#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +02001495 int stats_index = 0;
minyue58530ed2016-05-24 05:50:12 -07001496#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001497
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001498 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07001499 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001500
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001501 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1502
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001503 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001504 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +02001505 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001506
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001507 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001508
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001509 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08001510 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
1511 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001512
1513 max_output_average += MaxAudioFrame(*frame_);
1514
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001515 analog_level = apm_->gain_control()->stream_analog_level();
1516 analog_level_average += analog_level;
1517 if (apm_->gain_control()->stream_is_saturated()) {
1518 is_saturated_count++;
1519 }
Sam Zackrisson11b87032018-12-18 17:13:58 +01001520 AudioProcessingStats stats =
1521 apm_->GetStatistics(/*has_remote_tracks=*/false);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001522 EXPECT_TRUE(stats.voice_detected);
1523 EXPECT_TRUE(stats.output_rms_dbfs);
1524 has_voice_count += *stats.voice_detected ? 1 : 0;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001525 rms_dbfs_average += *stats.output_rms_dbfs;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001526
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001527 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
1528
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001529 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
Jonas Olssona4d87372019-07-05 19:08:33 +02001530 size_t write_count =
1531 fwrite(frame_->data(), sizeof(int16_t), frame_size, out_file_);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001532 ASSERT_EQ(frame_size, write_count);
1533
1534 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08001535 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001536 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07001537
1538#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1539 const int kStatsAggregationFrameNum = 100; // 1 second.
1540 if (frame_count % kStatsAggregationFrameNum == 0) {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001541 // Get echo and delay metrics.
1542 AudioProcessingStats stats =
1543 apm_->GetStatistics(true /* has_remote_tracks */);
minyue58530ed2016-05-24 05:50:12 -07001544
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001545 // Echo metrics.
1546 const float echo_return_loss = stats.echo_return_loss.value_or(-1.0f);
1547 const float echo_return_loss_enhancement =
1548 stats.echo_return_loss_enhancement.value_or(-1.0f);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001549 const float residual_echo_likelihood =
1550 stats.residual_echo_likelihood.value_or(-1.0f);
1551 const float residual_echo_likelihood_recent_max =
1552 stats.residual_echo_likelihood_recent_max.value_or(-1.0f);
1553
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001554 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
minyue58530ed2016-05-24 05:50:12 -07001555 const audioproc::Test::EchoMetrics& reference =
1556 test->echo_metrics(stats_index);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001557 constexpr float kEpsilon = 0.01;
1558 EXPECT_NEAR(echo_return_loss, reference.echo_return_loss(), kEpsilon);
1559 EXPECT_NEAR(echo_return_loss_enhancement,
1560 reference.echo_return_loss_enhancement(), kEpsilon);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001561 EXPECT_NEAR(residual_echo_likelihood,
1562 reference.residual_echo_likelihood(), kEpsilon);
1563 EXPECT_NEAR(residual_echo_likelihood_recent_max,
1564 reference.residual_echo_likelihood_recent_max(),
1565 kEpsilon);
minyue58530ed2016-05-24 05:50:12 -07001566 ++stats_index;
1567 } else {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001568 audioproc::Test::EchoMetrics* message_echo = test->add_echo_metrics();
1569 message_echo->set_echo_return_loss(echo_return_loss);
1570 message_echo->set_echo_return_loss_enhancement(
1571 echo_return_loss_enhancement);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001572 message_echo->set_residual_echo_likelihood(residual_echo_likelihood);
1573 message_echo->set_residual_echo_likelihood_recent_max(
1574 residual_echo_likelihood_recent_max);
minyue58530ed2016-05-24 05:50:12 -07001575 }
1576 }
1577#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001578 }
1579 max_output_average /= frame_count;
1580 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001581 ns_speech_prob_average /= frame_count;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001582 rms_dbfs_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001583
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001584 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001585 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001586 // When running the test on a N7 we get a {2, 6} difference of
1587 // |has_voice_count| and |max_output_average| is up to 18 higher.
1588 // All numbers being consistently higher on N7 compare to ref_data.
1589 // TODO(bjornv): If we start getting more of these offsets on Android we
1590 // should consider a different approach. Either using one slack for all,
1591 // or generate a separate android reference.
Kári Tristan Helgason640106e2018-09-06 15:29:45 +02001592#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001593 const int kHasVoiceCountOffset = 3;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001594 const int kHasVoiceCountNear = 8;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001595 const int kMaxOutputAverageOffset = 9;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001596 const int kMaxOutputAverageNear = 26;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001597#else
1598 const int kHasVoiceCountOffset = 0;
1599 const int kHasVoiceCountNear = kIntNear;
1600 const int kMaxOutputAverageOffset = 0;
1601 const int kMaxOutputAverageNear = kIntNear;
1602#endif
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001603 EXPECT_NEAR(test->has_voice_count(),
Jonas Olssona4d87372019-07-05 19:08:33 +02001604 has_voice_count - kHasVoiceCountOffset, kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001605 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001606
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001607 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001608 EXPECT_NEAR(test->max_output_average(),
1609 max_output_average - kMaxOutputAverageOffset,
1610 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00001611#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001612 const double kFloatNear = 0.0005;
Jonas Olssona4d87372019-07-05 19:08:33 +02001613 EXPECT_NEAR(test->ns_speech_probability_average(), ns_speech_prob_average,
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001614 kFloatNear);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001615 EXPECT_NEAR(test->rms_dbfs_average(), rms_dbfs_average, kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001616#endif
1617 } else {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001618 test->set_has_voice_count(has_voice_count);
1619 test->set_is_saturated_count(is_saturated_count);
1620
1621 test->set_analog_level_average(analog_level_average);
1622 test->set_max_output_average(max_output_average);
1623
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00001624#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001625 EXPECT_LE(0.0f, ns_speech_prob_average);
1626 EXPECT_GE(1.0f, ns_speech_prob_average);
1627 test->set_ns_speech_probability_average(ns_speech_prob_average);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001628 test->set_rms_dbfs_average(rms_dbfs_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001629#endif
1630 }
1631
1632 rewind(far_file_);
1633 rewind(near_file_);
1634 }
1635
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001636 if (absl::GetFlag(FLAGS_write_apm_ref_data)) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001637 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001638 }
1639}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001640
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001641TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
1642 struct ChannelFormat {
1643 AudioProcessing::ChannelLayout in_layout;
1644 AudioProcessing::ChannelLayout out_layout;
1645 };
1646 ChannelFormat cf[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001647 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
1648 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
1649 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001650 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001651
Ivo Creusen62337e52018-01-09 14:17:33 +01001652 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001653 // Enable one component just to ensure some processing takes place.
1654 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08001655 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001656 const int in_rate = 44100;
1657 const int out_rate = 48000;
1658 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
1659 TotalChannelsFromLayout(cf[i].in_layout));
1660 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
1661 ChannelsFromLayout(cf[i].out_layout));
1662
1663 // Run over a few chunks.
1664 for (int j = 0; j < 10; ++j) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001665 EXPECT_NOERR(ap->ProcessStream(in_cb.channels(), in_cb.num_frames(),
1666 in_rate, cf[i].in_layout, out_rate,
1667 cf[i].out_layout, out_cb.channels()));
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001668 }
1669 }
1670}
1671
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001672// Compares the reference and test arrays over a region around the expected
1673// delay. Finds the highest SNR in that region and adds the variance and squared
1674// error results to the supplied accumulators.
1675void UpdateBestSNR(const float* ref,
1676 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08001677 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001678 int expected_delay,
1679 double* variance_acc,
1680 double* sq_error_acc) {
1681 double best_snr = std::numeric_limits<double>::min();
1682 double best_variance = 0;
1683 double best_sq_error = 0;
1684 // Search over a region of eight samples around the expected delay.
1685 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
1686 ++delay) {
1687 double sq_error = 0;
1688 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08001689 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001690 double error = test[i + delay] - ref[i];
1691 sq_error += error * error;
1692 variance += ref[i] * ref[i];
1693 }
1694
1695 if (sq_error == 0) {
1696 *variance_acc += variance;
1697 return;
1698 }
1699 double snr = variance / sq_error;
1700 if (snr > best_snr) {
1701 best_snr = snr;
1702 best_variance = variance;
1703 best_sq_error = sq_error;
1704 }
1705 }
1706
1707 *variance_acc += best_variance;
1708 *sq_error_acc += best_sq_error;
1709}
1710
1711// Used to test a multitude of sample rate and channel combinations. It works
1712// by first producing a set of reference files (in SetUpTestCase) that are
1713// assumed to be correct, as the used parameters are verified by other tests
1714// in this collection. Primarily the reference files are all produced at
1715// "native" rates which do not involve any resampling.
1716
1717// Each test pass produces an output file with a particular format. The output
1718// is matched against the reference file closest to its internal processing
1719// format. If necessary the output is resampled back to its process format.
1720// Due to the resampling distortion, we don't expect identical results, but
1721// enforce SNR thresholds which vary depending on the format. 0 is a special
1722// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02001723typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001724class AudioProcessingTest
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001725 : public ::testing::TestWithParam<AudioProcessingTestData> {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001726 public:
1727 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02001728 : input_rate_(std::get<0>(GetParam())),
1729 output_rate_(std::get<1>(GetParam())),
1730 reverse_input_rate_(std::get<2>(GetParam())),
1731 reverse_output_rate_(std::get<3>(GetParam())),
1732 expected_snr_(std::get<4>(GetParam())),
1733 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001734
1735 virtual ~AudioProcessingTest() {}
1736
Mirko Bonadei71061bc2019-06-04 09:01:51 +02001737 static void SetUpTestSuite() {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001738 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07001739 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08001740 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08001741 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
1742 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
1743 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001744 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07001745 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
1746 kNativeRates[i], kNumChannels[j], kNumChannels[j],
1747 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001748 }
1749 }
1750 }
1751 }
1752
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02001753 void TearDown() {
1754 // Remove "out" files after each test.
1755 ClearTempOutFiles();
1756 }
1757
Mirko Bonadei71061bc2019-06-04 09:01:51 +02001758 static void TearDownTestSuite() { ClearTempFiles(); }
ekmeyerson60d9b332015-08-14 10:35:55 -07001759
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001760 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07001761 // to a file specified with |output_file_prefix|. Both forward and reverse
1762 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001763 static void ProcessFormat(int input_rate,
1764 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07001765 int reverse_input_rate,
1766 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001767 size_t num_input_channels,
1768 size_t num_output_channels,
1769 size_t num_reverse_input_channels,
1770 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02001771 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001772 Config config;
1773 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001774 std::unique_ptr<AudioProcessing> ap(
1775 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001776 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001777
ekmeyerson60d9b332015-08-14 10:35:55 -07001778 ProcessingConfig processing_config = {
1779 {{input_rate, num_input_channels},
1780 {output_rate, num_output_channels},
1781 {reverse_input_rate, num_reverse_input_channels},
1782 {reverse_output_rate, num_reverse_output_channels}}};
1783 ap->Initialize(processing_config);
1784
1785 FILE* far_file =
1786 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001787 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +02001788 FILE* out_file = fopen(
1789 OutputFilePath(
1790 output_file_prefix, input_rate, output_rate, reverse_input_rate,
1791 reverse_output_rate, num_input_channels, num_output_channels,
1792 num_reverse_input_channels, num_reverse_output_channels, kForward)
1793 .c_str(),
1794 "wb");
1795 FILE* rev_out_file = fopen(
1796 OutputFilePath(
1797 output_file_prefix, input_rate, output_rate, reverse_input_rate,
1798 reverse_output_rate, num_input_channels, num_output_channels,
1799 num_reverse_input_channels, num_reverse_output_channels, kReverse)
1800 .c_str(),
1801 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001802 ASSERT_TRUE(far_file != NULL);
1803 ASSERT_TRUE(near_file != NULL);
1804 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07001805 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001806
1807 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
1808 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07001809 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
1810 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001811 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
1812 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07001813 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
1814 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001815
1816 // Temporary buffers.
1817 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07001818 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
1819 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08001820 std::unique_ptr<float[]> float_data(new float[max_length]);
1821 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001822
1823 int analog_level = 127;
1824 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
1825 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07001826 EXPECT_NOERR(ap->ProcessReverseStream(
1827 rev_cb.channels(), processing_config.reverse_input_stream(),
1828 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001829
1830 EXPECT_NOERR(ap->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001831 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
1832
1833 EXPECT_NOERR(ap->ProcessStream(
Jonas Olssona4d87372019-07-05 19:08:33 +02001834 fwd_cb.channels(), fwd_cb.num_frames(), input_rate,
1835 LayoutFromChannels(num_input_channels), output_rate,
1836 LayoutFromChannels(num_output_channels), out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001837
ekmeyerson60d9b332015-08-14 10:35:55 -07001838 // Dump forward output to file.
1839 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001840 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08001841 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07001842
Jonas Olssona4d87372019-07-05 19:08:33 +02001843 ASSERT_EQ(out_length, fwrite(float_data.get(), sizeof(float_data[0]),
1844 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001845
ekmeyerson60d9b332015-08-14 10:35:55 -07001846 // Dump reverse output to file.
1847 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
1848 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08001849 size_t rev_out_length =
1850 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07001851
Jonas Olssona4d87372019-07-05 19:08:33 +02001852 ASSERT_EQ(rev_out_length, fwrite(float_data.get(), sizeof(float_data[0]),
1853 rev_out_length, rev_out_file));
ekmeyerson60d9b332015-08-14 10:35:55 -07001854
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001855 analog_level = ap->gain_control()->stream_analog_level();
1856 }
1857 fclose(far_file);
1858 fclose(near_file);
1859 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07001860 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001861 }
1862
1863 protected:
1864 int input_rate_;
1865 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07001866 int reverse_input_rate_;
1867 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001868 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07001869 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001870};
1871
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00001872TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001873 struct ChannelFormat {
1874 int num_input;
1875 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07001876 int num_reverse_input;
1877 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001878 };
1879 ChannelFormat cf[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001880 {1, 1, 1, 1}, {1, 1, 2, 1}, {2, 1, 1, 1},
1881 {2, 1, 2, 1}, {2, 2, 1, 1}, {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001882 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001883
pkasting25702cb2016-01-08 13:50:27 -08001884 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07001885 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
1886 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
1887 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07001888
ekmeyerson60d9b332015-08-14 10:35:55 -07001889 // Verify output for both directions.
1890 std::vector<StreamDirection> stream_directions;
1891 stream_directions.push_back(kForward);
1892 stream_directions.push_back(kReverse);
1893 for (StreamDirection file_direction : stream_directions) {
1894 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
1895 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
1896 const int out_num =
1897 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
1898 const double expected_snr =
1899 file_direction ? expected_reverse_snr_ : expected_snr_;
1900
1901 const int min_ref_rate = std::min(in_rate, out_rate);
1902 int ref_rate;
1903
1904 if (min_ref_rate > 32000) {
1905 ref_rate = 48000;
1906 } else if (min_ref_rate > 16000) {
1907 ref_rate = 32000;
1908 } else if (min_ref_rate > 8000) {
1909 ref_rate = 16000;
1910 } else {
1911 ref_rate = 8000;
1912 }
aluebs776593b2016-03-15 14:04:58 -07001913#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08001914 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07001915 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08001916 }
1917#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001918 FILE* out_file = fopen(
1919 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
1920 reverse_output_rate_, cf[i].num_input,
1921 cf[i].num_output, cf[i].num_reverse_input,
Jonas Olssona4d87372019-07-05 19:08:33 +02001922 cf[i].num_reverse_output, file_direction)
1923 .c_str(),
ekmeyerson60d9b332015-08-14 10:35:55 -07001924 "rb");
1925 // The reference files always have matching input and output channels.
Jonas Olssona4d87372019-07-05 19:08:33 +02001926 FILE* ref_file =
1927 fopen(OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
1928 cf[i].num_output, cf[i].num_output,
1929 cf[i].num_reverse_output,
1930 cf[i].num_reverse_output, file_direction)
1931 .c_str(),
1932 "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07001933 ASSERT_TRUE(out_file != NULL);
1934 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001935
pkasting25702cb2016-01-08 13:50:27 -08001936 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
1937 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07001938 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08001939 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07001940 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08001941 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07001942 // Data from the resampled output, in case the reference and output rates
1943 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08001944 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001945
ekmeyerson60d9b332015-08-14 10:35:55 -07001946 PushResampler<float> resampler;
1947 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001948
ekmeyerson60d9b332015-08-14 10:35:55 -07001949 // Compute the resampling delay of the output relative to the reference,
1950 // to find the region over which we should search for the best SNR.
1951 float expected_delay_sec = 0;
1952 if (in_rate != ref_rate) {
1953 // Input resampling delay.
1954 expected_delay_sec +=
1955 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
1956 }
1957 if (out_rate != ref_rate) {
1958 // Output resampling delay.
1959 expected_delay_sec +=
1960 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
1961 // Delay of converting the output back to its processing rate for
1962 // testing.
1963 expected_delay_sec +=
1964 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
1965 }
1966 int expected_delay =
Oleh Prypin708eccc2019-03-27 09:38:52 +01001967 std::floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001968
ekmeyerson60d9b332015-08-14 10:35:55 -07001969 double variance = 0;
1970 double sq_error = 0;
1971 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
1972 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
1973 float* out_ptr = out_data.get();
1974 if (out_rate != ref_rate) {
1975 // Resample the output back to its internal processing rate if
1976 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08001977 ASSERT_EQ(ref_length,
1978 static_cast<size_t>(resampler.Resample(
1979 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07001980 out_ptr = cmp_data.get();
1981 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001982
ekmeyerson60d9b332015-08-14 10:35:55 -07001983 // Update the |sq_error| and |variance| accumulators with the highest
1984 // SNR of reference vs output.
1985 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
1986 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001987 }
1988
ekmeyerson60d9b332015-08-14 10:35:55 -07001989 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
1990 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
1991 << cf[i].num_input << ", " << cf[i].num_output << ", "
1992 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
1993 << ", " << file_direction << "): ";
1994 if (sq_error > 0) {
1995 double snr = 10 * log10(variance / sq_error);
1996 EXPECT_GE(snr, expected_snr);
1997 EXPECT_NE(0, expected_snr);
1998 std::cout << "SNR=" << snr << " dB" << std::endl;
1999 } else {
aluebs776593b2016-03-15 14:04:58 -07002000 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002001 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002002
ekmeyerson60d9b332015-08-14 10:35:55 -07002003 fclose(out_file);
2004 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002005 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002006 }
2007}
2008
2009#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002010INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002011 CommonFormats,
2012 AudioProcessingTest,
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002013 ::testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2014 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2015 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2016 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2017 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2018 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2019 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2020 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2021 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2022 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2023 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2024 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002025
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002026 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2027 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2028 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2029 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2030 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2031 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2032 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2033 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2034 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2035 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2036 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2037 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002038
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002039 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2040 std::make_tuple(32000, 48000, 32000, 48000, 32, 30),
2041 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2042 std::make_tuple(32000, 44100, 48000, 44100, 19, 20),
2043 std::make_tuple(32000, 44100, 32000, 44100, 19, 15),
2044 std::make_tuple(32000, 44100, 16000, 44100, 19, 15),
2045 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2046 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2047 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2048 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2049 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2050 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002051
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002052 std::make_tuple(16000, 48000, 48000, 48000, 24, 0),
2053 std::make_tuple(16000, 48000, 32000, 48000, 24, 30),
2054 std::make_tuple(16000, 48000, 16000, 48000, 24, 20),
2055 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2056 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2057 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2058 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2059 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2060 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2061 std::make_tuple(16000, 16000, 48000, 16000, 39, 20),
2062 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2063 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002064
2065#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002066INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002067 CommonFormats,
2068 AudioProcessingTest,
Per Åhgren0aefbf02019-08-23 21:29:17 +02002069 ::testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 19, 0),
2070 std::make_tuple(48000, 48000, 32000, 48000, 19, 30),
2071 std::make_tuple(48000, 48000, 16000, 48000, 19, 20),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002072 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2073 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2074 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
Per Åhgren0aefbf02019-08-23 21:29:17 +02002075 std::make_tuple(48000, 32000, 48000, 32000, 19, 35),
2076 std::make_tuple(48000, 32000, 32000, 32000, 19, 0),
2077 std::make_tuple(48000, 32000, 16000, 32000, 19, 20),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002078 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2079 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2080 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002081
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002082 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2083 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2084 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2085 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2086 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2087 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
Per Åhgren0aefbf02019-08-23 21:29:17 +02002088 std::make_tuple(44100, 32000, 48000, 32000, 18, 35),
2089 std::make_tuple(44100, 32000, 32000, 32000, 18, 0),
2090 std::make_tuple(44100, 32000, 16000, 32000, 18, 20),
2091 std::make_tuple(44100, 16000, 48000, 16000, 19, 20),
2092 std::make_tuple(44100, 16000, 32000, 16000, 19, 20),
2093 std::make_tuple(44100, 16000, 16000, 16000, 19, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002094
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002095 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2096 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2097 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2098 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2099 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2100 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2101 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2102 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2103 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2104 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2105 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2106 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002107
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002108 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2109 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2110 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2111 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2112 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2113 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2114 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2115 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2116 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2117 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2118 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2119 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002120#endif
2121
Per Åhgren3e8bf282019-08-29 23:38:40 +02002122// Produces a scoped trace debug output.
2123std::string ProduceDebugText(int render_input_sample_rate_hz,
2124 int render_output_sample_rate_hz,
2125 int capture_input_sample_rate_hz,
2126 int capture_output_sample_rate_hz,
2127 size_t render_input_num_channels,
2128 size_t render_output_num_channels,
2129 size_t capture_input_num_channels,
2130 size_t capture_output_num_channels) {
2131 rtc::StringBuilder ss;
2132 ss << "Sample rates:"
2133 << "\n"
2134 << " Render input: " << render_input_sample_rate_hz << " Hz"
2135 << "\n"
2136 << " Render output: " << render_output_sample_rate_hz << " Hz"
2137 << "\n"
2138 << " Capture input: " << capture_input_sample_rate_hz << " Hz"
2139 << "\n"
2140 << " Capture output: " << capture_output_sample_rate_hz << " Hz"
2141 << "\n"
2142 << "Number of channels:"
2143 << "\n"
2144 << " Render input: " << render_input_num_channels << "\n"
2145 << " Render output: " << render_output_num_channels << "\n"
2146 << " Capture input: " << capture_input_num_channels << "\n"
2147 << " Capture output: " << capture_output_num_channels;
2148 return ss.Release();
2149}
2150
2151// Validates that running the audio processing module using various combinations
2152// of sample rates and number of channels works as intended.
2153void RunApmRateAndChannelTest(
2154 rtc::ArrayView<const int> sample_rates_hz,
2155 rtc::ArrayView<const int> render_channel_counts,
2156 rtc::ArrayView<const int> capture_channel_counts) {
2157 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2158 webrtc::AudioProcessing::Config apm_config;
2159 apm_config.echo_canceller.enabled = true;
2160 apm->ApplyConfig(apm_config);
2161
2162 StreamConfig render_input_stream_config;
2163 StreamConfig render_output_stream_config;
2164 StreamConfig capture_input_stream_config;
2165 StreamConfig capture_output_stream_config;
2166
2167 std::vector<float> render_input_frame_channels;
2168 std::vector<float*> render_input_frame;
2169 std::vector<float> render_output_frame_channels;
2170 std::vector<float*> render_output_frame;
2171 std::vector<float> capture_input_frame_channels;
2172 std::vector<float*> capture_input_frame;
2173 std::vector<float> capture_output_frame_channels;
2174 std::vector<float*> capture_output_frame;
2175
2176 for (auto render_input_sample_rate_hz : sample_rates_hz) {
2177 for (auto render_output_sample_rate_hz : sample_rates_hz) {
2178 for (auto capture_input_sample_rate_hz : sample_rates_hz) {
2179 for (auto capture_output_sample_rate_hz : sample_rates_hz) {
2180 for (size_t render_input_num_channels : render_channel_counts) {
2181 for (size_t capture_input_num_channels : capture_channel_counts) {
2182 size_t render_output_num_channels = render_input_num_channels;
2183 size_t capture_output_num_channels = capture_input_num_channels;
2184 auto populate_audio_frame = [](int sample_rate_hz,
2185 size_t num_channels,
2186 StreamConfig* cfg,
2187 std::vector<float>* channels_data,
2188 std::vector<float*>* frame_data) {
2189 cfg->set_sample_rate_hz(sample_rate_hz);
2190 cfg->set_num_channels(num_channels);
2191 cfg->set_has_keyboard(false);
2192
2193 size_t max_frame_size = ceil(sample_rate_hz / 100.f);
2194 channels_data->resize(num_channels * max_frame_size);
2195 std::fill(channels_data->begin(), channels_data->end(), 0.5f);
2196 frame_data->resize(num_channels);
2197 for (size_t channel = 0; channel < num_channels; ++channel) {
2198 (*frame_data)[channel] =
2199 &(*channels_data)[channel * max_frame_size];
2200 }
2201 };
2202
2203 populate_audio_frame(
2204 render_input_sample_rate_hz, render_input_num_channels,
2205 &render_input_stream_config, &render_input_frame_channels,
2206 &render_input_frame);
2207 populate_audio_frame(
2208 render_output_sample_rate_hz, render_output_num_channels,
2209 &render_output_stream_config, &render_output_frame_channels,
2210 &render_output_frame);
2211 populate_audio_frame(
2212 capture_input_sample_rate_hz, capture_input_num_channels,
2213 &capture_input_stream_config, &capture_input_frame_channels,
2214 &capture_input_frame);
2215 populate_audio_frame(
2216 capture_output_sample_rate_hz, capture_output_num_channels,
2217 &capture_output_stream_config, &capture_output_frame_channels,
2218 &capture_output_frame);
2219
2220 for (size_t frame = 0; frame < 2; ++frame) {
2221 SCOPED_TRACE(ProduceDebugText(
2222 render_input_sample_rate_hz, render_output_sample_rate_hz,
2223 capture_input_sample_rate_hz, capture_output_sample_rate_hz,
2224 render_input_num_channels, render_output_num_channels,
2225 render_input_num_channels, capture_output_num_channels));
2226
2227 int result = apm->ProcessReverseStream(
2228 &render_input_frame[0], render_input_stream_config,
2229 render_output_stream_config, &render_output_frame[0]);
2230 EXPECT_EQ(result, AudioProcessing::kNoError);
2231 result = apm->ProcessStream(
2232 &capture_input_frame[0], capture_input_stream_config,
2233 capture_output_stream_config, &capture_output_frame[0]);
2234 EXPECT_EQ(result, AudioProcessing::kNoError);
2235 }
2236 }
2237 }
2238 }
2239 }
2240 }
2241 }
2242}
2243
niklase@google.com470e71d2011-07-07 08:21:25 +00002244} // namespace
peahc19f3122016-10-07 14:54:10 -07002245
Alessio Bazzicac054e782018-04-16 12:10:09 +02002246TEST(RuntimeSettingTest, TestDefaultCtor) {
2247 auto s = AudioProcessing::RuntimeSetting();
2248 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2249}
2250
2251TEST(RuntimeSettingTest, TestCapturePreGain) {
2252 using Type = AudioProcessing::RuntimeSetting::Type;
2253 {
2254 auto s = AudioProcessing::RuntimeSetting::CreateCapturePreGain(1.25f);
2255 EXPECT_EQ(Type::kCapturePreGain, s.type());
2256 float v;
2257 s.GetFloat(&v);
2258 EXPECT_EQ(1.25f, v);
2259 }
2260
2261#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2262 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2263#endif
2264}
2265
Per Åhgren6ee75fd2019-04-26 11:33:37 +02002266TEST(RuntimeSettingTest, TestCaptureFixedPostGain) {
2267 using Type = AudioProcessing::RuntimeSetting::Type;
2268 {
2269 auto s = AudioProcessing::RuntimeSetting::CreateCaptureFixedPostGain(1.25f);
2270 EXPECT_EQ(Type::kCaptureFixedPostGain, s.type());
2271 float v;
2272 s.GetFloat(&v);
2273 EXPECT_EQ(1.25f, v);
2274 }
2275
2276#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2277 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2278#endif
2279}
2280
Alessio Bazzicac054e782018-04-16 12:10:09 +02002281TEST(RuntimeSettingTest, TestUsageWithSwapQueue) {
2282 SwapQueue<AudioProcessing::RuntimeSetting> q(1);
2283 auto s = AudioProcessing::RuntimeSetting();
2284 ASSERT_TRUE(q.Insert(&s));
2285 ASSERT_TRUE(q.Remove(&s));
2286 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2287}
2288
Sam Zackrisson0beac582017-09-25 12:04:02 +02002289TEST(ApmConfiguration, EnablePostProcessing) {
2290 // Verify that apm uses a capture post processing module if one is provided.
Sam Zackrisson0beac582017-09-25 12:04:02 +02002291 auto mock_post_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002292 new ::testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002293 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002294 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002295 rtc::scoped_refptr<AudioProcessing> apm =
2296 AudioProcessingBuilder()
2297 .SetCapturePostProcessing(std::move(mock_post_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002298 .Create();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002299
2300 AudioFrame audio;
2301 audio.num_channels_ = 1;
2302 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2303
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002304 EXPECT_CALL(*mock_post_processor_ptr, Process(::testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002305 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002306}
2307
Alex Loiko5825aa62017-12-18 16:02:40 +01002308TEST(ApmConfiguration, EnablePreProcessing) {
2309 // Verify that apm uses a capture post processing module if one is provided.
Alex Loiko5825aa62017-12-18 16:02:40 +01002310 auto mock_pre_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002311 new ::testing::NiceMock<test::MockCustomProcessing>();
Alex Loiko5825aa62017-12-18 16:02:40 +01002312 auto mock_pre_processor =
2313 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002314 rtc::scoped_refptr<AudioProcessing> apm =
2315 AudioProcessingBuilder()
2316 .SetRenderPreProcessing(std::move(mock_pre_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002317 .Create();
Alex Loiko5825aa62017-12-18 16:02:40 +01002318
2319 AudioFrame audio;
2320 audio.num_channels_ = 1;
2321 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2322
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002323 EXPECT_CALL(*mock_pre_processor_ptr, Process(::testing::_)).Times(1);
Alex Loiko5825aa62017-12-18 16:02:40 +01002324 apm->ProcessReverseStream(&audio);
2325}
2326
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002327TEST(ApmConfiguration, EnableCaptureAnalyzer) {
2328 // Verify that apm uses a capture analyzer if one is provided.
2329 auto mock_capture_analyzer_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002330 new ::testing::NiceMock<test::MockCustomAudioAnalyzer>();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002331 auto mock_capture_analyzer =
2332 std::unique_ptr<CustomAudioAnalyzer>(mock_capture_analyzer_ptr);
2333 rtc::scoped_refptr<AudioProcessing> apm =
2334 AudioProcessingBuilder()
2335 .SetCaptureAnalyzer(std::move(mock_capture_analyzer))
2336 .Create();
2337
2338 AudioFrame audio;
2339 audio.num_channels_ = 1;
2340 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2341
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002342 EXPECT_CALL(*mock_capture_analyzer_ptr, Analyze(::testing::_)).Times(1);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002343 apm->ProcessStream(&audio);
2344}
2345
Alex Loiko73ec0192018-05-15 10:52:28 +02002346TEST(ApmConfiguration, PreProcessingReceivesRuntimeSettings) {
2347 auto mock_pre_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002348 new ::testing::NiceMock<test::MockCustomProcessing>();
Alex Loiko73ec0192018-05-15 10:52:28 +02002349 auto mock_pre_processor =
2350 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
2351 rtc::scoped_refptr<AudioProcessing> apm =
2352 AudioProcessingBuilder()
2353 .SetRenderPreProcessing(std::move(mock_pre_processor))
2354 .Create();
2355 apm->SetRuntimeSetting(
2356 AudioProcessing::RuntimeSetting::CreateCustomRenderSetting(0));
2357
2358 // RuntimeSettings forwarded during 'Process*Stream' calls.
2359 // Therefore we have to make one such call.
2360 AudioFrame audio;
2361 audio.num_channels_ = 1;
2362 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2363
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002364 EXPECT_CALL(*mock_pre_processor_ptr, SetRuntimeSetting(::testing::_))
2365 .Times(1);
Alex Loiko73ec0192018-05-15 10:52:28 +02002366 apm->ProcessReverseStream(&audio);
2367}
2368
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002369class MyEchoControlFactory : public EchoControlFactory {
2370 public:
2371 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2372 auto ec = new test::MockEchoControl();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002373 EXPECT_CALL(*ec, AnalyzeRender(::testing::_)).Times(1);
2374 EXPECT_CALL(*ec, AnalyzeCapture(::testing::_)).Times(2);
2375 EXPECT_CALL(*ec, ProcessCapture(::testing::_, ::testing::_)).Times(2);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002376 return std::unique_ptr<EchoControl>(ec);
2377 }
Per Åhgrence202a02019-09-02 17:01:19 +02002378
2379 std::unique_ptr<EchoControl> Create(int sample_rate_hz,
2380 size_t num_render_channels,
2381 size_t num_capture_channels) {
2382 return Create(sample_rate_hz);
2383 }
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002384};
2385
2386TEST(ApmConfiguration, EchoControlInjection) {
2387 // Verify that apm uses an injected echo controller if one is provided.
2388 webrtc::Config webrtc_config;
2389 std::unique_ptr<EchoControlFactory> echo_control_factory(
2390 new MyEchoControlFactory());
2391
Alex Loiko5825aa62017-12-18 16:02:40 +01002392 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002393 AudioProcessingBuilder()
2394 .SetEchoControlFactory(std::move(echo_control_factory))
2395 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002396
2397 AudioFrame audio;
2398 audio.num_channels_ = 1;
2399 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2400 apm->ProcessStream(&audio);
2401 apm->ProcessReverseStream(&audio);
2402 apm->ProcessStream(&audio);
2403}
Ivo Creusenae026092017-11-20 13:07:16 +01002404
Per Åhgren8607f842019-04-12 22:02:26 +02002405std::unique_ptr<AudioProcessing> CreateApm(bool mobile_aec) {
Ivo Creusenae026092017-11-20 13:07:16 +01002406 Config old_config;
Ivo Creusen62337e52018-01-09 14:17:33 +01002407 std::unique_ptr<AudioProcessing> apm(
2408 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002409 if (!apm) {
2410 return apm;
2411 }
2412
2413 ProcessingConfig processing_config = {
2414 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2415
2416 if (apm->Initialize(processing_config) != 0) {
2417 return nullptr;
2418 }
2419
2420 // Disable all components except for an AEC and the residual echo detector.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002421 AudioProcessing::Config apm_config;
2422 apm_config.residual_echo_detector.enabled = true;
2423 apm_config.high_pass_filter.enabled = false;
2424 apm_config.gain_controller2.enabled = false;
2425 apm_config.echo_canceller.enabled = true;
Per Åhgren8607f842019-04-12 22:02:26 +02002426 apm_config.echo_canceller.mobile_mode = mobile_aec;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002427 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002428 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
Ivo Creusenae026092017-11-20 13:07:16 +01002429 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
Ivo Creusenae026092017-11-20 13:07:16 +01002430 return apm;
2431}
2432
2433#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
2434#define MAYBE_ApmStatistics DISABLED_ApmStatistics
2435#else
2436#define MAYBE_ApmStatistics ApmStatistics
2437#endif
2438
Per Åhgren8607f842019-04-12 22:02:26 +02002439TEST(MAYBE_ApmStatistics, AECEnabledTest) {
2440 // Set up APM with AEC3 and process some audio.
2441 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
Ivo Creusenae026092017-11-20 13:07:16 +01002442 ASSERT_TRUE(apm);
Per Åhgren200feba2019-03-06 04:16:46 +01002443 AudioProcessing::Config apm_config;
2444 apm_config.echo_canceller.enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002445 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002446
2447 // Set up an audioframe.
2448 AudioFrame frame;
2449 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002450 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002451
2452 // Fill the audio frame with a sawtooth pattern.
2453 int16_t* ptr = frame.mutable_data();
2454 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2455 ptr[i] = 10000 * ((i % 3) - 1);
2456 }
2457
2458 // Do some processing.
2459 for (int i = 0; i < 200; i++) {
2460 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2461 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2462 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2463 }
2464
2465 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002466 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002467 // We expect all statistics to be set and have a sensible value.
2468 ASSERT_TRUE(stats.residual_echo_likelihood);
2469 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2470 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2471 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
2472 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2473 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2474 ASSERT_TRUE(stats.echo_return_loss);
2475 EXPECT_NE(*stats.echo_return_loss, -100.0);
2476 ASSERT_TRUE(stats.echo_return_loss_enhancement);
2477 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
Ivo Creusenae026092017-11-20 13:07:16 +01002478
2479 // If there are no receive streams, we expect the stats not to be set. The
2480 // 'false' argument signals to APM that no receive streams are currently
2481 // active. In that situation the statistics would get stuck at their last
2482 // calculated value (AEC and echo detection need at least one stream in each
2483 // direction), so to avoid that, they should not be set by APM.
2484 stats = apm->GetStatistics(false);
2485 EXPECT_FALSE(stats.residual_echo_likelihood);
2486 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2487 EXPECT_FALSE(stats.echo_return_loss);
2488 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002489}
2490
2491TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
2492 // Set up APM with AECM and process some audio.
Per Åhgren8607f842019-04-12 22:02:26 +02002493 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002494 ASSERT_TRUE(apm);
2495
2496 // Set up an audioframe.
2497 AudioFrame frame;
2498 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002499 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002500
2501 // Fill the audio frame with a sawtooth pattern.
2502 int16_t* ptr = frame.mutable_data();
2503 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2504 ptr[i] = 10000 * ((i % 3) - 1);
2505 }
2506
2507 // Do some processing.
2508 for (int i = 0; i < 200; i++) {
2509 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2510 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2511 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2512 }
2513
2514 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002515 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002516 // We expect only the residual echo detector statistics to be set and have a
2517 // sensible value.
2518 EXPECT_TRUE(stats.residual_echo_likelihood);
2519 if (stats.residual_echo_likelihood) {
2520 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2521 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2522 }
2523 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
2524 if (stats.residual_echo_likelihood_recent_max) {
2525 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2526 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2527 }
2528 EXPECT_FALSE(stats.echo_return_loss);
2529 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002530
2531 // If there are no receive streams, we expect the stats not to be set.
2532 stats = apm->GetStatistics(false);
2533 EXPECT_FALSE(stats.residual_echo_likelihood);
2534 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2535 EXPECT_FALSE(stats.echo_return_loss);
2536 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002537}
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002538
2539TEST(ApmStatistics, ReportOutputRmsDbfs) {
2540 ProcessingConfig processing_config = {
2541 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2542 AudioProcessing::Config config;
2543
2544 // Set up an audioframe.
2545 AudioFrame frame;
2546 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002547 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002548
2549 // Fill the audio frame with a sawtooth pattern.
2550 int16_t* ptr = frame.mutable_data();
2551 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2552 ptr[i] = 10000 * ((i % 3) - 1);
2553 }
2554
2555 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2556 apm->Initialize(processing_config);
2557
2558 // If not enabled, no metric should be reported.
2559 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2560 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2561
2562 // If enabled, metrics should be reported.
2563 config.level_estimation.enabled = true;
2564 apm->ApplyConfig(config);
2565 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2566 auto stats = apm->GetStatistics(false);
2567 EXPECT_TRUE(stats.output_rms_dbfs);
2568 EXPECT_GE(*stats.output_rms_dbfs, 0);
2569
2570 // If re-disabled, the value is again not reported.
2571 config.level_estimation.enabled = false;
2572 apm->ApplyConfig(config);
2573 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2574 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2575}
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002576
2577TEST(ApmStatistics, ReportHasVoice) {
2578 ProcessingConfig processing_config = {
2579 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2580 AudioProcessing::Config config;
2581
2582 // Set up an audioframe.
2583 AudioFrame frame;
2584 frame.num_channels_ = 1;
2585 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
2586
2587 // Fill the audio frame with a sawtooth pattern.
2588 int16_t* ptr = frame.mutable_data();
2589 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2590 ptr[i] = 10000 * ((i % 3) - 1);
2591 }
2592
2593 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2594 apm->Initialize(processing_config);
2595
2596 // If not enabled, no metric should be reported.
2597 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2598 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2599
2600 // If enabled, metrics should be reported.
2601 config.voice_detection.enabled = true;
2602 apm->ApplyConfig(config);
2603 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2604 auto stats = apm->GetStatistics(false);
2605 EXPECT_TRUE(stats.voice_detected);
2606
2607 // If re-disabled, the value is again not reported.
2608 config.voice_detection.enabled = false;
2609 apm->ApplyConfig(config);
2610 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2611 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2612}
Per Åhgren3e8bf282019-08-29 23:38:40 +02002613
2614TEST(ApmConfiguration, HandlingOfRateAndChannelCombinations) {
2615 std::array<int, 3> sample_rates_hz = {16000, 32000, 48000};
2616 std::array<int, 2> render_channel_counts = {1, 7};
2617 std::array<int, 2> capture_channel_counts = {1, 7};
2618 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2619 capture_channel_counts);
2620}
2621
2622TEST(ApmConfiguration, HandlingOfChannelCombinations) {
2623 std::array<int, 1> sample_rates_hz = {48000};
2624 std::array<int, 8> render_channel_counts = {1, 2, 3, 4, 5, 6, 7, 8};
2625 std::array<int, 8> capture_channel_counts = {1, 2, 3, 4, 5, 6, 7, 8};
2626 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2627 capture_channel_counts);
2628}
2629
2630TEST(ApmConfiguration, HandlingOfRateCombinations) {
2631 std::array<int, 9> sample_rates_hz = {8000, 11025, 16000, 22050, 32000,
2632 48000, 96000, 192000, 384000};
2633 std::array<int, 1> render_channel_counts = {2};
2634 std::array<int, 1> capture_channel_counts = {2};
2635 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2636 capture_channel_counts);
2637}
2638
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002639} // namespace webrtc