blob: a75037b24788f1b9e6ae5782aa296b20b8f03d29 [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"
24#include "modules/audio_processing/beamformer/mock_nonlinear_beamformer.h"
25#include "modules/audio_processing/common.h"
26#include "modules/audio_processing/include/audio_processing.h"
Sam Zackrisson0beac582017-09-25 12:04:02 +020027#include "modules/audio_processing/include/mock_audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "modules/audio_processing/level_controller/level_controller_constants.h"
29#include "modules/audio_processing/test/protobuf_utils.h"
30#include "modules/audio_processing/test/test_utils.h"
31#include "modules/include/module_common_types.h"
32#include "rtc_base/arraysize.h"
33#include "rtc_base/checks.h"
34#include "rtc_base/gtest_prod_util.h"
35#include "rtc_base/ignore_wundef.h"
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +010036#include "rtc_base/numerics/safe_conversions.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010037#include "rtc_base/numerics/safe_minmax.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/protobuf_utils.h"
Niels Möller84255bb2017-10-06 13:43:23 +020039#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/task_queue.h"
41#include "rtc_base/thread.h"
42#include "system_wrappers/include/event_wrapper.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) {
181#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
182 EXPECT_NOERR(ap->echo_control_mobile()->Enable(true));
183
184 EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveDigital));
185 EXPECT_NOERR(ap->gain_control()->Enable(true));
186#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
187 EXPECT_NOERR(ap->echo_cancellation()->enable_drift_compensation(true));
188 EXPECT_NOERR(ap->echo_cancellation()->enable_metrics(true));
189 EXPECT_NOERR(ap->echo_cancellation()->enable_delay_logging(true));
190 EXPECT_NOERR(ap->echo_cancellation()->Enable(true));
191
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
196
peah8271d042016-11-22 07:24:52 -0800197 AudioProcessing::Config apm_config;
198 apm_config.high_pass_filter.enabled = true;
199 ap->ApplyConfig(apm_config);
200
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000201 EXPECT_NOERR(ap->level_estimator()->Enable(true));
202 EXPECT_NOERR(ap->noise_suppression()->Enable(true));
203
204 EXPECT_NOERR(ap->voice_detection()->Enable(true));
205}
206
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000207// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000208template <class T>
209T AbsValue(T a) {
210 return a > 0 ? a: -a;
211}
212
213int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800214 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700215 const int16_t* frame_data = frame.data();
216 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800217 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700218 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000219 }
220
221 return max_data;
222}
223
fischman@webrtc.orgf8be8df2013-12-17 23:46:39 +0000224#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
andrew@webrtc.org81865342012-10-27 00:28:27 +0000225void TestStats(const AudioProcessing::Statistic& test,
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000226 const audioproc::Test::Statistic& reference) {
minyue58530ed2016-05-24 05:50:12 -0700227 EXPECT_EQ(reference.instant(), test.instant);
228 EXPECT_EQ(reference.average(), test.average);
229 EXPECT_EQ(reference.maximum(), test.maximum);
230 EXPECT_EQ(reference.minimum(), test.minimum);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000231}
232
233void WriteStatsMessage(const AudioProcessing::Statistic& output,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000234 audioproc::Test::Statistic* msg) {
235 msg->set_instant(output.instant);
236 msg->set_average(output.average);
237 msg->set_maximum(output.maximum);
238 msg->set_minimum(output.minimum);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000239}
fischman@webrtc.orgf8be8df2013-12-17 23:46:39 +0000240#endif
andrew@webrtc.org81865342012-10-27 00:28:27 +0000241
Alex Loiko890988c2017-08-31 10:25:48 +0200242void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700243 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000244 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000245 ASSERT_TRUE(file != NULL);
246
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100247 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000248 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800249 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000250 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000251
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000252 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000253 ASSERT_EQ(static_cast<size_t>(size),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000254 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000255 fclose(file);
256}
257
Alex Loiko890988c2017-08-31 10:25:48 +0200258std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000259 std::ostringstream ss;
260 // Resource files are all stereo.
261 ss << name << sample_rate_hz / 1000 << "_stereo";
262 return test::ResourcePath(ss.str(), "pcm");
263}
264
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000265// Temporary filenames unique to this process. Used to be able to run these
266// tests in parallel as each process needs to be running in isolation they can't
267// have competing filenames.
268std::map<std::string, std::string> temp_filenames;
269
Alex Loiko890988c2017-08-31 10:25:48 +0200270std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000271 int input_rate,
272 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700273 int reverse_input_rate,
274 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800275 size_t num_input_channels,
276 size_t num_output_channels,
277 size_t num_reverse_input_channels,
278 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700279 StreamDirection file_direction) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000280 std::ostringstream ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700281 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
282 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000283 if (num_output_channels == 1) {
284 ss << "mono";
285 } else if (num_output_channels == 2) {
286 ss << "stereo";
287 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700288 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000289 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700290 ss << output_rate / 1000;
291 if (num_reverse_output_channels == 1) {
292 ss << "_rmono";
293 } else if (num_reverse_output_channels == 2) {
294 ss << "_rstereo";
295 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700296 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700297 }
298 ss << reverse_output_rate / 1000;
299 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000300
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000301 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700302 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000303 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
304 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000305}
306
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000307void ClearTempFiles() {
308 for (auto& kv : temp_filenames)
309 remove(kv.second.c_str());
310}
311
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200312// Only remove "out" files. Keep "ref" files.
313void ClearTempOutFiles() {
314 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
315 const std::string& filename = it->first;
316 if (filename.substr(0, 3).compare("out") == 0) {
317 remove(it->second.c_str());
318 temp_filenames.erase(it++);
319 } else {
320 it++;
321 }
322 }
323}
324
Alex Loiko890988c2017-08-31 10:25:48 +0200325void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000326 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000327 ASSERT_TRUE(file != NULL);
328 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000329 fclose(file);
330}
331
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000332// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
333// stereo) file, converts to deinterleaved float (optionally downmixing) and
334// returns the result in |cb|. Returns false if the file ended (or on error) and
335// true otherwise.
336//
337// |int_data| and |float_data| are just temporary space that must be
338// sufficiently large to hold the 10 ms chunk.
339bool ReadChunk(FILE* file, int16_t* int_data, float* float_data,
340 ChannelBuffer<float>* cb) {
341 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000342 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000343 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
344 if (read_count != frame_size) {
345 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700346 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000347 return false; // This is expected.
348 }
349
350 S16ToFloat(int_data, frame_size, float_data);
351 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000352 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000353 } else {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000354 Deinterleave(float_data, cb->num_frames(), 2,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000355 cb->channels());
356 }
357
358 return true;
359}
360
niklase@google.com470e71d2011-07-07 08:21:25 +0000361class ApmTest : public ::testing::Test {
362 protected:
363 ApmTest();
364 virtual void SetUp();
365 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000366
367 static void SetUpTestCase() {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000368 }
369
370 static void TearDownTestCase() {
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000371 ClearTempFiles();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000372 }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000373
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000374 // Used to select between int and float interface tests.
375 enum Format {
376 kIntFormat,
377 kFloatFormat
378 };
379
380 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000381 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000382 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800383 size_t num_input_channels,
384 size_t num_output_channels,
385 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000386 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000387 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000388 void EnableAllComponents();
389 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000390 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000391 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000392 void ReadFrameWithRewind(FILE* file, AudioFrame* frame,
393 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000394 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000395 void ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
396 int delay_min, int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700397 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800398 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700399 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800400 void TestChangingForwardChannels(size_t num_in_channels,
401 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700402 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800403 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700404 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000405 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
406 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000407 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000408 int ProcessStreamChooser(Format format);
409 int AnalyzeReverseStreamChooser(Format format);
410 void ProcessDebugDump(const std::string& in_filename,
411 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800412 Format format,
413 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000414 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000415
416 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000417 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800418 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000419 AudioFrame* frame_;
420 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800421 std::unique_ptr<ChannelBuffer<float> > float_cb_;
422 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000423 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800424 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000425 FILE* far_file_;
426 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000427 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000428};
429
430ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000431 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000432#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800433 ref_filename_(test::ResourcePath("audio_processing/output_data_fixed",
434 "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000435#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000436#if defined(WEBRTC_MAC)
437 // A different file for Mac is needed because on this platform the AEC
438 // constant |kFixedDelayMs| value is 20 and not 50 as it is on the rest.
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800439 ref_filename_(test::ResourcePath("audio_processing/output_data_mac",
440 "pb")),
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000441#else
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800442 ref_filename_(test::ResourcePath("audio_processing/output_data_float",
443 "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000444#endif
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000445#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000446 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000447 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000448 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000449 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000450 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000451 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000452 out_file_(NULL) {
453 Config config;
454 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100455 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000456}
niklase@google.com470e71d2011-07-07 08:21:25 +0000457
458void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000459 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000460
461 frame_ = new AudioFrame();
462 revframe_ = new AudioFrame();
463
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000464 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000465}
466
467void ApmTest::TearDown() {
468 if (frame_) {
469 delete frame_;
470 }
471 frame_ = NULL;
472
473 if (revframe_) {
474 delete revframe_;
475 }
476 revframe_ = NULL;
477
478 if (far_file_) {
479 ASSERT_EQ(0, fclose(far_file_));
480 }
481 far_file_ = NULL;
482
483 if (near_file_) {
484 ASSERT_EQ(0, fclose(near_file_));
485 }
486 near_file_ = NULL;
487
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000488 if (out_file_) {
489 ASSERT_EQ(0, fclose(out_file_));
490 }
491 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000492}
493
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000494void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000495 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700496 ap->Initialize(
497 {{{frame_->sample_rate_hz_, frame_->num_channels_},
498 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700499 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700500 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000501}
502
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000503void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000504 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000505 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800506 size_t num_input_channels,
507 size_t num_output_channels,
508 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000509 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000510 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000511 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000512 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000513
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000514 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
515 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000516 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000517
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000518 if (far_file_) {
519 ASSERT_EQ(0, fclose(far_file_));
520 }
521 std::string filename = ResourceFilePath("far", sample_rate_hz);
522 far_file_ = fopen(filename.c_str(), "rb");
523 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " <<
524 filename << "\n";
525
526 if (near_file_) {
527 ASSERT_EQ(0, fclose(near_file_));
528 }
529 filename = ResourceFilePath("near", sample_rate_hz);
530 near_file_ = fopen(filename.c_str(), "rb");
531 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " <<
532 filename << "\n";
533
534 if (open_output_file) {
535 if (out_file_) {
536 ASSERT_EQ(0, fclose(out_file_));
537 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700538 filename = OutputFilePath(
539 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
540 reverse_sample_rate_hz, num_input_channels, num_output_channels,
541 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000542 out_file_ = fopen(filename.c_str(), "wb");
543 ASSERT_TRUE(out_file_ != NULL) << "Could not open file " <<
544 filename << "\n";
545 }
546}
547
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000548void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000549 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000550}
551
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000552bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame,
553 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000554 // The files always contain stereo audio.
555 size_t frame_size = frame->samples_per_channel_ * 2;
yujo36b1a5f2017-06-12 12:45:32 -0700556 size_t read_count = fread(frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000557 sizeof(int16_t),
558 frame_size,
559 file);
560 if (read_count != frame_size) {
561 // Check that the file really ended.
562 EXPECT_NE(0, feof(file));
563 return false; // This is expected.
564 }
565
566 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700567 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000568 frame->samples_per_channel_);
569 }
570
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000571 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000572 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000573 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000574 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000575}
576
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000577bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
578 return ReadFrame(file, frame, NULL);
579}
580
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000581// If the end of the file has been reached, rewind it and attempt to read the
582// frame again.
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000583void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame,
584 ChannelBuffer<float>* cb) {
585 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000586 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000587 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000588 }
589}
590
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000591void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
592 ReadFrameWithRewind(file, frame, NULL);
593}
594
andrew@webrtc.org81865342012-10-27 00:28:27 +0000595void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
596 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000597 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000598 EXPECT_EQ(apm_->kNoError,
599 apm_->gain_control()->set_stream_analog_level(127));
600 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000601}
602
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000603int ApmTest::ProcessStreamChooser(Format format) {
604 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000605 return apm_->ProcessStream(frame_);
606 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000607 return apm_->ProcessStream(float_cb_->channels(),
608 frame_->samples_per_channel_,
609 frame_->sample_rate_hz_,
610 LayoutFromChannels(frame_->num_channels_),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000611 output_sample_rate_hz_,
612 LayoutFromChannels(num_output_channels_),
613 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000614}
615
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000616int ApmTest::AnalyzeReverseStreamChooser(Format format) {
617 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700618 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000619 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000620 return apm_->AnalyzeReverseStream(
621 revfloat_cb_->channels(),
622 revframe_->samples_per_channel_,
623 revframe_->sample_rate_hz_,
624 LayoutFromChannels(revframe_->num_channels_));
625}
626
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000627void ApmTest::ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
628 int delay_min, int delay_max) {
629 // The |revframe_| and |frame_| should include the proper frame information,
630 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000631 AudioFrame tmp_frame;
632 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000633 bool causal = true;
634
635 tmp_frame.CopyFrom(*revframe_);
636 SetFrameTo(&tmp_frame, 0);
637
638 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
639 // Initialize the |frame_queue| with empty frames.
640 int frame_delay = delay_ms / 10;
641 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000642 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000643 frame->CopyFrom(tmp_frame);
644 frame_queue.push(frame);
645 frame_delay++;
646 causal = false;
647 }
648 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000649 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000650 frame->CopyFrom(tmp_frame);
651 frame_queue.push(frame);
652 frame_delay--;
653 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000654 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
655 // need enough frames with audio to have reliable estimates, but as few as
656 // possible to keep processing time down. 4.5 seconds seemed to be a good
657 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000658 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000659 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000660 frame->CopyFrom(tmp_frame);
661 // Use the near end recording, since that has more speech in it.
662 ASSERT_TRUE(ReadFrame(near_file_, frame));
663 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000664 AudioFrame* reverse_frame = frame;
665 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000666 if (!causal) {
667 reverse_frame = frame_queue.front();
668 // When we call ProcessStream() the frame is modified, so we can't use the
669 // pointer directly when things are non-causal. Use an intermediate frame
670 // and copy the data.
671 process_frame = &tmp_frame;
672 process_frame->CopyFrom(*frame);
673 }
aluebsb0319552016-03-17 20:39:53 -0700674 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000675 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
676 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
677 frame = frame_queue.front();
678 frame_queue.pop();
679 delete frame;
680
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000681 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000682 int median;
683 int std;
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000684 float poor_fraction;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000685 // Discard the first delay metrics to avoid convergence effects.
686 EXPECT_EQ(apm_->kNoError,
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000687 apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
688 &poor_fraction));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000689 }
690 }
691
692 rewind(near_file_);
693 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000694 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000695 frame_queue.pop();
696 delete frame;
697 }
698 // Calculate expected delay estimate and acceptable regions. Further,
699 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700700 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700701 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700702 const int expected_median =
703 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
704 const int expected_median_high = rtc::SafeClamp<int>(
705 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700706 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700707 const int expected_median_low = rtc::SafeClamp<int>(
708 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700709 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000710 // Verify delay metrics.
711 int median;
712 int std;
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000713 float poor_fraction;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000714 EXPECT_EQ(apm_->kNoError,
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000715 apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
716 &poor_fraction));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000717 EXPECT_GE(expected_median_high, median);
718 EXPECT_LE(expected_median_low, median);
719}
720
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000721void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000722 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000723 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000724
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000725 // -- Missing AGC level --
niklase@google.com470e71d2011-07-07 08:21:25 +0000726 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000727 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000728 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000729
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000730 // Resets after successful ProcessStream().
niklase@google.com470e71d2011-07-07 08:21:25 +0000731 EXPECT_EQ(apm_->kNoError,
732 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000733 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000734 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000735 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000736
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000737 // Other stream parameters set correctly.
738 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
niklase@google.com470e71d2011-07-07 08:21:25 +0000739 EXPECT_EQ(apm_->kNoError,
740 apm_->echo_cancellation()->enable_drift_compensation(true));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000741 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000742 apm_->echo_cancellation()->set_stream_drift_samples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +0000743 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000744 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000745 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
746 EXPECT_EQ(apm_->kNoError,
747 apm_->echo_cancellation()->enable_drift_compensation(false));
748
749 // -- Missing delay --
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000750 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000751 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000752 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000753 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000754
755 // Resets after successful ProcessStream().
756 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000757 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000758 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000759 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000760
761 // Other stream parameters set correctly.
762 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
763 EXPECT_EQ(apm_->kNoError,
764 apm_->echo_cancellation()->enable_drift_compensation(true));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000765 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000766 EXPECT_EQ(apm_->kNoError,
767 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000768 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000769 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000770 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
771
772 // -- Missing drift --
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000773 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000774 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000775
776 // Resets after successful ProcessStream().
777 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000778 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000779 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000780 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000781 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000782
783 // Other stream parameters set correctly.
niklase@google.com470e71d2011-07-07 08:21:25 +0000784 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
785 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
786 EXPECT_EQ(apm_->kNoError,
787 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000788 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000789 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000790
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000791 // -- No stream parameters --
niklase@google.com470e71d2011-07-07 08:21:25 +0000792 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000793 AnalyzeReverseStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000794 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000795 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000796
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000797 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000798 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000799 apm_->echo_cancellation()->set_stream_drift_samples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +0000800 EXPECT_EQ(apm_->kNoError,
801 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000802 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000803}
804
805TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000806 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000807}
808
809TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000810 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000811}
812
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000813TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
814 EXPECT_EQ(0, apm_->delay_offset_ms());
815 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
816 EXPECT_EQ(50, apm_->stream_delay_ms());
817}
818
819TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
820 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000821 apm_->set_delay_offset_ms(100);
822 EXPECT_EQ(100, apm_->delay_offset_ms());
823 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000824 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000825 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
826 EXPECT_EQ(200, apm_->stream_delay_ms());
827
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000828 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000829 apm_->set_delay_offset_ms(-50);
830 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000831 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
832 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000833 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
834 EXPECT_EQ(50, apm_->stream_delay_ms());
835}
836
Michael Graczyk86c6d332015-07-23 11:41:39 -0700837void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800838 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700839 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000840 frame_->num_channels_ = num_channels;
841 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700842 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000843}
844
Michael Graczyk86c6d332015-07-23 11:41:39 -0700845void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800846 size_t num_in_channels,
847 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700848 AudioProcessing::Error expected_return) {
849 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
850 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
851
852 EXPECT_EQ(expected_return,
853 apm_->ProcessStream(float_cb_->channels(), input_stream,
854 output_stream, float_cb_->channels()));
855}
856
857void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800858 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700859 AudioProcessing::Error expected_return) {
860 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700861 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
862 {output_sample_rate_hz_, apm_->num_output_channels()},
863 {frame_->sample_rate_hz_, num_rev_channels},
864 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700865
ekmeyerson60d9b332015-08-14 10:35:55 -0700866 EXPECT_EQ(
867 expected_return,
868 apm_->ProcessReverseStream(
869 float_cb_->channels(), processing_config.reverse_input_stream(),
870 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700871}
872
873TEST_F(ApmTest, ChannelsInt16Interface) {
874 // Testing number of invalid and valid channels.
875 Init(16000, 16000, 16000, 4, 4, 4, false);
876
877 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
878
Peter Kasting69558702016-01-12 16:26:35 -0800879 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700880 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000881 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000882 }
883}
884
Michael Graczyk86c6d332015-07-23 11:41:39 -0700885TEST_F(ApmTest, Channels) {
886 // Testing number of invalid and valid channels.
887 Init(16000, 16000, 16000, 4, 4, 4, false);
888
889 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
890 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
891
Peter Kasting69558702016-01-12 16:26:35 -0800892 for (size_t i = 1; i < 4; ++i) {
893 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700894 // Output channels much be one or match input channels.
895 if (j == 1 || i == j) {
896 TestChangingForwardChannels(i, j, kNoErr);
897 TestChangingReverseChannels(i, kNoErr);
898
899 EXPECT_EQ(i, apm_->num_input_channels());
900 EXPECT_EQ(j, apm_->num_output_channels());
901 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800902 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700903 } else {
904 TestChangingForwardChannels(i, j,
905 AudioProcessing::kBadNumberChannelsError);
906 }
907 }
908 }
909}
910
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000911TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000912 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000913 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000914 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000915 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700916 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800917 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000918 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000919 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000920 }
921}
922
niklase@google.com470e71d2011-07-07 08:21:25 +0000923TEST_F(ApmTest, EchoCancellation) {
924 EXPECT_EQ(apm_->kNoError,
925 apm_->echo_cancellation()->enable_drift_compensation(true));
926 EXPECT_TRUE(apm_->echo_cancellation()->is_drift_compensation_enabled());
927 EXPECT_EQ(apm_->kNoError,
928 apm_->echo_cancellation()->enable_drift_compensation(false));
929 EXPECT_FALSE(apm_->echo_cancellation()->is_drift_compensation_enabled());
930
niklase@google.com470e71d2011-07-07 08:21:25 +0000931 EchoCancellation::SuppressionLevel level[] = {
932 EchoCancellation::kLowSuppression,
933 EchoCancellation::kModerateSuppression,
934 EchoCancellation::kHighSuppression,
935 };
pkasting25702cb2016-01-08 13:50:27 -0800936 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000937 EXPECT_EQ(apm_->kNoError,
938 apm_->echo_cancellation()->set_suppression_level(level[i]));
939 EXPECT_EQ(level[i],
940 apm_->echo_cancellation()->suppression_level());
941 }
942
943 EchoCancellation::Metrics metrics;
944 EXPECT_EQ(apm_->kNotEnabledError,
945 apm_->echo_cancellation()->GetMetrics(&metrics));
946
ivoc3e9a5372016-10-28 07:55:33 -0700947 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
948 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
949
niklase@google.com470e71d2011-07-07 08:21:25 +0000950 EXPECT_EQ(apm_->kNoError,
951 apm_->echo_cancellation()->enable_metrics(true));
952 EXPECT_TRUE(apm_->echo_cancellation()->are_metrics_enabled());
953 EXPECT_EQ(apm_->kNoError,
954 apm_->echo_cancellation()->enable_metrics(false));
955 EXPECT_FALSE(apm_->echo_cancellation()->are_metrics_enabled());
956
ivoc48dfab52016-10-28 03:29:31 -0700957 EXPECT_EQ(apm_->kNoError,
958 apm_->echo_cancellation()->enable_delay_logging(true));
959 EXPECT_TRUE(apm_->echo_cancellation()->is_delay_logging_enabled());
960 EXPECT_EQ(apm_->kNoError,
961 apm_->echo_cancellation()->enable_delay_logging(false));
962 EXPECT_FALSE(apm_->echo_cancellation()->is_delay_logging_enabled());
963
ivoc3e9a5372016-10-28 07:55:33 -0700964 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
965 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
966
967 int median = 0;
968 int std = 0;
969 float poor_fraction = 0;
970 EXPECT_EQ(apm_->kNotEnabledError, apm_->echo_cancellation()->GetDelayMetrics(
971 &median, &std, &poor_fraction));
972
niklase@google.com470e71d2011-07-07 08:21:25 +0000973 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
974 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
975 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
976 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
bjornv@webrtc.org91d11b32013-03-05 16:53:09 +0000977
978 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
979 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
980 EXPECT_TRUE(apm_->echo_cancellation()->aec_core() != NULL);
981 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
982 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
983 EXPECT_FALSE(apm_->echo_cancellation()->aec_core() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000984}
985
bjornv@webrtc.org84f8ec12014-06-19 12:14:33 +0000986TEST_F(ApmTest, DISABLED_EchoCancellationReportsCorrectDelays) {
bjornv@webrtc.orgbac00122015-01-02 09:23:49 +0000987 // TODO(bjornv): Fix this test to work with DA-AEC.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000988 // Enable AEC only.
989 EXPECT_EQ(apm_->kNoError,
990 apm_->echo_cancellation()->enable_drift_compensation(false));
991 EXPECT_EQ(apm_->kNoError,
992 apm_->echo_cancellation()->enable_metrics(false));
993 EXPECT_EQ(apm_->kNoError,
994 apm_->echo_cancellation()->enable_delay_logging(true));
995 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000996 Config config;
henrik.lundin0f133b92015-07-02 00:17:55 -0700997 config.Set<DelayAgnostic>(new DelayAgnostic(false));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000998 apm_->SetExtraOptions(config);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000999
1000 // Internally in the AEC the amount of lookahead the delay estimation can
1001 // handle is 15 blocks and the maximum delay is set to 60 blocks.
1002 const int kLookaheadBlocks = 15;
1003 const int kMaxDelayBlocks = 60;
1004 // The AEC has a startup time before it actually starts to process. This
1005 // procedure can flush the internal far-end buffer, which of course affects
1006 // the delay estimation. Therefore, we set a system_delay high enough to
1007 // avoid that. The smallest system_delay you can report without flushing the
1008 // buffer is 66 ms in 8 kHz.
1009 //
1010 // It is known that for 16 kHz (and 32 kHz) sampling frequency there is an
1011 // additional stuffing of 8 ms on the fly, but it seems to have no impact on
1012 // delay estimation. This should be noted though. In case of test failure,
1013 // this could be the cause.
1014 const int kSystemDelayMs = 66;
1015 // Test a couple of corner cases and verify that the estimated delay is
1016 // within a valid region (set to +-1.5 blocks). Note that these cases are
1017 // sampling frequency dependent.
pkasting25702cb2016-01-08 13:50:27 -08001018 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001019 Init(kProcessSampleRates[i],
1020 kProcessSampleRates[i],
1021 kProcessSampleRates[i],
1022 2,
1023 2,
1024 2,
1025 false);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001026 // Sampling frequency dependent variables.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001027 const int num_ms_per_block =
1028 std::max(4, static_cast<int>(640 / frame_->samples_per_channel_));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001029 const int delay_min_ms = -kLookaheadBlocks * num_ms_per_block;
1030 const int delay_max_ms = (kMaxDelayBlocks - 1) * num_ms_per_block;
1031
1032 // 1) Verify correct delay estimate at lookahead boundary.
1033 int delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_min_ms);
1034 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1035 delay_max_ms);
1036 // 2) A delay less than maximum lookahead should give an delay estimate at
1037 // the boundary (= -kLookaheadBlocks * num_ms_per_block).
1038 delay_ms -= 20;
1039 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1040 delay_max_ms);
1041 // 3) Three values around zero delay. Note that we need to compensate for
1042 // the fake system_delay.
1043 delay_ms = TruncateToMultipleOf10(kSystemDelayMs - 10);
1044 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1045 delay_max_ms);
1046 delay_ms = TruncateToMultipleOf10(kSystemDelayMs);
1047 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1048 delay_max_ms);
1049 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + 10);
1050 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1051 delay_max_ms);
1052 // 4) Verify correct delay estimate at maximum delay boundary.
1053 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_max_ms);
1054 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1055 delay_max_ms);
1056 // 5) A delay above the maximum delay should give an estimate at the
1057 // boundary (= (kMaxDelayBlocks - 1) * num_ms_per_block).
1058 delay_ms += 20;
1059 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1060 delay_max_ms);
1061 }
1062}
1063
niklase@google.com470e71d2011-07-07 08:21:25 +00001064TEST_F(ApmTest, EchoControlMobile) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001065 // Turn AECM on (and AEC off)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001066 Init(16000, 16000, 16000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001067 EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(true));
1068 EXPECT_TRUE(apm_->echo_control_mobile()->is_enabled());
1069
niklase@google.com470e71d2011-07-07 08:21:25 +00001070 // Toggle routing modes
1071 EchoControlMobile::RoutingMode mode[] = {
1072 EchoControlMobile::kQuietEarpieceOrHeadset,
1073 EchoControlMobile::kEarpiece,
1074 EchoControlMobile::kLoudEarpiece,
1075 EchoControlMobile::kSpeakerphone,
1076 EchoControlMobile::kLoudSpeakerphone,
1077 };
pkasting25702cb2016-01-08 13:50:27 -08001078 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001079 EXPECT_EQ(apm_->kNoError,
1080 apm_->echo_control_mobile()->set_routing_mode(mode[i]));
1081 EXPECT_EQ(mode[i],
1082 apm_->echo_control_mobile()->routing_mode());
1083 }
1084 // Turn comfort noise off/on
1085 EXPECT_EQ(apm_->kNoError,
1086 apm_->echo_control_mobile()->enable_comfort_noise(false));
1087 EXPECT_FALSE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
1088 EXPECT_EQ(apm_->kNoError,
1089 apm_->echo_control_mobile()->enable_comfort_noise(true));
1090 EXPECT_TRUE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001091 // Set and get echo path
ajm@google.com22e65152011-07-18 18:03:01 +00001092 const size_t echo_path_size =
1093 apm_->echo_control_mobile()->echo_path_size_bytes();
kwiberg62eaacf2016-02-17 06:39:05 -08001094 std::unique_ptr<char[]> echo_path_in(new char[echo_path_size]);
1095 std::unique_ptr<char[]> echo_path_out(new char[echo_path_size]);
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001096 EXPECT_EQ(apm_->kNullPointerError,
1097 apm_->echo_control_mobile()->SetEchoPath(NULL, echo_path_size));
1098 EXPECT_EQ(apm_->kNullPointerError,
1099 apm_->echo_control_mobile()->GetEchoPath(NULL, echo_path_size));
1100 EXPECT_EQ(apm_->kBadParameterError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001101 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(), 1));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001102 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001103 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001104 echo_path_size));
ajm@google.com22e65152011-07-18 18:03:01 +00001105 for (size_t i = 0; i < echo_path_size; i++) {
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001106 echo_path_in[i] = echo_path_out[i] + 1;
1107 }
1108 EXPECT_EQ(apm_->kBadParameterError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001109 apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(), 1));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001110 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001111 apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(),
1112 echo_path_size));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001113 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001114 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
1115 echo_path_size));
ajm@google.com22e65152011-07-18 18:03:01 +00001116 for (size_t i = 0; i < echo_path_size; i++) {
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001117 EXPECT_EQ(echo_path_in[i], echo_path_out[i]);
1118 }
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001119
1120 // Process a few frames with NS in the default disabled state. This exercises
1121 // a different codepath than with it enabled.
1122 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1123 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1124 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1125 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1126
niklase@google.com470e71d2011-07-07 08:21:25 +00001127 // Turn AECM off
1128 EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(false));
1129 EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1130}
1131
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +00001132TEST_F(ApmTest, GainControl) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001133 // Testing gain modes
niklase@google.com470e71d2011-07-07 08:21:25 +00001134 EXPECT_EQ(apm_->kNoError,
1135 apm_->gain_control()->set_mode(
1136 apm_->gain_control()->mode()));
1137
1138 GainControl::Mode mode[] = {
1139 GainControl::kAdaptiveAnalog,
1140 GainControl::kAdaptiveDigital,
1141 GainControl::kFixedDigital
1142 };
pkasting25702cb2016-01-08 13:50:27 -08001143 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001144 EXPECT_EQ(apm_->kNoError,
1145 apm_->gain_control()->set_mode(mode[i]));
1146 EXPECT_EQ(mode[i], apm_->gain_control()->mode());
1147 }
1148 // Testing invalid target levels
1149 EXPECT_EQ(apm_->kBadParameterError,
1150 apm_->gain_control()->set_target_level_dbfs(-3));
1151 EXPECT_EQ(apm_->kBadParameterError,
1152 apm_->gain_control()->set_target_level_dbfs(-40));
1153 // Testing valid target levels
1154 EXPECT_EQ(apm_->kNoError,
1155 apm_->gain_control()->set_target_level_dbfs(
1156 apm_->gain_control()->target_level_dbfs()));
1157
1158 int level_dbfs[] = {0, 6, 31};
pkasting25702cb2016-01-08 13:50:27 -08001159 for (size_t i = 0; i < arraysize(level_dbfs); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001160 EXPECT_EQ(apm_->kNoError,
1161 apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
1162 EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
1163 }
1164
1165 // Testing invalid compression gains
1166 EXPECT_EQ(apm_->kBadParameterError,
1167 apm_->gain_control()->set_compression_gain_db(-1));
1168 EXPECT_EQ(apm_->kBadParameterError,
1169 apm_->gain_control()->set_compression_gain_db(100));
1170
1171 // Testing valid compression gains
1172 EXPECT_EQ(apm_->kNoError,
1173 apm_->gain_control()->set_compression_gain_db(
1174 apm_->gain_control()->compression_gain_db()));
1175
1176 int gain_db[] = {0, 10, 90};
pkasting25702cb2016-01-08 13:50:27 -08001177 for (size_t i = 0; i < arraysize(gain_db); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001178 EXPECT_EQ(apm_->kNoError,
1179 apm_->gain_control()->set_compression_gain_db(gain_db[i]));
1180 EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
1181 }
1182
1183 // Testing limiter off/on
1184 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
1185 EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
1186 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
1187 EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
1188
1189 // Testing invalid level limits
1190 EXPECT_EQ(apm_->kBadParameterError,
1191 apm_->gain_control()->set_analog_level_limits(-1, 512));
1192 EXPECT_EQ(apm_->kBadParameterError,
1193 apm_->gain_control()->set_analog_level_limits(100000, 512));
1194 EXPECT_EQ(apm_->kBadParameterError,
1195 apm_->gain_control()->set_analog_level_limits(512, -1));
1196 EXPECT_EQ(apm_->kBadParameterError,
1197 apm_->gain_control()->set_analog_level_limits(512, 100000));
1198 EXPECT_EQ(apm_->kBadParameterError,
1199 apm_->gain_control()->set_analog_level_limits(512, 255));
1200
1201 // Testing valid level limits
1202 EXPECT_EQ(apm_->kNoError,
1203 apm_->gain_control()->set_analog_level_limits(
1204 apm_->gain_control()->analog_level_minimum(),
1205 apm_->gain_control()->analog_level_maximum()));
1206
1207 int min_level[] = {0, 255, 1024};
pkasting25702cb2016-01-08 13:50:27 -08001208 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001209 EXPECT_EQ(apm_->kNoError,
1210 apm_->gain_control()->set_analog_level_limits(min_level[i], 1024));
1211 EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
1212 }
1213
1214 int max_level[] = {0, 1024, 65535};
pkasting25702cb2016-01-08 13:50:27 -08001215 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001216 EXPECT_EQ(apm_->kNoError,
1217 apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
1218 EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
1219 }
1220
1221 // TODO(ajm): stream_is_saturated() and stream_analog_level()
1222
1223 // Turn AGC off
1224 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
1225 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1226}
1227
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001228void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001229 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001230 EXPECT_EQ(apm_->kNoError,
1231 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1232 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1233
1234 int out_analog_level = 0;
1235 for (int i = 0; i < 2000; ++i) {
1236 ReadFrameWithRewind(near_file_, frame_);
1237 // Ensure the audio is at a low level, so the AGC will try to increase it.
1238 ScaleFrame(frame_, 0.25);
1239
1240 // Always pass in the same volume.
1241 EXPECT_EQ(apm_->kNoError,
1242 apm_->gain_control()->set_stream_analog_level(100));
1243 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1244 out_analog_level = apm_->gain_control()->stream_analog_level();
1245 }
1246
1247 // Ensure the AGC is still able to reach the maximum.
1248 EXPECT_EQ(255, out_analog_level);
1249}
1250
1251// Verifies that despite volume slider quantization, the AGC can continue to
1252// increase its volume.
1253TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -08001254 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001255 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
1256 }
1257}
1258
1259void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001260 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001261 EXPECT_EQ(apm_->kNoError,
1262 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1263 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1264
1265 int out_analog_level = 100;
1266 for (int i = 0; i < 1000; ++i) {
1267 ReadFrameWithRewind(near_file_, frame_);
1268 // Ensure the audio is at a low level, so the AGC will try to increase it.
1269 ScaleFrame(frame_, 0.25);
1270
1271 EXPECT_EQ(apm_->kNoError,
1272 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1273 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1274 out_analog_level = apm_->gain_control()->stream_analog_level();
1275 }
1276
1277 // Ensure the volume was raised.
1278 EXPECT_GT(out_analog_level, 100);
1279 int highest_level_reached = out_analog_level;
1280 // Simulate a user manual volume change.
1281 out_analog_level = 100;
1282
1283 for (int i = 0; i < 300; ++i) {
1284 ReadFrameWithRewind(near_file_, frame_);
1285 ScaleFrame(frame_, 0.25);
1286
1287 EXPECT_EQ(apm_->kNoError,
1288 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1289 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1290 out_analog_level = apm_->gain_control()->stream_analog_level();
1291 // Check that AGC respected the manually adjusted volume.
1292 EXPECT_LT(out_analog_level, highest_level_reached);
1293 }
1294 // Check that the volume was still raised.
1295 EXPECT_GT(out_analog_level, 100);
1296}
1297
1298TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001299 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001300 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1301 }
1302}
1303
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001304#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
1305TEST_F(ApmTest, AgcOnlyAdaptsWhenTargetSignalIsPresent) {
1306 const int kSampleRateHz = 16000;
pkasting25702cb2016-01-08 13:50:27 -08001307 const size_t kSamplesPerChannel =
1308 static_cast<size_t>(AudioProcessing::kChunkSizeMs * kSampleRateHz / 1000);
Peter Kasting69558702016-01-12 16:26:35 -08001309 const size_t kNumInputChannels = 2;
1310 const size_t kNumOutputChannels = 1;
pkasting25702cb2016-01-08 13:50:27 -08001311 const size_t kNumChunks = 700;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001312 const float kScaleFactor = 0.25f;
1313 Config config;
1314 std::vector<webrtc::Point> geometry;
1315 geometry.push_back(webrtc::Point(0.f, 0.f, 0.f));
1316 geometry.push_back(webrtc::Point(0.05f, 0.f, 0.f));
1317 config.Set<Beamforming>(new Beamforming(true, geometry));
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +00001318 testing::NiceMock<MockNonlinearBeamformer>* beamformer =
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001319 new testing::NiceMock<MockNonlinearBeamformer>(geometry, 1u);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001320 std::unique_ptr<AudioProcessing> apm(
Ivo Creusen62337e52018-01-09 14:17:33 +01001321 AudioProcessingBuilder()
1322 .SetNonlinearBeamformer(
1323 std::unique_ptr<webrtc::NonlinearBeamformer>(beamformer))
1324 .Create(config));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001325 EXPECT_EQ(kNoErr, apm->gain_control()->Enable(true));
1326 ChannelBuffer<float> src_buf(kSamplesPerChannel, kNumInputChannels);
1327 ChannelBuffer<float> dest_buf(kSamplesPerChannel, kNumOutputChannels);
pkasting25702cb2016-01-08 13:50:27 -08001328 const size_t max_length = kSamplesPerChannel * std::max(kNumInputChannels,
1329 kNumOutputChannels);
kwiberg62eaacf2016-02-17 06:39:05 -08001330 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
1331 std::unique_ptr<float[]> float_data(new float[max_length]);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001332 std::string filename = ResourceFilePath("far", kSampleRateHz);
1333 FILE* far_file = fopen(filename.c_str(), "rb");
1334 ASSERT_TRUE(far_file != NULL) << "Could not open file " << filename << "\n";
1335 const int kDefaultVolume = apm->gain_control()->stream_analog_level();
1336 const int kDefaultCompressionGain =
1337 apm->gain_control()->compression_gain_db();
1338 bool is_target = false;
1339 EXPECT_CALL(*beamformer, is_target_present())
1340 .WillRepeatedly(testing::ReturnPointee(&is_target));
pkasting25702cb2016-01-08 13:50:27 -08001341 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001342 ASSERT_TRUE(ReadChunk(far_file,
1343 int_data.get(),
1344 float_data.get(),
1345 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001346 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001347 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001348 src_buf.channels()[j][k] *= kScaleFactor;
1349 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001350 }
1351 EXPECT_EQ(kNoErr,
1352 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001353 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001354 kSampleRateHz,
1355 LayoutFromChannels(src_buf.num_channels()),
1356 kSampleRateHz,
1357 LayoutFromChannels(dest_buf.num_channels()),
1358 dest_buf.channels()));
1359 }
1360 EXPECT_EQ(kDefaultVolume,
1361 apm->gain_control()->stream_analog_level());
1362 EXPECT_EQ(kDefaultCompressionGain,
1363 apm->gain_control()->compression_gain_db());
1364 rewind(far_file);
1365 is_target = true;
pkasting25702cb2016-01-08 13:50:27 -08001366 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001367 ASSERT_TRUE(ReadChunk(far_file,
1368 int_data.get(),
1369 float_data.get(),
1370 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001371 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001372 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001373 src_buf.channels()[j][k] *= kScaleFactor;
1374 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001375 }
1376 EXPECT_EQ(kNoErr,
1377 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001378 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001379 kSampleRateHz,
1380 LayoutFromChannels(src_buf.num_channels()),
1381 kSampleRateHz,
1382 LayoutFromChannels(dest_buf.num_channels()),
1383 dest_buf.channels()));
1384 }
1385 EXPECT_LT(kDefaultVolume,
1386 apm->gain_control()->stream_analog_level());
1387 EXPECT_LT(kDefaultCompressionGain,
1388 apm->gain_control()->compression_gain_db());
1389 ASSERT_EQ(0, fclose(far_file));
1390}
1391#endif
1392
niklase@google.com470e71d2011-07-07 08:21:25 +00001393TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001394 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001395 NoiseSuppression::Level level[] = {
1396 NoiseSuppression::kLow,
1397 NoiseSuppression::kModerate,
1398 NoiseSuppression::kHigh,
1399 NoiseSuppression::kVeryHigh
1400 };
pkasting25702cb2016-01-08 13:50:27 -08001401 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001402 EXPECT_EQ(apm_->kNoError,
1403 apm_->noise_suppression()->set_level(level[i]));
1404 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1405 }
1406
andrew@webrtc.org648af742012-02-08 01:57:29 +00001407 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001408 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1409 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1410 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1411 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1412}
1413
1414TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001415 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001416 AudioProcessing::Config apm_config;
1417 apm_config.high_pass_filter.enabled = true;
1418 apm_->ApplyConfig(apm_config);
1419 apm_config.high_pass_filter.enabled = false;
1420 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001421}
1422
1423TEST_F(ApmTest, LevelEstimator) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001424 // Turn level estimator on/off
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001425 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001426 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001427
1428 EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1429
1430 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1431 EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1432
1433 // Run this test in wideband; in super-wb, the splitting filter distorts the
1434 // audio enough to cause deviation from the expectation for small values.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001435 frame_->samples_per_channel_ = 160;
1436 frame_->num_channels_ = 2;
1437 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001438
1439 // Min value if no frames have been processed.
1440 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1441
1442 // Min value on zero frames.
1443 SetFrameTo(frame_, 0);
1444 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1445 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1446 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1447
1448 // Try a few RMS values.
1449 // (These also test that the value resets after retrieving it.)
1450 SetFrameTo(frame_, 32767);
1451 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1452 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1453 EXPECT_EQ(0, apm_->level_estimator()->RMS());
1454
1455 SetFrameTo(frame_, 30000);
1456 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1457 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1458 EXPECT_EQ(1, apm_->level_estimator()->RMS());
1459
1460 SetFrameTo(frame_, 10000);
1461 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1462 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1463 EXPECT_EQ(10, apm_->level_estimator()->RMS());
1464
1465 SetFrameTo(frame_, 10);
1466 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1467 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1468 EXPECT_EQ(70, apm_->level_estimator()->RMS());
1469
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001470 // Verify reset after enable/disable.
1471 SetFrameTo(frame_, 32767);
1472 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1473 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1474 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1475 SetFrameTo(frame_, 1);
1476 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1477 EXPECT_EQ(90, apm_->level_estimator()->RMS());
1478
1479 // Verify reset after initialize.
1480 SetFrameTo(frame_, 32767);
1481 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1482 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1483 SetFrameTo(frame_, 1);
1484 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1485 EXPECT_EQ(90, apm_->level_estimator()->RMS());
niklase@google.com470e71d2011-07-07 08:21:25 +00001486}
1487
1488TEST_F(ApmTest, VoiceDetection) {
1489 // Test external VAD
1490 EXPECT_EQ(apm_->kNoError,
1491 apm_->voice_detection()->set_stream_has_voice(true));
1492 EXPECT_TRUE(apm_->voice_detection()->stream_has_voice());
1493 EXPECT_EQ(apm_->kNoError,
1494 apm_->voice_detection()->set_stream_has_voice(false));
1495 EXPECT_FALSE(apm_->voice_detection()->stream_has_voice());
1496
andrew@webrtc.org648af742012-02-08 01:57:29 +00001497 // Test valid likelihoods
niklase@google.com470e71d2011-07-07 08:21:25 +00001498 VoiceDetection::Likelihood likelihood[] = {
1499 VoiceDetection::kVeryLowLikelihood,
1500 VoiceDetection::kLowLikelihood,
1501 VoiceDetection::kModerateLikelihood,
1502 VoiceDetection::kHighLikelihood
1503 };
pkasting25702cb2016-01-08 13:50:27 -08001504 for (size_t i = 0; i < arraysize(likelihood); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001505 EXPECT_EQ(apm_->kNoError,
1506 apm_->voice_detection()->set_likelihood(likelihood[i]));
1507 EXPECT_EQ(likelihood[i], apm_->voice_detection()->likelihood());
1508 }
1509
1510 /* TODO(bjornv): Enable once VAD supports other frame lengths than 10 ms
andrew@webrtc.org648af742012-02-08 01:57:29 +00001511 // Test invalid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001512 EXPECT_EQ(apm_->kBadParameterError,
1513 apm_->voice_detection()->set_frame_size_ms(12));
1514
andrew@webrtc.org648af742012-02-08 01:57:29 +00001515 // Test valid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001516 for (int i = 10; i <= 30; i += 10) {
1517 EXPECT_EQ(apm_->kNoError,
1518 apm_->voice_detection()->set_frame_size_ms(i));
1519 EXPECT_EQ(i, apm_->voice_detection()->frame_size_ms());
1520 }
1521 */
1522
andrew@webrtc.org648af742012-02-08 01:57:29 +00001523 // Turn VAD on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001524 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1525 EXPECT_TRUE(apm_->voice_detection()->is_enabled());
1526 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1527 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1528
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001529 // Test that AudioFrame activity is maintained when VAD is disabled.
1530 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1531 AudioFrame::VADActivity activity[] = {
1532 AudioFrame::kVadActive,
1533 AudioFrame::kVadPassive,
1534 AudioFrame::kVadUnknown
1535 };
pkasting25702cb2016-01-08 13:50:27 -08001536 for (size_t i = 0; i < arraysize(activity); i++) {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001537 frame_->vad_activity_ = activity[i];
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001538 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001539 EXPECT_EQ(activity[i], frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001540 }
1541
1542 // Test that AudioFrame activity is set when VAD is enabled.
1543 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001544 frame_->vad_activity_ = AudioFrame::kVadUnknown;
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001545 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001546 EXPECT_NE(AudioFrame::kVadUnknown, frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001547
niklase@google.com470e71d2011-07-07 08:21:25 +00001548 // TODO(bjornv): Add tests for streamed voice; stream_has_voice()
1549}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001550
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001551TEST_F(ApmTest, AllProcessingDisabledByDefault) {
1552 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
1553 EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1554 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1555 EXPECT_FALSE(apm_->high_pass_filter()->is_enabled());
1556 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1557 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1558 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1559}
1560
1561TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001562 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001563 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001564 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001565 AudioFrame frame_copy;
1566 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001567 for (int j = 0; j < 1000; j++) {
1568 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1569 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001570 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1571 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001572 }
1573 }
1574}
1575
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001576TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1577 // Test that ProcessStream copies input to output even with no processing.
1578 const size_t kSamples = 80;
1579 const int sample_rate = 8000;
1580 const float src[kSamples] = {
1581 -1.0f, 0.0f, 1.0f
1582 };
1583 float dest[kSamples] = {};
1584
1585 auto src_channels = &src[0];
1586 auto dest_channels = &dest[0];
1587
Ivo Creusen62337e52018-01-09 14:17:33 +01001588 apm_.reset(AudioProcessingBuilder().Create());
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001589 EXPECT_NOERR(apm_->ProcessStream(
1590 &src_channels, kSamples, sample_rate, LayoutFromChannels(1),
1591 sample_rate, LayoutFromChannels(1), &dest_channels));
1592
1593 for (size_t i = 0; i < kSamples; ++i) {
1594 EXPECT_EQ(src[i], dest[i]);
1595 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001596
1597 // Same for ProcessReverseStream.
1598 float rev_dest[kSamples] = {};
1599 auto rev_dest_channels = &rev_dest[0];
1600
1601 StreamConfig input_stream = {sample_rate, 1};
1602 StreamConfig output_stream = {sample_rate, 1};
1603 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1604 output_stream, &rev_dest_channels));
1605
1606 for (size_t i = 0; i < kSamples; ++i) {
1607 EXPECT_EQ(src[i], rev_dest[i]);
1608 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001609}
1610
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001611TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1612 EnableAllComponents();
1613
pkasting25702cb2016-01-08 13:50:27 -08001614 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001615 Init(kProcessSampleRates[i],
1616 kProcessSampleRates[i],
1617 kProcessSampleRates[i],
1618 2,
1619 2,
1620 2,
1621 false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001622 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001623 ASSERT_EQ(0, feof(far_file_));
1624 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001625 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001626 CopyLeftToRightChannel(revframe_->mutable_data(),
1627 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001628
aluebsb0319552016-03-17 20:39:53 -07001629 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001630
yujo36b1a5f2017-06-12 12:45:32 -07001631 CopyLeftToRightChannel(frame_->mutable_data(),
1632 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001633 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1634
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001635 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001636 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001637 ASSERT_EQ(kNoErr,
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001638 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001639 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001640 analog_level = apm_->gain_control()->stream_analog_level();
1641
yujo36b1a5f2017-06-12 12:45:32 -07001642 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001643 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001644 rewind(far_file_);
1645 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001646 }
1647}
1648
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001649TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001650 // Verify the filter is not active through undistorted audio when:
1651 // 1. No components are enabled...
1652 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001653 AudioFrame frame_copy;
1654 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001655 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1656 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1657 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1658
1659 // 2. Only the level estimator is enabled...
1660 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001661 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001662 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1663 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1664 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1665 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1666 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1667
1668 // 3. Only VAD is enabled...
1669 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001670 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001671 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1672 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1673 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1674 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1675 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1676
1677 // 4. Both VAD and the level estimator are enabled...
1678 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001679 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001680 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1681 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1682 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1683 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1684 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1685 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1686 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1687
1688 // 5. Not using super-wb.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001689 frame_->samples_per_channel_ = 160;
1690 frame_->num_channels_ = 2;
1691 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001692 // Enable AEC, which would require the filter in super-wb. We rely on the
1693 // first few frames of data being unaffected by the AEC.
1694 // TODO(andrew): This test, and the one below, rely rather tenuously on the
1695 // behavior of the AEC. Think of something more robust.
1696 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001697 // Make sure we have extended filter enabled. This makes sure nothing is
1698 // touched until we have a farend frame.
1699 Config config;
Henrik Lundin441f6342015-06-09 16:03:13 +02001700 config.Set<ExtendedFilter>(new ExtendedFilter(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001701 apm_->SetExtraOptions(config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001702 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001703 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001704 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001705 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001706 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1707 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001708 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001709 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1710 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1711
1712 // Check the test is valid. We should have distortion from the filter
1713 // when AEC is enabled (which won't affect the audio).
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001714 frame_->samples_per_channel_ = 320;
1715 frame_->num_channels_ = 2;
1716 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001717 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001718 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001719 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001720 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001721 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1722 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1723}
1724
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001725#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1726void ApmTest::ProcessDebugDump(const std::string& in_filename,
1727 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001728 Format format,
1729 int max_size_bytes) {
aleloif4dd1912017-06-15 01:55:38 -07001730 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001731 FILE* in_file = fopen(in_filename.c_str(), "rb");
1732 ASSERT_TRUE(in_file != NULL);
1733 audioproc::Event event_msg;
1734 bool first_init = true;
1735
1736 while (ReadMessageFromFile(in_file, &event_msg)) {
1737 if (event_msg.type() == audioproc::Event::INIT) {
1738 const audioproc::Init msg = event_msg.init();
1739 int reverse_sample_rate = msg.sample_rate();
1740 if (msg.has_reverse_sample_rate()) {
1741 reverse_sample_rate = msg.reverse_sample_rate();
1742 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001743 int output_sample_rate = msg.sample_rate();
1744 if (msg.has_output_sample_rate()) {
1745 output_sample_rate = msg.output_sample_rate();
1746 }
1747
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001748 Init(msg.sample_rate(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001749 output_sample_rate,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001750 reverse_sample_rate,
1751 msg.num_input_channels(),
1752 msg.num_output_channels(),
1753 msg.num_reverse_channels(),
1754 false);
1755 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001756 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001757 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001758 auto aec_dump =
1759 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1760 EXPECT_TRUE(aec_dump);
1761 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001762 first_init = false;
1763 }
1764
1765 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1766 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1767
1768 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001769 ASSERT_EQ(revframe_->num_channels_,
1770 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001771 for (int i = 0; i < msg.channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001772 memcpy(revfloat_cb_->channels()[i],
1773 msg.channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001774 msg.channel(i).size());
1775 }
1776 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001777 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001778 if (format == kFloatFormat) {
1779 // We're using an int16 input file; convert to float.
1780 ConvertToFloat(*revframe_, revfloat_cb_.get());
1781 }
1782 }
1783 AnalyzeReverseStreamChooser(format);
1784
1785 } else if (event_msg.type() == audioproc::Event::STREAM) {
1786 const audioproc::Stream msg = event_msg.stream();
1787 // ProcessStream could have changed this for the output frame.
1788 frame_->num_channels_ = apm_->num_input_channels();
1789
1790 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1791 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
1792 apm_->echo_cancellation()->set_stream_drift_samples(msg.drift());
1793 if (msg.has_keypress()) {
1794 apm_->set_stream_key_pressed(msg.keypress());
1795 } else {
1796 apm_->set_stream_key_pressed(true);
1797 }
1798
1799 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001800 ASSERT_EQ(frame_->num_channels_,
1801 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001802 for (int i = 0; i < msg.input_channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001803 memcpy(float_cb_->channels()[i],
1804 msg.input_channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001805 msg.input_channel(i).size());
1806 }
1807 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001808 memcpy(frame_->mutable_data(), msg.input_data().data(),
1809 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001810 if (format == kFloatFormat) {
1811 // We're using an int16 input file; convert to float.
1812 ConvertToFloat(*frame_, float_cb_.get());
1813 }
1814 }
1815 ProcessStreamChooser(format);
1816 }
1817 }
aleloif4dd1912017-06-15 01:55:38 -07001818 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001819 fclose(in_file);
1820}
1821
1822void ApmTest::VerifyDebugDumpTest(Format format) {
1823 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001824 std::string format_string;
1825 switch (format) {
1826 case kIntFormat:
1827 format_string = "_int";
1828 break;
1829 case kFloatFormat:
1830 format_string = "_float";
1831 break;
1832 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001833 const std::string ref_filename = test::TempFilename(
1834 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1835 const std::string out_filename = test::TempFilename(
1836 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001837 const std::string limited_filename = test::TempFilename(
1838 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1839 const size_t logging_limit_bytes = 100000;
1840 // We expect at least this many bytes in the created logfile.
1841 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001842 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001843 ProcessDebugDump(in_filename, ref_filename, format, -1);
1844 ProcessDebugDump(ref_filename, out_filename, format, -1);
1845 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001846
1847 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1848 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001849 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001850 ASSERT_TRUE(ref_file != NULL);
1851 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001852 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001853 std::unique_ptr<uint8_t[]> ref_bytes;
1854 std::unique_ptr<uint8_t[]> out_bytes;
1855 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001856
1857 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1858 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001859 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001860 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001861 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001862 while (ref_size > 0 && out_size > 0) {
1863 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001864 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001865 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001866 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001867 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001868 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001869 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1870 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001871 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001872 }
1873 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001874 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1875 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001876 EXPECT_NE(0, feof(ref_file));
1877 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001878 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001879 ASSERT_EQ(0, fclose(ref_file));
1880 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001881 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001882 remove(ref_filename.c_str());
1883 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001884 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001885}
1886
pbosc7a65692016-05-06 12:50:04 -07001887TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001888 VerifyDebugDumpTest(kIntFormat);
1889}
1890
pbosc7a65692016-05-06 12:50:04 -07001891TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001892 VerifyDebugDumpTest(kFloatFormat);
1893}
1894#endif
1895
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001896// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001897TEST_F(ApmTest, DebugDump) {
aleloif4dd1912017-06-15 01:55:38 -07001898 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001899 const std::string filename =
1900 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001901 {
1902 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1903 EXPECT_FALSE(aec_dump);
1904 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001905
1906#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1907 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001908 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001909
aleloif4dd1912017-06-15 01:55:38 -07001910 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1911 EXPECT_TRUE(aec_dump);
1912 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001913 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001914 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001915 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001916
1917 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001918 FILE* fid = fopen(filename.c_str(), "r");
1919 ASSERT_TRUE(fid != NULL);
1920
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001921 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001922 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001923 ASSERT_EQ(0, remove(filename.c_str()));
1924#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001925 // Verify the file has NOT been written.
1926 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1927#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1928}
1929
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001930// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001931TEST_F(ApmTest, DebugDumpFromFileHandle) {
aleloif4dd1912017-06-15 01:55:38 -07001932 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1933
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001934 const std::string filename =
1935 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001936 FILE* fid = fopen(filename.c_str(), "w");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001937 ASSERT_TRUE(fid);
1938
1939#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1940 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001941 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001942
aleloif4dd1912017-06-15 01:55:38 -07001943 auto aec_dump = AecDumpFactory::Create(fid, -1, &worker_queue);
1944 EXPECT_TRUE(aec_dump);
1945 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001946 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001947 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001948 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001949
1950 // Verify the file has been written.
1951 fid = fopen(filename.c_str(), "r");
1952 ASSERT_TRUE(fid != NULL);
1953
1954 // Clean it up.
1955 ASSERT_EQ(0, fclose(fid));
1956 ASSERT_EQ(0, remove(filename.c_str()));
1957#else
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001958 ASSERT_EQ(0, fclose(fid));
1959#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1960}
1961
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001962TEST_F(ApmTest, FloatAndIntInterfacesGiveSimilarResults) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001963 audioproc::OutputData ref_data;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001964 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001965
1966 Config config;
1967 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001968 std::unique_ptr<AudioProcessing> fapm(
1969 AudioProcessingBuilder().Create(config));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001970 EnableAllComponents();
1971 EnableAllAPComponents(fapm.get());
1972 for (int i = 0; i < ref_data.test_size(); i++) {
1973 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
1974
1975 audioproc::Test* test = ref_data.mutable_test(i);
1976 // TODO(ajm): Restore downmixing test cases.
1977 if (test->num_input_channels() != test->num_output_channels())
1978 continue;
1979
Peter Kasting69558702016-01-12 16:26:35 -08001980 const size_t num_render_channels =
1981 static_cast<size_t>(test->num_reverse_channels());
1982 const size_t num_input_channels =
1983 static_cast<size_t>(test->num_input_channels());
1984 const size_t num_output_channels =
1985 static_cast<size_t>(test->num_output_channels());
pkasting25702cb2016-01-08 13:50:27 -08001986 const size_t samples_per_channel = static_cast<size_t>(
1987 test->sample_rate() * AudioProcessing::kChunkSizeMs / 1000);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001988
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001989 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
1990 num_input_channels, num_output_channels, num_render_channels, true);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001991 Init(fapm.get());
1992
1993 ChannelBuffer<int16_t> output_cb(samples_per_channel, num_input_channels);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001994 ChannelBuffer<int16_t> output_int16(samples_per_channel,
1995 num_input_channels);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001996
1997 int analog_level = 127;
aluebs776593b2016-03-15 14:04:58 -07001998 size_t num_bad_chunks = 0;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001999 while (ReadFrame(far_file_, revframe_, revfloat_cb_.get()) &&
2000 ReadFrame(near_file_, frame_, float_cb_.get())) {
2001 frame_->vad_activity_ = AudioFrame::kVadUnknown;
2002
aluebsb0319552016-03-17 20:39:53 -07002003 EXPECT_NOERR(apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002004 EXPECT_NOERR(fapm->AnalyzeReverseStream(
2005 revfloat_cb_->channels(),
2006 samples_per_channel,
2007 test->sample_rate(),
2008 LayoutFromChannels(num_render_channels)));
2009
2010 EXPECT_NOERR(apm_->set_stream_delay_ms(0));
2011 EXPECT_NOERR(fapm->set_stream_delay_ms(0));
2012 apm_->echo_cancellation()->set_stream_drift_samples(0);
2013 fapm->echo_cancellation()->set_stream_drift_samples(0);
2014 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(analog_level));
2015 EXPECT_NOERR(fapm->gain_control()->set_stream_analog_level(analog_level));
2016
2017 EXPECT_NOERR(apm_->ProcessStream(frame_));
yujo36b1a5f2017-06-12 12:45:32 -07002018 Deinterleave(frame_->data(), samples_per_channel, num_output_channels,
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002019 output_int16.channels());
2020
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002021 EXPECT_NOERR(fapm->ProcessStream(
2022 float_cb_->channels(),
2023 samples_per_channel,
2024 test->sample_rate(),
2025 LayoutFromChannels(num_input_channels),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002026 test->sample_rate(),
2027 LayoutFromChannels(num_output_channels),
2028 float_cb_->channels()));
Peter Kasting69558702016-01-12 16:26:35 -08002029 for (size_t j = 0; j < num_output_channels; ++j) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002030 FloatToS16(float_cb_->channels()[j],
2031 samples_per_channel,
2032 output_cb.channels()[j]);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002033 float variance = 0;
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002034 float snr = ComputeSNR(output_int16.channels()[j],
2035 output_cb.channels()[j],
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002036 samples_per_channel, &variance);
aluebs776593b2016-03-15 14:04:58 -07002037
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002038 const float kVarianceThreshold = 20;
2039 const float kSNRThreshold = 20;
aluebs776593b2016-03-15 14:04:58 -07002040
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002041 // Skip frames with low energy.
aluebs776593b2016-03-15 14:04:58 -07002042 if (sqrt(variance) > kVarianceThreshold && snr < kSNRThreshold) {
2043 ++num_bad_chunks;
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002044 }
2045 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002046
2047 analog_level = fapm->gain_control()->stream_analog_level();
2048 EXPECT_EQ(apm_->gain_control()->stream_analog_level(),
2049 fapm->gain_control()->stream_analog_level());
2050 EXPECT_EQ(apm_->echo_cancellation()->stream_has_echo(),
2051 fapm->echo_cancellation()->stream_has_echo());
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002052 EXPECT_NEAR(apm_->noise_suppression()->speech_probability(),
2053 fapm->noise_suppression()->speech_probability(),
Alejandro Luebs47748742015-05-22 12:00:21 -07002054 0.01);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002055
2056 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002057 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002058 }
aluebs776593b2016-03-15 14:04:58 -07002059
2060#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2061 const size_t kMaxNumBadChunks = 0;
2062#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2063 // There are a few chunks in the fixed-point profile that give low SNR.
2064 // Listening confirmed the difference is acceptable.
2065 const size_t kMaxNumBadChunks = 60;
2066#endif
2067 EXPECT_LE(num_bad_chunks, kMaxNumBadChunks);
2068
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002069 rewind(far_file_);
2070 rewind(near_file_);
2071 }
2072}
2073
andrew@webrtc.org75f19482012-02-09 17:16:18 +00002074// TODO(andrew): Add a test to process a few frames with different combinations
2075// of enabled components.
2076
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002077TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002078 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002079 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002080
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002081 if (!write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002082 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002083 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002084 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08002085 for (size_t i = 0; i < arraysize(kChannels); i++) {
2086 for (size_t j = 0; j < arraysize(kChannels); j++) {
2087 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002088 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002089 test->set_num_reverse_channels(kChannels[i]);
2090 test->set_num_input_channels(kChannels[j]);
2091 test->set_num_output_channels(kChannels[j]);
2092 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002093 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002094 }
2095 }
2096 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002097#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2098 // To test the extended filter mode.
2099 audioproc::Test* test = ref_data.add_test();
2100 test->set_num_reverse_channels(2);
2101 test->set_num_input_channels(2);
2102 test->set_num_output_channels(2);
2103 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
2104 test->set_use_aec_extended_filter(true);
2105#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002106 }
2107
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002108 for (int i = 0; i < ref_data.test_size(); i++) {
2109 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002110
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002111 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002112 // TODO(ajm): We no longer allow different input and output channels. Skip
2113 // these tests for now, but they should be removed from the set.
2114 if (test->num_input_channels() != test->num_output_channels())
2115 continue;
2116
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002117 Config config;
2118 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02002119 config.Set<ExtendedFilter>(
2120 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01002121 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002122
2123 EnableAllComponents();
2124
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002125 Init(test->sample_rate(),
2126 test->sample_rate(),
2127 test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08002128 static_cast<size_t>(test->num_input_channels()),
2129 static_cast<size_t>(test->num_output_channels()),
2130 static_cast<size_t>(test->num_reverse_channels()),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002131 true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002132
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002133 int frame_count = 0;
2134 int has_echo_count = 0;
2135 int has_voice_count = 0;
2136 int is_saturated_count = 0;
2137 int analog_level = 127;
2138 int analog_level_average = 0;
2139 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002140 float ns_speech_prob_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07002141#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2142 int stats_index = 0;
2143#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002144
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002145 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07002146 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002147
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002148 frame_->vad_activity_ = AudioFrame::kVadUnknown;
2149
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002150 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00002151 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002152 EXPECT_EQ(apm_->kNoError,
2153 apm_->gain_control()->set_stream_analog_level(analog_level));
2154
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002155 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002156
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002157 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08002158 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
2159 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002160
2161 max_output_average += MaxAudioFrame(*frame_);
2162
2163 if (apm_->echo_cancellation()->stream_has_echo()) {
2164 has_echo_count++;
2165 }
2166
2167 analog_level = apm_->gain_control()->stream_analog_level();
2168 analog_level_average += analog_level;
2169 if (apm_->gain_control()->stream_is_saturated()) {
2170 is_saturated_count++;
2171 }
2172 if (apm_->voice_detection()->stream_has_voice()) {
2173 has_voice_count++;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002174 EXPECT_EQ(AudioFrame::kVadActive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002175 } else {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002176 EXPECT_EQ(AudioFrame::kVadPassive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002177 }
2178
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002179 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
2180
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002181 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07002182 size_t write_count = fwrite(frame_->data(),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002183 sizeof(int16_t),
2184 frame_size,
2185 out_file_);
2186 ASSERT_EQ(frame_size, write_count);
2187
2188 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002189 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002190 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07002191
2192#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2193 const int kStatsAggregationFrameNum = 100; // 1 second.
2194 if (frame_count % kStatsAggregationFrameNum == 0) {
2195 // Get echo metrics.
2196 EchoCancellation::Metrics echo_metrics;
2197 EXPECT_EQ(apm_->kNoError,
2198 apm_->echo_cancellation()->GetMetrics(&echo_metrics));
2199
2200 // Get delay metrics.
2201 int median = 0;
2202 int std = 0;
2203 float fraction_poor_delays = 0;
2204 EXPECT_EQ(apm_->kNoError,
2205 apm_->echo_cancellation()->GetDelayMetrics(
2206 &median, &std, &fraction_poor_delays));
2207
2208 // Get RMS.
2209 int rms_level = apm_->level_estimator()->RMS();
2210 EXPECT_LE(0, rms_level);
2211 EXPECT_GE(127, rms_level);
2212
2213 if (!write_ref_data) {
2214 const audioproc::Test::EchoMetrics& reference =
2215 test->echo_metrics(stats_index);
2216 TestStats(echo_metrics.residual_echo_return_loss,
2217 reference.residual_echo_return_loss());
2218 TestStats(echo_metrics.echo_return_loss,
2219 reference.echo_return_loss());
2220 TestStats(echo_metrics.echo_return_loss_enhancement,
2221 reference.echo_return_loss_enhancement());
2222 TestStats(echo_metrics.a_nlp,
2223 reference.a_nlp());
2224 EXPECT_EQ(echo_metrics.divergent_filter_fraction,
2225 reference.divergent_filter_fraction());
2226
2227 const audioproc::Test::DelayMetrics& reference_delay =
2228 test->delay_metrics(stats_index);
2229 EXPECT_EQ(reference_delay.median(), median);
2230 EXPECT_EQ(reference_delay.std(), std);
2231 EXPECT_EQ(reference_delay.fraction_poor_delays(),
2232 fraction_poor_delays);
2233
2234 EXPECT_EQ(test->rms_level(stats_index), rms_level);
2235
2236 ++stats_index;
2237 } else {
2238 audioproc::Test::EchoMetrics* message =
2239 test->add_echo_metrics();
2240 WriteStatsMessage(echo_metrics.residual_echo_return_loss,
2241 message->mutable_residual_echo_return_loss());
2242 WriteStatsMessage(echo_metrics.echo_return_loss,
2243 message->mutable_echo_return_loss());
2244 WriteStatsMessage(echo_metrics.echo_return_loss_enhancement,
2245 message->mutable_echo_return_loss_enhancement());
2246 WriteStatsMessage(echo_metrics.a_nlp,
2247 message->mutable_a_nlp());
2248 message->set_divergent_filter_fraction(
2249 echo_metrics.divergent_filter_fraction);
2250
2251 audioproc::Test::DelayMetrics* message_delay =
2252 test->add_delay_metrics();
2253 message_delay->set_median(median);
2254 message_delay->set_std(std);
2255 message_delay->set_fraction_poor_delays(fraction_poor_delays);
2256
2257 test->add_rms_level(rms_level);
2258 }
2259 }
2260#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002261 }
2262 max_output_average /= frame_count;
2263 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002264 ns_speech_prob_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002265
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002266 if (!write_ref_data) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002267 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002268 // When running the test on a N7 we get a {2, 6} difference of
2269 // |has_voice_count| and |max_output_average| is up to 18 higher.
2270 // All numbers being consistently higher on N7 compare to ref_data.
2271 // TODO(bjornv): If we start getting more of these offsets on Android we
2272 // should consider a different approach. Either using one slack for all,
2273 // or generate a separate android reference.
2274#if defined(WEBRTC_ANDROID)
2275 const int kHasVoiceCountOffset = 3;
Alejandro Luebs2a5609d2016-04-05 18:16:54 -07002276 const int kHasVoiceCountNear = 4;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002277 const int kMaxOutputAverageOffset = 9;
2278 const int kMaxOutputAverageNear = 9;
2279#else
2280 const int kHasVoiceCountOffset = 0;
2281 const int kHasVoiceCountNear = kIntNear;
2282 const int kMaxOutputAverageOffset = 0;
2283 const int kMaxOutputAverageNear = kIntNear;
2284#endif
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002285 EXPECT_NEAR(test->has_echo_count(), has_echo_count, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002286 EXPECT_NEAR(test->has_voice_count(),
2287 has_voice_count - kHasVoiceCountOffset,
2288 kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002289 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002290
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002291 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002292 EXPECT_NEAR(test->max_output_average(),
2293 max_output_average - kMaxOutputAverageOffset,
2294 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002295#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002296 const double kFloatNear = 0.0005;
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002297 EXPECT_NEAR(test->ns_speech_probability_average(),
2298 ns_speech_prob_average,
2299 kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002300#endif
2301 } else {
2302 test->set_has_echo_count(has_echo_count);
2303 test->set_has_voice_count(has_voice_count);
2304 test->set_is_saturated_count(is_saturated_count);
2305
2306 test->set_analog_level_average(analog_level_average);
2307 test->set_max_output_average(max_output_average);
2308
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002309#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002310 EXPECT_LE(0.0f, ns_speech_prob_average);
2311 EXPECT_GE(1.0f, ns_speech_prob_average);
2312 test->set_ns_speech_probability_average(ns_speech_prob_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002313#endif
2314 }
2315
2316 rewind(far_file_);
2317 rewind(near_file_);
2318 }
2319
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002320 if (write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002321 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002322 }
2323}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002324
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002325TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
2326 struct ChannelFormat {
2327 AudioProcessing::ChannelLayout in_layout;
2328 AudioProcessing::ChannelLayout out_layout;
2329 };
2330 ChannelFormat cf[] = {
2331 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
2332 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
2333 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
2334 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002335
Ivo Creusen62337e52018-01-09 14:17:33 +01002336 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002337 // Enable one component just to ensure some processing takes place.
2338 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08002339 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002340 const int in_rate = 44100;
2341 const int out_rate = 48000;
2342 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
2343 TotalChannelsFromLayout(cf[i].in_layout));
2344 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
2345 ChannelsFromLayout(cf[i].out_layout));
2346
2347 // Run over a few chunks.
2348 for (int j = 0; j < 10; ++j) {
2349 EXPECT_NOERR(ap->ProcessStream(
2350 in_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002351 in_cb.num_frames(),
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002352 in_rate,
2353 cf[i].in_layout,
2354 out_rate,
2355 cf[i].out_layout,
2356 out_cb.channels()));
2357 }
2358 }
2359}
2360
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002361// Compares the reference and test arrays over a region around the expected
2362// delay. Finds the highest SNR in that region and adds the variance and squared
2363// error results to the supplied accumulators.
2364void UpdateBestSNR(const float* ref,
2365 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08002366 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002367 int expected_delay,
2368 double* variance_acc,
2369 double* sq_error_acc) {
2370 double best_snr = std::numeric_limits<double>::min();
2371 double best_variance = 0;
2372 double best_sq_error = 0;
2373 // Search over a region of eight samples around the expected delay.
2374 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
2375 ++delay) {
2376 double sq_error = 0;
2377 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08002378 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002379 double error = test[i + delay] - ref[i];
2380 sq_error += error * error;
2381 variance += ref[i] * ref[i];
2382 }
2383
2384 if (sq_error == 0) {
2385 *variance_acc += variance;
2386 return;
2387 }
2388 double snr = variance / sq_error;
2389 if (snr > best_snr) {
2390 best_snr = snr;
2391 best_variance = variance;
2392 best_sq_error = sq_error;
2393 }
2394 }
2395
2396 *variance_acc += best_variance;
2397 *sq_error_acc += best_sq_error;
2398}
2399
2400// Used to test a multitude of sample rate and channel combinations. It works
2401// by first producing a set of reference files (in SetUpTestCase) that are
2402// assumed to be correct, as the used parameters are verified by other tests
2403// in this collection. Primarily the reference files are all produced at
2404// "native" rates which do not involve any resampling.
2405
2406// Each test pass produces an output file with a particular format. The output
2407// is matched against the reference file closest to its internal processing
2408// format. If necessary the output is resampled back to its process format.
2409// Due to the resampling distortion, we don't expect identical results, but
2410// enforce SNR thresholds which vary depending on the format. 0 is a special
2411// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02002412typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002413class AudioProcessingTest
2414 : public testing::TestWithParam<AudioProcessingTestData> {
2415 public:
2416 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02002417 : input_rate_(std::get<0>(GetParam())),
2418 output_rate_(std::get<1>(GetParam())),
2419 reverse_input_rate_(std::get<2>(GetParam())),
2420 reverse_output_rate_(std::get<3>(GetParam())),
2421 expected_snr_(std::get<4>(GetParam())),
2422 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002423
2424 virtual ~AudioProcessingTest() {}
2425
2426 static void SetUpTestCase() {
2427 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07002428 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08002429 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08002430 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
2431 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
2432 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002433 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07002434 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
2435 kNativeRates[i], kNumChannels[j], kNumChannels[j],
2436 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002437 }
2438 }
2439 }
2440 }
2441
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02002442 void TearDown() {
2443 // Remove "out" files after each test.
2444 ClearTempOutFiles();
2445 }
2446
pbos@webrtc.org200ac002015-02-03 14:14:01 +00002447 static void TearDownTestCase() {
2448 ClearTempFiles();
2449 }
ekmeyerson60d9b332015-08-14 10:35:55 -07002450
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002451 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07002452 // to a file specified with |output_file_prefix|. Both forward and reverse
2453 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002454 static void ProcessFormat(int input_rate,
2455 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07002456 int reverse_input_rate,
2457 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08002458 size_t num_input_channels,
2459 size_t num_output_channels,
2460 size_t num_reverse_input_channels,
2461 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02002462 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002463 Config config;
2464 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01002465 std::unique_ptr<AudioProcessing> ap(
2466 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002467 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002468
ekmeyerson60d9b332015-08-14 10:35:55 -07002469 ProcessingConfig processing_config = {
2470 {{input_rate, num_input_channels},
2471 {output_rate, num_output_channels},
2472 {reverse_input_rate, num_reverse_input_channels},
2473 {reverse_output_rate, num_reverse_output_channels}}};
2474 ap->Initialize(processing_config);
2475
2476 FILE* far_file =
2477 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002478 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07002479 FILE* out_file =
2480 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2481 reverse_input_rate, reverse_output_rate,
2482 num_input_channels, num_output_channels,
2483 num_reverse_input_channels,
2484 num_reverse_output_channels, kForward).c_str(),
2485 "wb");
2486 FILE* rev_out_file =
2487 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2488 reverse_input_rate, reverse_output_rate,
2489 num_input_channels, num_output_channels,
2490 num_reverse_input_channels,
2491 num_reverse_output_channels, kReverse).c_str(),
2492 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002493 ASSERT_TRUE(far_file != NULL);
2494 ASSERT_TRUE(near_file != NULL);
2495 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07002496 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002497
2498 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
2499 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002500 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
2501 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002502 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
2503 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002504 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
2505 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002506
2507 // Temporary buffers.
2508 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07002509 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
2510 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08002511 std::unique_ptr<float[]> float_data(new float[max_length]);
2512 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002513
2514 int analog_level = 127;
2515 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
2516 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002517 EXPECT_NOERR(ap->ProcessReverseStream(
2518 rev_cb.channels(), processing_config.reverse_input_stream(),
2519 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002520
2521 EXPECT_NOERR(ap->set_stream_delay_ms(0));
2522 ap->echo_cancellation()->set_stream_drift_samples(0);
2523 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
2524
2525 EXPECT_NOERR(ap->ProcessStream(
2526 fwd_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002527 fwd_cb.num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002528 input_rate,
2529 LayoutFromChannels(num_input_channels),
2530 output_rate,
2531 LayoutFromChannels(num_output_channels),
2532 out_cb.channels()));
2533
ekmeyerson60d9b332015-08-14 10:35:55 -07002534 // Dump forward output to file.
2535 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002536 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002537 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002538
pkasting25702cb2016-01-08 13:50:27 -08002539 ASSERT_EQ(out_length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002540 fwrite(float_data.get(), sizeof(float_data[0]),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002541 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002542
ekmeyerson60d9b332015-08-14 10:35:55 -07002543 // Dump reverse output to file.
2544 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
2545 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002546 size_t rev_out_length =
2547 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002548
pkasting25702cb2016-01-08 13:50:27 -08002549 ASSERT_EQ(rev_out_length,
ekmeyerson60d9b332015-08-14 10:35:55 -07002550 fwrite(float_data.get(), sizeof(float_data[0]), rev_out_length,
2551 rev_out_file));
2552
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002553 analog_level = ap->gain_control()->stream_analog_level();
2554 }
2555 fclose(far_file);
2556 fclose(near_file);
2557 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07002558 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002559 }
2560
2561 protected:
2562 int input_rate_;
2563 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002564 int reverse_input_rate_;
2565 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002566 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002567 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002568};
2569
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00002570TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002571 struct ChannelFormat {
2572 int num_input;
2573 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07002574 int num_reverse_input;
2575 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002576 };
2577 ChannelFormat cf[] = {
ekmeyerson60d9b332015-08-14 10:35:55 -07002578 {1, 1, 1, 1},
2579 {1, 1, 2, 1},
2580 {2, 1, 1, 1},
2581 {2, 1, 2, 1},
2582 {2, 2, 1, 1},
2583 {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002584 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002585
pkasting25702cb2016-01-08 13:50:27 -08002586 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002587 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
2588 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
2589 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07002590
ekmeyerson60d9b332015-08-14 10:35:55 -07002591 // Verify output for both directions.
2592 std::vector<StreamDirection> stream_directions;
2593 stream_directions.push_back(kForward);
2594 stream_directions.push_back(kReverse);
2595 for (StreamDirection file_direction : stream_directions) {
2596 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
2597 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
2598 const int out_num =
2599 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
2600 const double expected_snr =
2601 file_direction ? expected_reverse_snr_ : expected_snr_;
2602
2603 const int min_ref_rate = std::min(in_rate, out_rate);
2604 int ref_rate;
2605
2606 if (min_ref_rate > 32000) {
2607 ref_rate = 48000;
2608 } else if (min_ref_rate > 16000) {
2609 ref_rate = 32000;
2610 } else if (min_ref_rate > 8000) {
2611 ref_rate = 16000;
2612 } else {
2613 ref_rate = 8000;
2614 }
aluebs776593b2016-03-15 14:04:58 -07002615#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08002616 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07002617 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08002618 }
2619#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07002620 FILE* out_file = fopen(
2621 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
2622 reverse_output_rate_, cf[i].num_input,
2623 cf[i].num_output, cf[i].num_reverse_input,
2624 cf[i].num_reverse_output, file_direction).c_str(),
2625 "rb");
2626 // The reference files always have matching input and output channels.
2627 FILE* ref_file = fopen(
2628 OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
2629 cf[i].num_output, cf[i].num_output,
2630 cf[i].num_reverse_output, cf[i].num_reverse_output,
2631 file_direction).c_str(),
2632 "rb");
2633 ASSERT_TRUE(out_file != NULL);
2634 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002635
pkasting25702cb2016-01-08 13:50:27 -08002636 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2637 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002638 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002639 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002640 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002641 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002642 // Data from the resampled output, in case the reference and output rates
2643 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002644 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002645
ekmeyerson60d9b332015-08-14 10:35:55 -07002646 PushResampler<float> resampler;
2647 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002648
ekmeyerson60d9b332015-08-14 10:35:55 -07002649 // Compute the resampling delay of the output relative to the reference,
2650 // to find the region over which we should search for the best SNR.
2651 float expected_delay_sec = 0;
2652 if (in_rate != ref_rate) {
2653 // Input resampling delay.
2654 expected_delay_sec +=
2655 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2656 }
2657 if (out_rate != ref_rate) {
2658 // Output resampling delay.
2659 expected_delay_sec +=
2660 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2661 // Delay of converting the output back to its processing rate for
2662 // testing.
2663 expected_delay_sec +=
2664 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2665 }
2666 int expected_delay =
2667 floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002668
ekmeyerson60d9b332015-08-14 10:35:55 -07002669 double variance = 0;
2670 double sq_error = 0;
2671 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2672 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2673 float* out_ptr = out_data.get();
2674 if (out_rate != ref_rate) {
2675 // Resample the output back to its internal processing rate if
2676 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002677 ASSERT_EQ(ref_length,
2678 static_cast<size_t>(resampler.Resample(
2679 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002680 out_ptr = cmp_data.get();
2681 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002682
ekmeyerson60d9b332015-08-14 10:35:55 -07002683 // Update the |sq_error| and |variance| accumulators with the highest
2684 // SNR of reference vs output.
2685 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2686 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002687 }
2688
ekmeyerson60d9b332015-08-14 10:35:55 -07002689 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2690 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2691 << cf[i].num_input << ", " << cf[i].num_output << ", "
2692 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2693 << ", " << file_direction << "): ";
2694 if (sq_error > 0) {
2695 double snr = 10 * log10(variance / sq_error);
2696 EXPECT_GE(snr, expected_snr);
2697 EXPECT_NE(0, expected_snr);
2698 std::cout << "SNR=" << snr << " dB" << std::endl;
2699 } else {
aluebs776593b2016-03-15 14:04:58 -07002700 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002701 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002702
ekmeyerson60d9b332015-08-14 10:35:55 -07002703 fclose(out_file);
2704 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002705 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002706 }
2707}
2708
2709#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2710INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002711 CommonFormats,
2712 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002713 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2714 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2715 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2716 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2717 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2718 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2719 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2720 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2721 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2722 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2723 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2724 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002725
Edward Lemurc5ee9872017-10-23 23:33:04 +02002726 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2727 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2728 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2729 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2730 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2731 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2732 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2733 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2734 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2735 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2736 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2737 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002738
Edward Lemurc5ee9872017-10-23 23:33:04 +02002739 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2740 std::make_tuple(32000, 48000, 32000, 48000, 35, 30),
2741 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2742 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2743 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2744 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2745 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2746 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2747 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2748 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2749 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2750 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002751
Edward Lemurc5ee9872017-10-23 23:33:04 +02002752 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2753 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2754 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2755 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2756 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2757 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2758 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2759 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2760 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2761 std::make_tuple(16000, 16000, 48000, 16000, 40, 20),
2762 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2763 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002764
2765#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2766INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002767 CommonFormats,
2768 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002769 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 20, 0),
2770 std::make_tuple(48000, 48000, 32000, 48000, 20, 30),
2771 std::make_tuple(48000, 48000, 16000, 48000, 20, 20),
2772 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2773 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2774 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
2775 std::make_tuple(48000, 32000, 48000, 32000, 20, 35),
2776 std::make_tuple(48000, 32000, 32000, 32000, 20, 0),
2777 std::make_tuple(48000, 32000, 16000, 32000, 20, 20),
2778 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2779 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2780 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002781
Edward Lemurc5ee9872017-10-23 23:33:04 +02002782 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2783 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2784 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2785 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2786 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2787 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
2788 std::make_tuple(44100, 32000, 48000, 32000, 20, 35),
2789 std::make_tuple(44100, 32000, 32000, 32000, 20, 0),
2790 std::make_tuple(44100, 32000, 16000, 32000, 20, 20),
2791 std::make_tuple(44100, 16000, 48000, 16000, 20, 20),
2792 std::make_tuple(44100, 16000, 32000, 16000, 20, 20),
2793 std::make_tuple(44100, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002794
Edward Lemurc5ee9872017-10-23 23:33:04 +02002795 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2796 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2797 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2798 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2799 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2800 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2801 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2802 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2803 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2804 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2805 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2806 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002807
Edward Lemurc5ee9872017-10-23 23:33:04 +02002808 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2809 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2810 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2811 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2812 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2813 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2814 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2815 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2816 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2817 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2818 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2819 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002820#endif
2821
niklase@google.com470e71d2011-07-07 08:21:25 +00002822} // namespace
peahc19f3122016-10-07 14:54:10 -07002823
2824TEST(ApmConfiguration, DefaultBehavior) {
2825 // Verify that the level controller is default off, it can be activated using
2826 // the config, and that the default initial level is maintained after the
2827 // config has been applied.
2828 std::unique_ptr<AudioProcessingImpl> apm(
peaha9cc40b2017-06-29 08:32:09 -07002829 new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002830 AudioProcessing::Config config;
2831 EXPECT_FALSE(apm->config_.level_controller.enabled);
2832 // TODO(peah): Add test for the existence of the level controller object once
2833 // that is created only when that is specified in the config.
2834 // TODO(peah): Remove the testing for
2835 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2836 // is instead used to activate the level controller.
2837 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2838 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2839 apm->config_.level_controller.initial_peak_level_dbfs,
2840 std::numeric_limits<float>::epsilon());
2841 config.level_controller.enabled = true;
2842 apm->ApplyConfig(config);
2843 EXPECT_TRUE(apm->config_.level_controller.enabled);
2844 // TODO(peah): Add test for the existence of the level controller object once
2845 // that is created only when the that is specified in the config.
2846 // TODO(peah): Remove the testing for
2847 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2848 // is instead used to activate the level controller.
2849 EXPECT_TRUE(apm->capture_nonlocked_.level_controller_enabled);
2850 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2851 apm->config_.level_controller.initial_peak_level_dbfs,
2852 std::numeric_limits<float>::epsilon());
2853}
2854
2855TEST(ApmConfiguration, ValidConfigBehavior) {
2856 // Verify that the initial level can be specified and is retained after the
2857 // config has been applied.
2858 std::unique_ptr<AudioProcessingImpl> apm(
peaha9cc40b2017-06-29 08:32:09 -07002859 new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002860 AudioProcessing::Config config;
2861 config.level_controller.initial_peak_level_dbfs = -50.f;
2862 apm->ApplyConfig(config);
2863 EXPECT_FALSE(apm->config_.level_controller.enabled);
2864 // TODO(peah): Add test for the existence of the level controller object once
2865 // that is created only when the that is specified in the config.
2866 // TODO(peah): Remove the testing for
2867 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2868 // is instead used to activate the level controller.
2869 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2870 EXPECT_NEAR(-50.f, apm->config_.level_controller.initial_peak_level_dbfs,
2871 std::numeric_limits<float>::epsilon());
2872}
2873
2874TEST(ApmConfiguration, InValidConfigBehavior) {
2875 // Verify that the config is properly reset when nonproper values are applied
2876 // for the initial level.
2877
2878 // Verify that the config is properly reset when the specified initial peak
2879 // level is too low.
2880 std::unique_ptr<AudioProcessingImpl> apm(
peaha9cc40b2017-06-29 08:32:09 -07002881 new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002882 AudioProcessing::Config config;
2883 config.level_controller.enabled = true;
2884 config.level_controller.initial_peak_level_dbfs = -101.f;
2885 apm->ApplyConfig(config);
2886 EXPECT_FALSE(apm->config_.level_controller.enabled);
2887 // TODO(peah): Add test for the existence of the level controller object once
2888 // that is created only when the that is specified in the config.
2889 // TODO(peah): Remove the testing for
2890 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2891 // is instead used to activate the level controller.
2892 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2893 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2894 apm->config_.level_controller.initial_peak_level_dbfs,
2895 std::numeric_limits<float>::epsilon());
2896
2897 // Verify that the config is properly reset when the specified initial peak
2898 // level is too high.
peaha9cc40b2017-06-29 08:32:09 -07002899 apm.reset(new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002900 config = AudioProcessing::Config();
2901 config.level_controller.enabled = true;
2902 config.level_controller.initial_peak_level_dbfs = 1.f;
2903 apm->ApplyConfig(config);
2904 EXPECT_FALSE(apm->config_.level_controller.enabled);
2905 // TODO(peah): Add test for the existence of the level controller object once
2906 // that is created only when that is specified in the config.
2907 // TODO(peah): Remove the testing for
2908 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2909 // is instead used to activate the level controller.
2910 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2911 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2912 apm->config_.level_controller.initial_peak_level_dbfs,
2913 std::numeric_limits<float>::epsilon());
2914}
2915
Sam Zackrisson0beac582017-09-25 12:04:02 +02002916TEST(ApmConfiguration, EnablePostProcessing) {
2917 // Verify that apm uses a capture post processing module if one is provided.
2918 webrtc::Config webrtc_config;
2919 auto mock_post_processor_ptr =
Alex Loiko5825aa62017-12-18 16:02:40 +01002920 new testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002921 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002922 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002923 rtc::scoped_refptr<AudioProcessing> apm =
2924 AudioProcessingBuilder()
2925 .SetCapturePostProcessing(std::move(mock_post_processor))
2926 .Create(webrtc_config);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002927
2928 AudioFrame audio;
2929 audio.num_channels_ = 1;
2930 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2931
2932 EXPECT_CALL(*mock_post_processor_ptr, Process(testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002933 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002934}
2935
Alex Loiko5825aa62017-12-18 16:02:40 +01002936TEST(ApmConfiguration, EnablePreProcessing) {
2937 // Verify that apm uses a capture post processing module if one is provided.
2938 webrtc::Config webrtc_config;
2939 auto mock_pre_processor_ptr =
2940 new testing::NiceMock<test::MockCustomProcessing>();
2941 auto mock_pre_processor =
2942 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002943 rtc::scoped_refptr<AudioProcessing> apm =
2944 AudioProcessingBuilder()
2945 .SetRenderPreProcessing(std::move(mock_pre_processor))
2946 .Create(webrtc_config);
Alex Loiko5825aa62017-12-18 16:02:40 +01002947
2948 AudioFrame audio;
2949 audio.num_channels_ = 1;
2950 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2951
2952 EXPECT_CALL(*mock_pre_processor_ptr, Process(testing::_)).Times(1);
2953 apm->ProcessReverseStream(&audio);
2954}
2955
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002956class MyEchoControlFactory : public EchoControlFactory {
2957 public:
2958 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2959 auto ec = new test::MockEchoControl();
2960 EXPECT_CALL(*ec, AnalyzeRender(testing::_)).Times(1);
2961 EXPECT_CALL(*ec, AnalyzeCapture(testing::_)).Times(2);
2962 EXPECT_CALL(*ec, ProcessCapture(testing::_, testing::_)).Times(2);
2963 return std::unique_ptr<EchoControl>(ec);
2964 }
2965};
2966
2967TEST(ApmConfiguration, EchoControlInjection) {
2968 // Verify that apm uses an injected echo controller if one is provided.
2969 webrtc::Config webrtc_config;
2970 std::unique_ptr<EchoControlFactory> echo_control_factory(
2971 new MyEchoControlFactory());
2972
Alex Loiko5825aa62017-12-18 16:02:40 +01002973 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002974 AudioProcessingBuilder()
2975 .SetEchoControlFactory(std::move(echo_control_factory))
2976 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002977
2978 AudioFrame audio;
2979 audio.num_channels_ = 1;
2980 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2981 apm->ProcessStream(&audio);
2982 apm->ProcessReverseStream(&audio);
2983 apm->ProcessStream(&audio);
2984}
Ivo Creusenae026092017-11-20 13:07:16 +01002985
2986std::unique_ptr<AudioProcessing> CreateApm(bool use_AEC2) {
2987 Config old_config;
2988 if (use_AEC2) {
2989 old_config.Set<ExtendedFilter>(new ExtendedFilter(true));
2990 old_config.Set<DelayAgnostic>(new DelayAgnostic(true));
2991 }
Ivo Creusen62337e52018-01-09 14:17:33 +01002992 std::unique_ptr<AudioProcessing> apm(
2993 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002994 if (!apm) {
2995 return apm;
2996 }
2997
2998 ProcessingConfig processing_config = {
2999 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
3000
3001 if (apm->Initialize(processing_config) != 0) {
3002 return nullptr;
3003 }
3004
3005 // Disable all components except for an AEC and the residual echo detector.
3006 AudioProcessing::Config config;
3007 config.residual_echo_detector.enabled = true;
3008 config.echo_canceller3.enabled = false;
3009 config.high_pass_filter.enabled = false;
3010 config.gain_controller2.enabled = false;
3011 config.level_controller.enabled = false;
3012 apm->ApplyConfig(config);
3013 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
3014 EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
3015 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
3016 EXPECT_EQ(apm->voice_detection()->Enable(false), 0);
3017
3018 if (use_AEC2) {
3019 EXPECT_EQ(apm->echo_control_mobile()->Enable(false), 0);
3020 EXPECT_EQ(apm->echo_cancellation()->enable_metrics(true), 0);
3021 EXPECT_EQ(apm->echo_cancellation()->enable_delay_logging(true), 0);
3022 EXPECT_EQ(apm->echo_cancellation()->Enable(true), 0);
3023 } else {
3024 EXPECT_EQ(apm->echo_cancellation()->Enable(false), 0);
3025 EXPECT_EQ(apm->echo_control_mobile()->Enable(true), 0);
3026 }
3027 return apm;
3028}
3029
3030#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
3031#define MAYBE_ApmStatistics DISABLED_ApmStatistics
3032#else
3033#define MAYBE_ApmStatistics ApmStatistics
3034#endif
3035
3036TEST(MAYBE_ApmStatistics, AEC2EnabledTest) {
3037 // Set up APM with AEC2 and process some audio.
3038 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
3039 ASSERT_TRUE(apm);
3040
3041 // Set up an audioframe.
3042 AudioFrame frame;
3043 frame.num_channels_ = 1;
3044 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3045
3046 // Fill the audio frame with a sawtooth pattern.
3047 int16_t* ptr = frame.mutable_data();
3048 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3049 ptr[i] = 10000 * ((i % 3) - 1);
3050 }
3051
3052 // Do some processing.
3053 for (int i = 0; i < 200; i++) {
3054 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3055 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3056 EXPECT_EQ(apm->ProcessStream(&frame), 0);
3057 }
3058
3059 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01003060 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01003061 // We expect all statistics to be set and have a sensible value.
3062 ASSERT_TRUE(stats.residual_echo_likelihood);
3063 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3064 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3065 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
3066 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3067 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3068 ASSERT_TRUE(stats.echo_return_loss);
3069 EXPECT_NE(*stats.echo_return_loss, -100.0);
3070 ASSERT_TRUE(stats.echo_return_loss_enhancement);
3071 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
3072 ASSERT_TRUE(stats.divergent_filter_fraction);
3073 EXPECT_NE(*stats.divergent_filter_fraction, -1.0);
3074 ASSERT_TRUE(stats.delay_standard_deviation_ms);
3075 EXPECT_GE(*stats.delay_standard_deviation_ms, 0);
3076 // We don't check stats.delay_median_ms since it takes too long to settle to a
3077 // value. At least 20 seconds of data need to be processed before it will get
3078 // a value, which would make this test take too much time.
3079
3080 // If there are no receive streams, we expect the stats not to be set. The
3081 // 'false' argument signals to APM that no receive streams are currently
3082 // active. In that situation the statistics would get stuck at their last
3083 // calculated value (AEC and echo detection need at least one stream in each
3084 // direction), so to avoid that, they should not be set by APM.
3085 stats = apm->GetStatistics(false);
3086 EXPECT_FALSE(stats.residual_echo_likelihood);
3087 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3088 EXPECT_FALSE(stats.echo_return_loss);
3089 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3090 EXPECT_FALSE(stats.divergent_filter_fraction);
3091 EXPECT_FALSE(stats.delay_median_ms);
3092 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3093}
3094
3095TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
3096 // Set up APM with AECM and process some audio.
3097 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
3098 ASSERT_TRUE(apm);
3099
3100 // Set up an audioframe.
3101 AudioFrame frame;
3102 frame.num_channels_ = 1;
3103 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3104
3105 // Fill the audio frame with a sawtooth pattern.
3106 int16_t* ptr = frame.mutable_data();
3107 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3108 ptr[i] = 10000 * ((i % 3) - 1);
3109 }
3110
3111 // Do some processing.
3112 for (int i = 0; i < 200; i++) {
3113 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3114 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3115 EXPECT_EQ(apm->ProcessStream(&frame), 0);
3116 }
3117
3118 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01003119 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01003120 // We expect only the residual echo detector statistics to be set and have a
3121 // sensible value.
3122 EXPECT_TRUE(stats.residual_echo_likelihood);
3123 if (stats.residual_echo_likelihood) {
3124 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3125 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3126 }
3127 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
3128 if (stats.residual_echo_likelihood_recent_max) {
3129 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3130 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3131 }
3132 EXPECT_FALSE(stats.echo_return_loss);
3133 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3134 EXPECT_FALSE(stats.divergent_filter_fraction);
3135 EXPECT_FALSE(stats.delay_median_ms);
3136 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3137
3138 // If there are no receive streams, we expect the stats not to be set.
3139 stats = apm->GetStatistics(false);
3140 EXPECT_FALSE(stats.residual_echo_likelihood);
3141 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3142 EXPECT_FALSE(stats.echo_return_loss);
3143 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3144 EXPECT_FALSE(stats.divergent_filter_fraction);
3145 EXPECT_FALSE(stats.delay_median_ms);
3146 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3147}
andrew@webrtc.org27c69802014-02-18 20:24:56 +00003148} // namespace webrtc