blob: 2b8abd9294e292b7f54b7016e103a49dec6ac4ae [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->level_estimator()->Enable(true));
200 EXPECT_NOERR(ap->noise_suppression()->Enable(true));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000201}
202
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000203// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000204template <class T>
205T AbsValue(T a) {
Jonas Olssona4d87372019-07-05 19:08:33 +0200206 return a > 0 ? a : -a;
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000207}
208
209int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800210 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700211 const int16_t* frame_data = frame.data();
212 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800213 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700214 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000215 }
216
217 return max_data;
218}
219
Alex Loiko890988c2017-08-31 10:25:48 +0200220void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700221 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000222 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000223 ASSERT_TRUE(file != NULL);
224
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100225 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000226 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800227 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000228 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000229
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000230 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000231 ASSERT_EQ(static_cast<size_t>(size),
Jonas Olssona4d87372019-07-05 19:08:33 +0200232 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000233 fclose(file);
234}
235
Alex Loiko890988c2017-08-31 10:25:48 +0200236std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200237 rtc::StringBuilder ss;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000238 // Resource files are all stereo.
239 ss << name << sample_rate_hz / 1000 << "_stereo";
240 return test::ResourcePath(ss.str(), "pcm");
241}
242
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000243// Temporary filenames unique to this process. Used to be able to run these
244// tests in parallel as each process needs to be running in isolation they can't
245// have competing filenames.
246std::map<std::string, std::string> temp_filenames;
247
Alex Loiko890988c2017-08-31 10:25:48 +0200248std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000249 int input_rate,
250 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700251 int reverse_input_rate,
252 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800253 size_t num_input_channels,
254 size_t num_output_channels,
255 size_t num_reverse_input_channels,
256 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700257 StreamDirection file_direction) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200258 rtc::StringBuilder ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700259 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
260 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000261 if (num_output_channels == 1) {
262 ss << "mono";
263 } else if (num_output_channels == 2) {
264 ss << "stereo";
265 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700266 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000267 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700268 ss << output_rate / 1000;
269 if (num_reverse_output_channels == 1) {
270 ss << "_rmono";
271 } else if (num_reverse_output_channels == 2) {
272 ss << "_rstereo";
273 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700274 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700275 }
276 ss << reverse_output_rate / 1000;
277 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000278
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000279 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700280 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000281 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
282 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000283}
284
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000285void ClearTempFiles() {
286 for (auto& kv : temp_filenames)
287 remove(kv.second.c_str());
288}
289
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200290// Only remove "out" files. Keep "ref" files.
291void ClearTempOutFiles() {
292 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
293 const std::string& filename = it->first;
294 if (filename.substr(0, 3).compare("out") == 0) {
295 remove(it->second.c_str());
296 temp_filenames.erase(it++);
297 } else {
298 it++;
299 }
300 }
301}
302
Alex Loiko890988c2017-08-31 10:25:48 +0200303void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000304 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000305 ASSERT_TRUE(file != NULL);
306 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000307 fclose(file);
308}
309
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000310// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
311// stereo) file, converts to deinterleaved float (optionally downmixing) and
312// returns the result in |cb|. Returns false if the file ended (or on error) and
313// true otherwise.
314//
315// |int_data| and |float_data| are just temporary space that must be
316// sufficiently large to hold the 10 ms chunk.
Jonas Olssona4d87372019-07-05 19:08:33 +0200317bool ReadChunk(FILE* file,
318 int16_t* int_data,
319 float* float_data,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000320 ChannelBuffer<float>* cb) {
321 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000322 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000323 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
324 if (read_count != frame_size) {
325 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700326 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000327 return false; // This is expected.
328 }
329
330 S16ToFloat(int_data, frame_size, float_data);
331 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000332 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000333 } else {
Jonas Olssona4d87372019-07-05 19:08:33 +0200334 Deinterleave(float_data, cb->num_frames(), 2, cb->channels());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000335 }
336
337 return true;
338}
339
niklase@google.com470e71d2011-07-07 08:21:25 +0000340class ApmTest : public ::testing::Test {
341 protected:
342 ApmTest();
343 virtual void SetUp();
344 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000345
Mirko Bonadei71061bc2019-06-04 09:01:51 +0200346 static void SetUpTestSuite() {}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000347
Mirko Bonadei71061bc2019-06-04 09:01:51 +0200348 static void TearDownTestSuite() { ClearTempFiles(); }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000349
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000350 // Used to select between int and float interface tests.
Jonas Olssona4d87372019-07-05 19:08:33 +0200351 enum Format { kIntFormat, kFloatFormat };
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000352
353 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000354 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000355 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800356 size_t num_input_channels,
357 size_t num_output_channels,
358 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000359 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000360 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000361 void EnableAllComponents();
362 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000363 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000364 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
Jonas Olssona4d87372019-07-05 19:08:33 +0200365 void ReadFrameWithRewind(FILE* file,
366 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000367 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000368 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
Jonas Olssona4d87372019-07-05 19:08:33 +0200369 void ProcessDelayVerificationTest(int delay_ms,
370 int system_delay_ms,
371 int delay_min,
372 int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700373 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800374 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700375 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800376 void TestChangingForwardChannels(size_t num_in_channels,
377 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700378 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800379 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700380 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000381 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
382 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000383 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000384 int ProcessStreamChooser(Format format);
385 int AnalyzeReverseStreamChooser(Format format);
386 void ProcessDebugDump(const std::string& in_filename,
387 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800388 Format format,
389 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000390 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000391
392 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000393 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800394 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000395 AudioFrame* frame_;
396 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800397 std::unique_ptr<ChannelBuffer<float> > float_cb_;
398 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000399 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800400 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000401 FILE* far_file_;
402 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000403 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000404};
405
406ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000407 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000408#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +0200409 ref_filename_(
410 test::ResourcePath("audio_processing/output_data_fixed", "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000411#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +0200412 ref_filename_(
413 test::ResourcePath("audio_processing/output_data_float", "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000414#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000415 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000416 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000417 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000418 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000419 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000420 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000421 out_file_(NULL) {
422 Config config;
423 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100424 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000425}
niklase@google.com470e71d2011-07-07 08:21:25 +0000426
427void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000428 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000429
430 frame_ = new AudioFrame();
431 revframe_ = new AudioFrame();
432
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000433 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000434}
435
436void ApmTest::TearDown() {
437 if (frame_) {
438 delete frame_;
439 }
440 frame_ = NULL;
441
442 if (revframe_) {
443 delete revframe_;
444 }
445 revframe_ = NULL;
446
447 if (far_file_) {
448 ASSERT_EQ(0, fclose(far_file_));
449 }
450 far_file_ = NULL;
451
452 if (near_file_) {
453 ASSERT_EQ(0, fclose(near_file_));
454 }
455 near_file_ = NULL;
456
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000457 if (out_file_) {
458 ASSERT_EQ(0, fclose(out_file_));
459 }
460 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000461}
462
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000463void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000464 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700465 ap->Initialize(
466 {{{frame_->sample_rate_hz_, frame_->num_channels_},
467 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700468 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700469 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000470}
471
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000472void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000473 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000474 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800475 size_t num_input_channels,
476 size_t num_output_channels,
477 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000478 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000479 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000480 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000481 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000482
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000483 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
484 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000485 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000486
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000487 if (far_file_) {
488 ASSERT_EQ(0, fclose(far_file_));
489 }
490 std::string filename = ResourceFilePath("far", sample_rate_hz);
491 far_file_ = fopen(filename.c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200492 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000493
494 if (near_file_) {
495 ASSERT_EQ(0, fclose(near_file_));
496 }
497 filename = ResourceFilePath("near", sample_rate_hz);
498 near_file_ = fopen(filename.c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200499 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000500
501 if (open_output_file) {
502 if (out_file_) {
503 ASSERT_EQ(0, fclose(out_file_));
504 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700505 filename = OutputFilePath(
506 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
507 reverse_sample_rate_hz, num_input_channels, num_output_channels,
508 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000509 out_file_ = fopen(filename.c_str(), "wb");
Jonas Olssona4d87372019-07-05 19:08:33 +0200510 ASSERT_TRUE(out_file_ != NULL)
511 << "Could not open file " << filename << "\n";
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000512 }
513}
514
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000515void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000516 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000517}
518
Jonas Olssona4d87372019-07-05 19:08:33 +0200519bool ApmTest::ReadFrame(FILE* file,
520 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000521 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000522 // The files always contain stereo audio.
523 size_t frame_size = frame->samples_per_channel_ * 2;
Jonas Olssona4d87372019-07-05 19:08:33 +0200524 size_t read_count =
525 fread(frame->mutable_data(), sizeof(int16_t), frame_size, file);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000526 if (read_count != frame_size) {
527 // Check that the file really ended.
528 EXPECT_NE(0, feof(file));
529 return false; // This is expected.
530 }
531
532 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700533 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000534 frame->samples_per_channel_);
535 }
536
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000537 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000538 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000539 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000540 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000541}
542
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000543bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
544 return ReadFrame(file, frame, NULL);
545}
546
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000547// If the end of the file has been reached, rewind it and attempt to read the
548// frame again.
Jonas Olssona4d87372019-07-05 19:08:33 +0200549void ApmTest::ReadFrameWithRewind(FILE* file,
550 AudioFrame* frame,
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000551 ChannelBuffer<float>* cb) {
552 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000553 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000554 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000555 }
556}
557
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000558void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
559 ReadFrameWithRewind(file, frame, NULL);
560}
561
andrew@webrtc.org81865342012-10-27 00:28:27 +0000562void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
563 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
Jonas Olssona4d87372019-07-05 19:08:33 +0200564 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000565 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000566}
567
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000568int ApmTest::ProcessStreamChooser(Format format) {
569 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000570 return apm_->ProcessStream(frame_);
571 }
Jonas Olssona4d87372019-07-05 19:08:33 +0200572 return apm_->ProcessStream(
573 float_cb_->channels(), frame_->samples_per_channel_,
574 frame_->sample_rate_hz_, LayoutFromChannels(frame_->num_channels_),
575 output_sample_rate_hz_, LayoutFromChannels(num_output_channels_),
576 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000577}
578
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000579int ApmTest::AnalyzeReverseStreamChooser(Format format) {
580 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700581 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000582 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000583 return apm_->AnalyzeReverseStream(
Jonas Olssona4d87372019-07-05 19:08:33 +0200584 revfloat_cb_->channels(), revframe_->samples_per_channel_,
585 revframe_->sample_rate_hz_, LayoutFromChannels(revframe_->num_channels_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000586}
587
Jonas Olssona4d87372019-07-05 19:08:33 +0200588void ApmTest::ProcessDelayVerificationTest(int delay_ms,
589 int system_delay_ms,
590 int delay_min,
591 int delay_max) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000592 // The |revframe_| and |frame_| should include the proper frame information,
593 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000594 AudioFrame tmp_frame;
595 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000596 bool causal = true;
597
598 tmp_frame.CopyFrom(*revframe_);
599 SetFrameTo(&tmp_frame, 0);
600
601 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
602 // Initialize the |frame_queue| with empty frames.
603 int frame_delay = delay_ms / 10;
604 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000605 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000606 frame->CopyFrom(tmp_frame);
607 frame_queue.push(frame);
608 frame_delay++;
609 causal = false;
610 }
611 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000612 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000613 frame->CopyFrom(tmp_frame);
614 frame_queue.push(frame);
615 frame_delay--;
616 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000617 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
618 // need enough frames with audio to have reliable estimates, but as few as
619 // possible to keep processing time down. 4.5 seconds seemed to be a good
620 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000621 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000622 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000623 frame->CopyFrom(tmp_frame);
624 // Use the near end recording, since that has more speech in it.
625 ASSERT_TRUE(ReadFrame(near_file_, frame));
626 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000627 AudioFrame* reverse_frame = frame;
628 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000629 if (!causal) {
630 reverse_frame = frame_queue.front();
631 // When we call ProcessStream() the frame is modified, so we can't use the
632 // pointer directly when things are non-causal. Use an intermediate frame
633 // and copy the data.
634 process_frame = &tmp_frame;
635 process_frame->CopyFrom(*frame);
636 }
aluebsb0319552016-03-17 20:39:53 -0700637 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000638 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
639 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
640 frame = frame_queue.front();
641 frame_queue.pop();
642 delete frame;
643
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000644 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000645 // Discard the first delay metrics to avoid convergence effects.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200646 static_cast<void>(apm_->GetStatistics(true /* has_remote_tracks */));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000647 }
648 }
649
650 rewind(near_file_);
651 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000652 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000653 frame_queue.pop();
654 delete frame;
655 }
656 // Calculate expected delay estimate and acceptable regions. Further,
657 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700658 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700659 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700660 const int expected_median =
661 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
662 const int expected_median_high = rtc::SafeClamp<int>(
663 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700664 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700665 const int expected_median_low = rtc::SafeClamp<int>(
666 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700667 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000668 // Verify delay metrics.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200669 AudioProcessingStats stats =
670 apm_->GetStatistics(true /* has_remote_tracks */);
671 ASSERT_TRUE(stats.delay_median_ms.has_value());
672 int32_t median = *stats.delay_median_ms;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000673 EXPECT_GE(expected_median_high, median);
674 EXPECT_LE(expected_median_low, median);
675}
676
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000677void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000678 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000679 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000680
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000681 // -- Missing AGC level --
niklase@google.com470e71d2011-07-07 08:21:25 +0000682 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
Jonas Olssona4d87372019-07-05 19:08:33 +0200683 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000684
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000685 // Resets after successful ProcessStream().
Jonas Olssona4d87372019-07-05 19:08:33 +0200686 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000687 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Jonas Olssona4d87372019-07-05 19:08:33 +0200688 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000689
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000690 // Other stream parameters set correctly.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200691 AudioProcessing::Config apm_config = apm_->GetConfig();
692 apm_config.echo_canceller.enabled = true;
693 apm_config.echo_canceller.mobile_mode = false;
694 apm_->ApplyConfig(apm_config);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000695 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
Jonas Olssona4d87372019-07-05 19:08:33 +0200696 EXPECT_EQ(apm_->kStreamParameterNotSetError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000697 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000698
699 // -- Missing delay --
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000700 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100701 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000702
703 // Resets after successful ProcessStream().
704 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000705 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100706 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000707
708 // Other stream parameters set correctly.
709 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
Jonas Olssona4d87372019-07-05 19:08:33 +0200710 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
Per Åhgren200feba2019-03-06 04:16:46 +0100711 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000712 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
713
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000714 // -- No stream parameters --
Jonas Olssona4d87372019-07-05 19:08:33 +0200715 EXPECT_EQ(apm_->kNoError, AnalyzeReverseStreamChooser(format));
Per Åhgren200feba2019-03-06 04:16:46 +0100716 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000717
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000718 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000719 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
Jonas Olssona4d87372019-07-05 19:08:33 +0200720 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000721 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000722}
723
724TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000725 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000726}
727
728TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000729 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000730}
731
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000732TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
733 EXPECT_EQ(0, apm_->delay_offset_ms());
734 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
735 EXPECT_EQ(50, apm_->stream_delay_ms());
736}
737
738TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
739 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000740 apm_->set_delay_offset_ms(100);
741 EXPECT_EQ(100, apm_->delay_offset_ms());
742 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000743 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000744 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
745 EXPECT_EQ(200, apm_->stream_delay_ms());
746
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000747 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000748 apm_->set_delay_offset_ms(-50);
749 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000750 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
751 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000752 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
753 EXPECT_EQ(50, apm_->stream_delay_ms());
754}
755
Michael Graczyk86c6d332015-07-23 11:41:39 -0700756void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800757 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700758 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000759 frame_->num_channels_ = num_channels;
760 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700761 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000762}
763
Michael Graczyk86c6d332015-07-23 11:41:39 -0700764void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800765 size_t num_in_channels,
766 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700767 AudioProcessing::Error expected_return) {
768 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
769 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
770
771 EXPECT_EQ(expected_return,
772 apm_->ProcessStream(float_cb_->channels(), input_stream,
773 output_stream, float_cb_->channels()));
774}
775
776void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800777 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700778 AudioProcessing::Error expected_return) {
779 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700780 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
781 {output_sample_rate_hz_, apm_->num_output_channels()},
782 {frame_->sample_rate_hz_, num_rev_channels},
783 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700784
ekmeyerson60d9b332015-08-14 10:35:55 -0700785 EXPECT_EQ(
786 expected_return,
787 apm_->ProcessReverseStream(
788 float_cb_->channels(), processing_config.reverse_input_stream(),
789 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700790}
791
792TEST_F(ApmTest, ChannelsInt16Interface) {
793 // Testing number of invalid and valid channels.
794 Init(16000, 16000, 16000, 4, 4, 4, false);
795
796 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
797
Peter Kasting69558702016-01-12 16:26:35 -0800798 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700799 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000800 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000801 }
802}
803
Michael Graczyk86c6d332015-07-23 11:41:39 -0700804TEST_F(ApmTest, Channels) {
805 // Testing number of invalid and valid channels.
806 Init(16000, 16000, 16000, 4, 4, 4, false);
807
808 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
809 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
810
Peter Kasting69558702016-01-12 16:26:35 -0800811 for (size_t i = 1; i < 4; ++i) {
812 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700813 // Output channels much be one or match input channels.
814 if (j == 1 || i == j) {
815 TestChangingForwardChannels(i, j, kNoErr);
816 TestChangingReverseChannels(i, kNoErr);
817
818 EXPECT_EQ(i, apm_->num_input_channels());
819 EXPECT_EQ(j, apm_->num_output_channels());
820 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800821 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700822 } else {
823 TestChangingForwardChannels(i, j,
824 AudioProcessing::kBadNumberChannelsError);
825 }
826 }
827 }
828}
829
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000830TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000831 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000832 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000833 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000834 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700835 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800836 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000837 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000838 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000839 }
840}
841
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000842TEST_F(ApmTest, GainControl) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000843 // Testing gain modes
niklase@google.com470e71d2011-07-07 08:21:25 +0000844 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200845 apm_->gain_control()->set_mode(apm_->gain_control()->mode()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000846
Jonas Olssona4d87372019-07-05 19:08:33 +0200847 GainControl::Mode mode[] = {GainControl::kAdaptiveAnalog,
848 GainControl::kAdaptiveDigital,
849 GainControl::kFixedDigital};
pkasting25702cb2016-01-08 13:50:27 -0800850 for (size_t i = 0; i < arraysize(mode); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +0200851 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_mode(mode[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +0000852 EXPECT_EQ(mode[i], apm_->gain_control()->mode());
853 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100854 // Testing target levels
Jonas Olssona4d87372019-07-05 19:08:33 +0200855 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_target_level_dbfs(
856 apm_->gain_control()->target_level_dbfs()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000857
858 int level_dbfs[] = {0, 6, 31};
pkasting25702cb2016-01-08 13:50:27 -0800859 for (size_t i = 0; i < arraysize(level_dbfs); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000860 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200861 apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +0000862 EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
863 }
864
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100865 // Testing compression gains
Jonas Olssona4d87372019-07-05 19:08:33 +0200866 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_compression_gain_db(
867 apm_->gain_control()->compression_gain_db()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000868
869 int gain_db[] = {0, 10, 90};
pkasting25702cb2016-01-08 13:50:27 -0800870 for (size_t i = 0; i < arraysize(gain_db); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000871 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200872 apm_->gain_control()->set_compression_gain_db(gain_db[i]));
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100873 ProcessStreamChooser(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000874 EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
875 }
876
877 // Testing limiter off/on
878 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
879 EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
880 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
881 EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
882
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100883 // Testing level limits
Jonas Olssona4d87372019-07-05 19:08:33 +0200884 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_analog_level_limits(
885 apm_->gain_control()->analog_level_minimum(),
886 apm_->gain_control()->analog_level_maximum()));
niklase@google.com470e71d2011-07-07 08:21:25 +0000887
888 int min_level[] = {0, 255, 1024};
pkasting25702cb2016-01-08 13:50:27 -0800889 for (size_t i = 0; i < arraysize(min_level); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +0200890 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->set_analog_level_limits(
891 min_level[i], 1024));
niklase@google.com470e71d2011-07-07 08:21:25 +0000892 EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
893 }
894
895 int max_level[] = {0, 1024, 65535};
pkasting25702cb2016-01-08 13:50:27 -0800896 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000897 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200898 apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +0000899 EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
900 }
901
902 // TODO(ajm): stream_is_saturated() and stream_analog_level()
903
904 // Turn AGC off
905 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
906 EXPECT_FALSE(apm_->gain_control()->is_enabled());
907}
908
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100909#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
910TEST_F(ApmTest, GainControlDiesOnTooLowTargetLevelDbfs) {
911 EXPECT_DEATH(apm_->gain_control()->set_target_level_dbfs(-1), "");
912}
913
914TEST_F(ApmTest, GainControlDiesOnTooHighTargetLevelDbfs) {
915 EXPECT_DEATH(apm_->gain_control()->set_target_level_dbfs(32), "");
916}
917
918TEST_F(ApmTest, GainControlDiesOnTooLowCompressionGainDb) {
919 EXPECT_DEATH(apm_->gain_control()->set_compression_gain_db(-1), "");
920}
921
922TEST_F(ApmTest, GainControlDiesOnTooHighCompressionGainDb) {
923 EXPECT_DEATH(apm_->gain_control()->set_compression_gain_db(91), "");
924}
925
926TEST_F(ApmTest, GainControlDiesOnTooLowAnalogLevelLowerLimit) {
927 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(-1, 512), "");
928}
929
930TEST_F(ApmTest, GainControlDiesOnTooHighAnalogLevelUpperLimit) {
931 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(512, 65536), "");
932}
933
934TEST_F(ApmTest, GainControlDiesOnInvertedAnalogLevelLimits) {
935 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(512, 255), "");
936}
937
938TEST_F(ApmTest, ApmDiesOnTooLowAnalogLevel) {
939 apm_->gain_control()->set_analog_level_limits(255, 512);
940 EXPECT_DEATH(apm_->set_stream_analog_level(254), "");
941}
942
943TEST_F(ApmTest, ApmDiesOnTooHighAnalogLevel) {
944 apm_->gain_control()->set_analog_level_limits(255, 512);
945 EXPECT_DEATH(apm_->set_stream_analog_level(513), "");
946}
947#endif
948
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000949void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000950 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000951 EXPECT_EQ(apm_->kNoError,
952 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
953 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
954
955 int out_analog_level = 0;
956 for (int i = 0; i < 2000; ++i) {
957 ReadFrameWithRewind(near_file_, frame_);
958 // Ensure the audio is at a low level, so the AGC will try to increase it.
959 ScaleFrame(frame_, 0.25);
960
961 // Always pass in the same volume.
962 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200963 apm_->gain_control()->set_stream_analog_level(100));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000964 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
965 out_analog_level = apm_->gain_control()->stream_analog_level();
966 }
967
968 // Ensure the AGC is still able to reach the maximum.
969 EXPECT_EQ(255, out_analog_level);
970}
971
972// Verifies that despite volume slider quantization, the AGC can continue to
973// increase its volume.
974TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -0800975 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000976 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
977 }
978}
979
980void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000981 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000982 EXPECT_EQ(apm_->kNoError,
983 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
984 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
985
986 int out_analog_level = 100;
987 for (int i = 0; i < 1000; ++i) {
988 ReadFrameWithRewind(near_file_, frame_);
989 // Ensure the audio is at a low level, so the AGC will try to increase it.
990 ScaleFrame(frame_, 0.25);
991
992 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +0200993 apm_->gain_control()->set_stream_analog_level(out_analog_level));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000994 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
995 out_analog_level = apm_->gain_control()->stream_analog_level();
996 }
997
998 // Ensure the volume was raised.
999 EXPECT_GT(out_analog_level, 100);
1000 int highest_level_reached = out_analog_level;
1001 // Simulate a user manual volume change.
1002 out_analog_level = 100;
1003
1004 for (int i = 0; i < 300; ++i) {
1005 ReadFrameWithRewind(near_file_, frame_);
1006 ScaleFrame(frame_, 0.25);
1007
1008 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +02001009 apm_->gain_control()->set_stream_analog_level(out_analog_level));
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001010 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1011 out_analog_level = apm_->gain_control()->stream_analog_level();
1012 // Check that AGC respected the manually adjusted volume.
1013 EXPECT_LT(out_analog_level, highest_level_reached);
1014 }
1015 // Check that the volume was still raised.
1016 EXPECT_GT(out_analog_level, 100);
1017}
1018
1019TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001020 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001021 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1022 }
1023}
1024
niklase@google.com470e71d2011-07-07 08:21:25 +00001025TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001026 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001027 NoiseSuppression::Level level[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001028 NoiseSuppression::kLow, NoiseSuppression::kModerate,
1029 NoiseSuppression::kHigh, NoiseSuppression::kVeryHigh};
pkasting25702cb2016-01-08 13:50:27 -08001030 for (size_t i = 0; i < arraysize(level); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001031 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->set_level(level[i]));
niklase@google.com470e71d2011-07-07 08:21:25 +00001032 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1033 }
1034
andrew@webrtc.org648af742012-02-08 01:57:29 +00001035 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001036 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1037 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1038 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1039 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1040}
1041
1042TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001043 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001044 AudioProcessing::Config apm_config;
1045 apm_config.high_pass_filter.enabled = true;
1046 apm_->ApplyConfig(apm_config);
1047 apm_config.high_pass_filter.enabled = false;
1048 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001049}
1050
1051TEST_F(ApmTest, LevelEstimator) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001052 // Turn level estimator on/off
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001053 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001054 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001055
1056 EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1057
1058 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1059 EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1060
1061 // Run this test in wideband; in super-wb, the splitting filter distorts the
1062 // audio enough to cause deviation from the expectation for small values.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001063 frame_->samples_per_channel_ = 160;
1064 frame_->num_channels_ = 2;
1065 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001066
1067 // Min value if no frames have been processed.
1068 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1069
1070 // Min value on zero frames.
1071 SetFrameTo(frame_, 0);
1072 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1073 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1074 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1075
1076 // Try a few RMS values.
1077 // (These also test that the value resets after retrieving it.)
1078 SetFrameTo(frame_, 32767);
1079 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1080 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1081 EXPECT_EQ(0, apm_->level_estimator()->RMS());
1082
1083 SetFrameTo(frame_, 30000);
1084 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1085 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1086 EXPECT_EQ(1, apm_->level_estimator()->RMS());
1087
1088 SetFrameTo(frame_, 10000);
1089 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1090 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1091 EXPECT_EQ(10, apm_->level_estimator()->RMS());
1092
1093 SetFrameTo(frame_, 10);
1094 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1095 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1096 EXPECT_EQ(70, apm_->level_estimator()->RMS());
1097
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001098 // Verify reset after enable/disable.
1099 SetFrameTo(frame_, 32767);
1100 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1101 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1102 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1103 SetFrameTo(frame_, 1);
1104 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1105 EXPECT_EQ(90, apm_->level_estimator()->RMS());
1106
1107 // Verify reset after initialize.
1108 SetFrameTo(frame_, 32767);
1109 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1110 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1111 SetFrameTo(frame_, 1);
1112 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1113 EXPECT_EQ(90, apm_->level_estimator()->RMS());
niklase@google.com470e71d2011-07-07 08:21:25 +00001114}
1115
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001116TEST_F(ApmTest, AllProcessingDisabledByDefault) {
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001117 AudioProcessing::Config config = apm_->GetConfig();
1118 EXPECT_FALSE(config.echo_canceller.enabled);
1119 EXPECT_FALSE(config.high_pass_filter.enabled);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001120 EXPECT_FALSE(config.level_estimation.enabled);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001121 EXPECT_FALSE(config.voice_detection.enabled);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001122 EXPECT_FALSE(apm_->gain_control()->is_enabled());
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001123 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1124 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001125}
1126
1127TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001128 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001129 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001130 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001131 AudioFrame frame_copy;
1132 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001133 for (int j = 0; j < 1000; j++) {
1134 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1135 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001136 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1137 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001138 }
1139 }
1140}
1141
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001142TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1143 // Test that ProcessStream copies input to output even with no processing.
Per Åhgrenc8626b62019-08-23 15:49:51 +02001144 const size_t kSamples = 160;
1145 const int sample_rate = 16000;
Jonas Olssona4d87372019-07-05 19:08:33 +02001146 const float src[kSamples] = {-1.0f, 0.0f, 1.0f};
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001147 float dest[kSamples] = {};
1148
1149 auto src_channels = &src[0];
1150 auto dest_channels = &dest[0];
1151
Ivo Creusen62337e52018-01-09 14:17:33 +01001152 apm_.reset(AudioProcessingBuilder().Create());
Jonas Olssona4d87372019-07-05 19:08:33 +02001153 EXPECT_NOERR(apm_->ProcessStream(&src_channels, kSamples, sample_rate,
1154 LayoutFromChannels(1), sample_rate,
1155 LayoutFromChannels(1), &dest_channels));
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001156
1157 for (size_t i = 0; i < kSamples; ++i) {
1158 EXPECT_EQ(src[i], dest[i]);
1159 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001160
1161 // Same for ProcessReverseStream.
1162 float rev_dest[kSamples] = {};
1163 auto rev_dest_channels = &rev_dest[0];
1164
1165 StreamConfig input_stream = {sample_rate, 1};
1166 StreamConfig output_stream = {sample_rate, 1};
1167 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1168 output_stream, &rev_dest_channels));
1169
1170 for (size_t i = 0; i < kSamples; ++i) {
1171 EXPECT_EQ(src[i], rev_dest[i]);
1172 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001173}
1174
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001175TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1176 EnableAllComponents();
1177
pkasting25702cb2016-01-08 13:50:27 -08001178 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001179 Init(kProcessSampleRates[i], kProcessSampleRates[i], kProcessSampleRates[i],
1180 2, 2, 2, false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001181 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001182 ASSERT_EQ(0, feof(far_file_));
1183 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001184 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001185 CopyLeftToRightChannel(revframe_->mutable_data(),
1186 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001187
aluebsb0319552016-03-17 20:39:53 -07001188 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001189
yujo36b1a5f2017-06-12 12:45:32 -07001190 CopyLeftToRightChannel(frame_->mutable_data(),
1191 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001192 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1193
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001194 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001195 ASSERT_EQ(kNoErr,
Jonas Olssona4d87372019-07-05 19:08:33 +02001196 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001197 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001198 analog_level = apm_->gain_control()->stream_analog_level();
1199
yujo36b1a5f2017-06-12 12:45:32 -07001200 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001201 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001202 rewind(far_file_);
1203 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001204 }
1205}
1206
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001207TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001208 // Verify the filter is not active through undistorted audio when:
1209 // 1. No components are enabled...
1210 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001211 AudioFrame frame_copy;
1212 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001213 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1214 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1215 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1216
1217 // 2. Only the level estimator is enabled...
1218 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001219 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001220 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1221 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1222 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1223 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1224 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1225
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001226 // 3. Only GetStatistics-reporting VAD is enabled...
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001227 SetFrameTo(frame_, 1000);
1228 frame_copy.CopyFrom(*frame_);
1229 auto apm_config = apm_->GetConfig();
1230 apm_config.voice_detection.enabled = true;
1231 apm_->ApplyConfig(apm_config);
1232 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1233 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1234 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1235 apm_config.voice_detection.enabled = false;
1236 apm_->ApplyConfig(apm_config);
1237
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001238 // 4. Both the VAD and the level estimator are enabled...
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001239 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001240 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001241 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001242 apm_config.voice_detection.enabled = true;
1243 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001244 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1245 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1246 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1247 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001248 apm_config.voice_detection.enabled = false;
1249 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001250
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001251 // Check the test is valid. We should have distortion from the filter
1252 // when AEC is enabled (which won't affect the audio).
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001253 apm_config.echo_canceller.enabled = true;
1254 apm_config.echo_canceller.mobile_mode = false;
1255 apm_->ApplyConfig(apm_config);
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001256 frame_->samples_per_channel_ = 320;
1257 frame_->num_channels_ = 2;
1258 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001259 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001260 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001261 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001262 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1263 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1264}
1265
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001266#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1267void ApmTest::ProcessDebugDump(const std::string& in_filename,
1268 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001269 Format format,
1270 int max_size_bytes) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001271 TaskQueueForTest worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001272 FILE* in_file = fopen(in_filename.c_str(), "rb");
1273 ASSERT_TRUE(in_file != NULL);
1274 audioproc::Event event_msg;
1275 bool first_init = true;
1276
1277 while (ReadMessageFromFile(in_file, &event_msg)) {
1278 if (event_msg.type() == audioproc::Event::INIT) {
1279 const audioproc::Init msg = event_msg.init();
1280 int reverse_sample_rate = msg.sample_rate();
1281 if (msg.has_reverse_sample_rate()) {
1282 reverse_sample_rate = msg.reverse_sample_rate();
1283 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001284 int output_sample_rate = msg.sample_rate();
1285 if (msg.has_output_sample_rate()) {
1286 output_sample_rate = msg.output_sample_rate();
1287 }
1288
Jonas Olssona4d87372019-07-05 19:08:33 +02001289 Init(msg.sample_rate(), output_sample_rate, reverse_sample_rate,
1290 msg.num_input_channels(), msg.num_output_channels(),
1291 msg.num_reverse_channels(), false);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001292 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001293 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001294 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001295 auto aec_dump =
1296 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1297 EXPECT_TRUE(aec_dump);
1298 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001299 first_init = false;
1300 }
1301
1302 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1303 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1304
1305 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001306 ASSERT_EQ(revframe_->num_channels_,
1307 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001308 for (int i = 0; i < msg.channel_size(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001309 memcpy(revfloat_cb_->channels()[i], msg.channel(i).data(),
1310 msg.channel(i).size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001311 }
1312 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001313 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001314 if (format == kFloatFormat) {
1315 // We're using an int16 input file; convert to float.
1316 ConvertToFloat(*revframe_, revfloat_cb_.get());
1317 }
1318 }
1319 AnalyzeReverseStreamChooser(format);
1320
1321 } else if (event_msg.type() == audioproc::Event::STREAM) {
1322 const audioproc::Stream msg = event_msg.stream();
1323 // ProcessStream could have changed this for the output frame.
1324 frame_->num_channels_ = apm_->num_input_channels();
1325
1326 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1327 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001328 if (msg.has_keypress()) {
1329 apm_->set_stream_key_pressed(msg.keypress());
1330 } else {
1331 apm_->set_stream_key_pressed(true);
1332 }
1333
1334 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001335 ASSERT_EQ(frame_->num_channels_,
1336 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001337 for (int i = 0; i < msg.input_channel_size(); ++i) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001338 memcpy(float_cb_->channels()[i], msg.input_channel(i).data(),
1339 msg.input_channel(i).size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001340 }
1341 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001342 memcpy(frame_->mutable_data(), msg.input_data().data(),
1343 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001344 if (format == kFloatFormat) {
1345 // We're using an int16 input file; convert to float.
1346 ConvertToFloat(*frame_, float_cb_.get());
1347 }
1348 }
1349 ProcessStreamChooser(format);
1350 }
1351 }
aleloif4dd1912017-06-15 01:55:38 -07001352 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001353 fclose(in_file);
1354}
1355
1356void ApmTest::VerifyDebugDumpTest(Format format) {
Minyue Li656d6092018-08-10 15:38:52 +02001357 rtc::ScopedFakeClock fake_clock;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001358 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001359 std::string format_string;
1360 switch (format) {
1361 case kIntFormat:
1362 format_string = "_int";
1363 break;
1364 case kFloatFormat:
1365 format_string = "_float";
1366 break;
1367 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001368 const std::string ref_filename = test::TempFilename(
1369 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1370 const std::string out_filename = test::TempFilename(
1371 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001372 const std::string limited_filename = test::TempFilename(
1373 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1374 const size_t logging_limit_bytes = 100000;
1375 // We expect at least this many bytes in the created logfile.
1376 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001377 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001378 ProcessDebugDump(in_filename, ref_filename, format, -1);
1379 ProcessDebugDump(ref_filename, out_filename, format, -1);
1380 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001381
1382 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1383 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001384 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001385 ASSERT_TRUE(ref_file != NULL);
1386 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001387 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001388 std::unique_ptr<uint8_t[]> ref_bytes;
1389 std::unique_ptr<uint8_t[]> out_bytes;
1390 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001391
1392 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1393 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001394 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001395 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001396 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001397 while (ref_size > 0 && out_size > 0) {
1398 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001399 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001400 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001401 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001402 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001403 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001404 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1405 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001406 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001407 }
1408 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001409 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1410 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001411 EXPECT_NE(0, feof(ref_file));
1412 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001413 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001414 ASSERT_EQ(0, fclose(ref_file));
1415 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001416 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001417 remove(ref_filename.c_str());
1418 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001419 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001420}
1421
pbosc7a65692016-05-06 12:50:04 -07001422TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001423 VerifyDebugDumpTest(kIntFormat);
1424}
1425
pbosc7a65692016-05-06 12:50:04 -07001426TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001427 VerifyDebugDumpTest(kFloatFormat);
1428}
1429#endif
1430
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001431// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001432TEST_F(ApmTest, DebugDump) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001433 TaskQueueForTest worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001434 const std::string filename =
1435 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001436 {
1437 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1438 EXPECT_FALSE(aec_dump);
1439 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001440
1441#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1442 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001443 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001444
aleloif4dd1912017-06-15 01:55:38 -07001445 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1446 EXPECT_TRUE(aec_dump);
1447 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001448 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001449 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001450 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001451
1452 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001453 FILE* fid = fopen(filename.c_str(), "r");
1454 ASSERT_TRUE(fid != NULL);
1455
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001456 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001457 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001458 ASSERT_EQ(0, remove(filename.c_str()));
1459#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001460 // Verify the file has NOT been written.
1461 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1462#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1463}
1464
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001465// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001466TEST_F(ApmTest, DebugDumpFromFileHandle) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001467 TaskQueueForTest worker_queue("ApmTest_worker_queue");
aleloif4dd1912017-06-15 01:55:38 -07001468
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001469 const std::string filename =
1470 test::TempFilename(test::OutputPath(), "debug_aec");
Niels Möllere8e4dc42019-06-11 14:04:16 +02001471 FileWrapper f = FileWrapper::OpenWriteOnly(filename.c_str());
1472 ASSERT_TRUE(f.is_open());
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001473
1474#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1475 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001476 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001477
Niels Möllere8e4dc42019-06-11 14:04:16 +02001478 auto aec_dump = AecDumpFactory::Create(std::move(f), -1, &worker_queue);
aleloif4dd1912017-06-15 01:55:38 -07001479 EXPECT_TRUE(aec_dump);
1480 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001481 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001482 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001483 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001484
1485 // Verify the file has been written.
Niels Möllere8e4dc42019-06-11 14:04:16 +02001486 FILE* fid = fopen(filename.c_str(), "r");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001487 ASSERT_TRUE(fid != NULL);
1488
1489 // Clean it up.
1490 ASSERT_EQ(0, fclose(fid));
1491 ASSERT_EQ(0, remove(filename.c_str()));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001492#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1493}
1494
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001495// TODO(andrew): Add a test to process a few frames with different combinations
1496// of enabled components.
1497
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001498TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001499 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001500 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001501
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001502 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001503 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001504 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001505 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08001506 for (size_t i = 0; i < arraysize(kChannels); i++) {
1507 for (size_t j = 0; j < arraysize(kChannels); j++) {
1508 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001509 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001510 test->set_num_reverse_channels(kChannels[i]);
1511 test->set_num_input_channels(kChannels[j]);
1512 test->set_num_output_channels(kChannels[j]);
1513 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001514 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001515 }
1516 }
1517 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001518#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1519 // To test the extended filter mode.
1520 audioproc::Test* test = ref_data.add_test();
1521 test->set_num_reverse_channels(2);
1522 test->set_num_input_channels(2);
1523 test->set_num_output_channels(2);
1524 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
1525 test->set_use_aec_extended_filter(true);
1526#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001527 }
1528
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001529 for (int i = 0; i < ref_data.test_size(); i++) {
1530 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001531
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001532 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001533 // TODO(ajm): We no longer allow different input and output channels. Skip
1534 // these tests for now, but they should be removed from the set.
1535 if (test->num_input_channels() != test->num_output_channels())
1536 continue;
1537
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001538 Config config;
1539 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02001540 config.Set<ExtendedFilter>(
1541 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01001542 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001543
1544 EnableAllComponents();
1545
Jonas Olssona4d87372019-07-05 19:08:33 +02001546 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08001547 static_cast<size_t>(test->num_input_channels()),
1548 static_cast<size_t>(test->num_output_channels()),
Jonas Olssona4d87372019-07-05 19:08:33 +02001549 static_cast<size_t>(test->num_reverse_channels()), true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001550
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001551 int frame_count = 0;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001552 int has_voice_count = 0;
1553 int is_saturated_count = 0;
1554 int analog_level = 127;
1555 int analog_level_average = 0;
1556 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001557 float ns_speech_prob_average = 0.0f;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001558 float rms_dbfs_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07001559#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Jonas Olssona4d87372019-07-05 19:08:33 +02001560 int stats_index = 0;
minyue58530ed2016-05-24 05:50:12 -07001561#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001562
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001563 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07001564 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001565
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001566 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1567
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001568 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001569 EXPECT_EQ(apm_->kNoError,
Jonas Olssona4d87372019-07-05 19:08:33 +02001570 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001571
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001572 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001573
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001574 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08001575 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
1576 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001577
1578 max_output_average += MaxAudioFrame(*frame_);
1579
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001580 analog_level = apm_->gain_control()->stream_analog_level();
1581 analog_level_average += analog_level;
1582 if (apm_->gain_control()->stream_is_saturated()) {
1583 is_saturated_count++;
1584 }
Sam Zackrisson11b87032018-12-18 17:13:58 +01001585 AudioProcessingStats stats =
1586 apm_->GetStatistics(/*has_remote_tracks=*/false);
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001587 EXPECT_TRUE(stats.voice_detected);
1588 EXPECT_TRUE(stats.output_rms_dbfs);
1589 has_voice_count += *stats.voice_detected ? 1 : 0;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001590 rms_dbfs_average += *stats.output_rms_dbfs;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001591
Sam Zackrisson0824c6f2019-10-07 14:03:56 +02001592 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
1593
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001594 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
Jonas Olssona4d87372019-07-05 19:08:33 +02001595 size_t write_count =
1596 fwrite(frame_->data(), sizeof(int16_t), frame_size, out_file_);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001597 ASSERT_EQ(frame_size, write_count);
1598
1599 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08001600 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001601 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07001602
1603#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1604 const int kStatsAggregationFrameNum = 100; // 1 second.
1605 if (frame_count % kStatsAggregationFrameNum == 0) {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001606 // Get echo and delay metrics.
1607 AudioProcessingStats stats =
1608 apm_->GetStatistics(true /* has_remote_tracks */);
minyue58530ed2016-05-24 05:50:12 -07001609
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001610 // Echo metrics.
1611 const float echo_return_loss = stats.echo_return_loss.value_or(-1.0f);
1612 const float echo_return_loss_enhancement =
1613 stats.echo_return_loss_enhancement.value_or(-1.0f);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001614 const float residual_echo_likelihood =
1615 stats.residual_echo_likelihood.value_or(-1.0f);
1616 const float residual_echo_likelihood_recent_max =
1617 stats.residual_echo_likelihood_recent_max.value_or(-1.0f);
1618
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001619 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
minyue58530ed2016-05-24 05:50:12 -07001620 const audioproc::Test::EchoMetrics& reference =
1621 test->echo_metrics(stats_index);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001622 constexpr float kEpsilon = 0.01;
1623 EXPECT_NEAR(echo_return_loss, reference.echo_return_loss(), kEpsilon);
1624 EXPECT_NEAR(echo_return_loss_enhancement,
1625 reference.echo_return_loss_enhancement(), kEpsilon);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001626 EXPECT_NEAR(residual_echo_likelihood,
1627 reference.residual_echo_likelihood(), kEpsilon);
1628 EXPECT_NEAR(residual_echo_likelihood_recent_max,
1629 reference.residual_echo_likelihood_recent_max(),
1630 kEpsilon);
minyue58530ed2016-05-24 05:50:12 -07001631 ++stats_index;
1632 } else {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001633 audioproc::Test::EchoMetrics* message_echo = test->add_echo_metrics();
1634 message_echo->set_echo_return_loss(echo_return_loss);
1635 message_echo->set_echo_return_loss_enhancement(
1636 echo_return_loss_enhancement);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001637 message_echo->set_residual_echo_likelihood(residual_echo_likelihood);
1638 message_echo->set_residual_echo_likelihood_recent_max(
1639 residual_echo_likelihood_recent_max);
minyue58530ed2016-05-24 05:50:12 -07001640 }
1641 }
1642#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001643 }
1644 max_output_average /= frame_count;
1645 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001646 ns_speech_prob_average /= frame_count;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001647 rms_dbfs_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001648
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001649 if (!absl::GetFlag(FLAGS_write_apm_ref_data)) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001650 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001651 // When running the test on a N7 we get a {2, 6} difference of
1652 // |has_voice_count| and |max_output_average| is up to 18 higher.
1653 // All numbers being consistently higher on N7 compare to ref_data.
1654 // TODO(bjornv): If we start getting more of these offsets on Android we
1655 // should consider a different approach. Either using one slack for all,
1656 // or generate a separate android reference.
Kári Tristan Helgason640106e2018-09-06 15:29:45 +02001657#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001658 const int kHasVoiceCountOffset = 3;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001659 const int kHasVoiceCountNear = 8;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001660 const int kMaxOutputAverageOffset = 9;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001661 const int kMaxOutputAverageNear = 26;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001662#else
1663 const int kHasVoiceCountOffset = 0;
1664 const int kHasVoiceCountNear = kIntNear;
1665 const int kMaxOutputAverageOffset = 0;
1666 const int kMaxOutputAverageNear = kIntNear;
1667#endif
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001668 EXPECT_NEAR(test->has_voice_count(),
Jonas Olssona4d87372019-07-05 19:08:33 +02001669 has_voice_count - kHasVoiceCountOffset, kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001670 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001671
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001672 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001673 EXPECT_NEAR(test->max_output_average(),
1674 max_output_average - kMaxOutputAverageOffset,
1675 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00001676#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001677 const double kFloatNear = 0.0005;
Jonas Olssona4d87372019-07-05 19:08:33 +02001678 EXPECT_NEAR(test->ns_speech_probability_average(), ns_speech_prob_average,
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001679 kFloatNear);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001680 EXPECT_NEAR(test->rms_dbfs_average(), rms_dbfs_average, kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001681#endif
1682 } else {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001683 test->set_has_voice_count(has_voice_count);
1684 test->set_is_saturated_count(is_saturated_count);
1685
1686 test->set_analog_level_average(analog_level_average);
1687 test->set_max_output_average(max_output_average);
1688
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00001689#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001690 EXPECT_LE(0.0f, ns_speech_prob_average);
1691 EXPECT_GE(1.0f, ns_speech_prob_average);
1692 test->set_ns_speech_probability_average(ns_speech_prob_average);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001693 test->set_rms_dbfs_average(rms_dbfs_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001694#endif
1695 }
1696
1697 rewind(far_file_);
1698 rewind(near_file_);
1699 }
1700
Sam Zackrisson6558fa52019-08-26 10:12:41 +02001701 if (absl::GetFlag(FLAGS_write_apm_ref_data)) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001702 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001703 }
1704}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001705
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001706TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
1707 struct ChannelFormat {
1708 AudioProcessing::ChannelLayout in_layout;
1709 AudioProcessing::ChannelLayout out_layout;
1710 };
1711 ChannelFormat cf[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001712 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
1713 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
1714 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001715 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001716
Ivo Creusen62337e52018-01-09 14:17:33 +01001717 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001718 // Enable one component just to ensure some processing takes place.
1719 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08001720 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001721 const int in_rate = 44100;
1722 const int out_rate = 48000;
1723 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
1724 TotalChannelsFromLayout(cf[i].in_layout));
1725 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
1726 ChannelsFromLayout(cf[i].out_layout));
1727
1728 // Run over a few chunks.
1729 for (int j = 0; j < 10; ++j) {
Jonas Olssona4d87372019-07-05 19:08:33 +02001730 EXPECT_NOERR(ap->ProcessStream(in_cb.channels(), in_cb.num_frames(),
1731 in_rate, cf[i].in_layout, out_rate,
1732 cf[i].out_layout, out_cb.channels()));
andrew@webrtc.org103657b2014-04-24 18:28:56 +00001733 }
1734 }
1735}
1736
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001737// Compares the reference and test arrays over a region around the expected
1738// delay. Finds the highest SNR in that region and adds the variance and squared
1739// error results to the supplied accumulators.
1740void UpdateBestSNR(const float* ref,
1741 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08001742 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001743 int expected_delay,
1744 double* variance_acc,
1745 double* sq_error_acc) {
1746 double best_snr = std::numeric_limits<double>::min();
1747 double best_variance = 0;
1748 double best_sq_error = 0;
1749 // Search over a region of eight samples around the expected delay.
1750 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
1751 ++delay) {
1752 double sq_error = 0;
1753 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08001754 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001755 double error = test[i + delay] - ref[i];
1756 sq_error += error * error;
1757 variance += ref[i] * ref[i];
1758 }
1759
1760 if (sq_error == 0) {
1761 *variance_acc += variance;
1762 return;
1763 }
1764 double snr = variance / sq_error;
1765 if (snr > best_snr) {
1766 best_snr = snr;
1767 best_variance = variance;
1768 best_sq_error = sq_error;
1769 }
1770 }
1771
1772 *variance_acc += best_variance;
1773 *sq_error_acc += best_sq_error;
1774}
1775
1776// Used to test a multitude of sample rate and channel combinations. It works
1777// by first producing a set of reference files (in SetUpTestCase) that are
1778// assumed to be correct, as the used parameters are verified by other tests
1779// in this collection. Primarily the reference files are all produced at
1780// "native" rates which do not involve any resampling.
1781
1782// Each test pass produces an output file with a particular format. The output
1783// is matched against the reference file closest to its internal processing
1784// format. If necessary the output is resampled back to its process format.
1785// Due to the resampling distortion, we don't expect identical results, but
1786// enforce SNR thresholds which vary depending on the format. 0 is a special
1787// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02001788typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001789class AudioProcessingTest
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001790 : public ::testing::TestWithParam<AudioProcessingTestData> {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001791 public:
1792 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02001793 : input_rate_(std::get<0>(GetParam())),
1794 output_rate_(std::get<1>(GetParam())),
1795 reverse_input_rate_(std::get<2>(GetParam())),
1796 reverse_output_rate_(std::get<3>(GetParam())),
1797 expected_snr_(std::get<4>(GetParam())),
1798 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001799
1800 virtual ~AudioProcessingTest() {}
1801
Mirko Bonadei71061bc2019-06-04 09:01:51 +02001802 static void SetUpTestSuite() {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001803 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07001804 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08001805 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08001806 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
1807 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
1808 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001809 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07001810 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
1811 kNativeRates[i], kNumChannels[j], kNumChannels[j],
1812 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001813 }
1814 }
1815 }
1816 }
1817
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02001818 void TearDown() {
1819 // Remove "out" files after each test.
1820 ClearTempOutFiles();
1821 }
1822
Mirko Bonadei71061bc2019-06-04 09:01:51 +02001823 static void TearDownTestSuite() { ClearTempFiles(); }
ekmeyerson60d9b332015-08-14 10:35:55 -07001824
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001825 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07001826 // to a file specified with |output_file_prefix|. Both forward and reverse
1827 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001828 static void ProcessFormat(int input_rate,
1829 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07001830 int reverse_input_rate,
1831 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08001832 size_t num_input_channels,
1833 size_t num_output_channels,
1834 size_t num_reverse_input_channels,
1835 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02001836 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001837 Config config;
1838 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001839 std::unique_ptr<AudioProcessing> ap(
1840 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001841 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001842
ekmeyerson60d9b332015-08-14 10:35:55 -07001843 ProcessingConfig processing_config = {
1844 {{input_rate, num_input_channels},
1845 {output_rate, num_output_channels},
1846 {reverse_input_rate, num_reverse_input_channels},
1847 {reverse_output_rate, num_reverse_output_channels}}};
1848 ap->Initialize(processing_config);
1849
1850 FILE* far_file =
1851 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001852 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
Jonas Olssona4d87372019-07-05 19:08:33 +02001853 FILE* out_file = fopen(
1854 OutputFilePath(
1855 output_file_prefix, input_rate, output_rate, reverse_input_rate,
1856 reverse_output_rate, num_input_channels, num_output_channels,
1857 num_reverse_input_channels, num_reverse_output_channels, kForward)
1858 .c_str(),
1859 "wb");
1860 FILE* rev_out_file = fopen(
1861 OutputFilePath(
1862 output_file_prefix, input_rate, output_rate, reverse_input_rate,
1863 reverse_output_rate, num_input_channels, num_output_channels,
1864 num_reverse_input_channels, num_reverse_output_channels, kReverse)
1865 .c_str(),
1866 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001867 ASSERT_TRUE(far_file != NULL);
1868 ASSERT_TRUE(near_file != NULL);
1869 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07001870 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001871
1872 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
1873 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07001874 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
1875 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001876 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
1877 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07001878 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
1879 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001880
1881 // Temporary buffers.
1882 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07001883 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
1884 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08001885 std::unique_ptr<float[]> float_data(new float[max_length]);
1886 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001887
1888 int analog_level = 127;
1889 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
1890 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07001891 EXPECT_NOERR(ap->ProcessReverseStream(
1892 rev_cb.channels(), processing_config.reverse_input_stream(),
1893 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001894
1895 EXPECT_NOERR(ap->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001896 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
1897
1898 EXPECT_NOERR(ap->ProcessStream(
Jonas Olssona4d87372019-07-05 19:08:33 +02001899 fwd_cb.channels(), fwd_cb.num_frames(), input_rate,
1900 LayoutFromChannels(num_input_channels), output_rate,
1901 LayoutFromChannels(num_output_channels), out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001902
ekmeyerson60d9b332015-08-14 10:35:55 -07001903 // Dump forward output to file.
1904 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001905 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08001906 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07001907
Jonas Olssona4d87372019-07-05 19:08:33 +02001908 ASSERT_EQ(out_length, fwrite(float_data.get(), sizeof(float_data[0]),
1909 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001910
ekmeyerson60d9b332015-08-14 10:35:55 -07001911 // Dump reverse output to file.
1912 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
1913 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08001914 size_t rev_out_length =
1915 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07001916
Jonas Olssona4d87372019-07-05 19:08:33 +02001917 ASSERT_EQ(rev_out_length, fwrite(float_data.get(), sizeof(float_data[0]),
1918 rev_out_length, rev_out_file));
ekmeyerson60d9b332015-08-14 10:35:55 -07001919
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001920 analog_level = ap->gain_control()->stream_analog_level();
1921 }
1922 fclose(far_file);
1923 fclose(near_file);
1924 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07001925 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001926 }
1927
1928 protected:
1929 int input_rate_;
1930 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07001931 int reverse_input_rate_;
1932 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001933 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07001934 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001935};
1936
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00001937TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001938 struct ChannelFormat {
1939 int num_input;
1940 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07001941 int num_reverse_input;
1942 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001943 };
1944 ChannelFormat cf[] = {
Jonas Olssona4d87372019-07-05 19:08:33 +02001945 {1, 1, 1, 1}, {1, 1, 2, 1}, {2, 1, 1, 1},
1946 {2, 1, 2, 1}, {2, 2, 1, 1}, {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001947 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001948
pkasting25702cb2016-01-08 13:50:27 -08001949 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07001950 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
1951 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
1952 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07001953
ekmeyerson60d9b332015-08-14 10:35:55 -07001954 // Verify output for both directions.
1955 std::vector<StreamDirection> stream_directions;
1956 stream_directions.push_back(kForward);
1957 stream_directions.push_back(kReverse);
1958 for (StreamDirection file_direction : stream_directions) {
1959 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
1960 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
1961 const int out_num =
1962 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
1963 const double expected_snr =
1964 file_direction ? expected_reverse_snr_ : expected_snr_;
1965
1966 const int min_ref_rate = std::min(in_rate, out_rate);
1967 int ref_rate;
1968
1969 if (min_ref_rate > 32000) {
1970 ref_rate = 48000;
1971 } else if (min_ref_rate > 16000) {
1972 ref_rate = 32000;
1973 } else if (min_ref_rate > 8000) {
1974 ref_rate = 16000;
1975 } else {
1976 ref_rate = 8000;
1977 }
aluebs776593b2016-03-15 14:04:58 -07001978#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08001979 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07001980 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08001981 }
1982#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07001983 FILE* out_file = fopen(
1984 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
1985 reverse_output_rate_, cf[i].num_input,
1986 cf[i].num_output, cf[i].num_reverse_input,
Jonas Olssona4d87372019-07-05 19:08:33 +02001987 cf[i].num_reverse_output, file_direction)
1988 .c_str(),
ekmeyerson60d9b332015-08-14 10:35:55 -07001989 "rb");
1990 // The reference files always have matching input and output channels.
Jonas Olssona4d87372019-07-05 19:08:33 +02001991 FILE* ref_file =
1992 fopen(OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
1993 cf[i].num_output, cf[i].num_output,
1994 cf[i].num_reverse_output,
1995 cf[i].num_reverse_output, file_direction)
1996 .c_str(),
1997 "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07001998 ASSERT_TRUE(out_file != NULL);
1999 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002000
pkasting25702cb2016-01-08 13:50:27 -08002001 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2002 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002003 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002004 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002005 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002006 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002007 // Data from the resampled output, in case the reference and output rates
2008 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002009 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002010
ekmeyerson60d9b332015-08-14 10:35:55 -07002011 PushResampler<float> resampler;
2012 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002013
ekmeyerson60d9b332015-08-14 10:35:55 -07002014 // Compute the resampling delay of the output relative to the reference,
2015 // to find the region over which we should search for the best SNR.
2016 float expected_delay_sec = 0;
2017 if (in_rate != ref_rate) {
2018 // Input resampling delay.
2019 expected_delay_sec +=
2020 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2021 }
2022 if (out_rate != ref_rate) {
2023 // Output resampling delay.
2024 expected_delay_sec +=
2025 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2026 // Delay of converting the output back to its processing rate for
2027 // testing.
2028 expected_delay_sec +=
2029 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2030 }
2031 int expected_delay =
Oleh Prypin708eccc2019-03-27 09:38:52 +01002032 std::floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002033
ekmeyerson60d9b332015-08-14 10:35:55 -07002034 double variance = 0;
2035 double sq_error = 0;
2036 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2037 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2038 float* out_ptr = out_data.get();
2039 if (out_rate != ref_rate) {
2040 // Resample the output back to its internal processing rate if
2041 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002042 ASSERT_EQ(ref_length,
2043 static_cast<size_t>(resampler.Resample(
2044 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002045 out_ptr = cmp_data.get();
2046 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002047
ekmeyerson60d9b332015-08-14 10:35:55 -07002048 // Update the |sq_error| and |variance| accumulators with the highest
2049 // SNR of reference vs output.
2050 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2051 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002052 }
2053
ekmeyerson60d9b332015-08-14 10:35:55 -07002054 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2055 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2056 << cf[i].num_input << ", " << cf[i].num_output << ", "
2057 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2058 << ", " << file_direction << "): ";
2059 if (sq_error > 0) {
2060 double snr = 10 * log10(variance / sq_error);
2061 EXPECT_GE(snr, expected_snr);
2062 EXPECT_NE(0, expected_snr);
2063 std::cout << "SNR=" << snr << " dB" << std::endl;
2064 } else {
aluebs776593b2016-03-15 14:04:58 -07002065 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002066 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002067
ekmeyerson60d9b332015-08-14 10:35:55 -07002068 fclose(out_file);
2069 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002070 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002071 }
2072}
2073
2074#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002075INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002076 CommonFormats,
2077 AudioProcessingTest,
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002078 ::testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2079 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2080 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2081 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2082 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2083 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2084 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2085 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2086 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2087 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2088 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2089 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002090
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002091 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2092 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2093 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2094 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2095 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2096 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2097 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2098 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2099 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2100 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2101 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2102 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002103
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002104 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2105 std::make_tuple(32000, 48000, 32000, 48000, 32, 30),
2106 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2107 std::make_tuple(32000, 44100, 48000, 44100, 19, 20),
2108 std::make_tuple(32000, 44100, 32000, 44100, 19, 15),
2109 std::make_tuple(32000, 44100, 16000, 44100, 19, 15),
2110 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2111 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2112 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2113 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2114 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2115 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002116
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002117 std::make_tuple(16000, 48000, 48000, 48000, 24, 0),
2118 std::make_tuple(16000, 48000, 32000, 48000, 24, 30),
2119 std::make_tuple(16000, 48000, 16000, 48000, 24, 20),
2120 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2121 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2122 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2123 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2124 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2125 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2126 std::make_tuple(16000, 16000, 48000, 16000, 39, 20),
2127 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2128 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002129
2130#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002131INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002132 CommonFormats,
2133 AudioProcessingTest,
Per Åhgren0aefbf02019-08-23 21:29:17 +02002134 ::testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 19, 0),
2135 std::make_tuple(48000, 48000, 32000, 48000, 19, 30),
2136 std::make_tuple(48000, 48000, 16000, 48000, 19, 20),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002137 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2138 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2139 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
Per Åhgren0aefbf02019-08-23 21:29:17 +02002140 std::make_tuple(48000, 32000, 48000, 32000, 19, 35),
2141 std::make_tuple(48000, 32000, 32000, 32000, 19, 0),
2142 std::make_tuple(48000, 32000, 16000, 32000, 19, 20),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002143 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2144 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2145 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002146
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002147 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2148 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2149 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2150 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2151 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2152 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
Per Åhgren0aefbf02019-08-23 21:29:17 +02002153 std::make_tuple(44100, 32000, 48000, 32000, 18, 35),
2154 std::make_tuple(44100, 32000, 32000, 32000, 18, 0),
2155 std::make_tuple(44100, 32000, 16000, 32000, 18, 20),
2156 std::make_tuple(44100, 16000, 48000, 16000, 19, 20),
2157 std::make_tuple(44100, 16000, 32000, 16000, 19, 20),
2158 std::make_tuple(44100, 16000, 16000, 16000, 19, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002159
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002160 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2161 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2162 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2163 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2164 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2165 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2166 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2167 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2168 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2169 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2170 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2171 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002172
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002173 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2174 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2175 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2176 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2177 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2178 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2179 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2180 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2181 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2182 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2183 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2184 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002185#endif
2186
Per Åhgren3e8bf282019-08-29 23:38:40 +02002187// Produces a scoped trace debug output.
2188std::string ProduceDebugText(int render_input_sample_rate_hz,
2189 int render_output_sample_rate_hz,
2190 int capture_input_sample_rate_hz,
2191 int capture_output_sample_rate_hz,
2192 size_t render_input_num_channels,
2193 size_t render_output_num_channels,
2194 size_t capture_input_num_channels,
2195 size_t capture_output_num_channels) {
2196 rtc::StringBuilder ss;
2197 ss << "Sample rates:"
2198 << "\n"
2199 << " Render input: " << render_input_sample_rate_hz << " Hz"
2200 << "\n"
2201 << " Render output: " << render_output_sample_rate_hz << " Hz"
2202 << "\n"
2203 << " Capture input: " << capture_input_sample_rate_hz << " Hz"
2204 << "\n"
2205 << " Capture output: " << capture_output_sample_rate_hz << " Hz"
2206 << "\n"
2207 << "Number of channels:"
2208 << "\n"
2209 << " Render input: " << render_input_num_channels << "\n"
2210 << " Render output: " << render_output_num_channels << "\n"
2211 << " Capture input: " << capture_input_num_channels << "\n"
2212 << " Capture output: " << capture_output_num_channels;
2213 return ss.Release();
2214}
2215
2216// Validates that running the audio processing module using various combinations
2217// of sample rates and number of channels works as intended.
2218void RunApmRateAndChannelTest(
2219 rtc::ArrayView<const int> sample_rates_hz,
2220 rtc::ArrayView<const int> render_channel_counts,
2221 rtc::ArrayView<const int> capture_channel_counts) {
2222 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2223 webrtc::AudioProcessing::Config apm_config;
2224 apm_config.echo_canceller.enabled = true;
2225 apm->ApplyConfig(apm_config);
2226
2227 StreamConfig render_input_stream_config;
2228 StreamConfig render_output_stream_config;
2229 StreamConfig capture_input_stream_config;
2230 StreamConfig capture_output_stream_config;
2231
2232 std::vector<float> render_input_frame_channels;
2233 std::vector<float*> render_input_frame;
2234 std::vector<float> render_output_frame_channels;
2235 std::vector<float*> render_output_frame;
2236 std::vector<float> capture_input_frame_channels;
2237 std::vector<float*> capture_input_frame;
2238 std::vector<float> capture_output_frame_channels;
2239 std::vector<float*> capture_output_frame;
2240
2241 for (auto render_input_sample_rate_hz : sample_rates_hz) {
2242 for (auto render_output_sample_rate_hz : sample_rates_hz) {
2243 for (auto capture_input_sample_rate_hz : sample_rates_hz) {
2244 for (auto capture_output_sample_rate_hz : sample_rates_hz) {
2245 for (size_t render_input_num_channels : render_channel_counts) {
2246 for (size_t capture_input_num_channels : capture_channel_counts) {
2247 size_t render_output_num_channels = render_input_num_channels;
2248 size_t capture_output_num_channels = capture_input_num_channels;
2249 auto populate_audio_frame = [](int sample_rate_hz,
2250 size_t num_channels,
2251 StreamConfig* cfg,
2252 std::vector<float>* channels_data,
2253 std::vector<float*>* frame_data) {
2254 cfg->set_sample_rate_hz(sample_rate_hz);
2255 cfg->set_num_channels(num_channels);
2256 cfg->set_has_keyboard(false);
2257
2258 size_t max_frame_size = ceil(sample_rate_hz / 100.f);
2259 channels_data->resize(num_channels * max_frame_size);
2260 std::fill(channels_data->begin(), channels_data->end(), 0.5f);
2261 frame_data->resize(num_channels);
2262 for (size_t channel = 0; channel < num_channels; ++channel) {
2263 (*frame_data)[channel] =
2264 &(*channels_data)[channel * max_frame_size];
2265 }
2266 };
2267
2268 populate_audio_frame(
2269 render_input_sample_rate_hz, render_input_num_channels,
2270 &render_input_stream_config, &render_input_frame_channels,
2271 &render_input_frame);
2272 populate_audio_frame(
2273 render_output_sample_rate_hz, render_output_num_channels,
2274 &render_output_stream_config, &render_output_frame_channels,
2275 &render_output_frame);
2276 populate_audio_frame(
2277 capture_input_sample_rate_hz, capture_input_num_channels,
2278 &capture_input_stream_config, &capture_input_frame_channels,
2279 &capture_input_frame);
2280 populate_audio_frame(
2281 capture_output_sample_rate_hz, capture_output_num_channels,
2282 &capture_output_stream_config, &capture_output_frame_channels,
2283 &capture_output_frame);
2284
2285 for (size_t frame = 0; frame < 2; ++frame) {
2286 SCOPED_TRACE(ProduceDebugText(
2287 render_input_sample_rate_hz, render_output_sample_rate_hz,
2288 capture_input_sample_rate_hz, capture_output_sample_rate_hz,
2289 render_input_num_channels, render_output_num_channels,
2290 render_input_num_channels, capture_output_num_channels));
2291
2292 int result = apm->ProcessReverseStream(
2293 &render_input_frame[0], render_input_stream_config,
2294 render_output_stream_config, &render_output_frame[0]);
2295 EXPECT_EQ(result, AudioProcessing::kNoError);
2296 result = apm->ProcessStream(
2297 &capture_input_frame[0], capture_input_stream_config,
2298 capture_output_stream_config, &capture_output_frame[0]);
2299 EXPECT_EQ(result, AudioProcessing::kNoError);
2300 }
2301 }
2302 }
2303 }
2304 }
2305 }
2306 }
2307}
2308
niklase@google.com470e71d2011-07-07 08:21:25 +00002309} // namespace
peahc19f3122016-10-07 14:54:10 -07002310
Alessio Bazzicac054e782018-04-16 12:10:09 +02002311TEST(RuntimeSettingTest, TestDefaultCtor) {
2312 auto s = AudioProcessing::RuntimeSetting();
2313 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2314}
2315
2316TEST(RuntimeSettingTest, TestCapturePreGain) {
2317 using Type = AudioProcessing::RuntimeSetting::Type;
2318 {
2319 auto s = AudioProcessing::RuntimeSetting::CreateCapturePreGain(1.25f);
2320 EXPECT_EQ(Type::kCapturePreGain, s.type());
2321 float v;
2322 s.GetFloat(&v);
2323 EXPECT_EQ(1.25f, v);
2324 }
2325
2326#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2327 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2328#endif
2329}
2330
Per Åhgren6ee75fd2019-04-26 11:33:37 +02002331TEST(RuntimeSettingTest, TestCaptureFixedPostGain) {
2332 using Type = AudioProcessing::RuntimeSetting::Type;
2333 {
2334 auto s = AudioProcessing::RuntimeSetting::CreateCaptureFixedPostGain(1.25f);
2335 EXPECT_EQ(Type::kCaptureFixedPostGain, s.type());
2336 float v;
2337 s.GetFloat(&v);
2338 EXPECT_EQ(1.25f, v);
2339 }
2340
2341#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2342 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2343#endif
2344}
2345
Alessio Bazzicac054e782018-04-16 12:10:09 +02002346TEST(RuntimeSettingTest, TestUsageWithSwapQueue) {
2347 SwapQueue<AudioProcessing::RuntimeSetting> q(1);
2348 auto s = AudioProcessing::RuntimeSetting();
2349 ASSERT_TRUE(q.Insert(&s));
2350 ASSERT_TRUE(q.Remove(&s));
2351 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2352}
2353
Sam Zackrisson0beac582017-09-25 12:04:02 +02002354TEST(ApmConfiguration, EnablePostProcessing) {
2355 // Verify that apm uses a capture post processing module if one is provided.
Sam Zackrisson0beac582017-09-25 12:04:02 +02002356 auto mock_post_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002357 new ::testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002358 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002359 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002360 rtc::scoped_refptr<AudioProcessing> apm =
2361 AudioProcessingBuilder()
2362 .SetCapturePostProcessing(std::move(mock_post_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002363 .Create();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002364
2365 AudioFrame audio;
2366 audio.num_channels_ = 1;
2367 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2368
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002369 EXPECT_CALL(*mock_post_processor_ptr, Process(::testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002370 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002371}
2372
Alex Loiko5825aa62017-12-18 16:02:40 +01002373TEST(ApmConfiguration, EnablePreProcessing) {
2374 // Verify that apm uses a capture post processing module if one is provided.
Alex Loiko5825aa62017-12-18 16:02:40 +01002375 auto mock_pre_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002376 new ::testing::NiceMock<test::MockCustomProcessing>();
Alex Loiko5825aa62017-12-18 16:02:40 +01002377 auto mock_pre_processor =
2378 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002379 rtc::scoped_refptr<AudioProcessing> apm =
2380 AudioProcessingBuilder()
2381 .SetRenderPreProcessing(std::move(mock_pre_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002382 .Create();
Alex Loiko5825aa62017-12-18 16:02:40 +01002383
2384 AudioFrame audio;
2385 audio.num_channels_ = 1;
2386 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2387
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002388 EXPECT_CALL(*mock_pre_processor_ptr, Process(::testing::_)).Times(1);
Alex Loiko5825aa62017-12-18 16:02:40 +01002389 apm->ProcessReverseStream(&audio);
2390}
2391
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002392TEST(ApmConfiguration, EnableCaptureAnalyzer) {
2393 // Verify that apm uses a capture analyzer if one is provided.
2394 auto mock_capture_analyzer_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002395 new ::testing::NiceMock<test::MockCustomAudioAnalyzer>();
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002396 auto mock_capture_analyzer =
2397 std::unique_ptr<CustomAudioAnalyzer>(mock_capture_analyzer_ptr);
2398 rtc::scoped_refptr<AudioProcessing> apm =
2399 AudioProcessingBuilder()
2400 .SetCaptureAnalyzer(std::move(mock_capture_analyzer))
2401 .Create();
2402
2403 AudioFrame audio;
2404 audio.num_channels_ = 1;
2405 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2406
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002407 EXPECT_CALL(*mock_capture_analyzer_ptr, Analyze(::testing::_)).Times(1);
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002408 apm->ProcessStream(&audio);
2409}
2410
Alex Loiko73ec0192018-05-15 10:52:28 +02002411TEST(ApmConfiguration, PreProcessingReceivesRuntimeSettings) {
2412 auto mock_pre_processor_ptr =
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002413 new ::testing::NiceMock<test::MockCustomProcessing>();
Alex Loiko73ec0192018-05-15 10:52:28 +02002414 auto mock_pre_processor =
2415 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
2416 rtc::scoped_refptr<AudioProcessing> apm =
2417 AudioProcessingBuilder()
2418 .SetRenderPreProcessing(std::move(mock_pre_processor))
2419 .Create();
2420 apm->SetRuntimeSetting(
2421 AudioProcessing::RuntimeSetting::CreateCustomRenderSetting(0));
2422
2423 // RuntimeSettings forwarded during 'Process*Stream' calls.
2424 // Therefore we have to make one such call.
2425 AudioFrame audio;
2426 audio.num_channels_ = 1;
2427 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2428
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002429 EXPECT_CALL(*mock_pre_processor_ptr, SetRuntimeSetting(::testing::_))
2430 .Times(1);
Alex Loiko73ec0192018-05-15 10:52:28 +02002431 apm->ProcessReverseStream(&audio);
2432}
2433
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002434class MyEchoControlFactory : public EchoControlFactory {
2435 public:
2436 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2437 auto ec = new test::MockEchoControl();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02002438 EXPECT_CALL(*ec, AnalyzeRender(::testing::_)).Times(1);
2439 EXPECT_CALL(*ec, AnalyzeCapture(::testing::_)).Times(2);
2440 EXPECT_CALL(*ec, ProcessCapture(::testing::_, ::testing::_)).Times(2);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002441 return std::unique_ptr<EchoControl>(ec);
2442 }
Per Åhgrence202a02019-09-02 17:01:19 +02002443
2444 std::unique_ptr<EchoControl> Create(int sample_rate_hz,
2445 size_t num_render_channels,
2446 size_t num_capture_channels) {
2447 return Create(sample_rate_hz);
2448 }
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002449};
2450
2451TEST(ApmConfiguration, EchoControlInjection) {
2452 // Verify that apm uses an injected echo controller if one is provided.
2453 webrtc::Config webrtc_config;
2454 std::unique_ptr<EchoControlFactory> echo_control_factory(
2455 new MyEchoControlFactory());
2456
Alex Loiko5825aa62017-12-18 16:02:40 +01002457 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002458 AudioProcessingBuilder()
2459 .SetEchoControlFactory(std::move(echo_control_factory))
2460 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002461
2462 AudioFrame audio;
2463 audio.num_channels_ = 1;
2464 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2465 apm->ProcessStream(&audio);
2466 apm->ProcessReverseStream(&audio);
2467 apm->ProcessStream(&audio);
2468}
Ivo Creusenae026092017-11-20 13:07:16 +01002469
Per Åhgren8607f842019-04-12 22:02:26 +02002470std::unique_ptr<AudioProcessing> CreateApm(bool mobile_aec) {
Ivo Creusenae026092017-11-20 13:07:16 +01002471 Config old_config;
Ivo Creusen62337e52018-01-09 14:17:33 +01002472 std::unique_ptr<AudioProcessing> apm(
2473 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002474 if (!apm) {
2475 return apm;
2476 }
2477
2478 ProcessingConfig processing_config = {
2479 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2480
2481 if (apm->Initialize(processing_config) != 0) {
2482 return nullptr;
2483 }
2484
2485 // Disable all components except for an AEC and the residual echo detector.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002486 AudioProcessing::Config apm_config;
2487 apm_config.residual_echo_detector.enabled = true;
2488 apm_config.high_pass_filter.enabled = false;
2489 apm_config.gain_controller2.enabled = false;
2490 apm_config.echo_canceller.enabled = true;
Per Åhgren8607f842019-04-12 22:02:26 +02002491 apm_config.echo_canceller.mobile_mode = mobile_aec;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002492 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002493 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
2494 EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
2495 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
Ivo Creusenae026092017-11-20 13:07:16 +01002496 return apm;
2497}
2498
2499#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
2500#define MAYBE_ApmStatistics DISABLED_ApmStatistics
2501#else
2502#define MAYBE_ApmStatistics ApmStatistics
2503#endif
2504
Per Åhgren8607f842019-04-12 22:02:26 +02002505TEST(MAYBE_ApmStatistics, AECEnabledTest) {
2506 // Set up APM with AEC3 and process some audio.
2507 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
Ivo Creusenae026092017-11-20 13:07:16 +01002508 ASSERT_TRUE(apm);
Per Åhgren200feba2019-03-06 04:16:46 +01002509 AudioProcessing::Config apm_config;
2510 apm_config.echo_canceller.enabled = true;
Per Åhgren200feba2019-03-06 04:16:46 +01002511 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002512
2513 // Set up an audioframe.
2514 AudioFrame frame;
2515 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002516 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002517
2518 // Fill the audio frame with a sawtooth pattern.
2519 int16_t* ptr = frame.mutable_data();
2520 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2521 ptr[i] = 10000 * ((i % 3) - 1);
2522 }
2523
2524 // Do some processing.
2525 for (int i = 0; i < 200; i++) {
2526 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2527 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2528 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2529 }
2530
2531 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002532 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002533 // We expect all statistics to be set and have a sensible value.
2534 ASSERT_TRUE(stats.residual_echo_likelihood);
2535 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2536 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2537 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
2538 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2539 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2540 ASSERT_TRUE(stats.echo_return_loss);
2541 EXPECT_NE(*stats.echo_return_loss, -100.0);
2542 ASSERT_TRUE(stats.echo_return_loss_enhancement);
2543 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
Ivo Creusenae026092017-11-20 13:07:16 +01002544
2545 // If there are no receive streams, we expect the stats not to be set. The
2546 // 'false' argument signals to APM that no receive streams are currently
2547 // active. In that situation the statistics would get stuck at their last
2548 // calculated value (AEC and echo detection need at least one stream in each
2549 // direction), so to avoid that, they should not be set by APM.
2550 stats = apm->GetStatistics(false);
2551 EXPECT_FALSE(stats.residual_echo_likelihood);
2552 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2553 EXPECT_FALSE(stats.echo_return_loss);
2554 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002555}
2556
2557TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
2558 // Set up APM with AECM and process some audio.
Per Åhgren8607f842019-04-12 22:02:26 +02002559 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002560 ASSERT_TRUE(apm);
2561
2562 // Set up an audioframe.
2563 AudioFrame frame;
2564 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002565 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002566
2567 // Fill the audio frame with a sawtooth pattern.
2568 int16_t* ptr = frame.mutable_data();
2569 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2570 ptr[i] = 10000 * ((i % 3) - 1);
2571 }
2572
2573 // Do some processing.
2574 for (int i = 0; i < 200; i++) {
2575 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2576 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2577 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2578 }
2579
2580 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002581 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002582 // We expect only the residual echo detector statistics to be set and have a
2583 // sensible value.
2584 EXPECT_TRUE(stats.residual_echo_likelihood);
2585 if (stats.residual_echo_likelihood) {
2586 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2587 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2588 }
2589 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
2590 if (stats.residual_echo_likelihood_recent_max) {
2591 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2592 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2593 }
2594 EXPECT_FALSE(stats.echo_return_loss);
2595 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002596
2597 // If there are no receive streams, we expect the stats not to be set.
2598 stats = apm->GetStatistics(false);
2599 EXPECT_FALSE(stats.residual_echo_likelihood);
2600 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2601 EXPECT_FALSE(stats.echo_return_loss);
2602 EXPECT_FALSE(stats.echo_return_loss_enhancement);
Ivo Creusenae026092017-11-20 13:07:16 +01002603}
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002604
2605TEST(ApmStatistics, ReportOutputRmsDbfs) {
2606 ProcessingConfig processing_config = {
2607 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2608 AudioProcessing::Config config;
2609
2610 // Set up an audioframe.
2611 AudioFrame frame;
2612 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002613 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002614
2615 // Fill the audio frame with a sawtooth pattern.
2616 int16_t* ptr = frame.mutable_data();
2617 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2618 ptr[i] = 10000 * ((i % 3) - 1);
2619 }
2620
2621 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2622 apm->Initialize(processing_config);
2623
2624 // If not enabled, no metric should be reported.
2625 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2626 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2627
2628 // If enabled, metrics should be reported.
2629 config.level_estimation.enabled = true;
2630 apm->ApplyConfig(config);
2631 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2632 auto stats = apm->GetStatistics(false);
2633 EXPECT_TRUE(stats.output_rms_dbfs);
2634 EXPECT_GE(*stats.output_rms_dbfs, 0);
2635
2636 // If re-disabled, the value is again not reported.
2637 config.level_estimation.enabled = false;
2638 apm->ApplyConfig(config);
2639 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2640 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2641}
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002642
2643TEST(ApmStatistics, ReportHasVoice) {
2644 ProcessingConfig processing_config = {
2645 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2646 AudioProcessing::Config config;
2647
2648 // Set up an audioframe.
2649 AudioFrame frame;
2650 frame.num_channels_ = 1;
2651 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
2652
2653 // Fill the audio frame with a sawtooth pattern.
2654 int16_t* ptr = frame.mutable_data();
2655 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2656 ptr[i] = 10000 * ((i % 3) - 1);
2657 }
2658
2659 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2660 apm->Initialize(processing_config);
2661
2662 // If not enabled, no metric should be reported.
2663 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2664 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2665
2666 // If enabled, metrics should be reported.
2667 config.voice_detection.enabled = true;
2668 apm->ApplyConfig(config);
2669 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2670 auto stats = apm->GetStatistics(false);
2671 EXPECT_TRUE(stats.voice_detected);
2672
2673 // If re-disabled, the value is again not reported.
2674 config.voice_detection.enabled = false;
2675 apm->ApplyConfig(config);
2676 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2677 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2678}
Per Åhgren3e8bf282019-08-29 23:38:40 +02002679
2680TEST(ApmConfiguration, HandlingOfRateAndChannelCombinations) {
2681 std::array<int, 3> sample_rates_hz = {16000, 32000, 48000};
2682 std::array<int, 2> render_channel_counts = {1, 7};
2683 std::array<int, 2> capture_channel_counts = {1, 7};
2684 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2685 capture_channel_counts);
2686}
2687
2688TEST(ApmConfiguration, HandlingOfChannelCombinations) {
2689 std::array<int, 1> sample_rates_hz = {48000};
2690 std::array<int, 8> render_channel_counts = {1, 2, 3, 4, 5, 6, 7, 8};
2691 std::array<int, 8> capture_channel_counts = {1, 2, 3, 4, 5, 6, 7, 8};
2692 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2693 capture_channel_counts);
2694}
2695
2696TEST(ApmConfiguration, HandlingOfRateCombinations) {
2697 std::array<int, 9> sample_rates_hz = {8000, 11025, 16000, 22050, 32000,
2698 48000, 96000, 192000, 384000};
2699 std::array<int, 1> render_channel_counts = {2};
2700 std::array<int, 1> capture_channel_counts = {2};
2701 RunApmRateAndChannelTest(sample_rates_hz, render_channel_counts,
2702 capture_channel_counts);
2703}
2704
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002705} // namespace webrtc