blob: 90882d78745180cb9ccc0c14fde194c148b9e784 [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"
Minyue Li656d6092018-08-10 15:38:52 +020031#include "rtc_base/fakeclock.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"
Niels Möller84255bb2017-10-06 13:43:23 +020037#include "rtc_base/refcountedobject.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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "rtc_base/task_queue.h"
42#include "rtc_base/thread.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "test/gtest.h"
44#include "test/testsupport/fileutils.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;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000185
186 EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveDigital));
187 EXPECT_NOERR(ap->gain_control()->Enable(true));
188#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Sam Zackrissonb3b47ad2018-08-17 16:26:14 +0200189 apm_config.echo_canceller.mobile_mode = false;
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200190 apm_config.echo_canceller.legacy_moderate_suppression_level = true;
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000191
192 EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
193 EXPECT_NOERR(ap->gain_control()->set_analog_level_limits(0, 255));
194 EXPECT_NOERR(ap->gain_control()->Enable(true));
195#endif
Sam Zackrisson2a959d92018-07-23 14:48:07 +0000196
peah8271d042016-11-22 07:24:52 -0800197 apm_config.high_pass_filter.enabled = true;
198 ap->ApplyConfig(apm_config);
199
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000200 EXPECT_NOERR(ap->level_estimator()->Enable(true));
201 EXPECT_NOERR(ap->noise_suppression()->Enable(true));
202
203 EXPECT_NOERR(ap->voice_detection()->Enable(true));
204}
205
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000206// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000207template <class T>
208T AbsValue(T a) {
209 return a > 0 ? a: -a;
210}
211
212int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800213 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700214 const int16_t* frame_data = frame.data();
215 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800216 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700217 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000218 }
219
220 return max_data;
221}
222
Alex Loiko890988c2017-08-31 10:25:48 +0200223void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700224 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000225 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000226 ASSERT_TRUE(file != NULL);
227
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100228 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000229 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800230 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000231 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000232
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000233 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000234 ASSERT_EQ(static_cast<size_t>(size),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000235 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000236 fclose(file);
237}
238
Alex Loiko890988c2017-08-31 10:25:48 +0200239std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200240 rtc::StringBuilder ss;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000241 // Resource files are all stereo.
242 ss << name << sample_rate_hz / 1000 << "_stereo";
243 return test::ResourcePath(ss.str(), "pcm");
244}
245
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000246// Temporary filenames unique to this process. Used to be able to run these
247// tests in parallel as each process needs to be running in isolation they can't
248// have competing filenames.
249std::map<std::string, std::string> temp_filenames;
250
Alex Loiko890988c2017-08-31 10:25:48 +0200251std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000252 int input_rate,
253 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700254 int reverse_input_rate,
255 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800256 size_t num_input_channels,
257 size_t num_output_channels,
258 size_t num_reverse_input_channels,
259 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700260 StreamDirection file_direction) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200261 rtc::StringBuilder ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700262 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
263 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000264 if (num_output_channels == 1) {
265 ss << "mono";
266 } else if (num_output_channels == 2) {
267 ss << "stereo";
268 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700269 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000270 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700271 ss << output_rate / 1000;
272 if (num_reverse_output_channels == 1) {
273 ss << "_rmono";
274 } else if (num_reverse_output_channels == 2) {
275 ss << "_rstereo";
276 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700277 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700278 }
279 ss << reverse_output_rate / 1000;
280 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000281
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000282 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700283 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000284 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
285 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000286}
287
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000288void ClearTempFiles() {
289 for (auto& kv : temp_filenames)
290 remove(kv.second.c_str());
291}
292
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200293// Only remove "out" files. Keep "ref" files.
294void ClearTempOutFiles() {
295 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
296 const std::string& filename = it->first;
297 if (filename.substr(0, 3).compare("out") == 0) {
298 remove(it->second.c_str());
299 temp_filenames.erase(it++);
300 } else {
301 it++;
302 }
303 }
304}
305
Alex Loiko890988c2017-08-31 10:25:48 +0200306void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000307 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000308 ASSERT_TRUE(file != NULL);
309 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000310 fclose(file);
311}
312
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000313// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
314// stereo) file, converts to deinterleaved float (optionally downmixing) and
315// returns the result in |cb|. Returns false if the file ended (or on error) and
316// true otherwise.
317//
318// |int_data| and |float_data| are just temporary space that must be
319// sufficiently large to hold the 10 ms chunk.
320bool ReadChunk(FILE* file, int16_t* int_data, float* float_data,
321 ChannelBuffer<float>* cb) {
322 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000323 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000324 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
325 if (read_count != frame_size) {
326 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700327 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000328 return false; // This is expected.
329 }
330
331 S16ToFloat(int_data, frame_size, float_data);
332 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000333 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000334 } else {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000335 Deinterleave(float_data, cb->num_frames(), 2,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000336 cb->channels());
337 }
338
339 return true;
340}
341
niklase@google.com470e71d2011-07-07 08:21:25 +0000342class ApmTest : public ::testing::Test {
343 protected:
344 ApmTest();
345 virtual void SetUp();
346 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000347
348 static void SetUpTestCase() {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000349 }
350
351 static void TearDownTestCase() {
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000352 ClearTempFiles();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000353 }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000354
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000355 // Used to select between int and float interface tests.
356 enum Format {
357 kIntFormat,
358 kFloatFormat
359 };
360
361 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000362 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000363 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800364 size_t num_input_channels,
365 size_t num_output_channels,
366 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000367 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000368 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000369 void EnableAllComponents();
370 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000371 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000372 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000373 void ReadFrameWithRewind(FILE* file, AudioFrame* frame,
374 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000375 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000376 void ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
377 int delay_min, int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700378 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800379 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700380 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800381 void TestChangingForwardChannels(size_t num_in_channels,
382 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700383 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800384 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700385 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000386 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
387 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000388 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000389 int ProcessStreamChooser(Format format);
390 int AnalyzeReverseStreamChooser(Format format);
391 void ProcessDebugDump(const std::string& in_filename,
392 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800393 Format format,
394 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000395 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000396
397 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000398 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800399 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000400 AudioFrame* frame_;
401 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800402 std::unique_ptr<ChannelBuffer<float> > float_cb_;
403 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000404 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800405 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000406 FILE* far_file_;
407 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000408 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000409};
410
411ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000412 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000413#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800414 ref_filename_(test::ResourcePath("audio_processing/output_data_fixed",
415 "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000416#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000417#if defined(WEBRTC_MAC)
418 // A different file for Mac is needed because on this platform the AEC
419 // constant |kFixedDelayMs| value is 20 and not 50 as it is on the rest.
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800420 ref_filename_(test::ResourcePath("audio_processing/output_data_mac",
421 "pb")),
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000422#else
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800423 ref_filename_(test::ResourcePath("audio_processing/output_data_float",
424 "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000425#endif
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000426#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000427 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000428 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000429 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000430 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000431 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000432 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000433 out_file_(NULL) {
434 Config config;
435 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100436 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000437}
niklase@google.com470e71d2011-07-07 08:21:25 +0000438
439void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000440 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000441
442 frame_ = new AudioFrame();
443 revframe_ = new AudioFrame();
444
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000445 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000446}
447
448void ApmTest::TearDown() {
449 if (frame_) {
450 delete frame_;
451 }
452 frame_ = NULL;
453
454 if (revframe_) {
455 delete revframe_;
456 }
457 revframe_ = NULL;
458
459 if (far_file_) {
460 ASSERT_EQ(0, fclose(far_file_));
461 }
462 far_file_ = NULL;
463
464 if (near_file_) {
465 ASSERT_EQ(0, fclose(near_file_));
466 }
467 near_file_ = NULL;
468
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000469 if (out_file_) {
470 ASSERT_EQ(0, fclose(out_file_));
471 }
472 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000473}
474
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000475void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000476 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700477 ap->Initialize(
478 {{{frame_->sample_rate_hz_, frame_->num_channels_},
479 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700480 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700481 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000482}
483
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000484void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000485 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000486 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800487 size_t num_input_channels,
488 size_t num_output_channels,
489 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000490 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000491 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000492 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000493 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000494
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000495 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
496 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000497 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000498
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000499 if (far_file_) {
500 ASSERT_EQ(0, fclose(far_file_));
501 }
502 std::string filename = ResourceFilePath("far", sample_rate_hz);
503 far_file_ = fopen(filename.c_str(), "rb");
504 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " <<
505 filename << "\n";
506
507 if (near_file_) {
508 ASSERT_EQ(0, fclose(near_file_));
509 }
510 filename = ResourceFilePath("near", sample_rate_hz);
511 near_file_ = fopen(filename.c_str(), "rb");
512 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " <<
513 filename << "\n";
514
515 if (open_output_file) {
516 if (out_file_) {
517 ASSERT_EQ(0, fclose(out_file_));
518 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700519 filename = OutputFilePath(
520 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
521 reverse_sample_rate_hz, num_input_channels, num_output_channels,
522 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000523 out_file_ = fopen(filename.c_str(), "wb");
524 ASSERT_TRUE(out_file_ != NULL) << "Could not open file " <<
525 filename << "\n";
526 }
527}
528
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000529void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000530 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000531}
532
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000533bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame,
534 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000535 // The files always contain stereo audio.
536 size_t frame_size = frame->samples_per_channel_ * 2;
yujo36b1a5f2017-06-12 12:45:32 -0700537 size_t read_count = fread(frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000538 sizeof(int16_t),
539 frame_size,
540 file);
541 if (read_count != frame_size) {
542 // Check that the file really ended.
543 EXPECT_NE(0, feof(file));
544 return false; // This is expected.
545 }
546
547 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700548 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000549 frame->samples_per_channel_);
550 }
551
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000552 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000553 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000554 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000555 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000556}
557
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000558bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
559 return ReadFrame(file, frame, NULL);
560}
561
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000562// If the end of the file has been reached, rewind it and attempt to read the
563// frame again.
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000564void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame,
565 ChannelBuffer<float>* cb) {
566 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000567 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000568 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000569 }
570}
571
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000572void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
573 ReadFrameWithRewind(file, frame, NULL);
574}
575
andrew@webrtc.org81865342012-10-27 00:28:27 +0000576void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
577 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000578 EXPECT_EQ(apm_->kNoError,
579 apm_->gain_control()->set_stream_analog_level(127));
580 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000581}
582
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000583int ApmTest::ProcessStreamChooser(Format format) {
584 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000585 return apm_->ProcessStream(frame_);
586 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000587 return apm_->ProcessStream(float_cb_->channels(),
588 frame_->samples_per_channel_,
589 frame_->sample_rate_hz_,
590 LayoutFromChannels(frame_->num_channels_),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000591 output_sample_rate_hz_,
592 LayoutFromChannels(num_output_channels_),
593 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000594}
595
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000596int ApmTest::AnalyzeReverseStreamChooser(Format format) {
597 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700598 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000599 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000600 return apm_->AnalyzeReverseStream(
601 revfloat_cb_->channels(),
602 revframe_->samples_per_channel_,
603 revframe_->sample_rate_hz_,
604 LayoutFromChannels(revframe_->num_channels_));
605}
606
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000607void ApmTest::ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
608 int delay_min, int delay_max) {
609 // The |revframe_| and |frame_| should include the proper frame information,
610 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000611 AudioFrame tmp_frame;
612 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000613 bool causal = true;
614
615 tmp_frame.CopyFrom(*revframe_);
616 SetFrameTo(&tmp_frame, 0);
617
618 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
619 // Initialize the |frame_queue| with empty frames.
620 int frame_delay = delay_ms / 10;
621 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000622 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000623 frame->CopyFrom(tmp_frame);
624 frame_queue.push(frame);
625 frame_delay++;
626 causal = false;
627 }
628 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000629 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000630 frame->CopyFrom(tmp_frame);
631 frame_queue.push(frame);
632 frame_delay--;
633 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000634 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
635 // need enough frames with audio to have reliable estimates, but as few as
636 // possible to keep processing time down. 4.5 seconds seemed to be a good
637 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000638 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000639 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000640 frame->CopyFrom(tmp_frame);
641 // Use the near end recording, since that has more speech in it.
642 ASSERT_TRUE(ReadFrame(near_file_, frame));
643 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000644 AudioFrame* reverse_frame = frame;
645 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000646 if (!causal) {
647 reverse_frame = frame_queue.front();
648 // When we call ProcessStream() the frame is modified, so we can't use the
649 // pointer directly when things are non-causal. Use an intermediate frame
650 // and copy the data.
651 process_frame = &tmp_frame;
652 process_frame->CopyFrom(*frame);
653 }
aluebsb0319552016-03-17 20:39:53 -0700654 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000655 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
656 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
657 frame = frame_queue.front();
658 frame_queue.pop();
659 delete frame;
660
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000661 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000662 // Discard the first delay metrics to avoid convergence effects.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200663 static_cast<void>(apm_->GetStatistics(true /* has_remote_tracks */));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000664 }
665 }
666
667 rewind(near_file_);
668 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000669 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000670 frame_queue.pop();
671 delete frame;
672 }
673 // Calculate expected delay estimate and acceptable regions. Further,
674 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700675 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700676 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700677 const int expected_median =
678 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
679 const int expected_median_high = rtc::SafeClamp<int>(
680 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700681 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700682 const int expected_median_low = rtc::SafeClamp<int>(
683 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700684 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000685 // Verify delay metrics.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200686 AudioProcessingStats stats =
687 apm_->GetStatistics(true /* has_remote_tracks */);
688 ASSERT_TRUE(stats.delay_median_ms.has_value());
689 int32_t median = *stats.delay_median_ms;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000690 EXPECT_GE(expected_median_high, median);
691 EXPECT_LE(expected_median_low, median);
692}
693
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000694void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000695 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000696 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000697
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000698 // -- Missing AGC level --
niklase@google.com470e71d2011-07-07 08:21:25 +0000699 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000700 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000701 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000702
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000703 // Resets after successful ProcessStream().
niklase@google.com470e71d2011-07-07 08:21:25 +0000704 EXPECT_EQ(apm_->kNoError,
705 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000706 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000707 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000708 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000709
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000710 // Other stream parameters set correctly.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200711 AudioProcessing::Config apm_config = apm_->GetConfig();
712 apm_config.echo_canceller.enabled = true;
713 apm_config.echo_canceller.mobile_mode = false;
714 apm_->ApplyConfig(apm_config);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000715 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
niklase@google.com470e71d2011-07-07 08:21:25 +0000716 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000717 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000718 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000719
720 // -- Missing delay --
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000721 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +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
725 // Resets after successful ProcessStream().
726 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000727 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000728 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000729 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000730
731 // Other stream parameters set correctly.
732 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
733 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000734 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000735 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000736 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000737 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
738
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000739 // -- No stream parameters --
niklase@google.com470e71d2011-07-07 08:21:25 +0000740 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000741 AnalyzeReverseStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000742 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000743 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000744
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000745 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000746 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
niklase@google.com470e71d2011-07-07 08:21:25 +0000747 EXPECT_EQ(apm_->kNoError,
748 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000749 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000750}
751
752TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000753 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000754}
755
756TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000757 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000758}
759
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000760TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
761 EXPECT_EQ(0, apm_->delay_offset_ms());
762 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
763 EXPECT_EQ(50, apm_->stream_delay_ms());
764}
765
766TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
767 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000768 apm_->set_delay_offset_ms(100);
769 EXPECT_EQ(100, apm_->delay_offset_ms());
770 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000771 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000772 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
773 EXPECT_EQ(200, apm_->stream_delay_ms());
774
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000775 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000776 apm_->set_delay_offset_ms(-50);
777 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000778 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
779 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000780 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
781 EXPECT_EQ(50, apm_->stream_delay_ms());
782}
783
Michael Graczyk86c6d332015-07-23 11:41:39 -0700784void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800785 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700786 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000787 frame_->num_channels_ = num_channels;
788 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700789 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000790}
791
Michael Graczyk86c6d332015-07-23 11:41:39 -0700792void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800793 size_t num_in_channels,
794 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700795 AudioProcessing::Error expected_return) {
796 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
797 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
798
799 EXPECT_EQ(expected_return,
800 apm_->ProcessStream(float_cb_->channels(), input_stream,
801 output_stream, float_cb_->channels()));
802}
803
804void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800805 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700806 AudioProcessing::Error expected_return) {
807 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700808 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
809 {output_sample_rate_hz_, apm_->num_output_channels()},
810 {frame_->sample_rate_hz_, num_rev_channels},
811 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700812
ekmeyerson60d9b332015-08-14 10:35:55 -0700813 EXPECT_EQ(
814 expected_return,
815 apm_->ProcessReverseStream(
816 float_cb_->channels(), processing_config.reverse_input_stream(),
817 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700818}
819
820TEST_F(ApmTest, ChannelsInt16Interface) {
821 // Testing number of invalid and valid channels.
822 Init(16000, 16000, 16000, 4, 4, 4, false);
823
824 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
825
Peter Kasting69558702016-01-12 16:26:35 -0800826 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700827 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000828 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000829 }
830}
831
Michael Graczyk86c6d332015-07-23 11:41:39 -0700832TEST_F(ApmTest, Channels) {
833 // Testing number of invalid and valid channels.
834 Init(16000, 16000, 16000, 4, 4, 4, false);
835
836 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
837 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
838
Peter Kasting69558702016-01-12 16:26:35 -0800839 for (size_t i = 1; i < 4; ++i) {
840 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700841 // Output channels much be one or match input channels.
842 if (j == 1 || i == j) {
843 TestChangingForwardChannels(i, j, kNoErr);
844 TestChangingReverseChannels(i, kNoErr);
845
846 EXPECT_EQ(i, apm_->num_input_channels());
847 EXPECT_EQ(j, apm_->num_output_channels());
848 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800849 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700850 } else {
851 TestChangingForwardChannels(i, j,
852 AudioProcessing::kBadNumberChannelsError);
853 }
854 }
855 }
856}
857
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000858TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000859 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000860 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000861 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000862 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700863 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800864 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000865 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000866 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000867 }
868}
869
bjornv@webrtc.org84f8ec12014-06-19 12:14:33 +0000870TEST_F(ApmTest, DISABLED_EchoCancellationReportsCorrectDelays) {
bjornv@webrtc.orgbac00122015-01-02 09:23:49 +0000871 // TODO(bjornv): Fix this test to work with DA-AEC.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000872 // Enable AEC only.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +0200873 AudioProcessing::Config apm_config = apm_->GetConfig();
874 apm_config.echo_canceller.enabled = true;
875 apm_config.echo_canceller.mobile_mode = false;
876 apm_->ApplyConfig(apm_config);
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000877 Config config;
henrik.lundin0f133b92015-07-02 00:17:55 -0700878 config.Set<DelayAgnostic>(new DelayAgnostic(false));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000879 apm_->SetExtraOptions(config);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000880
881 // Internally in the AEC the amount of lookahead the delay estimation can
882 // handle is 15 blocks and the maximum delay is set to 60 blocks.
883 const int kLookaheadBlocks = 15;
884 const int kMaxDelayBlocks = 60;
885 // The AEC has a startup time before it actually starts to process. This
886 // procedure can flush the internal far-end buffer, which of course affects
887 // the delay estimation. Therefore, we set a system_delay high enough to
888 // avoid that. The smallest system_delay you can report without flushing the
889 // buffer is 66 ms in 8 kHz.
890 //
891 // It is known that for 16 kHz (and 32 kHz) sampling frequency there is an
892 // additional stuffing of 8 ms on the fly, but it seems to have no impact on
893 // delay estimation. This should be noted though. In case of test failure,
894 // this could be the cause.
895 const int kSystemDelayMs = 66;
896 // Test a couple of corner cases and verify that the estimated delay is
897 // within a valid region (set to +-1.5 blocks). Note that these cases are
898 // sampling frequency dependent.
pkasting25702cb2016-01-08 13:50:27 -0800899 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000900 Init(kProcessSampleRates[i],
901 kProcessSampleRates[i],
902 kProcessSampleRates[i],
903 2,
904 2,
905 2,
906 false);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000907 // Sampling frequency dependent variables.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700908 const int num_ms_per_block =
909 std::max(4, static_cast<int>(640 / frame_->samples_per_channel_));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000910 const int delay_min_ms = -kLookaheadBlocks * num_ms_per_block;
911 const int delay_max_ms = (kMaxDelayBlocks - 1) * num_ms_per_block;
912
913 // 1) Verify correct delay estimate at lookahead boundary.
914 int delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_min_ms);
915 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
916 delay_max_ms);
917 // 2) A delay less than maximum lookahead should give an delay estimate at
918 // the boundary (= -kLookaheadBlocks * num_ms_per_block).
919 delay_ms -= 20;
920 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
921 delay_max_ms);
922 // 3) Three values around zero delay. Note that we need to compensate for
923 // the fake system_delay.
924 delay_ms = TruncateToMultipleOf10(kSystemDelayMs - 10);
925 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
926 delay_max_ms);
927 delay_ms = TruncateToMultipleOf10(kSystemDelayMs);
928 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
929 delay_max_ms);
930 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + 10);
931 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
932 delay_max_ms);
933 // 4) Verify correct delay estimate at maximum delay boundary.
934 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_max_ms);
935 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
936 delay_max_ms);
937 // 5) A delay above the maximum delay should give an estimate at the
938 // boundary (= (kMaxDelayBlocks - 1) * num_ms_per_block).
939 delay_ms += 20;
940 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
941 delay_max_ms);
942 }
943}
944
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000945TEST_F(ApmTest, GainControl) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000946 // Testing gain modes
niklase@google.com470e71d2011-07-07 08:21:25 +0000947 EXPECT_EQ(apm_->kNoError,
948 apm_->gain_control()->set_mode(
949 apm_->gain_control()->mode()));
950
951 GainControl::Mode mode[] = {
952 GainControl::kAdaptiveAnalog,
953 GainControl::kAdaptiveDigital,
954 GainControl::kFixedDigital
955 };
pkasting25702cb2016-01-08 13:50:27 -0800956 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000957 EXPECT_EQ(apm_->kNoError,
958 apm_->gain_control()->set_mode(mode[i]));
959 EXPECT_EQ(mode[i], apm_->gain_control()->mode());
960 }
961 // Testing invalid target levels
962 EXPECT_EQ(apm_->kBadParameterError,
963 apm_->gain_control()->set_target_level_dbfs(-3));
964 EXPECT_EQ(apm_->kBadParameterError,
965 apm_->gain_control()->set_target_level_dbfs(-40));
966 // Testing valid target levels
967 EXPECT_EQ(apm_->kNoError,
968 apm_->gain_control()->set_target_level_dbfs(
969 apm_->gain_control()->target_level_dbfs()));
970
971 int level_dbfs[] = {0, 6, 31};
pkasting25702cb2016-01-08 13:50:27 -0800972 for (size_t i = 0; i < arraysize(level_dbfs); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000973 EXPECT_EQ(apm_->kNoError,
974 apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
975 EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
976 }
977
978 // Testing invalid compression gains
979 EXPECT_EQ(apm_->kBadParameterError,
980 apm_->gain_control()->set_compression_gain_db(-1));
981 EXPECT_EQ(apm_->kBadParameterError,
982 apm_->gain_control()->set_compression_gain_db(100));
983
984 // Testing valid compression gains
985 EXPECT_EQ(apm_->kNoError,
986 apm_->gain_control()->set_compression_gain_db(
987 apm_->gain_control()->compression_gain_db()));
988
989 int gain_db[] = {0, 10, 90};
pkasting25702cb2016-01-08 13:50:27 -0800990 for (size_t i = 0; i < arraysize(gain_db); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000991 EXPECT_EQ(apm_->kNoError,
992 apm_->gain_control()->set_compression_gain_db(gain_db[i]));
993 EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
994 }
995
996 // Testing limiter off/on
997 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
998 EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
999 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
1000 EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
1001
1002 // Testing invalid level limits
1003 EXPECT_EQ(apm_->kBadParameterError,
1004 apm_->gain_control()->set_analog_level_limits(-1, 512));
1005 EXPECT_EQ(apm_->kBadParameterError,
1006 apm_->gain_control()->set_analog_level_limits(100000, 512));
1007 EXPECT_EQ(apm_->kBadParameterError,
1008 apm_->gain_control()->set_analog_level_limits(512, -1));
1009 EXPECT_EQ(apm_->kBadParameterError,
1010 apm_->gain_control()->set_analog_level_limits(512, 100000));
1011 EXPECT_EQ(apm_->kBadParameterError,
1012 apm_->gain_control()->set_analog_level_limits(512, 255));
1013
1014 // Testing valid level limits
1015 EXPECT_EQ(apm_->kNoError,
1016 apm_->gain_control()->set_analog_level_limits(
1017 apm_->gain_control()->analog_level_minimum(),
1018 apm_->gain_control()->analog_level_maximum()));
1019
1020 int min_level[] = {0, 255, 1024};
pkasting25702cb2016-01-08 13:50:27 -08001021 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001022 EXPECT_EQ(apm_->kNoError,
1023 apm_->gain_control()->set_analog_level_limits(min_level[i], 1024));
1024 EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
1025 }
1026
1027 int max_level[] = {0, 1024, 65535};
pkasting25702cb2016-01-08 13:50:27 -08001028 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001029 EXPECT_EQ(apm_->kNoError,
1030 apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
1031 EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
1032 }
1033
1034 // TODO(ajm): stream_is_saturated() and stream_analog_level()
1035
1036 // Turn AGC off
1037 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
1038 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1039}
1040
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001041void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001042 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001043 EXPECT_EQ(apm_->kNoError,
1044 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1045 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1046
1047 int out_analog_level = 0;
1048 for (int i = 0; i < 2000; ++i) {
1049 ReadFrameWithRewind(near_file_, frame_);
1050 // Ensure the audio is at a low level, so the AGC will try to increase it.
1051 ScaleFrame(frame_, 0.25);
1052
1053 // Always pass in the same volume.
1054 EXPECT_EQ(apm_->kNoError,
1055 apm_->gain_control()->set_stream_analog_level(100));
1056 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1057 out_analog_level = apm_->gain_control()->stream_analog_level();
1058 }
1059
1060 // Ensure the AGC is still able to reach the maximum.
1061 EXPECT_EQ(255, out_analog_level);
1062}
1063
1064// Verifies that despite volume slider quantization, the AGC can continue to
1065// increase its volume.
1066TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -08001067 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001068 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
1069 }
1070}
1071
1072void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001073 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001074 EXPECT_EQ(apm_->kNoError,
1075 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1076 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1077
1078 int out_analog_level = 100;
1079 for (int i = 0; i < 1000; ++i) {
1080 ReadFrameWithRewind(near_file_, frame_);
1081 // Ensure the audio is at a low level, so the AGC will try to increase it.
1082 ScaleFrame(frame_, 0.25);
1083
1084 EXPECT_EQ(apm_->kNoError,
1085 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1086 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1087 out_analog_level = apm_->gain_control()->stream_analog_level();
1088 }
1089
1090 // Ensure the volume was raised.
1091 EXPECT_GT(out_analog_level, 100);
1092 int highest_level_reached = out_analog_level;
1093 // Simulate a user manual volume change.
1094 out_analog_level = 100;
1095
1096 for (int i = 0; i < 300; ++i) {
1097 ReadFrameWithRewind(near_file_, frame_);
1098 ScaleFrame(frame_, 0.25);
1099
1100 EXPECT_EQ(apm_->kNoError,
1101 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1102 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1103 out_analog_level = apm_->gain_control()->stream_analog_level();
1104 // Check that AGC respected the manually adjusted volume.
1105 EXPECT_LT(out_analog_level, highest_level_reached);
1106 }
1107 // Check that the volume was still raised.
1108 EXPECT_GT(out_analog_level, 100);
1109}
1110
1111TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001112 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001113 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1114 }
1115}
1116
niklase@google.com470e71d2011-07-07 08:21:25 +00001117TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001118 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001119 NoiseSuppression::Level level[] = {
1120 NoiseSuppression::kLow,
1121 NoiseSuppression::kModerate,
1122 NoiseSuppression::kHigh,
1123 NoiseSuppression::kVeryHigh
1124 };
pkasting25702cb2016-01-08 13:50:27 -08001125 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001126 EXPECT_EQ(apm_->kNoError,
1127 apm_->noise_suppression()->set_level(level[i]));
1128 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1129 }
1130
andrew@webrtc.org648af742012-02-08 01:57:29 +00001131 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001132 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1133 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1134 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1135 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1136}
1137
1138TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001139 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001140 AudioProcessing::Config apm_config;
1141 apm_config.high_pass_filter.enabled = true;
1142 apm_->ApplyConfig(apm_config);
1143 apm_config.high_pass_filter.enabled = false;
1144 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001145}
1146
1147TEST_F(ApmTest, LevelEstimator) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001148 // Turn level estimator on/off
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001149 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001150 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001151
1152 EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1153
1154 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1155 EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1156
1157 // Run this test in wideband; in super-wb, the splitting filter distorts the
1158 // audio enough to cause deviation from the expectation for small values.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001159 frame_->samples_per_channel_ = 160;
1160 frame_->num_channels_ = 2;
1161 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001162
1163 // Min value if no frames have been processed.
1164 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1165
1166 // Min value on zero frames.
1167 SetFrameTo(frame_, 0);
1168 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1169 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1170 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1171
1172 // Try a few RMS values.
1173 // (These also test that the value resets after retrieving it.)
1174 SetFrameTo(frame_, 32767);
1175 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1176 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1177 EXPECT_EQ(0, apm_->level_estimator()->RMS());
1178
1179 SetFrameTo(frame_, 30000);
1180 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1181 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1182 EXPECT_EQ(1, apm_->level_estimator()->RMS());
1183
1184 SetFrameTo(frame_, 10000);
1185 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1186 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1187 EXPECT_EQ(10, apm_->level_estimator()->RMS());
1188
1189 SetFrameTo(frame_, 10);
1190 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1191 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1192 EXPECT_EQ(70, apm_->level_estimator()->RMS());
1193
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001194 // Verify reset after enable/disable.
1195 SetFrameTo(frame_, 32767);
1196 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1197 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1198 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1199 SetFrameTo(frame_, 1);
1200 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1201 EXPECT_EQ(90, apm_->level_estimator()->RMS());
1202
1203 // Verify reset after initialize.
1204 SetFrameTo(frame_, 32767);
1205 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1206 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1207 SetFrameTo(frame_, 1);
1208 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1209 EXPECT_EQ(90, apm_->level_estimator()->RMS());
niklase@google.com470e71d2011-07-07 08:21:25 +00001210}
1211
1212TEST_F(ApmTest, VoiceDetection) {
1213 // Test external VAD
1214 EXPECT_EQ(apm_->kNoError,
1215 apm_->voice_detection()->set_stream_has_voice(true));
1216 EXPECT_TRUE(apm_->voice_detection()->stream_has_voice());
1217 EXPECT_EQ(apm_->kNoError,
1218 apm_->voice_detection()->set_stream_has_voice(false));
1219 EXPECT_FALSE(apm_->voice_detection()->stream_has_voice());
1220
andrew@webrtc.org648af742012-02-08 01:57:29 +00001221 // Test valid likelihoods
niklase@google.com470e71d2011-07-07 08:21:25 +00001222 VoiceDetection::Likelihood likelihood[] = {
1223 VoiceDetection::kVeryLowLikelihood,
1224 VoiceDetection::kLowLikelihood,
1225 VoiceDetection::kModerateLikelihood,
1226 VoiceDetection::kHighLikelihood
1227 };
pkasting25702cb2016-01-08 13:50:27 -08001228 for (size_t i = 0; i < arraysize(likelihood); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001229 EXPECT_EQ(apm_->kNoError,
1230 apm_->voice_detection()->set_likelihood(likelihood[i]));
1231 EXPECT_EQ(likelihood[i], apm_->voice_detection()->likelihood());
1232 }
1233
1234 /* TODO(bjornv): Enable once VAD supports other frame lengths than 10 ms
andrew@webrtc.org648af742012-02-08 01:57:29 +00001235 // Test invalid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001236 EXPECT_EQ(apm_->kBadParameterError,
1237 apm_->voice_detection()->set_frame_size_ms(12));
1238
andrew@webrtc.org648af742012-02-08 01:57:29 +00001239 // Test valid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001240 for (int i = 10; i <= 30; i += 10) {
1241 EXPECT_EQ(apm_->kNoError,
1242 apm_->voice_detection()->set_frame_size_ms(i));
1243 EXPECT_EQ(i, apm_->voice_detection()->frame_size_ms());
1244 }
1245 */
1246
andrew@webrtc.org648af742012-02-08 01:57:29 +00001247 // Turn VAD on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001248 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1249 EXPECT_TRUE(apm_->voice_detection()->is_enabled());
1250 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1251 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1252
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001253 // Test that AudioFrame activity is maintained when VAD is disabled.
1254 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1255 AudioFrame::VADActivity activity[] = {
1256 AudioFrame::kVadActive,
1257 AudioFrame::kVadPassive,
1258 AudioFrame::kVadUnknown
1259 };
pkasting25702cb2016-01-08 13:50:27 -08001260 for (size_t i = 0; i < arraysize(activity); i++) {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001261 frame_->vad_activity_ = activity[i];
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001262 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001263 EXPECT_EQ(activity[i], frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001264 }
1265
1266 // Test that AudioFrame activity is set when VAD is enabled.
1267 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001268 frame_->vad_activity_ = AudioFrame::kVadUnknown;
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001269 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001270 EXPECT_NE(AudioFrame::kVadUnknown, frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001271
niklase@google.com470e71d2011-07-07 08:21:25 +00001272 // TODO(bjornv): Add tests for streamed voice; stream_has_voice()
1273}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001274
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001275TEST_F(ApmTest, AllProcessingDisabledByDefault) {
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001276 AudioProcessing::Config config = apm_->GetConfig();
1277 EXPECT_FALSE(config.echo_canceller.enabled);
1278 EXPECT_FALSE(config.high_pass_filter.enabled);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001279 EXPECT_FALSE(apm_->gain_control()->is_enabled());
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001280 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1281 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1282 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1283}
1284
1285TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001286 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001287 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001288 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001289 AudioFrame frame_copy;
1290 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001291 for (int j = 0; j < 1000; j++) {
1292 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1293 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001294 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1295 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001296 }
1297 }
1298}
1299
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001300TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1301 // Test that ProcessStream copies input to output even with no processing.
1302 const size_t kSamples = 80;
1303 const int sample_rate = 8000;
1304 const float src[kSamples] = {
1305 -1.0f, 0.0f, 1.0f
1306 };
1307 float dest[kSamples] = {};
1308
1309 auto src_channels = &src[0];
1310 auto dest_channels = &dest[0];
1311
Ivo Creusen62337e52018-01-09 14:17:33 +01001312 apm_.reset(AudioProcessingBuilder().Create());
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001313 EXPECT_NOERR(apm_->ProcessStream(
1314 &src_channels, kSamples, sample_rate, LayoutFromChannels(1),
1315 sample_rate, LayoutFromChannels(1), &dest_channels));
1316
1317 for (size_t i = 0; i < kSamples; ++i) {
1318 EXPECT_EQ(src[i], dest[i]);
1319 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001320
1321 // Same for ProcessReverseStream.
1322 float rev_dest[kSamples] = {};
1323 auto rev_dest_channels = &rev_dest[0];
1324
1325 StreamConfig input_stream = {sample_rate, 1};
1326 StreamConfig output_stream = {sample_rate, 1};
1327 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1328 output_stream, &rev_dest_channels));
1329
1330 for (size_t i = 0; i < kSamples; ++i) {
1331 EXPECT_EQ(src[i], rev_dest[i]);
1332 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001333}
1334
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001335TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1336 EnableAllComponents();
1337
pkasting25702cb2016-01-08 13:50:27 -08001338 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001339 Init(kProcessSampleRates[i],
1340 kProcessSampleRates[i],
1341 kProcessSampleRates[i],
1342 2,
1343 2,
1344 2,
1345 false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001346 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001347 ASSERT_EQ(0, feof(far_file_));
1348 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001349 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001350 CopyLeftToRightChannel(revframe_->mutable_data(),
1351 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001352
aluebsb0319552016-03-17 20:39:53 -07001353 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001354
yujo36b1a5f2017-06-12 12:45:32 -07001355 CopyLeftToRightChannel(frame_->mutable_data(),
1356 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001357 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1358
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001359 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001360 ASSERT_EQ(kNoErr,
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001361 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001362 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001363 analog_level = apm_->gain_control()->stream_analog_level();
1364
yujo36b1a5f2017-06-12 12:45:32 -07001365 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001366 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001367 rewind(far_file_);
1368 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001369 }
1370}
1371
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001372TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001373 // Verify the filter is not active through undistorted audio when:
1374 // 1. No components are enabled...
1375 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001376 AudioFrame frame_copy;
1377 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001378 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1379 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1380 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1381
1382 // 2. Only the level estimator is enabled...
1383 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001384 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001385 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1386 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1387 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1388 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1389 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1390
1391 // 3. Only VAD is enabled...
1392 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001393 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001394 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1395 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1396 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1397 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1398 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1399
1400 // 4. Both VAD and the level estimator are enabled...
1401 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001402 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001403 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1404 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1405 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1406 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1407 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1408 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1409 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1410
Sam Zackrissoncb1b5562018-09-28 14:15:09 +02001411 // Check the test is valid. We should have distortion from the filter
1412 // when AEC is enabled (which won't affect the audio).
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02001413 AudioProcessing::Config apm_config = apm_->GetConfig();
1414 apm_config.echo_canceller.enabled = true;
1415 apm_config.echo_canceller.mobile_mode = false;
1416 apm_->ApplyConfig(apm_config);
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001417 frame_->samples_per_channel_ = 320;
1418 frame_->num_channels_ = 2;
1419 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001420 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001421 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001422 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001423 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1424 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1425}
1426
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001427#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1428void ApmTest::ProcessDebugDump(const std::string& in_filename,
1429 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001430 Format format,
1431 int max_size_bytes) {
aleloif4dd1912017-06-15 01:55:38 -07001432 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001433 FILE* in_file = fopen(in_filename.c_str(), "rb");
1434 ASSERT_TRUE(in_file != NULL);
1435 audioproc::Event event_msg;
1436 bool first_init = true;
1437
1438 while (ReadMessageFromFile(in_file, &event_msg)) {
1439 if (event_msg.type() == audioproc::Event::INIT) {
1440 const audioproc::Init msg = event_msg.init();
1441 int reverse_sample_rate = msg.sample_rate();
1442 if (msg.has_reverse_sample_rate()) {
1443 reverse_sample_rate = msg.reverse_sample_rate();
1444 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001445 int output_sample_rate = msg.sample_rate();
1446 if (msg.has_output_sample_rate()) {
1447 output_sample_rate = msg.output_sample_rate();
1448 }
1449
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001450 Init(msg.sample_rate(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001451 output_sample_rate,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001452 reverse_sample_rate,
1453 msg.num_input_channels(),
1454 msg.num_output_channels(),
1455 msg.num_reverse_channels(),
1456 false);
1457 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001458 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001459 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001460 auto aec_dump =
1461 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1462 EXPECT_TRUE(aec_dump);
1463 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001464 first_init = false;
1465 }
1466
1467 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1468 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1469
1470 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001471 ASSERT_EQ(revframe_->num_channels_,
1472 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001473 for (int i = 0; i < msg.channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001474 memcpy(revfloat_cb_->channels()[i],
1475 msg.channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001476 msg.channel(i).size());
1477 }
1478 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001479 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001480 if (format == kFloatFormat) {
1481 // We're using an int16 input file; convert to float.
1482 ConvertToFloat(*revframe_, revfloat_cb_.get());
1483 }
1484 }
1485 AnalyzeReverseStreamChooser(format);
1486
1487 } else if (event_msg.type() == audioproc::Event::STREAM) {
1488 const audioproc::Stream msg = event_msg.stream();
1489 // ProcessStream could have changed this for the output frame.
1490 frame_->num_channels_ = apm_->num_input_channels();
1491
1492 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1493 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001494 if (msg.has_keypress()) {
1495 apm_->set_stream_key_pressed(msg.keypress());
1496 } else {
1497 apm_->set_stream_key_pressed(true);
1498 }
1499
1500 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001501 ASSERT_EQ(frame_->num_channels_,
1502 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001503 for (int i = 0; i < msg.input_channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001504 memcpy(float_cb_->channels()[i],
1505 msg.input_channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001506 msg.input_channel(i).size());
1507 }
1508 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001509 memcpy(frame_->mutable_data(), msg.input_data().data(),
1510 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001511 if (format == kFloatFormat) {
1512 // We're using an int16 input file; convert to float.
1513 ConvertToFloat(*frame_, float_cb_.get());
1514 }
1515 }
1516 ProcessStreamChooser(format);
1517 }
1518 }
aleloif4dd1912017-06-15 01:55:38 -07001519 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001520 fclose(in_file);
1521}
1522
1523void ApmTest::VerifyDebugDumpTest(Format format) {
Minyue Li656d6092018-08-10 15:38:52 +02001524 rtc::ScopedFakeClock fake_clock;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001525 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001526 std::string format_string;
1527 switch (format) {
1528 case kIntFormat:
1529 format_string = "_int";
1530 break;
1531 case kFloatFormat:
1532 format_string = "_float";
1533 break;
1534 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001535 const std::string ref_filename = test::TempFilename(
1536 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1537 const std::string out_filename = test::TempFilename(
1538 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001539 const std::string limited_filename = test::TempFilename(
1540 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1541 const size_t logging_limit_bytes = 100000;
1542 // We expect at least this many bytes in the created logfile.
1543 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001544 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001545 ProcessDebugDump(in_filename, ref_filename, format, -1);
1546 ProcessDebugDump(ref_filename, out_filename, format, -1);
1547 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001548
1549 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1550 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001551 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001552 ASSERT_TRUE(ref_file != NULL);
1553 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001554 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001555 std::unique_ptr<uint8_t[]> ref_bytes;
1556 std::unique_ptr<uint8_t[]> out_bytes;
1557 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001558
1559 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1560 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001561 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001562 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001563 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001564 while (ref_size > 0 && out_size > 0) {
1565 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001566 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001567 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001568 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001569 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001570 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001571 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1572 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001573 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001574 }
1575 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001576 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1577 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001578 EXPECT_NE(0, feof(ref_file));
1579 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001580 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001581 ASSERT_EQ(0, fclose(ref_file));
1582 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001583 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001584 remove(ref_filename.c_str());
1585 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001586 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001587}
1588
pbosc7a65692016-05-06 12:50:04 -07001589TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001590 VerifyDebugDumpTest(kIntFormat);
1591}
1592
pbosc7a65692016-05-06 12:50:04 -07001593TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001594 VerifyDebugDumpTest(kFloatFormat);
1595}
1596#endif
1597
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001598// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001599TEST_F(ApmTest, DebugDump) {
aleloif4dd1912017-06-15 01:55:38 -07001600 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001601 const std::string filename =
1602 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001603 {
1604 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1605 EXPECT_FALSE(aec_dump);
1606 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001607
1608#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1609 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001610 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001611
aleloif4dd1912017-06-15 01:55:38 -07001612 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1613 EXPECT_TRUE(aec_dump);
1614 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001615 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001616 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001617 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001618
1619 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001620 FILE* fid = fopen(filename.c_str(), "r");
1621 ASSERT_TRUE(fid != NULL);
1622
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001623 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001624 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001625 ASSERT_EQ(0, remove(filename.c_str()));
1626#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001627 // Verify the file has NOT been written.
1628 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1629#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1630}
1631
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001632// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001633TEST_F(ApmTest, DebugDumpFromFileHandle) {
aleloif4dd1912017-06-15 01:55:38 -07001634 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1635
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001636 const std::string filename =
1637 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001638 FILE* fid = fopen(filename.c_str(), "w");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001639 ASSERT_TRUE(fid);
1640
1641#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1642 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001643 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001644
aleloif4dd1912017-06-15 01:55:38 -07001645 auto aec_dump = AecDumpFactory::Create(fid, -1, &worker_queue);
1646 EXPECT_TRUE(aec_dump);
1647 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001648 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001649 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001650 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001651
1652 // Verify the file has been written.
1653 fid = fopen(filename.c_str(), "r");
1654 ASSERT_TRUE(fid != NULL);
1655
1656 // Clean it up.
1657 ASSERT_EQ(0, fclose(fid));
1658 ASSERT_EQ(0, remove(filename.c_str()));
1659#else
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001660 ASSERT_EQ(0, fclose(fid));
1661#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1662}
1663
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001664TEST_F(ApmTest, FloatAndIntInterfacesGiveSimilarResults) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001665 audioproc::OutputData ref_data;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001666 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001667
1668 Config config;
1669 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001670 std::unique_ptr<AudioProcessing> fapm(
1671 AudioProcessingBuilder().Create(config));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001672 EnableAllComponents();
1673 EnableAllAPComponents(fapm.get());
1674 for (int i = 0; i < ref_data.test_size(); i++) {
1675 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
1676
1677 audioproc::Test* test = ref_data.mutable_test(i);
1678 // TODO(ajm): Restore downmixing test cases.
1679 if (test->num_input_channels() != test->num_output_channels())
1680 continue;
1681
Peter Kasting69558702016-01-12 16:26:35 -08001682 const size_t num_render_channels =
1683 static_cast<size_t>(test->num_reverse_channels());
1684 const size_t num_input_channels =
1685 static_cast<size_t>(test->num_input_channels());
1686 const size_t num_output_channels =
1687 static_cast<size_t>(test->num_output_channels());
pkasting25702cb2016-01-08 13:50:27 -08001688 const size_t samples_per_channel = static_cast<size_t>(
1689 test->sample_rate() * AudioProcessing::kChunkSizeMs / 1000);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001690
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001691 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
1692 num_input_channels, num_output_channels, num_render_channels, true);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001693 Init(fapm.get());
1694
1695 ChannelBuffer<int16_t> output_cb(samples_per_channel, num_input_channels);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001696 ChannelBuffer<int16_t> output_int16(samples_per_channel,
1697 num_input_channels);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001698
1699 int analog_level = 127;
aluebs776593b2016-03-15 14:04:58 -07001700 size_t num_bad_chunks = 0;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001701 while (ReadFrame(far_file_, revframe_, revfloat_cb_.get()) &&
1702 ReadFrame(near_file_, frame_, float_cb_.get())) {
1703 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1704
aluebsb0319552016-03-17 20:39:53 -07001705 EXPECT_NOERR(apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001706 EXPECT_NOERR(fapm->AnalyzeReverseStream(
1707 revfloat_cb_->channels(),
1708 samples_per_channel,
1709 test->sample_rate(),
1710 LayoutFromChannels(num_render_channels)));
1711
1712 EXPECT_NOERR(apm_->set_stream_delay_ms(0));
1713 EXPECT_NOERR(fapm->set_stream_delay_ms(0));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001714 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(analog_level));
1715 EXPECT_NOERR(fapm->gain_control()->set_stream_analog_level(analog_level));
1716
1717 EXPECT_NOERR(apm_->ProcessStream(frame_));
yujo36b1a5f2017-06-12 12:45:32 -07001718 Deinterleave(frame_->data(), samples_per_channel, num_output_channels,
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001719 output_int16.channels());
1720
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001721 EXPECT_NOERR(fapm->ProcessStream(
1722 float_cb_->channels(),
1723 samples_per_channel,
1724 test->sample_rate(),
1725 LayoutFromChannels(num_input_channels),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001726 test->sample_rate(),
1727 LayoutFromChannels(num_output_channels),
1728 float_cb_->channels()));
Peter Kasting69558702016-01-12 16:26:35 -08001729 for (size_t j = 0; j < num_output_channels; ++j) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001730 FloatToS16(float_cb_->channels()[j],
1731 samples_per_channel,
1732 output_cb.channels()[j]);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001733 float variance = 0;
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001734 float snr = ComputeSNR(output_int16.channels()[j],
1735 output_cb.channels()[j],
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001736 samples_per_channel, &variance);
aluebs776593b2016-03-15 14:04:58 -07001737
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001738 const float kVarianceThreshold = 20;
1739 const float kSNRThreshold = 20;
aluebs776593b2016-03-15 14:04:58 -07001740
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001741 // Skip frames with low energy.
aluebs776593b2016-03-15 14:04:58 -07001742 if (sqrt(variance) > kVarianceThreshold && snr < kSNRThreshold) {
1743 ++num_bad_chunks;
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001744 }
1745 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001746
1747 analog_level = fapm->gain_control()->stream_analog_level();
1748 EXPECT_EQ(apm_->gain_control()->stream_analog_level(),
1749 fapm->gain_control()->stream_analog_level());
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001750 EXPECT_NEAR(apm_->noise_suppression()->speech_probability(),
1751 fapm->noise_suppression()->speech_probability(),
Alejandro Luebs47748742015-05-22 12:00:21 -07001752 0.01);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001753
1754 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08001755 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001756 }
aluebs776593b2016-03-15 14:04:58 -07001757
1758#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1759 const size_t kMaxNumBadChunks = 0;
1760#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
1761 // There are a few chunks in the fixed-point profile that give low SNR.
1762 // Listening confirmed the difference is acceptable.
1763 const size_t kMaxNumBadChunks = 60;
1764#endif
1765 EXPECT_LE(num_bad_chunks, kMaxNumBadChunks);
1766
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001767 rewind(far_file_);
1768 rewind(near_file_);
1769 }
1770}
1771
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001772// TODO(andrew): Add a test to process a few frames with different combinations
1773// of enabled components.
1774
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001775TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001776 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001777 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001778
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001779 if (!write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001780 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001781 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001782 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08001783 for (size_t i = 0; i < arraysize(kChannels); i++) {
1784 for (size_t j = 0; j < arraysize(kChannels); j++) {
1785 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001786 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001787 test->set_num_reverse_channels(kChannels[i]);
1788 test->set_num_input_channels(kChannels[j]);
1789 test->set_num_output_channels(kChannels[j]);
1790 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001791 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001792 }
1793 }
1794 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001795#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1796 // To test the extended filter mode.
1797 audioproc::Test* test = ref_data.add_test();
1798 test->set_num_reverse_channels(2);
1799 test->set_num_input_channels(2);
1800 test->set_num_output_channels(2);
1801 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
1802 test->set_use_aec_extended_filter(true);
1803#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001804 }
1805
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001806 for (int i = 0; i < ref_data.test_size(); i++) {
1807 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001808
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001809 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00001810 // TODO(ajm): We no longer allow different input and output channels. Skip
1811 // these tests for now, but they should be removed from the set.
1812 if (test->num_input_channels() != test->num_output_channels())
1813 continue;
1814
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001815 Config config;
1816 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02001817 config.Set<ExtendedFilter>(
1818 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01001819 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00001820
1821 EnableAllComponents();
1822
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001823 Init(test->sample_rate(),
1824 test->sample_rate(),
1825 test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08001826 static_cast<size_t>(test->num_input_channels()),
1827 static_cast<size_t>(test->num_output_channels()),
1828 static_cast<size_t>(test->num_reverse_channels()),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001829 true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001830
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001831 int frame_count = 0;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001832 int has_voice_count = 0;
1833 int is_saturated_count = 0;
1834 int analog_level = 127;
1835 int analog_level_average = 0;
1836 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001837 float ns_speech_prob_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07001838#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1839 int stats_index = 0;
1840#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001841
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001842 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07001843 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001844
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001845 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1846
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001847 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001848 EXPECT_EQ(apm_->kNoError,
1849 apm_->gain_control()->set_stream_analog_level(analog_level));
1850
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001851 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001852
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001853 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08001854 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
1855 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001856
1857 max_output_average += MaxAudioFrame(*frame_);
1858
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001859 analog_level = apm_->gain_control()->stream_analog_level();
1860 analog_level_average += analog_level;
1861 if (apm_->gain_control()->stream_is_saturated()) {
1862 is_saturated_count++;
1863 }
1864 if (apm_->voice_detection()->stream_has_voice()) {
1865 has_voice_count++;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001866 EXPECT_EQ(AudioFrame::kVadActive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001867 } else {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001868 EXPECT_EQ(AudioFrame::kVadPassive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001869 }
1870
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001871 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
1872
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001873 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07001874 size_t write_count = fwrite(frame_->data(),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001875 sizeof(int16_t),
1876 frame_size,
1877 out_file_);
1878 ASSERT_EQ(frame_size, write_count);
1879
1880 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08001881 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001882 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07001883
1884#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
1885 const int kStatsAggregationFrameNum = 100; // 1 second.
1886 if (frame_count % kStatsAggregationFrameNum == 0) {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001887 // Get echo and delay metrics.
1888 AudioProcessingStats stats =
1889 apm_->GetStatistics(true /* has_remote_tracks */);
minyue58530ed2016-05-24 05:50:12 -07001890
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001891 // Echo metrics.
1892 const float echo_return_loss = stats.echo_return_loss.value_or(-1.0f);
1893 const float echo_return_loss_enhancement =
1894 stats.echo_return_loss_enhancement.value_or(-1.0f);
1895 const float divergent_filter_fraction =
1896 stats.divergent_filter_fraction.value_or(-1.0f);
1897 const float residual_echo_likelihood =
1898 stats.residual_echo_likelihood.value_or(-1.0f);
1899 const float residual_echo_likelihood_recent_max =
1900 stats.residual_echo_likelihood_recent_max.value_or(-1.0f);
1901
1902 // Delay metrics.
1903 const int32_t delay_median_ms = stats.delay_median_ms.value_or(-1.0);
1904 const int32_t delay_standard_deviation_ms =
1905 stats.delay_standard_deviation_ms.value_or(-1.0);
minyue58530ed2016-05-24 05:50:12 -07001906
1907 // Get RMS.
1908 int rms_level = apm_->level_estimator()->RMS();
1909 EXPECT_LE(0, rms_level);
1910 EXPECT_GE(127, rms_level);
1911
1912 if (!write_ref_data) {
1913 const audioproc::Test::EchoMetrics& reference =
1914 test->echo_metrics(stats_index);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001915 constexpr float kEpsilon = 0.01;
1916 EXPECT_NEAR(echo_return_loss, reference.echo_return_loss(), kEpsilon);
1917 EXPECT_NEAR(echo_return_loss_enhancement,
1918 reference.echo_return_loss_enhancement(), kEpsilon);
1919 EXPECT_NEAR(divergent_filter_fraction,
1920 reference.divergent_filter_fraction(), kEpsilon);
1921 EXPECT_NEAR(residual_echo_likelihood,
1922 reference.residual_echo_likelihood(), kEpsilon);
1923 EXPECT_NEAR(residual_echo_likelihood_recent_max,
1924 reference.residual_echo_likelihood_recent_max(),
1925 kEpsilon);
minyue58530ed2016-05-24 05:50:12 -07001926
1927 const audioproc::Test::DelayMetrics& reference_delay =
1928 test->delay_metrics(stats_index);
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001929 EXPECT_EQ(reference_delay.median(), delay_median_ms);
1930 EXPECT_EQ(reference_delay.std(), delay_standard_deviation_ms);
minyue58530ed2016-05-24 05:50:12 -07001931
1932 EXPECT_EQ(test->rms_level(stats_index), rms_level);
1933
1934 ++stats_index;
1935 } else {
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001936 audioproc::Test::EchoMetrics* message_echo = test->add_echo_metrics();
1937 message_echo->set_echo_return_loss(echo_return_loss);
1938 message_echo->set_echo_return_loss_enhancement(
1939 echo_return_loss_enhancement);
1940 message_echo->set_divergent_filter_fraction(
1941 divergent_filter_fraction);
1942 message_echo->set_residual_echo_likelihood(residual_echo_likelihood);
1943 message_echo->set_residual_echo_likelihood_recent_max(
1944 residual_echo_likelihood_recent_max);
minyue58530ed2016-05-24 05:50:12 -07001945 audioproc::Test::DelayMetrics* message_delay =
1946 test->add_delay_metrics();
Sam Zackrissonaf6c1392018-09-13 12:59:09 +02001947 message_delay->set_median(delay_median_ms);
1948 message_delay->set_std(delay_standard_deviation_ms);
minyue58530ed2016-05-24 05:50:12 -07001949
1950 test->add_rms_level(rms_level);
1951 }
1952 }
1953#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001954 }
1955 max_output_average /= frame_count;
1956 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00001957 ns_speech_prob_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001958
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00001959 if (!write_ref_data) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001960 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001961 // When running the test on a N7 we get a {2, 6} difference of
1962 // |has_voice_count| and |max_output_average| is up to 18 higher.
1963 // All numbers being consistently higher on N7 compare to ref_data.
1964 // TODO(bjornv): If we start getting more of these offsets on Android we
1965 // should consider a different approach. Either using one slack for all,
1966 // or generate a separate android reference.
Kári Tristan Helgason640106e2018-09-06 15:29:45 +02001967#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001968 const int kHasVoiceCountOffset = 3;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001969 const int kHasVoiceCountNear = 8;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001970 const int kMaxOutputAverageOffset = 9;
Sam Zackrissone507b0c2018-07-20 15:22:50 +02001971 const int kMaxOutputAverageNear = 26;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001972#else
1973 const int kHasVoiceCountOffset = 0;
1974 const int kHasVoiceCountNear = kIntNear;
1975 const int kMaxOutputAverageOffset = 0;
1976 const int kMaxOutputAverageNear = kIntNear;
1977#endif
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001978 EXPECT_NEAR(test->has_voice_count(),
1979 has_voice_count - kHasVoiceCountOffset,
1980 kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001981 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001982
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001983 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00001984 EXPECT_NEAR(test->max_output_average(),
1985 max_output_average - kMaxOutputAverageOffset,
1986 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00001987#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001988 const double kFloatNear = 0.0005;
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00001989 EXPECT_NEAR(test->ns_speech_probability_average(),
1990 ns_speech_prob_average,
1991 kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001992#endif
1993 } else {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001994 test->set_has_voice_count(has_voice_count);
1995 test->set_is_saturated_count(is_saturated_count);
1996
1997 test->set_analog_level_average(analog_level_average);
1998 test->set_max_output_average(max_output_average);
1999
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002000#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002001 EXPECT_LE(0.0f, ns_speech_prob_average);
2002 EXPECT_GE(1.0f, ns_speech_prob_average);
2003 test->set_ns_speech_probability_average(ns_speech_prob_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002004#endif
2005 }
2006
2007 rewind(far_file_);
2008 rewind(near_file_);
2009 }
2010
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002011 if (write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002012 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002013 }
2014}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002015
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002016TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
2017 struct ChannelFormat {
2018 AudioProcessing::ChannelLayout in_layout;
2019 AudioProcessing::ChannelLayout out_layout;
2020 };
2021 ChannelFormat cf[] = {
2022 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
2023 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
2024 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
2025 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002026
Ivo Creusen62337e52018-01-09 14:17:33 +01002027 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002028 // Enable one component just to ensure some processing takes place.
2029 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08002030 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002031 const int in_rate = 44100;
2032 const int out_rate = 48000;
2033 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
2034 TotalChannelsFromLayout(cf[i].in_layout));
2035 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
2036 ChannelsFromLayout(cf[i].out_layout));
2037
2038 // Run over a few chunks.
2039 for (int j = 0; j < 10; ++j) {
2040 EXPECT_NOERR(ap->ProcessStream(
2041 in_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002042 in_cb.num_frames(),
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002043 in_rate,
2044 cf[i].in_layout,
2045 out_rate,
2046 cf[i].out_layout,
2047 out_cb.channels()));
2048 }
2049 }
2050}
2051
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002052// Compares the reference and test arrays over a region around the expected
2053// delay. Finds the highest SNR in that region and adds the variance and squared
2054// error results to the supplied accumulators.
2055void UpdateBestSNR(const float* ref,
2056 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08002057 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002058 int expected_delay,
2059 double* variance_acc,
2060 double* sq_error_acc) {
2061 double best_snr = std::numeric_limits<double>::min();
2062 double best_variance = 0;
2063 double best_sq_error = 0;
2064 // Search over a region of eight samples around the expected delay.
2065 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
2066 ++delay) {
2067 double sq_error = 0;
2068 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08002069 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002070 double error = test[i + delay] - ref[i];
2071 sq_error += error * error;
2072 variance += ref[i] * ref[i];
2073 }
2074
2075 if (sq_error == 0) {
2076 *variance_acc += variance;
2077 return;
2078 }
2079 double snr = variance / sq_error;
2080 if (snr > best_snr) {
2081 best_snr = snr;
2082 best_variance = variance;
2083 best_sq_error = sq_error;
2084 }
2085 }
2086
2087 *variance_acc += best_variance;
2088 *sq_error_acc += best_sq_error;
2089}
2090
2091// Used to test a multitude of sample rate and channel combinations. It works
2092// by first producing a set of reference files (in SetUpTestCase) that are
2093// assumed to be correct, as the used parameters are verified by other tests
2094// in this collection. Primarily the reference files are all produced at
2095// "native" rates which do not involve any resampling.
2096
2097// Each test pass produces an output file with a particular format. The output
2098// is matched against the reference file closest to its internal processing
2099// format. If necessary the output is resampled back to its process format.
2100// Due to the resampling distortion, we don't expect identical results, but
2101// enforce SNR thresholds which vary depending on the format. 0 is a special
2102// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02002103typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002104class AudioProcessingTest
2105 : public testing::TestWithParam<AudioProcessingTestData> {
2106 public:
2107 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02002108 : input_rate_(std::get<0>(GetParam())),
2109 output_rate_(std::get<1>(GetParam())),
2110 reverse_input_rate_(std::get<2>(GetParam())),
2111 reverse_output_rate_(std::get<3>(GetParam())),
2112 expected_snr_(std::get<4>(GetParam())),
2113 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002114
2115 virtual ~AudioProcessingTest() {}
2116
2117 static void SetUpTestCase() {
2118 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07002119 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08002120 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08002121 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
2122 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
2123 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002124 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07002125 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
2126 kNativeRates[i], kNumChannels[j], kNumChannels[j],
2127 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002128 }
2129 }
2130 }
2131 }
2132
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02002133 void TearDown() {
2134 // Remove "out" files after each test.
2135 ClearTempOutFiles();
2136 }
2137
pbos@webrtc.org200ac002015-02-03 14:14:01 +00002138 static void TearDownTestCase() {
2139 ClearTempFiles();
2140 }
ekmeyerson60d9b332015-08-14 10:35:55 -07002141
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002142 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07002143 // to a file specified with |output_file_prefix|. Both forward and reverse
2144 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002145 static void ProcessFormat(int input_rate,
2146 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07002147 int reverse_input_rate,
2148 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08002149 size_t num_input_channels,
2150 size_t num_output_channels,
2151 size_t num_reverse_input_channels,
2152 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02002153 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002154 Config config;
2155 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01002156 std::unique_ptr<AudioProcessing> ap(
2157 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002158 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002159
ekmeyerson60d9b332015-08-14 10:35:55 -07002160 ProcessingConfig processing_config = {
2161 {{input_rate, num_input_channels},
2162 {output_rate, num_output_channels},
2163 {reverse_input_rate, num_reverse_input_channels},
2164 {reverse_output_rate, num_reverse_output_channels}}};
2165 ap->Initialize(processing_config);
2166
2167 FILE* far_file =
2168 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002169 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07002170 FILE* out_file =
2171 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2172 reverse_input_rate, reverse_output_rate,
2173 num_input_channels, num_output_channels,
2174 num_reverse_input_channels,
2175 num_reverse_output_channels, kForward).c_str(),
2176 "wb");
2177 FILE* rev_out_file =
2178 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2179 reverse_input_rate, reverse_output_rate,
2180 num_input_channels, num_output_channels,
2181 num_reverse_input_channels,
2182 num_reverse_output_channels, kReverse).c_str(),
2183 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002184 ASSERT_TRUE(far_file != NULL);
2185 ASSERT_TRUE(near_file != NULL);
2186 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07002187 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002188
2189 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
2190 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002191 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
2192 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002193 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
2194 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002195 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
2196 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002197
2198 // Temporary buffers.
2199 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07002200 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
2201 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08002202 std::unique_ptr<float[]> float_data(new float[max_length]);
2203 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002204
2205 int analog_level = 127;
2206 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
2207 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002208 EXPECT_NOERR(ap->ProcessReverseStream(
2209 rev_cb.channels(), processing_config.reverse_input_stream(),
2210 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002211
2212 EXPECT_NOERR(ap->set_stream_delay_ms(0));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002213 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
2214
2215 EXPECT_NOERR(ap->ProcessStream(
2216 fwd_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002217 fwd_cb.num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002218 input_rate,
2219 LayoutFromChannels(num_input_channels),
2220 output_rate,
2221 LayoutFromChannels(num_output_channels),
2222 out_cb.channels()));
2223
ekmeyerson60d9b332015-08-14 10:35:55 -07002224 // Dump forward output to file.
2225 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002226 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002227 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002228
pkasting25702cb2016-01-08 13:50:27 -08002229 ASSERT_EQ(out_length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002230 fwrite(float_data.get(), sizeof(float_data[0]),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002231 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002232
ekmeyerson60d9b332015-08-14 10:35:55 -07002233 // Dump reverse output to file.
2234 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
2235 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002236 size_t rev_out_length =
2237 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002238
pkasting25702cb2016-01-08 13:50:27 -08002239 ASSERT_EQ(rev_out_length,
ekmeyerson60d9b332015-08-14 10:35:55 -07002240 fwrite(float_data.get(), sizeof(float_data[0]), rev_out_length,
2241 rev_out_file));
2242
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002243 analog_level = ap->gain_control()->stream_analog_level();
2244 }
2245 fclose(far_file);
2246 fclose(near_file);
2247 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07002248 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002249 }
2250
2251 protected:
2252 int input_rate_;
2253 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002254 int reverse_input_rate_;
2255 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002256 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002257 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002258};
2259
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00002260TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002261 struct ChannelFormat {
2262 int num_input;
2263 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07002264 int num_reverse_input;
2265 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002266 };
2267 ChannelFormat cf[] = {
ekmeyerson60d9b332015-08-14 10:35:55 -07002268 {1, 1, 1, 1},
2269 {1, 1, 2, 1},
2270 {2, 1, 1, 1},
2271 {2, 1, 2, 1},
2272 {2, 2, 1, 1},
2273 {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002274 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002275
pkasting25702cb2016-01-08 13:50:27 -08002276 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002277 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
2278 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
2279 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07002280
ekmeyerson60d9b332015-08-14 10:35:55 -07002281 // Verify output for both directions.
2282 std::vector<StreamDirection> stream_directions;
2283 stream_directions.push_back(kForward);
2284 stream_directions.push_back(kReverse);
2285 for (StreamDirection file_direction : stream_directions) {
2286 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
2287 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
2288 const int out_num =
2289 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
2290 const double expected_snr =
2291 file_direction ? expected_reverse_snr_ : expected_snr_;
2292
2293 const int min_ref_rate = std::min(in_rate, out_rate);
2294 int ref_rate;
2295
2296 if (min_ref_rate > 32000) {
2297 ref_rate = 48000;
2298 } else if (min_ref_rate > 16000) {
2299 ref_rate = 32000;
2300 } else if (min_ref_rate > 8000) {
2301 ref_rate = 16000;
2302 } else {
2303 ref_rate = 8000;
2304 }
aluebs776593b2016-03-15 14:04:58 -07002305#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08002306 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07002307 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08002308 }
2309#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07002310 FILE* out_file = fopen(
2311 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
2312 reverse_output_rate_, cf[i].num_input,
2313 cf[i].num_output, cf[i].num_reverse_input,
2314 cf[i].num_reverse_output, file_direction).c_str(),
2315 "rb");
2316 // The reference files always have matching input and output channels.
2317 FILE* ref_file = fopen(
2318 OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
2319 cf[i].num_output, cf[i].num_output,
2320 cf[i].num_reverse_output, cf[i].num_reverse_output,
2321 file_direction).c_str(),
2322 "rb");
2323 ASSERT_TRUE(out_file != NULL);
2324 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002325
pkasting25702cb2016-01-08 13:50:27 -08002326 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2327 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002328 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002329 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002330 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002331 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002332 // Data from the resampled output, in case the reference and output rates
2333 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002334 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002335
ekmeyerson60d9b332015-08-14 10:35:55 -07002336 PushResampler<float> resampler;
2337 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002338
ekmeyerson60d9b332015-08-14 10:35:55 -07002339 // Compute the resampling delay of the output relative to the reference,
2340 // to find the region over which we should search for the best SNR.
2341 float expected_delay_sec = 0;
2342 if (in_rate != ref_rate) {
2343 // Input resampling delay.
2344 expected_delay_sec +=
2345 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2346 }
2347 if (out_rate != ref_rate) {
2348 // Output resampling delay.
2349 expected_delay_sec +=
2350 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2351 // Delay of converting the output back to its processing rate for
2352 // testing.
2353 expected_delay_sec +=
2354 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2355 }
2356 int expected_delay =
2357 floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002358
ekmeyerson60d9b332015-08-14 10:35:55 -07002359 double variance = 0;
2360 double sq_error = 0;
2361 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2362 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2363 float* out_ptr = out_data.get();
2364 if (out_rate != ref_rate) {
2365 // Resample the output back to its internal processing rate if
2366 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002367 ASSERT_EQ(ref_length,
2368 static_cast<size_t>(resampler.Resample(
2369 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002370 out_ptr = cmp_data.get();
2371 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002372
ekmeyerson60d9b332015-08-14 10:35:55 -07002373 // Update the |sq_error| and |variance| accumulators with the highest
2374 // SNR of reference vs output.
2375 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2376 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002377 }
2378
ekmeyerson60d9b332015-08-14 10:35:55 -07002379 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2380 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2381 << cf[i].num_input << ", " << cf[i].num_output << ", "
2382 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2383 << ", " << file_direction << "): ";
2384 if (sq_error > 0) {
2385 double snr = 10 * log10(variance / sq_error);
2386 EXPECT_GE(snr, expected_snr);
2387 EXPECT_NE(0, expected_snr);
2388 std::cout << "SNR=" << snr << " dB" << std::endl;
2389 } else {
aluebs776593b2016-03-15 14:04:58 -07002390 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002391 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002392
ekmeyerson60d9b332015-08-14 10:35:55 -07002393 fclose(out_file);
2394 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002395 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002396 }
2397}
2398
2399#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2400INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002401 CommonFormats,
2402 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002403 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2404 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2405 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2406 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2407 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2408 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2409 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2410 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2411 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2412 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2413 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2414 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002415
Edward Lemurc5ee9872017-10-23 23:33:04 +02002416 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2417 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2418 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2419 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2420 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2421 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2422 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2423 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2424 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2425 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2426 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2427 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002428
Edward Lemurc5ee9872017-10-23 23:33:04 +02002429 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2430 std::make_tuple(32000, 48000, 32000, 48000, 35, 30),
2431 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2432 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2433 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2434 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2435 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2436 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2437 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2438 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2439 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2440 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002441
Edward Lemurc5ee9872017-10-23 23:33:04 +02002442 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2443 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2444 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2445 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2446 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2447 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2448 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2449 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2450 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2451 std::make_tuple(16000, 16000, 48000, 16000, 40, 20),
2452 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2453 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002454
2455#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2456INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002457 CommonFormats,
2458 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002459 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 20, 0),
2460 std::make_tuple(48000, 48000, 32000, 48000, 20, 30),
2461 std::make_tuple(48000, 48000, 16000, 48000, 20, 20),
2462 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2463 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2464 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
2465 std::make_tuple(48000, 32000, 48000, 32000, 20, 35),
2466 std::make_tuple(48000, 32000, 32000, 32000, 20, 0),
2467 std::make_tuple(48000, 32000, 16000, 32000, 20, 20),
2468 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2469 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2470 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002471
Edward Lemurc5ee9872017-10-23 23:33:04 +02002472 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2473 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2474 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2475 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2476 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2477 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
2478 std::make_tuple(44100, 32000, 48000, 32000, 20, 35),
2479 std::make_tuple(44100, 32000, 32000, 32000, 20, 0),
2480 std::make_tuple(44100, 32000, 16000, 32000, 20, 20),
2481 std::make_tuple(44100, 16000, 48000, 16000, 20, 20),
2482 std::make_tuple(44100, 16000, 32000, 16000, 20, 20),
2483 std::make_tuple(44100, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002484
Edward Lemurc5ee9872017-10-23 23:33:04 +02002485 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2486 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2487 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2488 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2489 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2490 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2491 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2492 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2493 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2494 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2495 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2496 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002497
Edward Lemurc5ee9872017-10-23 23:33:04 +02002498 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2499 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2500 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2501 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2502 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2503 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2504 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2505 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2506 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2507 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2508 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2509 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002510#endif
2511
niklase@google.com470e71d2011-07-07 08:21:25 +00002512} // namespace
peahc19f3122016-10-07 14:54:10 -07002513
Alessio Bazzicac054e782018-04-16 12:10:09 +02002514TEST(RuntimeSettingTest, TestDefaultCtor) {
2515 auto s = AudioProcessing::RuntimeSetting();
2516 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2517}
2518
2519TEST(RuntimeSettingTest, TestCapturePreGain) {
2520 using Type = AudioProcessing::RuntimeSetting::Type;
2521 {
2522 auto s = AudioProcessing::RuntimeSetting::CreateCapturePreGain(1.25f);
2523 EXPECT_EQ(Type::kCapturePreGain, s.type());
2524 float v;
2525 s.GetFloat(&v);
2526 EXPECT_EQ(1.25f, v);
2527 }
2528
2529#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2530 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2531#endif
2532}
2533
2534TEST(RuntimeSettingTest, TestUsageWithSwapQueue) {
2535 SwapQueue<AudioProcessing::RuntimeSetting> q(1);
2536 auto s = AudioProcessing::RuntimeSetting();
2537 ASSERT_TRUE(q.Insert(&s));
2538 ASSERT_TRUE(q.Remove(&s));
2539 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2540}
2541
Sam Zackrisson0beac582017-09-25 12:04:02 +02002542TEST(ApmConfiguration, EnablePostProcessing) {
2543 // Verify that apm uses a capture post processing module if one is provided.
Sam Zackrisson0beac582017-09-25 12:04:02 +02002544 auto mock_post_processor_ptr =
Alex Loiko5825aa62017-12-18 16:02:40 +01002545 new testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002546 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002547 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002548 rtc::scoped_refptr<AudioProcessing> apm =
2549 AudioProcessingBuilder()
2550 .SetCapturePostProcessing(std::move(mock_post_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002551 .Create();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002552
2553 AudioFrame audio;
2554 audio.num_channels_ = 1;
2555 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2556
2557 EXPECT_CALL(*mock_post_processor_ptr, Process(testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002558 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002559}
2560
Alex Loiko5825aa62017-12-18 16:02:40 +01002561TEST(ApmConfiguration, EnablePreProcessing) {
2562 // Verify that apm uses a capture post processing module if one is provided.
Alex Loiko5825aa62017-12-18 16:02:40 +01002563 auto mock_pre_processor_ptr =
2564 new testing::NiceMock<test::MockCustomProcessing>();
2565 auto mock_pre_processor =
2566 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002567 rtc::scoped_refptr<AudioProcessing> apm =
2568 AudioProcessingBuilder()
2569 .SetRenderPreProcessing(std::move(mock_pre_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002570 .Create();
Alex Loiko5825aa62017-12-18 16:02:40 +01002571
2572 AudioFrame audio;
2573 audio.num_channels_ = 1;
2574 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2575
2576 EXPECT_CALL(*mock_pre_processor_ptr, Process(testing::_)).Times(1);
2577 apm->ProcessReverseStream(&audio);
2578}
2579
Valeriia Nemychnikovaf06eb572018-08-29 10:37:09 +02002580TEST(ApmConfiguration, EnableCaptureAnalyzer) {
2581 // Verify that apm uses a capture analyzer if one is provided.
2582 auto mock_capture_analyzer_ptr =
2583 new testing::NiceMock<test::MockCustomAudioAnalyzer>();
2584 auto mock_capture_analyzer =
2585 std::unique_ptr<CustomAudioAnalyzer>(mock_capture_analyzer_ptr);
2586 rtc::scoped_refptr<AudioProcessing> apm =
2587 AudioProcessingBuilder()
2588 .SetCaptureAnalyzer(std::move(mock_capture_analyzer))
2589 .Create();
2590
2591 AudioFrame audio;
2592 audio.num_channels_ = 1;
2593 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2594
2595 EXPECT_CALL(*mock_capture_analyzer_ptr, Analyze(testing::_)).Times(1);
2596 apm->ProcessStream(&audio);
2597}
2598
Alex Loiko73ec0192018-05-15 10:52:28 +02002599TEST(ApmConfiguration, PreProcessingReceivesRuntimeSettings) {
2600 auto mock_pre_processor_ptr =
2601 new testing::NiceMock<test::MockCustomProcessing>();
2602 auto mock_pre_processor =
2603 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
2604 rtc::scoped_refptr<AudioProcessing> apm =
2605 AudioProcessingBuilder()
2606 .SetRenderPreProcessing(std::move(mock_pre_processor))
2607 .Create();
2608 apm->SetRuntimeSetting(
2609 AudioProcessing::RuntimeSetting::CreateCustomRenderSetting(0));
2610
2611 // RuntimeSettings forwarded during 'Process*Stream' calls.
2612 // Therefore we have to make one such call.
2613 AudioFrame audio;
2614 audio.num_channels_ = 1;
2615 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2616
2617 EXPECT_CALL(*mock_pre_processor_ptr, SetRuntimeSetting(testing::_)).Times(1);
2618 apm->ProcessReverseStream(&audio);
2619}
2620
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002621class MyEchoControlFactory : public EchoControlFactory {
2622 public:
2623 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2624 auto ec = new test::MockEchoControl();
2625 EXPECT_CALL(*ec, AnalyzeRender(testing::_)).Times(1);
2626 EXPECT_CALL(*ec, AnalyzeCapture(testing::_)).Times(2);
2627 EXPECT_CALL(*ec, ProcessCapture(testing::_, testing::_)).Times(2);
2628 return std::unique_ptr<EchoControl>(ec);
2629 }
2630};
2631
2632TEST(ApmConfiguration, EchoControlInjection) {
2633 // Verify that apm uses an injected echo controller if one is provided.
2634 webrtc::Config webrtc_config;
2635 std::unique_ptr<EchoControlFactory> echo_control_factory(
2636 new MyEchoControlFactory());
2637
Alex Loiko5825aa62017-12-18 16:02:40 +01002638 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002639 AudioProcessingBuilder()
2640 .SetEchoControlFactory(std::move(echo_control_factory))
2641 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002642
2643 AudioFrame audio;
2644 audio.num_channels_ = 1;
2645 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2646 apm->ProcessStream(&audio);
2647 apm->ProcessReverseStream(&audio);
2648 apm->ProcessStream(&audio);
2649}
Ivo Creusenae026092017-11-20 13:07:16 +01002650
2651std::unique_ptr<AudioProcessing> CreateApm(bool use_AEC2) {
2652 Config old_config;
2653 if (use_AEC2) {
2654 old_config.Set<ExtendedFilter>(new ExtendedFilter(true));
2655 old_config.Set<DelayAgnostic>(new DelayAgnostic(true));
2656 }
Ivo Creusen62337e52018-01-09 14:17:33 +01002657 std::unique_ptr<AudioProcessing> apm(
2658 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002659 if (!apm) {
2660 return apm;
2661 }
2662
2663 ProcessingConfig processing_config = {
2664 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2665
2666 if (apm->Initialize(processing_config) != 0) {
2667 return nullptr;
2668 }
2669
2670 // Disable all components except for an AEC and the residual echo detector.
Sam Zackrissoncdf0e6d2018-09-17 11:05:17 +02002671 AudioProcessing::Config apm_config;
2672 apm_config.residual_echo_detector.enabled = true;
2673 apm_config.high_pass_filter.enabled = false;
2674 apm_config.gain_controller2.enabled = false;
2675 apm_config.echo_canceller.enabled = true;
2676 apm_config.echo_canceller.mobile_mode = !use_AEC2;
2677 apm->ApplyConfig(apm_config);
Ivo Creusenae026092017-11-20 13:07:16 +01002678 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
2679 EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
2680 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
2681 EXPECT_EQ(apm->voice_detection()->Enable(false), 0);
Ivo Creusenae026092017-11-20 13:07:16 +01002682 return apm;
2683}
2684
2685#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
2686#define MAYBE_ApmStatistics DISABLED_ApmStatistics
2687#else
2688#define MAYBE_ApmStatistics ApmStatistics
2689#endif
2690
2691TEST(MAYBE_ApmStatistics, AEC2EnabledTest) {
2692 // Set up APM with AEC2 and process some audio.
2693 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
2694 ASSERT_TRUE(apm);
2695
2696 // Set up an audioframe.
2697 AudioFrame frame;
2698 frame.num_channels_ = 1;
2699 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
2700
2701 // Fill the audio frame with a sawtooth pattern.
2702 int16_t* ptr = frame.mutable_data();
2703 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2704 ptr[i] = 10000 * ((i % 3) - 1);
2705 }
2706
2707 // Do some processing.
2708 for (int i = 0; i < 200; i++) {
2709 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2710 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2711 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2712 }
2713
2714 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002715 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002716 // We expect all statistics to be set and have a sensible value.
2717 ASSERT_TRUE(stats.residual_echo_likelihood);
2718 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2719 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2720 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
2721 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2722 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2723 ASSERT_TRUE(stats.echo_return_loss);
2724 EXPECT_NE(*stats.echo_return_loss, -100.0);
2725 ASSERT_TRUE(stats.echo_return_loss_enhancement);
2726 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
2727 ASSERT_TRUE(stats.divergent_filter_fraction);
2728 EXPECT_NE(*stats.divergent_filter_fraction, -1.0);
2729 ASSERT_TRUE(stats.delay_standard_deviation_ms);
2730 EXPECT_GE(*stats.delay_standard_deviation_ms, 0);
2731 // We don't check stats.delay_median_ms since it takes too long to settle to a
2732 // value. At least 20 seconds of data need to be processed before it will get
2733 // a value, which would make this test take too much time.
2734
2735 // If there are no receive streams, we expect the stats not to be set. The
2736 // 'false' argument signals to APM that no receive streams are currently
2737 // active. In that situation the statistics would get stuck at their last
2738 // calculated value (AEC and echo detection need at least one stream in each
2739 // direction), so to avoid that, they should not be set by APM.
2740 stats = apm->GetStatistics(false);
2741 EXPECT_FALSE(stats.residual_echo_likelihood);
2742 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2743 EXPECT_FALSE(stats.echo_return_loss);
2744 EXPECT_FALSE(stats.echo_return_loss_enhancement);
2745 EXPECT_FALSE(stats.divergent_filter_fraction);
2746 EXPECT_FALSE(stats.delay_median_ms);
2747 EXPECT_FALSE(stats.delay_standard_deviation_ms);
2748}
2749
2750TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
2751 // Set up APM with AECM and process some audio.
2752 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
2753 ASSERT_TRUE(apm);
2754
2755 // Set up an audioframe.
2756 AudioFrame frame;
2757 frame.num_channels_ = 1;
2758 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
2759
2760 // Fill the audio frame with a sawtooth pattern.
2761 int16_t* ptr = frame.mutable_data();
2762 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2763 ptr[i] = 10000 * ((i % 3) - 1);
2764 }
2765
2766 // Do some processing.
2767 for (int i = 0; i < 200; i++) {
2768 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2769 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2770 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2771 }
2772
2773 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002774 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002775 // We expect only the residual echo detector statistics to be set and have a
2776 // sensible value.
2777 EXPECT_TRUE(stats.residual_echo_likelihood);
2778 if (stats.residual_echo_likelihood) {
2779 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2780 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2781 }
2782 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
2783 if (stats.residual_echo_likelihood_recent_max) {
2784 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2785 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2786 }
2787 EXPECT_FALSE(stats.echo_return_loss);
2788 EXPECT_FALSE(stats.echo_return_loss_enhancement);
2789 EXPECT_FALSE(stats.divergent_filter_fraction);
2790 EXPECT_FALSE(stats.delay_median_ms);
2791 EXPECT_FALSE(stats.delay_standard_deviation_ms);
2792
2793 // If there are no receive streams, we expect the stats not to be set.
2794 stats = apm->GetStatistics(false);
2795 EXPECT_FALSE(stats.residual_echo_likelihood);
2796 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2797 EXPECT_FALSE(stats.echo_return_loss);
2798 EXPECT_FALSE(stats.echo_return_loss_enhancement);
2799 EXPECT_FALSE(stats.divergent_filter_fraction);
2800 EXPECT_FALSE(stats.delay_median_ms);
2801 EXPECT_FALSE(stats.delay_standard_deviation_ms);
2802}
Sam Zackrissonb24c00f2018-11-26 16:18:25 +01002803
2804TEST(ApmStatistics, ReportOutputRmsDbfs) {
2805 ProcessingConfig processing_config = {
2806 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2807 AudioProcessing::Config config;
2808
2809 // Set up an audioframe.
2810 AudioFrame frame;
2811 frame.num_channels_ = 1;
2812 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
2813
2814 // Fill the audio frame with a sawtooth pattern.
2815 int16_t* ptr = frame.mutable_data();
2816 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2817 ptr[i] = 10000 * ((i % 3) - 1);
2818 }
2819
2820 std::unique_ptr<AudioProcessing> apm(AudioProcessingBuilder().Create());
2821 apm->Initialize(processing_config);
2822
2823 // If not enabled, no metric should be reported.
2824 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2825 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2826
2827 // If enabled, metrics should be reported.
2828 config.level_estimation.enabled = true;
2829 apm->ApplyConfig(config);
2830 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2831 auto stats = apm->GetStatistics(false);
2832 EXPECT_TRUE(stats.output_rms_dbfs);
2833 EXPECT_GE(*stats.output_rms_dbfs, 0);
2834
2835 // If re-disabled, the value is again not reported.
2836 config.level_estimation.enabled = false;
2837 apm->ApplyConfig(config);
2838 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2839 EXPECT_FALSE(apm->GetStatistics(false).output_rms_dbfs);
2840}
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002841} // namespace webrtc