blob: b5fb2b85c8b186e880679554deb25a57a4958206 [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 */
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000010#include <math.h>
ajm@google.com59e41402011-07-28 17:34:04 +000011#include <stdio.h>
kwiberg62eaacf2016-02-17 06:39:05 -080012
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000013#include <algorithm>
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000014#include <limits>
kwiberg62eaacf2016-02-17 06:39:05 -080015#include <memory>
bjornv@webrtc.org3e102492013-02-14 15:29:09 +000016#include <queue>
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "common_audio/include/audio_util.h"
19#include "common_audio/resampler/include/push_resampler.h"
20#include "common_audio/resampler/push_sinc_resampler.h"
21#include "common_audio/signal_processing/include/signal_processing_library.h"
22#include "modules/audio_processing/aec_dump/aec_dump_factory.h"
23#include "modules/audio_processing/audio_processing_impl.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/audio_processing/common.h"
25#include "modules/audio_processing/include/audio_processing.h"
Sam Zackrisson0beac582017-09-25 12:04:02 +020026#include "modules/audio_processing/include/mock_audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/audio_processing/test/protobuf_utils.h"
28#include "modules/audio_processing/test/test_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/arraysize.h"
30#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/fake_clock.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/gtest_prod_util.h"
33#include "rtc_base/ignore_wundef.h"
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +010034#include "rtc_base/numerics/safe_conversions.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010035#include "rtc_base/numerics/safe_minmax.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/protobuf_utils.h"
Steve Anton10542f22019-01-11 09:11:00 -080037#include "rtc_base/ref_counted_object.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020038#include "rtc_base/strings/string_builder.h"
Alessio Bazzicac054e782018-04-16 12:10:09 +020039#include "rtc_base/swap_queue.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020040#include "rtc_base/system/arch.h"
Danil Chapovalov07122bc2019-03-26 14:37:01 +010041#include "rtc_base/task_queue_for_test.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/thread.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "test/gtest.h"
Steve Anton10542f22019-01-11 09:11:00 -080044#include "test/testsupport/file_utils.h"
kwiberg77eab702016-09-28 17:42:01 -070045
46RTC_PUSH_IGNORING_WUNDEF()
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000047#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000048#include "external/webrtc/webrtc/modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000049#else
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000051#endif
kwiberg77eab702016-09-28 17:42:01 -070052RTC_POP_IGNORING_WUNDEF()
niklase@google.com470e71d2011-07-07 08:21:25 +000053
andrew@webrtc.org27c69802014-02-18 20:24:56 +000054namespace webrtc {
niklase@google.com470e71d2011-07-07 08:21:25 +000055namespace {
andrew@webrtc.org17e40642014-03-04 20:58:13 +000056
ekmeyerson60d9b332015-08-14 10:35:55 -070057// TODO(ekmeyerson): Switch to using StreamConfig and ProcessingConfig where
58// applicable.
59
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +000060// TODO(bjornv): This is not feasible until the functionality has been
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +000061// re-implemented; see comment at the bottom of this file. For now, the user has
62// to hard code the |write_ref_data| value.
ajm@google.com59e41402011-07-28 17:34:04 +000063// When false, this will compare the output data with the results stored to
niklase@google.com470e71d2011-07-07 08:21:25 +000064// file. This is the typical case. When the file should be updated, it can
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +000065// be set to true with the command-line switch --write_ref_data.
66bool write_ref_data = false;
mbonadei7c2c8432017-04-07 00:59:12 -070067const int32_t kChannels[] = {1, 2};
Alejandro Luebs47748742015-05-22 12:00:21 -070068const int kSampleRates[] = {8000, 16000, 32000, 48000};
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +000069
aluebseb3603b2016-04-20 15:27:58 -070070#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
71// Android doesn't support 48kHz.
72const int kProcessSampleRates[] = {8000, 16000, 32000};
73#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Alejandro Luebs47748742015-05-22 12:00:21 -070074const int kProcessSampleRates[] = {8000, 16000, 32000, 48000};
aluebseb3603b2016-04-20 15:27:58 -070075#endif
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000076
ekmeyerson60d9b332015-08-14 10:35:55 -070077enum StreamDirection { kForward = 0, kReverse };
78
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000079void ConvertToFloat(const int16_t* int_data, ChannelBuffer<float>* cb) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000080 ChannelBuffer<int16_t> cb_int(cb->num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000081 cb->num_channels());
82 Deinterleave(int_data,
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000083 cb->num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000084 cb->num_channels(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000085 cb_int.channels());
Peter Kasting69558702016-01-12 16:26:35 -080086 for (size_t i = 0; i < cb->num_channels(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000087 S16ToFloat(cb_int.channels()[i],
88 cb->num_frames(),
89 cb->channels()[i]);
90 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000091}
andrew@webrtc.org17e40642014-03-04 20:58:13 +000092
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000093void ConvertToFloat(const AudioFrame& frame, ChannelBuffer<float>* cb) {
yujo36b1a5f2017-06-12 12:45:32 -070094 ConvertToFloat(frame.data(), cb);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000095}
96
andrew@webrtc.org103657b2014-04-24 18:28:56 +000097// Number of channels including the keyboard channel.
Peter Kasting69558702016-01-12 16:26:35 -080098size_t TotalChannelsFromLayout(AudioProcessing::ChannelLayout layout) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +000099 switch (layout) {
100 case AudioProcessing::kMono:
101 return 1;
102 case AudioProcessing::kMonoAndKeyboard:
103 case AudioProcessing::kStereo:
104 return 2;
105 case AudioProcessing::kStereoAndKeyboard:
106 return 3;
107 }
kwiberg9e2be5f2016-09-14 05:23:22 -0700108 RTC_NOTREACHED();
pkasting25702cb2016-01-08 13:50:27 -0800109 return 0;
andrew@webrtc.org103657b2014-04-24 18:28:56 +0000110}
111
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000112int TruncateToMultipleOf10(int value) {
113 return (value / 10) * 10;
114}
115
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000116void MixStereoToMono(const float* stereo, float* mono,
pkasting25702cb2016-01-08 13:50:27 -0800117 size_t samples_per_channel) {
118 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000119 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) / 2;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000120}
121
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000122void MixStereoToMono(const int16_t* stereo, int16_t* mono,
pkasting25702cb2016-01-08 13:50:27 -0800123 size_t samples_per_channel) {
124 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000125 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) >> 1;
126}
127
pkasting25702cb2016-01-08 13:50:27 -0800128void CopyLeftToRightChannel(int16_t* stereo, size_t samples_per_channel) {
129 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000130 stereo[i * 2 + 1] = stereo[i * 2];
131 }
132}
133
yujo36b1a5f2017-06-12 12:45:32 -0700134void VerifyChannelsAreEqual(const int16_t* stereo, size_t samples_per_channel) {
pkasting25702cb2016-01-08 13:50:27 -0800135 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000136 EXPECT_EQ(stereo[i * 2 + 1], stereo[i * 2]);
137 }
138}
139
140void SetFrameTo(AudioFrame* frame, int16_t value) {
yujo36b1a5f2017-06-12 12:45:32 -0700141 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700142 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
143 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700144 frame_data[i] = value;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000145 }
146}
147
148void SetFrameTo(AudioFrame* frame, int16_t left, int16_t right) {
Peter Kasting69558702016-01-12 16:26:35 -0800149 ASSERT_EQ(2u, frame->num_channels_);
yujo36b1a5f2017-06-12 12:45:32 -0700150 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700151 for (size_t i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
yujo36b1a5f2017-06-12 12:45:32 -0700152 frame_data[i] = left;
153 frame_data[i + 1] = right;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000154 }
155}
156
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000157void ScaleFrame(AudioFrame* frame, float scale) {
yujo36b1a5f2017-06-12 12:45:32 -0700158 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700159 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
160 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700161 frame_data[i] = FloatS16ToS16(frame_data[i] * scale);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000162 }
163}
164
andrew@webrtc.org81865342012-10-27 00:28:27 +0000165bool FrameDataAreEqual(const AudioFrame& frame1, const AudioFrame& frame2) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000166 if (frame1.samples_per_channel_ != frame2.samples_per_channel_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000167 return false;
168 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000169 if (frame1.num_channels_ != frame2.num_channels_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000170 return false;
171 }
yujo36b1a5f2017-06-12 12:45:32 -0700172 if (memcmp(frame1.data(), frame2.data(),
andrew@webrtc.org81865342012-10-27 00:28:27 +0000173 frame1.samples_per_channel_ * frame1.num_channels_ *
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000174 sizeof(int16_t))) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000175 return false;
176 }
177 return true;
178}
179
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000180void EnableAllAPComponents(AudioProcessing* ap) {
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200181 AudioProcessing::Config apm_config = ap->GetConfig();
182 apm_config.echo_canceller.enabled = true;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000183#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200184 apm_config.echo_canceller.mobile_mode = true;
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100185
186 apm_config.gain_controller1.enabled = true;
187 apm_config.gain_controller1.mode =
188 AudioProcessing::Config::GainController1::kAdaptiveDigital;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000189#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Per Ã…hgren200feba2019-03-06 04:16:46 +0100190 // TODO(peah): Update tests to instead use AEC3.
191 apm_config.echo_canceller.use_legacy_aec = true;
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200192 apm_config.echo_canceller.mobile_mode = false;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200193 apm_config.echo_canceller.legacy_moderate_suppression_level = true;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000194
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100195 apm_config.gain_controller1.enabled = true;
196 apm_config.gain_controller1.mode =
197 AudioProcessing::Config::GainController1::kAdaptiveAnalog;
198 apm_config.gain_controller1.analog_level_minimum = 0;
199 apm_config.gain_controller1.analog_level_maximum = 255;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000200#endif
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000201
peah8271d042016-11-22 07:24:52 -0800202 apm_config.high_pass_filter.enabled = true;
Sam Zackrisson11b87032018-12-18 17:13:58 +0100203 apm_config.level_estimation.enabled = true;
peah8271d042016-11-22 07:24:52 -0800204 ap->ApplyConfig(apm_config);
205
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000206 EXPECT_NOERR(ap->level_estimator()->Enable(true));
207 EXPECT_NOERR(ap->noise_suppression()->Enable(true));
208
209 EXPECT_NOERR(ap->voice_detection()->Enable(true));
210}
211
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000212// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000213template <class T>
214T AbsValue(T a) {
215 return a > 0 ? a: -a;
216}
217
218int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800219 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700220 const int16_t* frame_data = frame.data();
221 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800222 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700223 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000224 }
225
226 return max_data;
227}
228
Alex Loiko890988c2017-08-31 10:25:48 +0200229void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700230 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000231 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000232 ASSERT_TRUE(file != NULL);
233
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100234 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000235 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800236 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000237 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000238
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000239 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000240 ASSERT_EQ(static_cast<size_t>(size),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000241 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000242 fclose(file);
243}
244
Alex Loiko890988c2017-08-31 10:25:48 +0200245std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200246 rtc::StringBuilder ss;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000247 // Resource files are all stereo.
248 ss << name << sample_rate_hz / 1000 << "_stereo";
249 return test::ResourcePath(ss.str(), "pcm");
250}
251
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000252// Temporary filenames unique to this process. Used to be able to run these
253// tests in parallel as each process needs to be running in isolation they can't
254// have competing filenames.
255std::map<std::string, std::string> temp_filenames;
256
Alex Loiko890988c2017-08-31 10:25:48 +0200257std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000258 int input_rate,
259 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700260 int reverse_input_rate,
261 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800262 size_t num_input_channels,
263 size_t num_output_channels,
264 size_t num_reverse_input_channels,
265 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700266 StreamDirection file_direction) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200267 rtc::StringBuilder ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700268 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
269 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000270 if (num_output_channels == 1) {
271 ss << "mono";
272 } else if (num_output_channels == 2) {
273 ss << "stereo";
274 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700275 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000276 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700277 ss << output_rate / 1000;
278 if (num_reverse_output_channels == 1) {
279 ss << "_rmono";
280 } else if (num_reverse_output_channels == 2) {
281 ss << "_rstereo";
282 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700283 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700284 }
285 ss << reverse_output_rate / 1000;
286 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000287
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000288 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700289 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000290 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
291 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000292}
293
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000294void ClearTempFiles() {
295 for (auto& kv : temp_filenames)
296 remove(kv.second.c_str());
297}
298
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200299// Only remove "out" files. Keep "ref" files.
300void ClearTempOutFiles() {
301 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
302 const std::string& filename = it->first;
303 if (filename.substr(0, 3).compare("out") == 0) {
304 remove(it->second.c_str());
305 temp_filenames.erase(it++);
306 } else {
307 it++;
308 }
309 }
310}
311
Alex Loiko890988c2017-08-31 10:25:48 +0200312void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000313 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000314 ASSERT_TRUE(file != NULL);
315 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000316 fclose(file);
317}
318
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000319// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
320// stereo) file, converts to deinterleaved float (optionally downmixing) and
321// returns the result in |cb|. Returns false if the file ended (or on error) and
322// true otherwise.
323//
324// |int_data| and |float_data| are just temporary space that must be
325// sufficiently large to hold the 10 ms chunk.
326bool ReadChunk(FILE* file, int16_t* int_data, float* float_data,
327 ChannelBuffer<float>* cb) {
328 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000329 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000330 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
331 if (read_count != frame_size) {
332 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700333 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000334 return false; // This is expected.
335 }
336
337 S16ToFloat(int_data, frame_size, float_data);
338 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000339 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000340 } else {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000341 Deinterleave(float_data, cb->num_frames(), 2,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000342 cb->channels());
343 }
344
345 return true;
346}
347
niklase@google.com470e71d2011-07-07 08:21:25 +0000348class ApmTest : public ::testing::Test {
349 protected:
350 ApmTest();
351 virtual void SetUp();
352 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000353
354 static void SetUpTestCase() {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000355 }
356
357 static void TearDownTestCase() {
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000358 ClearTempFiles();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000359 }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000360
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000361 // Used to select between int and float interface tests.
362 enum Format {
363 kIntFormat,
364 kFloatFormat
365 };
366
367 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000368 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000369 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800370 size_t num_input_channels,
371 size_t num_output_channels,
372 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000373 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000374 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000375 void EnableAllComponents();
376 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000377 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000378 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000379 void ReadFrameWithRewind(FILE* file, AudioFrame* frame,
380 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000381 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000382 void ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
383 int delay_min, int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700384 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800385 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700386 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800387 void TestChangingForwardChannels(size_t num_in_channels,
388 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700389 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800390 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700391 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000392 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
393 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000394 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000395 int ProcessStreamChooser(Format format);
396 int AnalyzeReverseStreamChooser(Format format);
397 void ProcessDebugDump(const std::string& in_filename,
398 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800399 Format format,
400 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000401 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000402
403 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000404 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800405 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000406 AudioFrame* frame_;
407 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800408 std::unique_ptr<ChannelBuffer<float> > float_cb_;
409 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000410 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800411 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000412 FILE* far_file_;
413 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000414 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000415};
416
417ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000418 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000419#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800420 ref_filename_(test::ResourcePath("audio_processing/output_data_fixed",
421 "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000422#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000423#if defined(WEBRTC_MAC)
424 // A different file for Mac is needed because on this platform the AEC
425 // constant |kFixedDelayMs| value is 20 and not 50 as it is on the rest.
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800426 ref_filename_(test::ResourcePath("audio_processing/output_data_mac",
427 "pb")),
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000428#else
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800429 ref_filename_(test::ResourcePath("audio_processing/output_data_float",
430 "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000431#endif
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000432#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000433 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000434 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000435 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000436 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000437 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000438 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000439 out_file_(NULL) {
440 Config config;
441 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100442 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000443}
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
445void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000446 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000447
448 frame_ = new AudioFrame();
449 revframe_ = new AudioFrame();
450
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000451 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000452}
453
454void ApmTest::TearDown() {
455 if (frame_) {
456 delete frame_;
457 }
458 frame_ = NULL;
459
460 if (revframe_) {
461 delete revframe_;
462 }
463 revframe_ = NULL;
464
465 if (far_file_) {
466 ASSERT_EQ(0, fclose(far_file_));
467 }
468 far_file_ = NULL;
469
470 if (near_file_) {
471 ASSERT_EQ(0, fclose(near_file_));
472 }
473 near_file_ = NULL;
474
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000475 if (out_file_) {
476 ASSERT_EQ(0, fclose(out_file_));
477 }
478 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000479}
480
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000481void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000482 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700483 ap->Initialize(
484 {{{frame_->sample_rate_hz_, frame_->num_channels_},
485 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700486 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700487 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000488}
489
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000490void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000491 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000492 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800493 size_t num_input_channels,
494 size_t num_output_channels,
495 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000496 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000497 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000498 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000499 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000500
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000501 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
502 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000503 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000504
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000505 if (far_file_) {
506 ASSERT_EQ(0, fclose(far_file_));
507 }
508 std::string filename = ResourceFilePath("far", sample_rate_hz);
509 far_file_ = fopen(filename.c_str(), "rb");
510 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " <<
511 filename << "\n";
512
513 if (near_file_) {
514 ASSERT_EQ(0, fclose(near_file_));
515 }
516 filename = ResourceFilePath("near", sample_rate_hz);
517 near_file_ = fopen(filename.c_str(), "rb");
518 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " <<
519 filename << "\n";
520
521 if (open_output_file) {
522 if (out_file_) {
523 ASSERT_EQ(0, fclose(out_file_));
524 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700525 filename = OutputFilePath(
526 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
527 reverse_sample_rate_hz, num_input_channels, num_output_channels,
528 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000529 out_file_ = fopen(filename.c_str(), "wb");
530 ASSERT_TRUE(out_file_ != NULL) << "Could not open file " <<
531 filename << "\n";
532 }
533}
534
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000535void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000536 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000537}
538
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000539bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame,
540 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000541 // The files always contain stereo audio.
542 size_t frame_size = frame->samples_per_channel_ * 2;
yujo36b1a5f2017-06-12 12:45:32 -0700543 size_t read_count = fread(frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000544 sizeof(int16_t),
545 frame_size,
546 file);
547 if (read_count != frame_size) {
548 // Check that the file really ended.
549 EXPECT_NE(0, feof(file));
550 return false; // This is expected.
551 }
552
553 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700554 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000555 frame->samples_per_channel_);
556 }
557
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000558 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000559 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000560 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000561 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000562}
563
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000564bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
565 return ReadFrame(file, frame, NULL);
566}
567
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000568// If the end of the file has been reached, rewind it and attempt to read the
569// frame again.
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000570void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame,
571 ChannelBuffer<float>* cb) {
572 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000573 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000574 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000575 }
576}
577
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000578void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
579 ReadFrameWithRewind(file, frame, NULL);
580}
581
andrew@webrtc.org81865342012-10-27 00:28:27 +0000582void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
583 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000584 EXPECT_EQ(apm_->kNoError,
585 apm_->gain_control()->set_stream_analog_level(127));
586 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000587}
588
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000589int ApmTest::ProcessStreamChooser(Format format) {
590 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000591 return apm_->ProcessStream(frame_);
592 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000593 return apm_->ProcessStream(float_cb_->channels(),
594 frame_->samples_per_channel_,
595 frame_->sample_rate_hz_,
596 LayoutFromChannels(frame_->num_channels_),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000597 output_sample_rate_hz_,
598 LayoutFromChannels(num_output_channels_),
599 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000600}
601
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000602int ApmTest::AnalyzeReverseStreamChooser(Format format) {
603 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700604 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000605 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000606 return apm_->AnalyzeReverseStream(
607 revfloat_cb_->channels(),
608 revframe_->samples_per_channel_,
609 revframe_->sample_rate_hz_,
610 LayoutFromChannels(revframe_->num_channels_));
611}
612
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000613void ApmTest::ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
614 int delay_min, int delay_max) {
615 // The |revframe_| and |frame_| should include the proper frame information,
616 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000617 AudioFrame tmp_frame;
618 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000619 bool causal = true;
620
621 tmp_frame.CopyFrom(*revframe_);
622 SetFrameTo(&tmp_frame, 0);
623
624 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
625 // Initialize the |frame_queue| with empty frames.
626 int frame_delay = delay_ms / 10;
627 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000628 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000629 frame->CopyFrom(tmp_frame);
630 frame_queue.push(frame);
631 frame_delay++;
632 causal = false;
633 }
634 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000635 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000636 frame->CopyFrom(tmp_frame);
637 frame_queue.push(frame);
638 frame_delay--;
639 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000640 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
641 // need enough frames with audio to have reliable estimates, but as few as
642 // possible to keep processing time down. 4.5 seconds seemed to be a good
643 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000644 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000645 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000646 frame->CopyFrom(tmp_frame);
647 // Use the near end recording, since that has more speech in it.
648 ASSERT_TRUE(ReadFrame(near_file_, frame));
649 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000650 AudioFrame* reverse_frame = frame;
651 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000652 if (!causal) {
653 reverse_frame = frame_queue.front();
654 // When we call ProcessStream() the frame is modified, so we can't use the
655 // pointer directly when things are non-causal. Use an intermediate frame
656 // and copy the data.
657 process_frame = &tmp_frame;
658 process_frame->CopyFrom(*frame);
659 }
aluebsb0319552016-03-17 20:39:53 -0700660 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000661 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
662 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
663 frame = frame_queue.front();
664 frame_queue.pop();
665 delete frame;
666
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000667 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000668 // Discard the first delay metrics to avoid convergence effects.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200669 static_cast<void>(apm_->GetStatistics(true /* has_remote_tracks */));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000670 }
671 }
672
673 rewind(near_file_);
674 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000675 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000676 frame_queue.pop();
677 delete frame;
678 }
679 // Calculate expected delay estimate and acceptable regions. Further,
680 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700681 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700682 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700683 const int expected_median =
684 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
685 const int expected_median_high = rtc::SafeClamp<int>(
686 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700687 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700688 const int expected_median_low = rtc::SafeClamp<int>(
689 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700690 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000691 // Verify delay metrics.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200692 AudioProcessingStats stats =
693 apm_->GetStatistics(true /* has_remote_tracks */);
694 ASSERT_TRUE(stats.delay_median_ms.has_value());
695 int32_t median = *stats.delay_median_ms;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000696 EXPECT_GE(expected_median_high, median);
697 EXPECT_LE(expected_median_low, median);
698}
699
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000700void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000701 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000702 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000703
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000704 // -- Missing AGC level --
niklase@google.com470e71d2011-07-07 08:21:25 +0000705 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000706 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000707 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000708
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000709 // Resets after successful ProcessStream().
niklase@google.com470e71d2011-07-07 08:21:25 +0000710 EXPECT_EQ(apm_->kNoError,
711 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000712 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000713 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000714 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000715
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000716 // Other stream parameters set correctly.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200717 AudioProcessing::Config apm_config = apm_->GetConfig();
718 apm_config.echo_canceller.enabled = true;
719 apm_config.echo_canceller.mobile_mode = false;
720 apm_->ApplyConfig(apm_config);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000721 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
niklase@google.com470e71d2011-07-07 08:21:25 +0000722 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000723 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000724 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000725
726 // -- Missing delay --
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000727 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Ã…hgren200feba2019-03-06 04:16:46 +0100728 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000729
730 // Resets after successful ProcessStream().
731 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000732 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
Per Ã…hgren200feba2019-03-06 04:16:46 +0100733 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000734
735 // Other stream parameters set correctly.
736 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
737 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000738 apm_->gain_control()->set_stream_analog_level(127));
Per Ã…hgren200feba2019-03-06 04:16:46 +0100739 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000740 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
741
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000742 // -- No stream parameters --
niklase@google.com470e71d2011-07-07 08:21:25 +0000743 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000744 AnalyzeReverseStreamChooser(format));
Per Ã…hgren200feba2019-03-06 04:16:46 +0100745 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000746
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000747 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000748 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
niklase@google.com470e71d2011-07-07 08:21:25 +0000749 EXPECT_EQ(apm_->kNoError,
750 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000751 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000752}
753
754TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000755 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000756}
757
758TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000759 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000760}
761
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000762TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
763 EXPECT_EQ(0, apm_->delay_offset_ms());
764 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
765 EXPECT_EQ(50, apm_->stream_delay_ms());
766}
767
768TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
769 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000770 apm_->set_delay_offset_ms(100);
771 EXPECT_EQ(100, apm_->delay_offset_ms());
772 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000773 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000774 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
775 EXPECT_EQ(200, apm_->stream_delay_ms());
776
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000777 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000778 apm_->set_delay_offset_ms(-50);
779 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000780 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
781 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000782 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
783 EXPECT_EQ(50, apm_->stream_delay_ms());
784}
785
Michael Graczyk86c6d332015-07-23 11:41:39 -0700786void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800787 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700788 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000789 frame_->num_channels_ = num_channels;
790 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700791 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000792}
793
Michael Graczyk86c6d332015-07-23 11:41:39 -0700794void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800795 size_t num_in_channels,
796 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700797 AudioProcessing::Error expected_return) {
798 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
799 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
800
801 EXPECT_EQ(expected_return,
802 apm_->ProcessStream(float_cb_->channels(), input_stream,
803 output_stream, float_cb_->channels()));
804}
805
806void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800807 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700808 AudioProcessing::Error expected_return) {
809 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700810 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
811 {output_sample_rate_hz_, apm_->num_output_channels()},
812 {frame_->sample_rate_hz_, num_rev_channels},
813 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700814
ekmeyerson60d9b332015-08-14 10:35:55 -0700815 EXPECT_EQ(
816 expected_return,
817 apm_->ProcessReverseStream(
818 float_cb_->channels(), processing_config.reverse_input_stream(),
819 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700820}
821
822TEST_F(ApmTest, ChannelsInt16Interface) {
823 // Testing number of invalid and valid channels.
824 Init(16000, 16000, 16000, 4, 4, 4, false);
825
826 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
827
Peter Kasting69558702016-01-12 16:26:35 -0800828 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700829 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000830 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000831 }
832}
833
Michael Graczyk86c6d332015-07-23 11:41:39 -0700834TEST_F(ApmTest, Channels) {
835 // Testing number of invalid and valid channels.
836 Init(16000, 16000, 16000, 4, 4, 4, false);
837
838 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
839 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
840
Peter Kasting69558702016-01-12 16:26:35 -0800841 for (size_t i = 1; i < 4; ++i) {
842 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700843 // Output channels much be one or match input channels.
844 if (j == 1 || i == j) {
845 TestChangingForwardChannels(i, j, kNoErr);
846 TestChangingReverseChannels(i, kNoErr);
847
848 EXPECT_EQ(i, apm_->num_input_channels());
849 EXPECT_EQ(j, apm_->num_output_channels());
850 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800851 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700852 } else {
853 TestChangingForwardChannels(i, j,
854 AudioProcessing::kBadNumberChannelsError);
855 }
856 }
857 }
858}
859
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000860TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000861 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000862 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000863 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000864 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700865 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800866 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000867 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000868 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000869 }
870}
871
bjornv@webrtc.org84f8ec12014-06-19 12:14:33 +0000872TEST_F(ApmTest, DISABLED_EchoCancellationReportsCorrectDelays) {
bjornv@webrtc.orgbac00122015-01-02 09:23:49 +0000873 // TODO(bjornv): Fix this test to work with DA-AEC.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000874 // Enable AEC only.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200875 AudioProcessing::Config apm_config = apm_->GetConfig();
876 apm_config.echo_canceller.enabled = true;
Per Ã…hgren200feba2019-03-06 04:16:46 +0100877 // TODO(peah): Update tests to instead use AEC3.
878 apm_config.echo_canceller.use_legacy_aec = true;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200879 apm_config.echo_canceller.mobile_mode = false;
880 apm_->ApplyConfig(apm_config);
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000881 Config config;
henrik.lundin0f133b92015-07-02 00:17:55 -0700882 config.Set<DelayAgnostic>(new DelayAgnostic(false));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000883 apm_->SetExtraOptions(config);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000884
885 // Internally in the AEC the amount of lookahead the delay estimation can
886 // handle is 15 blocks and the maximum delay is set to 60 blocks.
887 const int kLookaheadBlocks = 15;
888 const int kMaxDelayBlocks = 60;
889 // The AEC has a startup time before it actually starts to process. This
890 // procedure can flush the internal far-end buffer, which of course affects
891 // the delay estimation. Therefore, we set a system_delay high enough to
892 // avoid that. The smallest system_delay you can report without flushing the
893 // buffer is 66 ms in 8 kHz.
894 //
895 // It is known that for 16 kHz (and 32 kHz) sampling frequency there is an
896 // additional stuffing of 8 ms on the fly, but it seems to have no impact on
897 // delay estimation. This should be noted though. In case of test failure,
898 // this could be the cause.
899 const int kSystemDelayMs = 66;
900 // Test a couple of corner cases and verify that the estimated delay is
901 // within a valid region (set to +-1.5 blocks). Note that these cases are
902 // sampling frequency dependent.
pkasting25702cb2016-01-08 13:50:27 -0800903 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000904 Init(kProcessSampleRates[i],
905 kProcessSampleRates[i],
906 kProcessSampleRates[i],
907 2,
908 2,
909 2,
910 false);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000911 // Sampling frequency dependent variables.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700912 const int num_ms_per_block =
913 std::max(4, static_cast<int>(640 / frame_->samples_per_channel_));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000914 const int delay_min_ms = -kLookaheadBlocks * num_ms_per_block;
915 const int delay_max_ms = (kMaxDelayBlocks - 1) * num_ms_per_block;
916
917 // 1) Verify correct delay estimate at lookahead boundary.
918 int delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_min_ms);
919 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
920 delay_max_ms);
921 // 2) A delay less than maximum lookahead should give an delay estimate at
922 // the boundary (= -kLookaheadBlocks * num_ms_per_block).
923 delay_ms -= 20;
924 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
925 delay_max_ms);
926 // 3) Three values around zero delay. Note that we need to compensate for
927 // the fake system_delay.
928 delay_ms = TruncateToMultipleOf10(kSystemDelayMs - 10);
929 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
930 delay_max_ms);
931 delay_ms = TruncateToMultipleOf10(kSystemDelayMs);
932 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
933 delay_max_ms);
934 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + 10);
935 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
936 delay_max_ms);
937 // 4) Verify correct delay estimate at maximum delay boundary.
938 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_max_ms);
939 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
940 delay_max_ms);
941 // 5) A delay above the maximum delay should give an estimate at the
942 // boundary (= (kMaxDelayBlocks - 1) * num_ms_per_block).
943 delay_ms += 20;
944 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
945 delay_max_ms);
946 }
947}
948
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000949TEST_F(ApmTest, GainControl) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000950 // Testing gain modes
niklase@google.com470e71d2011-07-07 08:21:25 +0000951 EXPECT_EQ(apm_->kNoError,
952 apm_->gain_control()->set_mode(
953 apm_->gain_control()->mode()));
954
955 GainControl::Mode mode[] = {
956 GainControl::kAdaptiveAnalog,
957 GainControl::kAdaptiveDigital,
958 GainControl::kFixedDigital
959 };
pkasting25702cb2016-01-08 13:50:27 -0800960 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000961 EXPECT_EQ(apm_->kNoError,
962 apm_->gain_control()->set_mode(mode[i]));
963 EXPECT_EQ(mode[i], apm_->gain_control()->mode());
964 }
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100965 // Testing target levels
niklase@google.com470e71d2011-07-07 08:21:25 +0000966 EXPECT_EQ(apm_->kNoError,
967 apm_->gain_control()->set_target_level_dbfs(
968 apm_->gain_control()->target_level_dbfs()));
969
970 int level_dbfs[] = {0, 6, 31};
pkasting25702cb2016-01-08 13:50:27 -0800971 for (size_t i = 0; i < arraysize(level_dbfs); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000972 EXPECT_EQ(apm_->kNoError,
973 apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
974 EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
975 }
976
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100977 // Testing compression gains
niklase@google.com470e71d2011-07-07 08:21:25 +0000978 EXPECT_EQ(apm_->kNoError,
979 apm_->gain_control()->set_compression_gain_db(
980 apm_->gain_control()->compression_gain_db()));
981
982 int gain_db[] = {0, 10, 90};
pkasting25702cb2016-01-08 13:50:27 -0800983 for (size_t i = 0; i < arraysize(gain_db); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000984 EXPECT_EQ(apm_->kNoError,
985 apm_->gain_control()->set_compression_gain_db(gain_db[i]));
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100986 ProcessStreamChooser(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000987 EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
988 }
989
990 // Testing limiter off/on
991 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
992 EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
993 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
994 EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
995
Sam Zackrissonf0d1c032019-03-27 13:28:08 +0100996 // Testing level limits
niklase@google.com470e71d2011-07-07 08:21:25 +0000997 EXPECT_EQ(apm_->kNoError,
998 apm_->gain_control()->set_analog_level_limits(
999 apm_->gain_control()->analog_level_minimum(),
1000 apm_->gain_control()->analog_level_maximum()));
1001
1002 int min_level[] = {0, 255, 1024};
pkasting25702cb2016-01-08 13:50:27 -08001003 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001004 EXPECT_EQ(apm_->kNoError,
1005 apm_->gain_control()->set_analog_level_limits(min_level[i], 1024));
1006 EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
1007 }
1008
1009 int max_level[] = {0, 1024, 65535};
pkasting25702cb2016-01-08 13:50:27 -08001010 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001011 EXPECT_EQ(apm_->kNoError,
1012 apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
1013 EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
1014 }
1015
1016 // TODO(ajm): stream_is_saturated() and stream_analog_level()
1017
1018 // Turn AGC off
1019 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
1020 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1021}
1022
Sam Zackrissonf0d1c032019-03-27 13:28:08 +01001023#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
1024TEST_F(ApmTest, GainControlDiesOnTooLowTargetLevelDbfs) {
1025 EXPECT_DEATH(apm_->gain_control()->set_target_level_dbfs(-1), "");
1026}
1027
1028TEST_F(ApmTest, GainControlDiesOnTooHighTargetLevelDbfs) {
1029 EXPECT_DEATH(apm_->gain_control()->set_target_level_dbfs(32), "");
1030}
1031
1032TEST_F(ApmTest, GainControlDiesOnTooLowCompressionGainDb) {
1033 EXPECT_DEATH(apm_->gain_control()->set_compression_gain_db(-1), "");
1034}
1035
1036TEST_F(ApmTest, GainControlDiesOnTooHighCompressionGainDb) {
1037 EXPECT_DEATH(apm_->gain_control()->set_compression_gain_db(91), "");
1038}
1039
1040TEST_F(ApmTest, GainControlDiesOnTooLowAnalogLevelLowerLimit) {
1041 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(-1, 512), "");
1042}
1043
1044TEST_F(ApmTest, GainControlDiesOnTooHighAnalogLevelUpperLimit) {
1045 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(512, 65536), "");
1046}
1047
1048TEST_F(ApmTest, GainControlDiesOnInvertedAnalogLevelLimits) {
1049 EXPECT_DEATH(apm_->gain_control()->set_analog_level_limits(512, 255), "");
1050}
1051
1052TEST_F(ApmTest, ApmDiesOnTooLowAnalogLevel) {
1053 apm_->gain_control()->set_analog_level_limits(255, 512);
1054 EXPECT_DEATH(apm_->set_stream_analog_level(254), "");
1055}
1056
1057TEST_F(ApmTest, ApmDiesOnTooHighAnalogLevel) {
1058 apm_->gain_control()->set_analog_level_limits(255, 512);
1059 EXPECT_DEATH(apm_->set_stream_analog_level(513), "");
1060}
1061#endif
1062
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001063void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001064 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001065 EXPECT_EQ(apm_->kNoError,
1066 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1067 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1068
1069 int out_analog_level = 0;
1070 for (int i = 0; i < 2000; ++i) {
1071 ReadFrameWithRewind(near_file_, frame_);
1072 // Ensure the audio is at a low level, so the AGC will try to increase it.
1073 ScaleFrame(frame_, 0.25);
1074
1075 // Always pass in the same volume.
1076 EXPECT_EQ(apm_->kNoError,
1077 apm_->gain_control()->set_stream_analog_level(100));
1078 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1079 out_analog_level = apm_->gain_control()->stream_analog_level();
1080 }
1081
1082 // Ensure the AGC is still able to reach the maximum.
1083 EXPECT_EQ(255, out_analog_level);
1084}
1085
1086// Verifies that despite volume slider quantization, the AGC can continue to
1087// increase its volume.
1088TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -08001089 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001090 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
1091 }
1092}
1093
1094void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001095 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001096 EXPECT_EQ(apm_->kNoError,
1097 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1098 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1099
1100 int out_analog_level = 100;
1101 for (int i = 0; i < 1000; ++i) {
1102 ReadFrameWithRewind(near_file_, frame_);
1103 // Ensure the audio is at a low level, so the AGC will try to increase it.
1104 ScaleFrame(frame_, 0.25);
1105
1106 EXPECT_EQ(apm_->kNoError,
1107 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1108 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1109 out_analog_level = apm_->gain_control()->stream_analog_level();
1110 }
1111
1112 // Ensure the volume was raised.
1113 EXPECT_GT(out_analog_level, 100);
1114 int highest_level_reached = out_analog_level;
1115 // Simulate a user manual volume change.
1116 out_analog_level = 100;
1117
1118 for (int i = 0; i < 300; ++i) {
1119 ReadFrameWithRewind(near_file_, frame_);
1120 ScaleFrame(frame_, 0.25);
1121
1122 EXPECT_EQ(apm_->kNoError,
1123 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1124 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1125 out_analog_level = apm_->gain_control()->stream_analog_level();
1126 // Check that AGC respected the manually adjusted volume.
1127 EXPECT_LT(out_analog_level, highest_level_reached);
1128 }
1129 // Check that the volume was still raised.
1130 EXPECT_GT(out_analog_level, 100);
1131}
1132
1133TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001134 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001135 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1136 }
1137}
1138
niklase@google.com470e71d2011-07-07 08:21:25 +00001139TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001140 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001141 NoiseSuppression::Level level[] = {
1142 NoiseSuppression::kLow,
1143 NoiseSuppression::kModerate,
1144 NoiseSuppression::kHigh,
1145 NoiseSuppression::kVeryHigh
1146 };
pkasting25702cb2016-01-08 13:50:27 -08001147 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001148 EXPECT_EQ(apm_->kNoError,
1149 apm_->noise_suppression()->set_level(level[i]));
1150 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1151 }
1152
andrew@webrtc.org648af742012-02-08 01:57:29 +00001153 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001154 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1155 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1156 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1157 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1158}
1159
1160TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001161 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001162 AudioProcessing::Config apm_config;
1163 apm_config.high_pass_filter.enabled = true;
1164 apm_->ApplyConfig(apm_config);
1165 apm_config.high_pass_filter.enabled = false;
1166 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001167}
1168
1169TEST_F(ApmTest, LevelEstimator) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001170 // Turn level estimator on/off
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001171 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001172 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001173
1174 EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1175
1176 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1177 EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1178
1179 // Run this test in wideband; in super-wb, the splitting filter distorts the
1180 // audio enough to cause deviation from the expectation for small values.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001181 frame_->samples_per_channel_ = 160;
1182 frame_->num_channels_ = 2;
1183 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001184
1185 // Min value if no frames have been processed.
1186 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1187
1188 // Min value on zero frames.
1189 SetFrameTo(frame_, 0);
1190 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1191 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1192 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1193
1194 // Try a few RMS values.
1195 // (These also test that the value resets after retrieving it.)
1196 SetFrameTo(frame_, 32767);
1197 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1198 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1199 EXPECT_EQ(0, apm_->level_estimator()->RMS());
1200
1201 SetFrameTo(frame_, 30000);
1202 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1203 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1204 EXPECT_EQ(1, apm_->level_estimator()->RMS());
1205
1206 SetFrameTo(frame_, 10000);
1207 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1208 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1209 EXPECT_EQ(10, apm_->level_estimator()->RMS());
1210
1211 SetFrameTo(frame_, 10);
1212 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1213 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1214 EXPECT_EQ(70, apm_->level_estimator()->RMS());
1215
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001216 // Verify reset after enable/disable.
1217 SetFrameTo(frame_, 32767);
1218 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1219 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1220 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1221 SetFrameTo(frame_, 1);
1222 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1223 EXPECT_EQ(90, apm_->level_estimator()->RMS());
1224
1225 // Verify reset after initialize.
1226 SetFrameTo(frame_, 32767);
1227 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1228 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1229 SetFrameTo(frame_, 1);
1230 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1231 EXPECT_EQ(90, apm_->level_estimator()->RMS());
niklase@google.com470e71d2011-07-07 08:21:25 +00001232}
1233
1234TEST_F(ApmTest, VoiceDetection) {
1235 // Test external VAD
1236 EXPECT_EQ(apm_->kNoError,
1237 apm_->voice_detection()->set_stream_has_voice(true));
1238 EXPECT_TRUE(apm_->voice_detection()->stream_has_voice());
1239 EXPECT_EQ(apm_->kNoError,
1240 apm_->voice_detection()->set_stream_has_voice(false));
1241 EXPECT_FALSE(apm_->voice_detection()->stream_has_voice());
1242
andrew@webrtc.org648af742012-02-08 01:57:29 +00001243 // Test valid likelihoods
niklase@google.com470e71d2011-07-07 08:21:25 +00001244 VoiceDetection::Likelihood likelihood[] = {
1245 VoiceDetection::kVeryLowLikelihood,
1246 VoiceDetection::kLowLikelihood,
1247 VoiceDetection::kModerateLikelihood,
1248 VoiceDetection::kHighLikelihood
1249 };
pkasting25702cb2016-01-08 13:50:27 -08001250 for (size_t i = 0; i < arraysize(likelihood); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001251 EXPECT_EQ(apm_->kNoError,
1252 apm_->voice_detection()->set_likelihood(likelihood[i]));
1253 EXPECT_EQ(likelihood[i], apm_->voice_detection()->likelihood());
1254 }
1255
1256 /* TODO(bjornv): Enable once VAD supports other frame lengths than 10 ms
andrew@webrtc.org648af742012-02-08 01:57:29 +00001257 // Test invalid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001258 EXPECT_EQ(apm_->kBadParameterError,
1259 apm_->voice_detection()->set_frame_size_ms(12));
1260
andrew@webrtc.org648af742012-02-08 01:57:29 +00001261 // Test valid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001262 for (int i = 10; i <= 30; i += 10) {
1263 EXPECT_EQ(apm_->kNoError,
1264 apm_->voice_detection()->set_frame_size_ms(i));
1265 EXPECT_EQ(i, apm_->voice_detection()->frame_size_ms());
1266 }
1267 */
1268
andrew@webrtc.org648af742012-02-08 01:57:29 +00001269 // Turn VAD on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001270 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1271 EXPECT_TRUE(apm_->voice_detection()->is_enabled());
1272 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1273 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1274
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001275 // Test that AudioFrame activity is maintained when VAD is disabled.
1276 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1277 AudioFrame::VADActivity activity[] = {
1278 AudioFrame::kVadActive,
1279 AudioFrame::kVadPassive,
1280 AudioFrame::kVadUnknown
1281 };
pkasting25702cb2016-01-08 13:50:27 -08001282 for (size_t i = 0; i < arraysize(activity); i++) {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001283 frame_->vad_activity_ = activity[i];
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001284 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001285 EXPECT_EQ(activity[i], frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001286 }
1287
1288 // Test that AudioFrame activity is set when VAD is enabled.
1289 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001290 frame_->vad_activity_ = AudioFrame::kVadUnknown;
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001291 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001292 EXPECT_NE(AudioFrame::kVadUnknown, frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001293
niklase@google.com470e71d2011-07-07 08:21:25 +00001294 // TODO(bjornv): Add tests for streamed voice; stream_has_voice()
1295}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001296
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001297TEST_F(ApmTest, AllProcessingDisabledByDefault) {
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001298 AudioProcessing::Config config = apm_->GetConfig();
1299 EXPECT_FALSE(config.echo_canceller.enabled);
1300 EXPECT_FALSE(config.high_pass_filter.enabled);
Sam Zackrisson11b87032018-12-18 17:13:58 +01001301 EXPECT_FALSE(config.level_estimation.enabled);
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001302 EXPECT_FALSE(config.voice_detection.enabled);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001303 EXPECT_FALSE(apm_->gain_control()->is_enabled());
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001304 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1305 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1306 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1307}
1308
1309TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001310 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001311 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001312 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001313 AudioFrame frame_copy;
1314 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001315 for (int j = 0; j < 1000; j++) {
1316 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1317 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001318 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1319 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001320 }
1321 }
1322}
1323
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001324TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1325 // Test that ProcessStream copies input to output even with no processing.
1326 const size_t kSamples = 80;
1327 const int sample_rate = 8000;
1328 const float src[kSamples] = {
1329 -1.0f, 0.0f, 1.0f
1330 };
1331 float dest[kSamples] = {};
1332
1333 auto src_channels = &src[0];
1334 auto dest_channels = &dest[0];
1335
Ivo Creusen62337e52018-01-09 14:17:33 +01001336 apm_.reset(AudioProcessingBuilder().Create());
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001337 EXPECT_NOERR(apm_->ProcessStream(
1338 &src_channels, kSamples, sample_rate, LayoutFromChannels(1),
1339 sample_rate, LayoutFromChannels(1), &dest_channels));
1340
1341 for (size_t i = 0; i < kSamples; ++i) {
1342 EXPECT_EQ(src[i], dest[i]);
1343 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001344
1345 // Same for ProcessReverseStream.
1346 float rev_dest[kSamples] = {};
1347 auto rev_dest_channels = &rev_dest[0];
1348
1349 StreamConfig input_stream = {sample_rate, 1};
1350 StreamConfig output_stream = {sample_rate, 1};
1351 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1352 output_stream, &rev_dest_channels));
1353
1354 for (size_t i = 0; i < kSamples; ++i) {
1355 EXPECT_EQ(src[i], rev_dest[i]);
1356 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001357}
1358
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001359TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1360 EnableAllComponents();
1361
pkasting25702cb2016-01-08 13:50:27 -08001362 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001363 Init(kProcessSampleRates[i],
1364 kProcessSampleRates[i],
1365 kProcessSampleRates[i],
1366 2,
1367 2,
1368 2,
1369 false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001370 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001371 ASSERT_EQ(0, feof(far_file_));
1372 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001373 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001374 CopyLeftToRightChannel(revframe_->mutable_data(),
1375 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001376
aluebsb0319552016-03-17 20:39:53 -07001377 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001378
yujo36b1a5f2017-06-12 12:45:32 -07001379 CopyLeftToRightChannel(frame_->mutable_data(),
1380 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001381 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1382
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001383 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001384 ASSERT_EQ(kNoErr,
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001385 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001386 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001387 analog_level = apm_->gain_control()->stream_analog_level();
1388
yujo36b1a5f2017-06-12 12:45:32 -07001389 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001390 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001391 rewind(far_file_);
1392 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001393 }
1394}
1395
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001396TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001397 // Verify the filter is not active through undistorted audio when:
1398 // 1. No components are enabled...
1399 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001400 AudioFrame frame_copy;
1401 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001402 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1403 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1404 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1405
1406 // 2. Only the level estimator is enabled...
1407 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001408 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001409 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1410 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1411 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1412 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1413 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1414
1415 // 3. Only VAD is enabled...
1416 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001417 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001418 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1419 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1420 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1421 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1422 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1423
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001424 // 4. Only GetStatistics-reporting VAD is enabled...
1425 SetFrameTo(frame_, 1000);
1426 frame_copy.CopyFrom(*frame_);
1427 auto apm_config = apm_->GetConfig();
1428 apm_config.voice_detection.enabled = true;
1429 apm_->ApplyConfig(apm_config);
1430 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1431 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1432 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1433 apm_config.voice_detection.enabled = false;
1434 apm_->ApplyConfig(apm_config);
1435
1436 // 5. Both VADs and the level estimator are enabled...
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001437 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001438 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001439 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1440 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001441 apm_config.voice_detection.enabled = true;
1442 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001443 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1444 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1445 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1446 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1447 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
Sam Zackrisson6c330ab2019-01-04 10:35:53 +01001448 apm_config.voice_detection.enabled = false;
1449 apm_->ApplyConfig(apm_config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001450
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001451 // Check the test is valid. We should have distortion from the filter
1452 // when AEC is enabled (which won't affect the audio).
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001453 apm_config.echo_canceller.enabled = true;
Per Ã…hgren200feba2019-03-06 04:16:46 +01001454 // TODO(peah): Update tests to instead use AEC3.
1455 apm_config.echo_canceller.use_legacy_aec = true;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001456 apm_config.echo_canceller.mobile_mode = false;
1457 apm_->ApplyConfig(apm_config);
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001458 frame_->samples_per_channel_ = 320;
1459 frame_->num_channels_ = 2;
1460 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001461 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001462 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001463 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001464 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1465 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1466}
1467
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001468#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1469void ApmTest::ProcessDebugDump(const std::string& in_filename,
1470 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001471 Format format,
1472 int max_size_bytes) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001473 TaskQueueForTest worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001474 FILE* in_file = fopen(in_filename.c_str(), "rb");
1475 ASSERT_TRUE(in_file != NULL);
1476 audioproc::Event event_msg;
1477 bool first_init = true;
1478
1479 while (ReadMessageFromFile(in_file, &event_msg)) {
1480 if (event_msg.type() == audioproc::Event::INIT) {
1481 const audioproc::Init msg = event_msg.init();
1482 int reverse_sample_rate = msg.sample_rate();
1483 if (msg.has_reverse_sample_rate()) {
1484 reverse_sample_rate = msg.reverse_sample_rate();
1485 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001486 int output_sample_rate = msg.sample_rate();
1487 if (msg.has_output_sample_rate()) {
1488 output_sample_rate = msg.output_sample_rate();
1489 }
1490
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001491 Init(msg.sample_rate(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001492 output_sample_rate,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001493 reverse_sample_rate,
1494 msg.num_input_channels(),
1495 msg.num_output_channels(),
1496 msg.num_reverse_channels(),
1497 false);
1498 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001499 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001500 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001501 auto aec_dump =
1502 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1503 EXPECT_TRUE(aec_dump);
1504 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001505 first_init = false;
1506 }
1507
1508 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1509 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1510
1511 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001512 ASSERT_EQ(revframe_->num_channels_,
1513 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001514 for (int i = 0; i < msg.channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001515 memcpy(revfloat_cb_->channels()[i],
1516 msg.channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001517 msg.channel(i).size());
1518 }
1519 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001520 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001521 if (format == kFloatFormat) {
1522 // We're using an int16 input file; convert to float.
1523 ConvertToFloat(*revframe_, revfloat_cb_.get());
1524 }
1525 }
1526 AnalyzeReverseStreamChooser(format);
1527
1528 } else if (event_msg.type() == audioproc::Event::STREAM) {
1529 const audioproc::Stream msg = event_msg.stream();
1530 // ProcessStream could have changed this for the output frame.
1531 frame_->num_channels_ = apm_->num_input_channels();
1532
1533 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1534 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001535 if (msg.has_keypress()) {
1536 apm_->set_stream_key_pressed(msg.keypress());
1537 } else {
1538 apm_->set_stream_key_pressed(true);
1539 }
1540
1541 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001542 ASSERT_EQ(frame_->num_channels_,
1543 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001544 for (int i = 0; i < msg.input_channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001545 memcpy(float_cb_->channels()[i],
1546 msg.input_channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001547 msg.input_channel(i).size());
1548 }
1549 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001550 memcpy(frame_->mutable_data(), msg.input_data().data(),
1551 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001552 if (format == kFloatFormat) {
1553 // We're using an int16 input file; convert to float.
1554 ConvertToFloat(*frame_, float_cb_.get());
1555 }
1556 }
1557 ProcessStreamChooser(format);
1558 }
1559 }
aleloif4dd1912017-06-15 01:55:38 -07001560 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001561 fclose(in_file);
1562}
1563
1564void ApmTest::VerifyDebugDumpTest(Format format) {
Minyue Li656d6092018-08-10 15:38:52 +02001565 rtc::ScopedFakeClock fake_clock;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001566 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001567 std::string format_string;
1568 switch (format) {
1569 case kIntFormat:
1570 format_string = "_int";
1571 break;
1572 case kFloatFormat:
1573 format_string = "_float";
1574 break;
1575 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001576 const std::string ref_filename = test::TempFilename(
1577 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1578 const std::string out_filename = test::TempFilename(
1579 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001580 const std::string limited_filename = test::TempFilename(
1581 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1582 const size_t logging_limit_bytes = 100000;
1583 // We expect at least this many bytes in the created logfile.
1584 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001585 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001586 ProcessDebugDump(in_filename, ref_filename, format, -1);
1587 ProcessDebugDump(ref_filename, out_filename, format, -1);
1588 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001589
1590 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1591 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001592 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001593 ASSERT_TRUE(ref_file != NULL);
1594 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001595 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001596 std::unique_ptr<uint8_t[]> ref_bytes;
1597 std::unique_ptr<uint8_t[]> out_bytes;
1598 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001599
1600 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1601 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001602 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001603 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001604 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001605 while (ref_size > 0 && out_size > 0) {
1606 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001607 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001608 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001609 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001610 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001611 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001612 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1613 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001614 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001615 }
1616 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001617 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1618 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001619 EXPECT_NE(0, feof(ref_file));
1620 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001621 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001622 ASSERT_EQ(0, fclose(ref_file));
1623 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001624 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001625 remove(ref_filename.c_str());
1626 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001627 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001628}
1629
pbosc7a65692016-05-06 12:50:04 -07001630TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001631 VerifyDebugDumpTest(kIntFormat);
1632}
1633
pbosc7a65692016-05-06 12:50:04 -07001634TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001635 VerifyDebugDumpTest(kFloatFormat);
1636}
1637#endif
1638
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001639// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001640TEST_F(ApmTest, DebugDump) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001641 TaskQueueForTest worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001642 const std::string filename =
1643 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001644 {
1645 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1646 EXPECT_FALSE(aec_dump);
1647 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001648
1649#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1650 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001651 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001652
aleloif4dd1912017-06-15 01:55:38 -07001653 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1654 EXPECT_TRUE(aec_dump);
1655 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001656 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001657 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001658 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001659
1660 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001661 FILE* fid = fopen(filename.c_str(), "r");
1662 ASSERT_TRUE(fid != NULL);
1663
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001664 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001665 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001666 ASSERT_EQ(0, remove(filename.c_str()));
1667#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001668 // Verify the file has NOT been written.
1669 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1670#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1671}
1672
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001673// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001674TEST_F(ApmTest, DebugDumpFromFileHandle) {
Danil Chapovalov07122bc2019-03-26 14:37:01 +01001675 TaskQueueForTest worker_queue("ApmTest_worker_queue");
aleloif4dd1912017-06-15 01:55:38 -07001676
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001677 const std::string filename =
1678 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001679 FILE* fid = fopen(filename.c_str(), "w");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001680 ASSERT_TRUE(fid);
1681
1682#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1683 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001684 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001685
aleloif4dd1912017-06-15 01:55:38 -07001686 auto aec_dump = AecDumpFactory::Create(fid, -1, &worker_queue);
1687 EXPECT_TRUE(aec_dump);
1688 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001689 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001690 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001691 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001692
1693 // Verify the file has been written.
1694 fid = fopen(filename.c_str(), "r");
1695 ASSERT_TRUE(fid != NULL);
1696
1697 // Clean it up.
1698 ASSERT_EQ(0, fclose(fid));
1699 ASSERT_EQ(0, remove(filename.c_str()));
1700#else
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001701 ASSERT_EQ(0, fclose(fid));
1702#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1703}
1704
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001705TEST_F(ApmTest, FloatAndIntInterfacesGiveSimilarResults) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001706 audioproc::OutputData ref_data;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001707 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001708
1709 Config config;
1710 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001711 std::unique_ptr<AudioProcessing> fapm(
1712 AudioProcessingBuilder().Create(config));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001713 EnableAllComponents();
1714 EnableAllAPComponents(fapm.get());
1715 for (int i = 0; i < ref_data.test_size(); i++) {
1716 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
1717
1718 audioproc::Test* test = ref_data.mutable_test(i);
1719 // TODO(ajm): Restore downmixing test cases.
1720 if (test->num_input_channels() != test->num_output_channels())
1721 continue;
1722
Peter Kasting69558702016-01-12 16:26:35 -08001723 const size_t num_render_channels =
1724 static_cast<size_t>(test->num_reverse_channels());
1725 const size_t num_input_channels =
1726 static_cast<size_t>(test->num_input_channels());
1727 const size_t num_output_channels =
1728 static_cast<size_t>(test->num_output_channels());
pkasting25702cb2016-01-08 13:50:27 -08001729 const size_t samples_per_channel = static_cast<size_t>(
1730 test->sample_rate() * AudioProcessing::kChunkSizeMs / 1000);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001731
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001732 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
1733 num_input_channels, num_output_channels, num_render_channels, true);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001734 Init(fapm.get());
1735
1736 ChannelBuffer<int16_t> output_cb(samples_per_channel, num_input_channels);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001737 ChannelBuffer<int16_t> output_int16(samples_per_channel,
1738 num_input_channels);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001739
1740 int analog_level = 127;
aluebs776593b2016-03-15 14:04:58 -07001741 size_t num_bad_chunks = 0;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001742 while (ReadFrame(far_file_, revframe_, revfloat_cb_.get()) &&
1743 ReadFrame(near_file_, frame_, float_cb_.get())) {
1744 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1745
aluebsb0319552016-03-17 20:39:53 -07001746 EXPECT_NOERR(apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001747 EXPECT_NOERR(fapm->AnalyzeReverseStream(
1748 revfloat_cb_->channels(),
1749 samples_per_channel,
1750 test->sample_rate(),
1751 LayoutFromChannels(num_render_channels)));
1752
1753 EXPECT_NOERR(apm_->set_stream_delay_ms(0));
1754 EXPECT_NOERR(fapm->set_stream_delay_ms(0));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001755 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(analog_level));
1756 EXPECT_NOERR(fapm->gain_control()->set_stream_analog_level(analog_level));
1757
1758 EXPECT_NOERR(apm_->ProcessStream(frame_));
yujo36b1a5f2017-06-12 12:45:32 -07001759 Deinterleave(frame_->data(), samples_per_channel, num_output_channels,
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001760 output_int16.channels());
1761
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001762 EXPECT_NOERR(fapm->ProcessStream(
1763 float_cb_->channels(),
1764 samples_per_channel,
1765 test->sample_rate(),
1766 LayoutFromChannels(num_input_channels),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001767 test->sample_rate(),
1768 LayoutFromChannels(num_output_channels),
1769 float_cb_->channels()));
Peter Kasting69558702016-01-12 16:26:35 -08001770 for (size_t j = 0; j < num_output_channels; ++j) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001771 FloatToS16(float_cb_->channels()[j],
1772 samples_per_channel,
1773 output_cb.channels()[j]);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001774 float variance = 0;
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001775 float snr = ComputeSNR(output_int16.channels()[j],
1776 output_cb.channels()[j],
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001777 samples_per_channel, &variance);
aluebs776593b2016-03-15 14:04:58 -07001778
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001779 const float kVarianceThreshold = 20;
1780 const float kSNRThreshold = 20;
aluebs776593b2016-03-15 14:04:58 -07001781
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001782 // Skip frames with low energy.
aluebs776593b2016-03-15 14:04:58 -07001783 if (sqrt(variance) > kVarianceThreshold && snr < kSNRThreshold) {
1784 ++num_bad_chunks;
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001785 }
1786 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001787
1788 analog_level = fapm->gain_control()->stream_analog_level();
1789 EXPECT_EQ(apm_->gain_control()->stream_analog_level(),
1790 fapm->gain_control()->stream_analog_level());
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001791 EXPECT_NEAR(apm_->noise_suppression()->speech_probability(),
1792 fapm->noise_suppression()->speech_probability(),
Alejandro Luebs47748742015-05-22 12:00:21 -07001793 0.01);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001794
1795 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08001796 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001797 }
aluebs776593b2016-03-15 14:04:58 -07001798
1799#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1800 const size_t kMaxNumBadChunks = 0;
1801#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
1802 // There are a few chunks in the fixed-point profile that give low SNR.
1803 // Listening confirmed the difference is acceptable.
1804 const size_t kMaxNumBadChunks = 60;
1805#endif
1806 EXPECT_LE(num_bad_chunks, kMaxNumBadChunks);
1807
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001808 rewind(far_file_);
1809 rewind(near_file_);
1810 }
1811}
1812
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001813// TODO(andrew): Add a test to process a few frames with different combinations
1814// of enabled components.
1815
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001816TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001817 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001818 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001819
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001820 if (!write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001821 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001822 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001823 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08001824 for (size_t i = 0; i < arraysize(kChannels); i++) {
1825 for (size_t j = 0; j < arraysize(kChannels); j++) {
1826 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001827 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001828 test->set_num_reverse_channels(kChannels[i]);
1829 test->set_num_input_channels(kChannels[j]);
1830 test->set_num_output_channels(kChannels[j]);
1831 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001832 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001833 }
1834 }
1835 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001836#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1837 // To test the extended filter mode.
1838 audioproc::Test* test = ref_data.add_test();
1839 test->set_num_reverse_channels(2);
1840 test->set_num_input_channels(2);
1841 test->set_num_output_channels(2);
1842 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
1843 test->set_use_aec_extended_filter(true);
1844#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001845 }
1846
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001847 for (int i = 0; i < ref_data.test_size(); i++) {
1848 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001849
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001850 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001851 // TODO(ajm): We no longer allow different input and output channels. Skip
1852 // these tests for now, but they should be removed from the set.
1853 if (test->num_input_channels() != test->num_output_channels())
1854 continue;
1855
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001856 Config config;
1857 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02001858 config.Set<ExtendedFilter>(
1859 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01001860 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001861
1862 EnableAllComponents();
1863
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001864 Init(test->sample_rate(),
1865 test->sample_rate(),
1866 test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08001867 static_cast<size_t>(test->num_input_channels()),
1868 static_cast<size_t>(test->num_output_channels()),
1869 static_cast<size_t>(test->num_reverse_channels()),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001870 true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001871
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001872 int frame_count = 0;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001873 int has_voice_count = 0;
1874 int is_saturated_count = 0;
1875 int analog_level = 127;
1876 int analog_level_average = 0;
1877 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001878 float ns_speech_prob_average = 0.0f;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001879 float rms_dbfs_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07001880#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1881 int stats_index = 0;
1882#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001883
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001884 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07001885 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001886
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001887 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1888
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001889 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001890 EXPECT_EQ(apm_->kNoError,
1891 apm_->gain_control()->set_stream_analog_level(analog_level));
1892
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001893 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001894
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001895 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08001896 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
1897 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001898
1899 max_output_average += MaxAudioFrame(*frame_);
1900
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001901 analog_level = apm_->gain_control()->stream_analog_level();
1902 analog_level_average += analog_level;
1903 if (apm_->gain_control()->stream_is_saturated()) {
1904 is_saturated_count++;
1905 }
1906 if (apm_->voice_detection()->stream_has_voice()) {
1907 has_voice_count++;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001908 EXPECT_EQ(AudioFrame::kVadActive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001909 } else {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001910 EXPECT_EQ(AudioFrame::kVadPassive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001911 }
1912
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001913 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
Sam Zackrisson11b87032018-12-18 17:13:58 +01001914 AudioProcessingStats stats =
1915 apm_->GetStatistics(/*has_remote_tracks=*/false);
1916 rms_dbfs_average += *stats.output_rms_dbfs;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001917
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001918 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001919 size_t write_count = fwrite(frame_->data(),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001920 sizeof(int16_t),
1921 frame_size,
1922 out_file_);
1923 ASSERT_EQ(frame_size, write_count);
1924
1925 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08001926 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001927 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07001928
1929#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1930 const int kStatsAggregationFrameNum = 100; // 1 second.
1931 if (frame_count % kStatsAggregationFrameNum == 0) {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001932 // Get echo and delay metrics.
1933 AudioProcessingStats stats =
1934 apm_->GetStatistics(true /* has_remote_tracks */);
minyue58530ed2016-05-24 05:50:12 -07001935
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001936 // Echo metrics.
1937 const float echo_return_loss = stats.echo_return_loss.value_or(-1.0f);
1938 const float echo_return_loss_enhancement =
1939 stats.echo_return_loss_enhancement.value_or(-1.0f);
1940 const float divergent_filter_fraction =
1941 stats.divergent_filter_fraction.value_or(-1.0f);
1942 const float residual_echo_likelihood =
1943 stats.residual_echo_likelihood.value_or(-1.0f);
1944 const float residual_echo_likelihood_recent_max =
1945 stats.residual_echo_likelihood_recent_max.value_or(-1.0f);
1946
1947 // Delay metrics.
1948 const int32_t delay_median_ms = stats.delay_median_ms.value_or(-1.0);
1949 const int32_t delay_standard_deviation_ms =
1950 stats.delay_standard_deviation_ms.value_or(-1.0);
minyue58530ed2016-05-24 05:50:12 -07001951
minyue58530ed2016-05-24 05:50:12 -07001952 if (!write_ref_data) {
1953 const audioproc::Test::EchoMetrics& reference =
1954 test->echo_metrics(stats_index);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001955 constexpr float kEpsilon = 0.01;
1956 EXPECT_NEAR(echo_return_loss, reference.echo_return_loss(), kEpsilon);
1957 EXPECT_NEAR(echo_return_loss_enhancement,
1958 reference.echo_return_loss_enhancement(), kEpsilon);
1959 EXPECT_NEAR(divergent_filter_fraction,
1960 reference.divergent_filter_fraction(), kEpsilon);
1961 EXPECT_NEAR(residual_echo_likelihood,
1962 reference.residual_echo_likelihood(), kEpsilon);
1963 EXPECT_NEAR(residual_echo_likelihood_recent_max,
1964 reference.residual_echo_likelihood_recent_max(),
1965 kEpsilon);
minyue58530ed2016-05-24 05:50:12 -07001966
1967 const audioproc::Test::DelayMetrics& reference_delay =
1968 test->delay_metrics(stats_index);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001969 EXPECT_EQ(reference_delay.median(), delay_median_ms);
1970 EXPECT_EQ(reference_delay.std(), delay_standard_deviation_ms);
minyue58530ed2016-05-24 05:50:12 -07001971
minyue58530ed2016-05-24 05:50:12 -07001972 ++stats_index;
1973 } else {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001974 audioproc::Test::EchoMetrics* message_echo = test->add_echo_metrics();
1975 message_echo->set_echo_return_loss(echo_return_loss);
1976 message_echo->set_echo_return_loss_enhancement(
1977 echo_return_loss_enhancement);
1978 message_echo->set_divergent_filter_fraction(
1979 divergent_filter_fraction);
1980 message_echo->set_residual_echo_likelihood(residual_echo_likelihood);
1981 message_echo->set_residual_echo_likelihood_recent_max(
1982 residual_echo_likelihood_recent_max);
minyue58530ed2016-05-24 05:50:12 -07001983 audioproc::Test::DelayMetrics* message_delay =
1984 test->add_delay_metrics();
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001985 message_delay->set_median(delay_median_ms);
1986 message_delay->set_std(delay_standard_deviation_ms);
minyue58530ed2016-05-24 05:50:12 -07001987 }
1988 }
1989#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001990 }
1991 max_output_average /= frame_count;
1992 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001993 ns_speech_prob_average /= frame_count;
Sam Zackrisson11b87032018-12-18 17:13:58 +01001994 rms_dbfs_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001995
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001996 if (!write_ref_data) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001997 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001998 // When running the test on a N7 we get a {2, 6} difference of
1999 // |has_voice_count| and |max_output_average| is up to 18 higher.
2000 // All numbers being consistently higher on N7 compare to ref_data.
2001 // TODO(bjornv): If we start getting more of these offsets on Android we
2002 // should consider a different approach. Either using one slack for all,
2003 // or generate a separate android reference.
Kári Tristan Helgason640106e2018-09-06 15:29:45 +02002004#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002005 const int kHasVoiceCountOffset = 3;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02002006 const int kHasVoiceCountNear = 8;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002007 const int kMaxOutputAverageOffset = 9;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02002008 const int kMaxOutputAverageNear = 26;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002009#else
2010 const int kHasVoiceCountOffset = 0;
2011 const int kHasVoiceCountNear = kIntNear;
2012 const int kMaxOutputAverageOffset = 0;
2013 const int kMaxOutputAverageNear = kIntNear;
2014#endif
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002015 EXPECT_NEAR(test->has_voice_count(),
2016 has_voice_count - kHasVoiceCountOffset,
2017 kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002018 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002019
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002020 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002021 EXPECT_NEAR(test->max_output_average(),
2022 max_output_average - kMaxOutputAverageOffset,
2023 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002024#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002025 const double kFloatNear = 0.0005;
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002026 EXPECT_NEAR(test->ns_speech_probability_average(),
2027 ns_speech_prob_average,
2028 kFloatNear);
Sam Zackrisson11b87032018-12-18 17:13:58 +01002029 EXPECT_NEAR(test->rms_dbfs_average(), rms_dbfs_average, kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002030#endif
2031 } else {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002032 test->set_has_voice_count(has_voice_count);
2033 test->set_is_saturated_count(is_saturated_count);
2034
2035 test->set_analog_level_average(analog_level_average);
2036 test->set_max_output_average(max_output_average);
2037
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002038#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002039 EXPECT_LE(0.0f, ns_speech_prob_average);
2040 EXPECT_GE(1.0f, ns_speech_prob_average);
2041 test->set_ns_speech_probability_average(ns_speech_prob_average);
Sam Zackrisson11b87032018-12-18 17:13:58 +01002042 test->set_rms_dbfs_average(rms_dbfs_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002043#endif
2044 }
2045
2046 rewind(far_file_);
2047 rewind(near_file_);
2048 }
2049
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002050 if (write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002051 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002052 }
2053}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002054
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002055TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
2056 struct ChannelFormat {
2057 AudioProcessing::ChannelLayout in_layout;
2058 AudioProcessing::ChannelLayout out_layout;
2059 };
2060 ChannelFormat cf[] = {
2061 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
2062 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
2063 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
2064 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002065
Ivo Creusen62337e52018-01-09 14:17:33 +01002066 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002067 // Enable one component just to ensure some processing takes place.
2068 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08002069 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002070 const int in_rate = 44100;
2071 const int out_rate = 48000;
2072 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
2073 TotalChannelsFromLayout(cf[i].in_layout));
2074 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
2075 ChannelsFromLayout(cf[i].out_layout));
2076
2077 // Run over a few chunks.
2078 for (int j = 0; j < 10; ++j) {
2079 EXPECT_NOERR(ap->ProcessStream(
2080 in_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002081 in_cb.num_frames(),
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002082 in_rate,
2083 cf[i].in_layout,
2084 out_rate,
2085 cf[i].out_layout,
2086 out_cb.channels()));
2087 }
2088 }
2089}
2090
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002091// Compares the reference and test arrays over a region around the expected
2092// delay. Finds the highest SNR in that region and adds the variance and squared
2093// error results to the supplied accumulators.
2094void UpdateBestSNR(const float* ref,
2095 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08002096 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002097 int expected_delay,
2098 double* variance_acc,
2099 double* sq_error_acc) {
2100 double best_snr = std::numeric_limits<double>::min();
2101 double best_variance = 0;
2102 double best_sq_error = 0;
2103 // Search over a region of eight samples around the expected delay.
2104 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
2105 ++delay) {
2106 double sq_error = 0;
2107 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08002108 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002109 double error = test[i + delay] - ref[i];
2110 sq_error += error * error;
2111 variance += ref[i] * ref[i];
2112 }
2113
2114 if (sq_error == 0) {
2115 *variance_acc += variance;
2116 return;
2117 }
2118 double snr = variance / sq_error;
2119 if (snr > best_snr) {
2120 best_snr = snr;
2121 best_variance = variance;
2122 best_sq_error = sq_error;
2123 }
2124 }
2125
2126 *variance_acc += best_variance;
2127 *sq_error_acc += best_sq_error;
2128}
2129
2130// Used to test a multitude of sample rate and channel combinations. It works
2131// by first producing a set of reference files (in SetUpTestCase) that are
2132// assumed to be correct, as the used parameters are verified by other tests
2133// in this collection. Primarily the reference files are all produced at
2134// "native" rates which do not involve any resampling.
2135
2136// Each test pass produces an output file with a particular format. The output
2137// is matched against the reference file closest to its internal processing
2138// format. If necessary the output is resampled back to its process format.
2139// Due to the resampling distortion, we don't expect identical results, but
2140// enforce SNR thresholds which vary depending on the format. 0 is a special
2141// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02002142typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002143class AudioProcessingTest
2144 : public testing::TestWithParam<AudioProcessingTestData> {
2145 public:
2146 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02002147 : input_rate_(std::get<0>(GetParam())),
2148 output_rate_(std::get<1>(GetParam())),
2149 reverse_input_rate_(std::get<2>(GetParam())),
2150 reverse_output_rate_(std::get<3>(GetParam())),
2151 expected_snr_(std::get<4>(GetParam())),
2152 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002153
2154 virtual ~AudioProcessingTest() {}
2155
2156 static void SetUpTestCase() {
2157 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07002158 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08002159 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08002160 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
2161 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
2162 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002163 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07002164 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
2165 kNativeRates[i], kNumChannels[j], kNumChannels[j],
2166 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002167 }
2168 }
2169 }
2170 }
2171
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02002172 void TearDown() {
2173 // Remove "out" files after each test.
2174 ClearTempOutFiles();
2175 }
2176
pbos@webrtc.org200ac002015-02-03 14:14:01 +00002177 static void TearDownTestCase() {
2178 ClearTempFiles();
2179 }
ekmeyerson60d9b332015-08-14 10:35:55 -07002180
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002181 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07002182 // to a file specified with |output_file_prefix|. Both forward and reverse
2183 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002184 static void ProcessFormat(int input_rate,
2185 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07002186 int reverse_input_rate,
2187 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08002188 size_t num_input_channels,
2189 size_t num_output_channels,
2190 size_t num_reverse_input_channels,
2191 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02002192 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002193 Config config;
2194 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01002195 std::unique_ptr<AudioProcessing> ap(
2196 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002197 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002198
ekmeyerson60d9b332015-08-14 10:35:55 -07002199 ProcessingConfig processing_config = {
2200 {{input_rate, num_input_channels},
2201 {output_rate, num_output_channels},
2202 {reverse_input_rate, num_reverse_input_channels},
2203 {reverse_output_rate, num_reverse_output_channels}}};
2204 ap->Initialize(processing_config);
2205
2206 FILE* far_file =
2207 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002208 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07002209 FILE* out_file =
2210 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2211 reverse_input_rate, reverse_output_rate,
2212 num_input_channels, num_output_channels,
2213 num_reverse_input_channels,
2214 num_reverse_output_channels, kForward).c_str(),
2215 "wb");
2216 FILE* rev_out_file =
2217 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2218 reverse_input_rate, reverse_output_rate,
2219 num_input_channels, num_output_channels,
2220 num_reverse_input_channels,
2221 num_reverse_output_channels, kReverse).c_str(),
2222 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002223 ASSERT_TRUE(far_file != NULL);
2224 ASSERT_TRUE(near_file != NULL);
2225 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07002226 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002227
2228 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
2229 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002230 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
2231 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002232 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
2233 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002234 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
2235 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002236
2237 // Temporary buffers.
2238 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07002239 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
2240 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08002241 std::unique_ptr<float[]> float_data(new float[max_length]);
2242 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002243
2244 int analog_level = 127;
2245 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
2246 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002247 EXPECT_NOERR(ap->ProcessReverseStream(
2248 rev_cb.channels(), processing_config.reverse_input_stream(),
2249 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002250
2251 EXPECT_NOERR(ap->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002252 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
2253
2254 EXPECT_NOERR(ap->ProcessStream(
2255 fwd_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002256 fwd_cb.num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002257 input_rate,
2258 LayoutFromChannels(num_input_channels),
2259 output_rate,
2260 LayoutFromChannels(num_output_channels),
2261 out_cb.channels()));
2262
ekmeyerson60d9b332015-08-14 10:35:55 -07002263 // Dump forward output to file.
2264 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002265 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002266 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002267
pkasting25702cb2016-01-08 13:50:27 -08002268 ASSERT_EQ(out_length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002269 fwrite(float_data.get(), sizeof(float_data[0]),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002270 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002271
ekmeyerson60d9b332015-08-14 10:35:55 -07002272 // Dump reverse output to file.
2273 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
2274 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002275 size_t rev_out_length =
2276 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002277
pkasting25702cb2016-01-08 13:50:27 -08002278 ASSERT_EQ(rev_out_length,
ekmeyerson60d9b332015-08-14 10:35:55 -07002279 fwrite(float_data.get(), sizeof(float_data[0]), rev_out_length,
2280 rev_out_file));
2281
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002282 analog_level = ap->gain_control()->stream_analog_level();
2283 }
2284 fclose(far_file);
2285 fclose(near_file);
2286 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07002287 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002288 }
2289
2290 protected:
2291 int input_rate_;
2292 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002293 int reverse_input_rate_;
2294 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002295 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002296 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002297};
2298
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00002299TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002300 struct ChannelFormat {
2301 int num_input;
2302 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07002303 int num_reverse_input;
2304 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002305 };
2306 ChannelFormat cf[] = {
ekmeyerson60d9b332015-08-14 10:35:55 -07002307 {1, 1, 1, 1},
2308 {1, 1, 2, 1},
2309 {2, 1, 1, 1},
2310 {2, 1, 2, 1},
2311 {2, 2, 1, 1},
2312 {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002313 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002314
pkasting25702cb2016-01-08 13:50:27 -08002315 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002316 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
2317 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
2318 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07002319
ekmeyerson60d9b332015-08-14 10:35:55 -07002320 // Verify output for both directions.
2321 std::vector<StreamDirection> stream_directions;
2322 stream_directions.push_back(kForward);
2323 stream_directions.push_back(kReverse);
2324 for (StreamDirection file_direction : stream_directions) {
2325 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
2326 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
2327 const int out_num =
2328 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
2329 const double expected_snr =
2330 file_direction ? expected_reverse_snr_ : expected_snr_;
2331
2332 const int min_ref_rate = std::min(in_rate, out_rate);
2333 int ref_rate;
2334
2335 if (min_ref_rate > 32000) {
2336 ref_rate = 48000;
2337 } else if (min_ref_rate > 16000) {
2338 ref_rate = 32000;
2339 } else if (min_ref_rate > 8000) {
2340 ref_rate = 16000;
2341 } else {
2342 ref_rate = 8000;
2343 }
aluebs776593b2016-03-15 14:04:58 -07002344#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08002345 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07002346 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08002347 }
2348#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07002349 FILE* out_file = fopen(
2350 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
2351 reverse_output_rate_, cf[i].num_input,
2352 cf[i].num_output, cf[i].num_reverse_input,
2353 cf[i].num_reverse_output, file_direction).c_str(),
2354 "rb");
2355 // The reference files always have matching input and output channels.
2356 FILE* ref_file = fopen(
2357 OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
2358 cf[i].num_output, cf[i].num_output,
2359 cf[i].num_reverse_output, cf[i].num_reverse_output,
2360 file_direction).c_str(),
2361 "rb");
2362 ASSERT_TRUE(out_file != NULL);
2363 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002364
pkasting25702cb2016-01-08 13:50:27 -08002365 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2366 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002367 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002368 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002369 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002370 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002371 // Data from the resampled output, in case the reference and output rates
2372 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002373 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002374
ekmeyerson60d9b332015-08-14 10:35:55 -07002375 PushResampler<float> resampler;
2376 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002377
ekmeyerson60d9b332015-08-14 10:35:55 -07002378 // Compute the resampling delay of the output relative to the reference,
2379 // to find the region over which we should search for the best SNR.
2380 float expected_delay_sec = 0;
2381 if (in_rate != ref_rate) {
2382 // Input resampling delay.
2383 expected_delay_sec +=
2384 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2385 }
2386 if (out_rate != ref_rate) {
2387 // Output resampling delay.
2388 expected_delay_sec +=
2389 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2390 // Delay of converting the output back to its processing rate for
2391 // testing.
2392 expected_delay_sec +=
2393 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2394 }
2395 int expected_delay =
2396 floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002397
ekmeyerson60d9b332015-08-14 10:35:55 -07002398 double variance = 0;
2399 double sq_error = 0;
2400 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2401 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2402 float* out_ptr = out_data.get();
2403 if (out_rate != ref_rate) {
2404 // Resample the output back to its internal processing rate if
2405 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002406 ASSERT_EQ(ref_length,
2407 static_cast<size_t>(resampler.Resample(
2408 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002409 out_ptr = cmp_data.get();
2410 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002411
ekmeyerson60d9b332015-08-14 10:35:55 -07002412 // Update the |sq_error| and |variance| accumulators with the highest
2413 // SNR of reference vs output.
2414 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2415 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002416 }
2417
ekmeyerson60d9b332015-08-14 10:35:55 -07002418 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2419 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2420 << cf[i].num_input << ", " << cf[i].num_output << ", "
2421 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2422 << ", " << file_direction << "): ";
2423 if (sq_error > 0) {
2424 double snr = 10 * log10(variance / sq_error);
2425 EXPECT_GE(snr, expected_snr);
2426 EXPECT_NE(0, expected_snr);
2427 std::cout << "SNR=" << snr << " dB" << std::endl;
2428 } else {
aluebs776593b2016-03-15 14:04:58 -07002429 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002430 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002431
ekmeyerson60d9b332015-08-14 10:35:55 -07002432 fclose(out_file);
2433 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002434 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002435 }
2436}
2437
2438#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002439INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002440 CommonFormats,
2441 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002442 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2443 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2444 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2445 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2446 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2447 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2448 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2449 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2450 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2451 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2452 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2453 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002454
Edward Lemurc5ee9872017-10-23 23:33:04 +02002455 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2456 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2457 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2458 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2459 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2460 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2461 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2462 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2463 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2464 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2465 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2466 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002467
Edward Lemurc5ee9872017-10-23 23:33:04 +02002468 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
Per Ã…hgren200feba2019-03-06 04:16:46 +01002469 std::make_tuple(32000, 48000, 32000, 48000, 32, 30),
Edward Lemurc5ee9872017-10-23 23:33:04 +02002470 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
Per Ã…hgren200feba2019-03-06 04:16:46 +01002471 std::make_tuple(32000, 44100, 48000, 44100, 19, 20),
2472 std::make_tuple(32000, 44100, 32000, 44100, 19, 15),
2473 std::make_tuple(32000, 44100, 16000, 44100, 19, 15),
Edward Lemurc5ee9872017-10-23 23:33:04 +02002474 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2475 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2476 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2477 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2478 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2479 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002480
Per Ã…hgren200feba2019-03-06 04:16:46 +01002481 std::make_tuple(16000, 48000, 48000, 48000, 24, 0),
2482 std::make_tuple(16000, 48000, 32000, 48000, 24, 30),
2483 std::make_tuple(16000, 48000, 16000, 48000, 24, 20),
Edward Lemurc5ee9872017-10-23 23:33:04 +02002484 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2485 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2486 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2487 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2488 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2489 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
Per Ã…hgren200feba2019-03-06 04:16:46 +01002490 std::make_tuple(16000, 16000, 48000, 16000, 39, 20),
Edward Lemurc5ee9872017-10-23 23:33:04 +02002491 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2492 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002493
2494#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
Mirko Bonadeic84f6612019-01-31 12:20:57 +01002495INSTANTIATE_TEST_SUITE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002496 CommonFormats,
2497 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002498 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 20, 0),
2499 std::make_tuple(48000, 48000, 32000, 48000, 20, 30),
2500 std::make_tuple(48000, 48000, 16000, 48000, 20, 20),
2501 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2502 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2503 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
2504 std::make_tuple(48000, 32000, 48000, 32000, 20, 35),
2505 std::make_tuple(48000, 32000, 32000, 32000, 20, 0),
2506 std::make_tuple(48000, 32000, 16000, 32000, 20, 20),
2507 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2508 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2509 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002510
Edward Lemurc5ee9872017-10-23 23:33:04 +02002511 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2512 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2513 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2514 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2515 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2516 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
2517 std::make_tuple(44100, 32000, 48000, 32000, 20, 35),
2518 std::make_tuple(44100, 32000, 32000, 32000, 20, 0),
2519 std::make_tuple(44100, 32000, 16000, 32000, 20, 20),
2520 std::make_tuple(44100, 16000, 48000, 16000, 20, 20),
2521 std::make_tuple(44100, 16000, 32000, 16000, 20, 20),
2522 std::make_tuple(44100, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002523
Edward Lemurc5ee9872017-10-23 23:33:04 +02002524 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2525 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2526 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2527 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2528 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2529 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2530 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2531 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2532 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2533 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2534 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2535 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002536
Edward Lemurc5ee9872017-10-23 23:33:04 +02002537 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2538 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2539 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2540 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2541 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2542 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2543 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2544 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2545 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2546 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2547 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2548 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002549#endif
2550
niklase@google.com470e71d2011-07-07 08:21:25 +00002551} // namespace
peahc19f3122016-10-07 14:54:10 -07002552
Alessio Bazzicac054e782018-04-16 12:10:09 +02002553TEST(RuntimeSettingTest, TestDefaultCtor) {
2554 auto s = AudioProcessing::RuntimeSetting();
2555 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2556}
2557
2558TEST(RuntimeSettingTest, TestCapturePreGain) {
2559 using Type = AudioProcessing::RuntimeSetting::Type;
2560 {
2561 auto s = AudioProcessing::RuntimeSetting::CreateCapturePreGain(1.25f);
2562 EXPECT_EQ(Type::kCapturePreGain, s.type());
2563 float v;
2564 s.GetFloat(&v);
2565 EXPECT_EQ(1.25f, v);
2566 }
2567
2568#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2569 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2570#endif
2571}
2572
2573TEST(RuntimeSettingTest, TestUsageWithSwapQueue) {
2574 SwapQueue<AudioProcessing::RuntimeSetting> q(1);
2575 auto s = AudioProcessing::RuntimeSetting();
2576 ASSERT_TRUE(q.Insert(&s));
2577 ASSERT_TRUE(q.Remove(&s));
2578 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2579}
2580
Sam Zackrisson0beac582017-09-25 12:04:02 +02002581TEST(ApmConfiguration, EnablePostProcessing) {
2582 // Verify that apm uses a capture post processing module if one is provided.
Sam Zackrisson0beac582017-09-25 12:04:02 +02002583 auto mock_post_processor_ptr =
Alex Loiko5825aa62017-12-18 16:02:40 +01002584 new testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002585 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002586 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002587 rtc::scoped_refptr<AudioProcessing> apm =
2588 AudioProcessingBuilder()
2589 .SetCapturePostProcessing(std::move(mock_post_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002590 .Create();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002591
2592 AudioFrame audio;
2593 audio.num_channels_ = 1;
2594 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2595
2596 EXPECT_CALL(*mock_post_processor_ptr, Process(testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002597 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002598}
2599
Alex Loiko5825aa62017-12-18 16:02:40 +01002600TEST(ApmConfiguration, EnablePreProcessing) {
2601 // Verify that apm uses a capture post processing module if one is provided.
Alex Loiko5825aa62017-12-18 16:02:40 +01002602 auto mock_pre_processor_ptr =
2603 new testing::NiceMock<test::MockCustomProcessing>();
2604 auto mock_pre_processor =
2605 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002606 rtc::scoped_refptr<AudioProcessing> apm =
2607 AudioProcessingBuilder()
2608 .SetRenderPreProcessing(std::move(mock_pre_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002609 .Create();
Alex Loiko5825aa62017-12-18 16:02:40 +01002610
2611 AudioFrame audio;
2612 audio.num_channels_ = 1;
2613 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2614
2615 EXPECT_CALL(*mock_pre_processor_ptr, Process(testing::_)).Times(1);
2616 apm->ProcessReverseStream(&audio);
2617}
2618
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002619TEST(ApmConfiguration, EnableCaptureAnalyzer) {
2620 // Verify that apm uses a capture analyzer if one is provided.
2621 auto mock_capture_analyzer_ptr =
2622 new testing::NiceMock<test::MockCustomAudioAnalyzer>();
2623 auto mock_capture_analyzer =
2624 std::unique_ptr<CustomAudioAnalyzer>(mock_capture_analyzer_ptr);
2625 rtc::scoped_refptr<AudioProcessing> apm =
2626 AudioProcessingBuilder()
2627 .SetCaptureAnalyzer(std::move(mock_capture_analyzer))
2628 .Create();
2629
2630 AudioFrame audio;
2631 audio.num_channels_ = 1;
2632 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2633
2634 EXPECT_CALL(*mock_capture_analyzer_ptr, Analyze(testing::_)).Times(1);
2635 apm->ProcessStream(&audio);
2636}
2637
Alex Loiko73ec0192018-05-15 10:52:28 +02002638TEST(ApmConfiguration, PreProcessingReceivesRuntimeSettings) {
2639 auto mock_pre_processor_ptr =
2640 new testing::NiceMock<test::MockCustomProcessing>();
2641 auto mock_pre_processor =
2642 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
2643 rtc::scoped_refptr<AudioProcessing> apm =
2644 AudioProcessingBuilder()
2645 .SetRenderPreProcessing(std::move(mock_pre_processor))
2646 .Create();
2647 apm->SetRuntimeSetting(
2648 AudioProcessing::RuntimeSetting::CreateCustomRenderSetting(0));
2649
2650 // RuntimeSettings forwarded during 'Process*Stream' calls.
2651 // Therefore we have to make one such call.
2652 AudioFrame audio;
2653 audio.num_channels_ = 1;
2654 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2655
2656 EXPECT_CALL(*mock_pre_processor_ptr, SetRuntimeSetting(testing::_)).Times(1);
2657 apm->ProcessReverseStream(&audio);
2658}
2659
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002660class MyEchoControlFactory : public EchoControlFactory {
2661 public:
2662 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2663 auto ec = new test::MockEchoControl();
2664 EXPECT_CALL(*ec, AnalyzeRender(testing::_)).Times(1);
2665 EXPECT_CALL(*ec, AnalyzeCapture(testing::_)).Times(2);
2666 EXPECT_CALL(*ec, ProcessCapture(testing::_, testing::_)).Times(2);
2667 return std::unique_ptr<EchoControl>(ec);
2668 }
2669};
2670
2671TEST(ApmConfiguration, EchoControlInjection) {
2672 // Verify that apm uses an injected echo controller if one is provided.
2673 webrtc::Config webrtc_config;
2674 std::unique_ptr<EchoControlFactory> echo_control_factory(
2675 new MyEchoControlFactory());
2676
Alex Loiko5825aa62017-12-18 16:02:40 +01002677 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002678 AudioProcessingBuilder()
2679 .SetEchoControlFactory(std::move(echo_control_factory))
2680 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002681
2682 AudioFrame audio;
2683 audio.num_channels_ = 1;
2684 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2685 apm->ProcessStream(&audio);
2686 apm->ProcessReverseStream(&audio);
2687 apm->ProcessStream(&audio);
2688}
Ivo Creusenae026092017-11-20 13:07:16 +01002689
2690std::unique_ptr<AudioProcessing> CreateApm(bool use_AEC2) {
2691 Config old_config;
2692 if (use_AEC2) {
2693 old_config.Set<ExtendedFilter>(new ExtendedFilter(true));
2694 old_config.Set<DelayAgnostic>(new DelayAgnostic(true));
2695 }
Ivo Creusen62337e52018-01-09 14:17:33 +01002696 std::unique_ptr<AudioProcessing> apm(
2697 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002698 if (!apm) {
2699 return apm;
2700 }
2701
2702 ProcessingConfig processing_config = {
2703 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2704
2705 if (apm->Initialize(processing_config) != 0) {
2706 return nullptr;
2707 }
2708
2709 // Disable all components except for an AEC and the residual echo detector.
Per Ã…hgren200feba2019-03-06 04:16:46 +01002710 // TODO(peah): Update this to also work on AEC3.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002711 AudioProcessing::Config apm_config;
2712 apm_config.residual_echo_detector.enabled = true;
2713 apm_config.high_pass_filter.enabled = false;
2714 apm_config.gain_controller2.enabled = false;
2715 apm_config.echo_canceller.enabled = true;
2716 apm_config.echo_canceller.mobile_mode = !use_AEC2;
Per Ã…hgren200feba2019-03-06 04:16:46 +01002717 apm_config.echo_canceller.use_legacy_aec = use_AEC2;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002718 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002719 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
2720 EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
2721 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
2722 EXPECT_EQ(apm->voice_detection()->Enable(false), 0);
Ivo Creusenae026092017-11-20 13:07:16 +01002723 return apm;
2724}
2725
2726#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
2727#define MAYBE_ApmStatistics DISABLED_ApmStatistics
2728#else
2729#define MAYBE_ApmStatistics ApmStatistics
2730#endif
2731
2732TEST(MAYBE_ApmStatistics, AEC2EnabledTest) {
2733 // Set up APM with AEC2 and process some audio.
2734 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
2735 ASSERT_TRUE(apm);
Per Ã…hgren200feba2019-03-06 04:16:46 +01002736 AudioProcessing::Config apm_config;
2737 apm_config.echo_canceller.enabled = true;
2738 // TODO(peah): Update tests to instead use AEC3.
2739 apm_config.echo_canceller.use_legacy_aec = true;
2740 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002741
2742 // Set up an audioframe.
2743 AudioFrame frame;
2744 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002745 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002746
2747 // Fill the audio frame with a sawtooth pattern.
2748 int16_t* ptr = frame.mutable_data();
2749 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2750 ptr[i] = 10000 * ((i % 3) - 1);
2751 }
2752
2753 // Do some processing.
2754 for (int i = 0; i < 200; i++) {
2755 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2756 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2757 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2758 }
2759
2760 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002761 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002762 // We expect all statistics to be set and have a sensible value.
2763 ASSERT_TRUE(stats.residual_echo_likelihood);
2764 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2765 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2766 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
2767 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2768 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2769 ASSERT_TRUE(stats.echo_return_loss);
2770 EXPECT_NE(*stats.echo_return_loss, -100.0);
2771 ASSERT_TRUE(stats.echo_return_loss_enhancement);
2772 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
2773 ASSERT_TRUE(stats.divergent_filter_fraction);
2774 EXPECT_NE(*stats.divergent_filter_fraction, -1.0);
2775 ASSERT_TRUE(stats.delay_standard_deviation_ms);
2776 EXPECT_GE(*stats.delay_standard_deviation_ms, 0);
2777 // We don't check stats.delay_median_ms since it takes too long to settle to a
2778 // value. At least 20 seconds of data need to be processed before it will get
2779 // a value, which would make this test take too much time.
2780
2781 // If there are no receive streams, we expect the stats not to be set. The
2782 // 'false' argument signals to APM that no receive streams are currently
2783 // active. In that situation the statistics would get stuck at their last
2784 // calculated value (AEC and echo detection need at least one stream in each
2785 // direction), so to avoid that, they should not be set by APM.
2786 stats = apm->GetStatistics(false);
2787 EXPECT_FALSE(stats.residual_echo_likelihood);
2788 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2789 EXPECT_FALSE(stats.echo_return_loss);
2790 EXPECT_FALSE(stats.echo_return_loss_enhancement);
2791 EXPECT_FALSE(stats.divergent_filter_fraction);
2792 EXPECT_FALSE(stats.delay_median_ms);
2793 EXPECT_FALSE(stats.delay_standard_deviation_ms);
2794}
2795
2796TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
2797 // Set up APM with AECM and process some audio.
2798 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
2799 ASSERT_TRUE(apm);
2800
2801 // Set up an audioframe.
2802 AudioFrame frame;
2803 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002804 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Ivo Creusenae026092017-11-20 13:07:16 +01002805
2806 // Fill the audio frame with a sawtooth pattern.
2807 int16_t* ptr = frame.mutable_data();
2808 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2809 ptr[i] = 10000 * ((i % 3) - 1);
2810 }
2811
2812 // Do some processing.
2813 for (int i = 0; i < 200; i++) {
2814 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2815 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2816 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2817 }
2818
2819 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002820 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002821 // We expect only the residual echo detector statistics to be set and have a
2822 // sensible value.
2823 EXPECT_TRUE(stats.residual_echo_likelihood);
2824 if (stats.residual_echo_likelihood) {
2825 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2826 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2827 }
2828 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
2829 if (stats.residual_echo_likelihood_recent_max) {
2830 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2831 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2832 }
2833 EXPECT_FALSE(stats.echo_return_loss);
2834 EXPECT_FALSE(stats.echo_return_loss_enhancement);
2835 EXPECT_FALSE(stats.divergent_filter_fraction);
2836 EXPECT_FALSE(stats.delay_median_ms);
2837 EXPECT_FALSE(stats.delay_standard_deviation_ms);
2838
2839 // If there are no receive streams, we expect the stats not to be set.
2840 stats = apm->GetStatistics(false);
2841 EXPECT_FALSE(stats.residual_echo_likelihood);
2842 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2843 EXPECT_FALSE(stats.echo_return_loss);
2844 EXPECT_FALSE(stats.echo_return_loss_enhancement);
2845 EXPECT_FALSE(stats.divergent_filter_fraction);
2846 EXPECT_FALSE(stats.delay_median_ms);
2847 EXPECT_FALSE(stats.delay_standard_deviation_ms);
2848}
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002849
2850TEST(ApmStatistics, ReportOutputRmsDbfs) {
2851 ProcessingConfig processing_config = {
2852 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2853 AudioProcessing::Config config;
2854
2855 // Set up an audioframe.
2856 AudioFrame frame;
2857 frame.num_channels_ = 1;
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002858 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002859
2860 // Fill the audio frame with a sawtooth pattern.
2861 int16_t* ptr = frame.mutable_data();
2862 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2863 ptr[i] = 10000 * ((i % 3) - 1);
2864 }
2865
2866 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2867 apm->Initialize(processing_config);
2868
2869 // If not enabled, no metric should be reported.
2870 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2871 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2872
2873 // If enabled, metrics should be reported.
2874 config.level_estimation.enabled = true;
2875 apm->ApplyConfig(config);
2876 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2877 auto stats = apm->GetStatistics(false);
2878 EXPECT_TRUE(stats.output_rms_dbfs);
2879 EXPECT_GE(*stats.output_rms_dbfs, 0);
2880
2881 // If re-disabled, the value is again not reported.
2882 config.level_estimation.enabled = false;
2883 apm->ApplyConfig(config);
2884 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2885 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2886}
Sam Zackrisson4db667b2018-12-21 16:29:27 +01002887
2888TEST(ApmStatistics, ReportHasVoice) {
2889 ProcessingConfig processing_config = {
2890 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2891 AudioProcessing::Config config;
2892
2893 // Set up an audioframe.
2894 AudioFrame frame;
2895 frame.num_channels_ = 1;
2896 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate32kHz);
2897
2898 // Fill the audio frame with a sawtooth pattern.
2899 int16_t* ptr = frame.mutable_data();
2900 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2901 ptr[i] = 10000 * ((i % 3) - 1);
2902 }
2903
2904 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2905 apm->Initialize(processing_config);
2906
2907 // If not enabled, no metric should be reported.
2908 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2909 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2910
2911 // If enabled, metrics should be reported.
2912 config.voice_detection.enabled = true;
2913 apm->ApplyConfig(config);
2914 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2915 auto stats = apm->GetStatistics(false);
2916 EXPECT_TRUE(stats.voice_detected);
2917
2918 // If re-disabled, the value is again not reported.
2919 config.voice_detection.enabled = false;
2920 apm->ApplyConfig(config);
2921 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2922 EXPECT_FALSE(apm->GetStatistics(false).voice_detected);
2923}
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002924} // namespace webrtc