blob: 5984ed72a5e4414c06c94ac848635eac56833b6c [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));
455 apm_.reset(AudioProcessing::Create(config));
456}
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(
1321 AudioProcessing::Create(config, nullptr, nullptr, beamformer));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001322 EXPECT_EQ(kNoErr, apm->gain_control()->Enable(true));
1323 ChannelBuffer<float> src_buf(kSamplesPerChannel, kNumInputChannels);
1324 ChannelBuffer<float> dest_buf(kSamplesPerChannel, kNumOutputChannels);
pkasting25702cb2016-01-08 13:50:27 -08001325 const size_t max_length = kSamplesPerChannel * std::max(kNumInputChannels,
1326 kNumOutputChannels);
kwiberg62eaacf2016-02-17 06:39:05 -08001327 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
1328 std::unique_ptr<float[]> float_data(new float[max_length]);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001329 std::string filename = ResourceFilePath("far", kSampleRateHz);
1330 FILE* far_file = fopen(filename.c_str(), "rb");
1331 ASSERT_TRUE(far_file != NULL) << "Could not open file " << filename << "\n";
1332 const int kDefaultVolume = apm->gain_control()->stream_analog_level();
1333 const int kDefaultCompressionGain =
1334 apm->gain_control()->compression_gain_db();
1335 bool is_target = false;
1336 EXPECT_CALL(*beamformer, is_target_present())
1337 .WillRepeatedly(testing::ReturnPointee(&is_target));
pkasting25702cb2016-01-08 13:50:27 -08001338 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001339 ASSERT_TRUE(ReadChunk(far_file,
1340 int_data.get(),
1341 float_data.get(),
1342 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001343 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001344 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001345 src_buf.channels()[j][k] *= kScaleFactor;
1346 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001347 }
1348 EXPECT_EQ(kNoErr,
1349 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001350 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001351 kSampleRateHz,
1352 LayoutFromChannels(src_buf.num_channels()),
1353 kSampleRateHz,
1354 LayoutFromChannels(dest_buf.num_channels()),
1355 dest_buf.channels()));
1356 }
1357 EXPECT_EQ(kDefaultVolume,
1358 apm->gain_control()->stream_analog_level());
1359 EXPECT_EQ(kDefaultCompressionGain,
1360 apm->gain_control()->compression_gain_db());
1361 rewind(far_file);
1362 is_target = true;
pkasting25702cb2016-01-08 13:50:27 -08001363 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001364 ASSERT_TRUE(ReadChunk(far_file,
1365 int_data.get(),
1366 float_data.get(),
1367 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001368 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001369 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001370 src_buf.channels()[j][k] *= kScaleFactor;
1371 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001372 }
1373 EXPECT_EQ(kNoErr,
1374 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001375 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001376 kSampleRateHz,
1377 LayoutFromChannels(src_buf.num_channels()),
1378 kSampleRateHz,
1379 LayoutFromChannels(dest_buf.num_channels()),
1380 dest_buf.channels()));
1381 }
1382 EXPECT_LT(kDefaultVolume,
1383 apm->gain_control()->stream_analog_level());
1384 EXPECT_LT(kDefaultCompressionGain,
1385 apm->gain_control()->compression_gain_db());
1386 ASSERT_EQ(0, fclose(far_file));
1387}
1388#endif
1389
niklase@google.com470e71d2011-07-07 08:21:25 +00001390TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001391 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001392 NoiseSuppression::Level level[] = {
1393 NoiseSuppression::kLow,
1394 NoiseSuppression::kModerate,
1395 NoiseSuppression::kHigh,
1396 NoiseSuppression::kVeryHigh
1397 };
pkasting25702cb2016-01-08 13:50:27 -08001398 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001399 EXPECT_EQ(apm_->kNoError,
1400 apm_->noise_suppression()->set_level(level[i]));
1401 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1402 }
1403
andrew@webrtc.org648af742012-02-08 01:57:29 +00001404 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001405 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1406 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1407 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1408 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1409}
1410
1411TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001412 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001413 AudioProcessing::Config apm_config;
1414 apm_config.high_pass_filter.enabled = true;
1415 apm_->ApplyConfig(apm_config);
1416 apm_config.high_pass_filter.enabled = false;
1417 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001418}
1419
1420TEST_F(ApmTest, LevelEstimator) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001421 // Turn level estimator on/off
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001422 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001423 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001424
1425 EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1426
1427 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1428 EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1429
1430 // Run this test in wideband; in super-wb, the splitting filter distorts the
1431 // audio enough to cause deviation from the expectation for small values.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001432 frame_->samples_per_channel_ = 160;
1433 frame_->num_channels_ = 2;
1434 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001435
1436 // Min value if no frames have been processed.
1437 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1438
1439 // Min value on zero frames.
1440 SetFrameTo(frame_, 0);
1441 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1442 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1443 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1444
1445 // Try a few RMS values.
1446 // (These also test that the value resets after retrieving it.)
1447 SetFrameTo(frame_, 32767);
1448 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1449 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1450 EXPECT_EQ(0, apm_->level_estimator()->RMS());
1451
1452 SetFrameTo(frame_, 30000);
1453 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1454 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1455 EXPECT_EQ(1, apm_->level_estimator()->RMS());
1456
1457 SetFrameTo(frame_, 10000);
1458 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1459 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1460 EXPECT_EQ(10, apm_->level_estimator()->RMS());
1461
1462 SetFrameTo(frame_, 10);
1463 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1464 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1465 EXPECT_EQ(70, apm_->level_estimator()->RMS());
1466
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001467 // Verify reset after enable/disable.
1468 SetFrameTo(frame_, 32767);
1469 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1470 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1471 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1472 SetFrameTo(frame_, 1);
1473 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1474 EXPECT_EQ(90, apm_->level_estimator()->RMS());
1475
1476 // Verify reset after initialize.
1477 SetFrameTo(frame_, 32767);
1478 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1479 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1480 SetFrameTo(frame_, 1);
1481 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1482 EXPECT_EQ(90, apm_->level_estimator()->RMS());
niklase@google.com470e71d2011-07-07 08:21:25 +00001483}
1484
1485TEST_F(ApmTest, VoiceDetection) {
1486 // Test external VAD
1487 EXPECT_EQ(apm_->kNoError,
1488 apm_->voice_detection()->set_stream_has_voice(true));
1489 EXPECT_TRUE(apm_->voice_detection()->stream_has_voice());
1490 EXPECT_EQ(apm_->kNoError,
1491 apm_->voice_detection()->set_stream_has_voice(false));
1492 EXPECT_FALSE(apm_->voice_detection()->stream_has_voice());
1493
andrew@webrtc.org648af742012-02-08 01:57:29 +00001494 // Test valid likelihoods
niklase@google.com470e71d2011-07-07 08:21:25 +00001495 VoiceDetection::Likelihood likelihood[] = {
1496 VoiceDetection::kVeryLowLikelihood,
1497 VoiceDetection::kLowLikelihood,
1498 VoiceDetection::kModerateLikelihood,
1499 VoiceDetection::kHighLikelihood
1500 };
pkasting25702cb2016-01-08 13:50:27 -08001501 for (size_t i = 0; i < arraysize(likelihood); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001502 EXPECT_EQ(apm_->kNoError,
1503 apm_->voice_detection()->set_likelihood(likelihood[i]));
1504 EXPECT_EQ(likelihood[i], apm_->voice_detection()->likelihood());
1505 }
1506
1507 /* TODO(bjornv): Enable once VAD supports other frame lengths than 10 ms
andrew@webrtc.org648af742012-02-08 01:57:29 +00001508 // Test invalid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001509 EXPECT_EQ(apm_->kBadParameterError,
1510 apm_->voice_detection()->set_frame_size_ms(12));
1511
andrew@webrtc.org648af742012-02-08 01:57:29 +00001512 // Test valid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001513 for (int i = 10; i <= 30; i += 10) {
1514 EXPECT_EQ(apm_->kNoError,
1515 apm_->voice_detection()->set_frame_size_ms(i));
1516 EXPECT_EQ(i, apm_->voice_detection()->frame_size_ms());
1517 }
1518 */
1519
andrew@webrtc.org648af742012-02-08 01:57:29 +00001520 // Turn VAD on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001521 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1522 EXPECT_TRUE(apm_->voice_detection()->is_enabled());
1523 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1524 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1525
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001526 // Test that AudioFrame activity is maintained when VAD is disabled.
1527 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1528 AudioFrame::VADActivity activity[] = {
1529 AudioFrame::kVadActive,
1530 AudioFrame::kVadPassive,
1531 AudioFrame::kVadUnknown
1532 };
pkasting25702cb2016-01-08 13:50:27 -08001533 for (size_t i = 0; i < arraysize(activity); i++) {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001534 frame_->vad_activity_ = activity[i];
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001535 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001536 EXPECT_EQ(activity[i], frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001537 }
1538
1539 // Test that AudioFrame activity is set when VAD is enabled.
1540 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001541 frame_->vad_activity_ = AudioFrame::kVadUnknown;
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001542 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001543 EXPECT_NE(AudioFrame::kVadUnknown, frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001544
niklase@google.com470e71d2011-07-07 08:21:25 +00001545 // TODO(bjornv): Add tests for streamed voice; stream_has_voice()
1546}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001547
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001548TEST_F(ApmTest, AllProcessingDisabledByDefault) {
1549 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
1550 EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1551 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1552 EXPECT_FALSE(apm_->high_pass_filter()->is_enabled());
1553 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1554 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1555 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1556}
1557
1558TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001559 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001560 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001561 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001562 AudioFrame frame_copy;
1563 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001564 for (int j = 0; j < 1000; j++) {
1565 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1566 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001567 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1568 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001569 }
1570 }
1571}
1572
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001573TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1574 // Test that ProcessStream copies input to output even with no processing.
1575 const size_t kSamples = 80;
1576 const int sample_rate = 8000;
1577 const float src[kSamples] = {
1578 -1.0f, 0.0f, 1.0f
1579 };
1580 float dest[kSamples] = {};
1581
1582 auto src_channels = &src[0];
1583 auto dest_channels = &dest[0];
1584
1585 apm_.reset(AudioProcessing::Create());
1586 EXPECT_NOERR(apm_->ProcessStream(
1587 &src_channels, kSamples, sample_rate, LayoutFromChannels(1),
1588 sample_rate, LayoutFromChannels(1), &dest_channels));
1589
1590 for (size_t i = 0; i < kSamples; ++i) {
1591 EXPECT_EQ(src[i], dest[i]);
1592 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001593
1594 // Same for ProcessReverseStream.
1595 float rev_dest[kSamples] = {};
1596 auto rev_dest_channels = &rev_dest[0];
1597
1598 StreamConfig input_stream = {sample_rate, 1};
1599 StreamConfig output_stream = {sample_rate, 1};
1600 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1601 output_stream, &rev_dest_channels));
1602
1603 for (size_t i = 0; i < kSamples; ++i) {
1604 EXPECT_EQ(src[i], rev_dest[i]);
1605 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001606}
1607
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001608TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1609 EnableAllComponents();
1610
pkasting25702cb2016-01-08 13:50:27 -08001611 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001612 Init(kProcessSampleRates[i],
1613 kProcessSampleRates[i],
1614 kProcessSampleRates[i],
1615 2,
1616 2,
1617 2,
1618 false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001619 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001620 ASSERT_EQ(0, feof(far_file_));
1621 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001622 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001623 CopyLeftToRightChannel(revframe_->mutable_data(),
1624 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001625
aluebsb0319552016-03-17 20:39:53 -07001626 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001627
yujo36b1a5f2017-06-12 12:45:32 -07001628 CopyLeftToRightChannel(frame_->mutable_data(),
1629 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001630 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1631
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001632 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001633 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001634 ASSERT_EQ(kNoErr,
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001635 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001636 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001637 analog_level = apm_->gain_control()->stream_analog_level();
1638
yujo36b1a5f2017-06-12 12:45:32 -07001639 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001640 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001641 rewind(far_file_);
1642 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001643 }
1644}
1645
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001646TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001647 // Verify the filter is not active through undistorted audio when:
1648 // 1. No components are enabled...
1649 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001650 AudioFrame frame_copy;
1651 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001652 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1653 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1654 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1655
1656 // 2. Only the level estimator is enabled...
1657 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001658 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001659 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1660 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1661 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1662 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1663 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1664
1665 // 3. Only VAD is enabled...
1666 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001667 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001668 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1669 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1670 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1671 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1672 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1673
1674 // 4. Both VAD and the level estimator are enabled...
1675 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001676 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001677 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1678 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1679 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1680 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1681 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1682 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1683 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1684
1685 // 5. Not using super-wb.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001686 frame_->samples_per_channel_ = 160;
1687 frame_->num_channels_ = 2;
1688 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001689 // Enable AEC, which would require the filter in super-wb. We rely on the
1690 // first few frames of data being unaffected by the AEC.
1691 // TODO(andrew): This test, and the one below, rely rather tenuously on the
1692 // behavior of the AEC. Think of something more robust.
1693 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001694 // Make sure we have extended filter enabled. This makes sure nothing is
1695 // touched until we have a farend frame.
1696 Config config;
Henrik Lundin441f6342015-06-09 16:03:13 +02001697 config.Set<ExtendedFilter>(new ExtendedFilter(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001698 apm_->SetExtraOptions(config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001699 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001700 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001701 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001702 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001703 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1704 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_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1708
1709 // Check the test is valid. We should have distortion from the filter
1710 // when AEC is enabled (which won't affect the audio).
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001711 frame_->samples_per_channel_ = 320;
1712 frame_->num_channels_ = 2;
1713 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001714 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001715 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001716 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001717 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001718 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1719 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1720}
1721
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001722#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1723void ApmTest::ProcessDebugDump(const std::string& in_filename,
1724 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001725 Format format,
1726 int max_size_bytes) {
aleloif4dd1912017-06-15 01:55:38 -07001727 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001728 FILE* in_file = fopen(in_filename.c_str(), "rb");
1729 ASSERT_TRUE(in_file != NULL);
1730 audioproc::Event event_msg;
1731 bool first_init = true;
1732
1733 while (ReadMessageFromFile(in_file, &event_msg)) {
1734 if (event_msg.type() == audioproc::Event::INIT) {
1735 const audioproc::Init msg = event_msg.init();
1736 int reverse_sample_rate = msg.sample_rate();
1737 if (msg.has_reverse_sample_rate()) {
1738 reverse_sample_rate = msg.reverse_sample_rate();
1739 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001740 int output_sample_rate = msg.sample_rate();
1741 if (msg.has_output_sample_rate()) {
1742 output_sample_rate = msg.output_sample_rate();
1743 }
1744
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001745 Init(msg.sample_rate(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001746 output_sample_rate,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001747 reverse_sample_rate,
1748 msg.num_input_channels(),
1749 msg.num_output_channels(),
1750 msg.num_reverse_channels(),
1751 false);
1752 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001753 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001754 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001755 auto aec_dump =
1756 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1757 EXPECT_TRUE(aec_dump);
1758 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001759 first_init = false;
1760 }
1761
1762 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1763 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1764
1765 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001766 ASSERT_EQ(revframe_->num_channels_,
1767 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001768 for (int i = 0; i < msg.channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001769 memcpy(revfloat_cb_->channels()[i],
1770 msg.channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001771 msg.channel(i).size());
1772 }
1773 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001774 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001775 if (format == kFloatFormat) {
1776 // We're using an int16 input file; convert to float.
1777 ConvertToFloat(*revframe_, revfloat_cb_.get());
1778 }
1779 }
1780 AnalyzeReverseStreamChooser(format);
1781
1782 } else if (event_msg.type() == audioproc::Event::STREAM) {
1783 const audioproc::Stream msg = event_msg.stream();
1784 // ProcessStream could have changed this for the output frame.
1785 frame_->num_channels_ = apm_->num_input_channels();
1786
1787 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1788 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
1789 apm_->echo_cancellation()->set_stream_drift_samples(msg.drift());
1790 if (msg.has_keypress()) {
1791 apm_->set_stream_key_pressed(msg.keypress());
1792 } else {
1793 apm_->set_stream_key_pressed(true);
1794 }
1795
1796 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001797 ASSERT_EQ(frame_->num_channels_,
1798 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001799 for (int i = 0; i < msg.input_channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001800 memcpy(float_cb_->channels()[i],
1801 msg.input_channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001802 msg.input_channel(i).size());
1803 }
1804 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001805 memcpy(frame_->mutable_data(), msg.input_data().data(),
1806 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001807 if (format == kFloatFormat) {
1808 // We're using an int16 input file; convert to float.
1809 ConvertToFloat(*frame_, float_cb_.get());
1810 }
1811 }
1812 ProcessStreamChooser(format);
1813 }
1814 }
aleloif4dd1912017-06-15 01:55:38 -07001815 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001816 fclose(in_file);
1817}
1818
1819void ApmTest::VerifyDebugDumpTest(Format format) {
1820 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001821 std::string format_string;
1822 switch (format) {
1823 case kIntFormat:
1824 format_string = "_int";
1825 break;
1826 case kFloatFormat:
1827 format_string = "_float";
1828 break;
1829 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001830 const std::string ref_filename = test::TempFilename(
1831 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1832 const std::string out_filename = test::TempFilename(
1833 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001834 const std::string limited_filename = test::TempFilename(
1835 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1836 const size_t logging_limit_bytes = 100000;
1837 // We expect at least this many bytes in the created logfile.
1838 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001839 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001840 ProcessDebugDump(in_filename, ref_filename, format, -1);
1841 ProcessDebugDump(ref_filename, out_filename, format, -1);
1842 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001843
1844 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1845 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001846 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001847 ASSERT_TRUE(ref_file != NULL);
1848 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001849 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001850 std::unique_ptr<uint8_t[]> ref_bytes;
1851 std::unique_ptr<uint8_t[]> out_bytes;
1852 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001853
1854 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1855 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001856 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001857 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001858 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001859 while (ref_size > 0 && out_size > 0) {
1860 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001861 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001862 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001863 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001864 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001865 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001866 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1867 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001868 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001869 }
1870 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001871 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1872 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001873 EXPECT_NE(0, feof(ref_file));
1874 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001875 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001876 ASSERT_EQ(0, fclose(ref_file));
1877 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001878 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001879 remove(ref_filename.c_str());
1880 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001881 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001882}
1883
pbosc7a65692016-05-06 12:50:04 -07001884TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001885 VerifyDebugDumpTest(kIntFormat);
1886}
1887
pbosc7a65692016-05-06 12:50:04 -07001888TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001889 VerifyDebugDumpTest(kFloatFormat);
1890}
1891#endif
1892
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001893// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001894TEST_F(ApmTest, DebugDump) {
aleloif4dd1912017-06-15 01:55:38 -07001895 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001896 const std::string filename =
1897 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001898 {
1899 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1900 EXPECT_FALSE(aec_dump);
1901 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001902
1903#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1904 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001905 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001906
aleloif4dd1912017-06-15 01:55:38 -07001907 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1908 EXPECT_TRUE(aec_dump);
1909 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001910 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001911 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001912 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001913
1914 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001915 FILE* fid = fopen(filename.c_str(), "r");
1916 ASSERT_TRUE(fid != NULL);
1917
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001918 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001919 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001920 ASSERT_EQ(0, remove(filename.c_str()));
1921#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001922 // Verify the file has NOT been written.
1923 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1924#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1925}
1926
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001927// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001928TEST_F(ApmTest, DebugDumpFromFileHandle) {
aleloif4dd1912017-06-15 01:55:38 -07001929 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1930
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001931 const std::string filename =
1932 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001933 FILE* fid = fopen(filename.c_str(), "w");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001934 ASSERT_TRUE(fid);
1935
1936#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1937 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001938 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001939
aleloif4dd1912017-06-15 01:55:38 -07001940 auto aec_dump = AecDumpFactory::Create(fid, -1, &worker_queue);
1941 EXPECT_TRUE(aec_dump);
1942 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001943 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001944 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001945 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001946
1947 // Verify the file has been written.
1948 fid = fopen(filename.c_str(), "r");
1949 ASSERT_TRUE(fid != NULL);
1950
1951 // Clean it up.
1952 ASSERT_EQ(0, fclose(fid));
1953 ASSERT_EQ(0, remove(filename.c_str()));
1954#else
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001955 ASSERT_EQ(0, fclose(fid));
1956#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1957}
1958
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001959TEST_F(ApmTest, FloatAndIntInterfacesGiveSimilarResults) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001960 audioproc::OutputData ref_data;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001961 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001962
1963 Config config;
1964 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
kwiberg62eaacf2016-02-17 06:39:05 -08001965 std::unique_ptr<AudioProcessing> fapm(AudioProcessing::Create(config));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001966 EnableAllComponents();
1967 EnableAllAPComponents(fapm.get());
1968 for (int i = 0; i < ref_data.test_size(); i++) {
1969 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
1970
1971 audioproc::Test* test = ref_data.mutable_test(i);
1972 // TODO(ajm): Restore downmixing test cases.
1973 if (test->num_input_channels() != test->num_output_channels())
1974 continue;
1975
Peter Kasting69558702016-01-12 16:26:35 -08001976 const size_t num_render_channels =
1977 static_cast<size_t>(test->num_reverse_channels());
1978 const size_t num_input_channels =
1979 static_cast<size_t>(test->num_input_channels());
1980 const size_t num_output_channels =
1981 static_cast<size_t>(test->num_output_channels());
pkasting25702cb2016-01-08 13:50:27 -08001982 const size_t samples_per_channel = static_cast<size_t>(
1983 test->sample_rate() * AudioProcessing::kChunkSizeMs / 1000);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001984
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001985 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
1986 num_input_channels, num_output_channels, num_render_channels, true);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001987 Init(fapm.get());
1988
1989 ChannelBuffer<int16_t> output_cb(samples_per_channel, num_input_channels);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001990 ChannelBuffer<int16_t> output_int16(samples_per_channel,
1991 num_input_channels);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001992
1993 int analog_level = 127;
aluebs776593b2016-03-15 14:04:58 -07001994 size_t num_bad_chunks = 0;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001995 while (ReadFrame(far_file_, revframe_, revfloat_cb_.get()) &&
1996 ReadFrame(near_file_, frame_, float_cb_.get())) {
1997 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1998
aluebsb0319552016-03-17 20:39:53 -07001999 EXPECT_NOERR(apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002000 EXPECT_NOERR(fapm->AnalyzeReverseStream(
2001 revfloat_cb_->channels(),
2002 samples_per_channel,
2003 test->sample_rate(),
2004 LayoutFromChannels(num_render_channels)));
2005
2006 EXPECT_NOERR(apm_->set_stream_delay_ms(0));
2007 EXPECT_NOERR(fapm->set_stream_delay_ms(0));
2008 apm_->echo_cancellation()->set_stream_drift_samples(0);
2009 fapm->echo_cancellation()->set_stream_drift_samples(0);
2010 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(analog_level));
2011 EXPECT_NOERR(fapm->gain_control()->set_stream_analog_level(analog_level));
2012
2013 EXPECT_NOERR(apm_->ProcessStream(frame_));
yujo36b1a5f2017-06-12 12:45:32 -07002014 Deinterleave(frame_->data(), samples_per_channel, num_output_channels,
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002015 output_int16.channels());
2016
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002017 EXPECT_NOERR(fapm->ProcessStream(
2018 float_cb_->channels(),
2019 samples_per_channel,
2020 test->sample_rate(),
2021 LayoutFromChannels(num_input_channels),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002022 test->sample_rate(),
2023 LayoutFromChannels(num_output_channels),
2024 float_cb_->channels()));
Peter Kasting69558702016-01-12 16:26:35 -08002025 for (size_t j = 0; j < num_output_channels; ++j) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002026 FloatToS16(float_cb_->channels()[j],
2027 samples_per_channel,
2028 output_cb.channels()[j]);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002029 float variance = 0;
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002030 float snr = ComputeSNR(output_int16.channels()[j],
2031 output_cb.channels()[j],
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002032 samples_per_channel, &variance);
aluebs776593b2016-03-15 14:04:58 -07002033
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002034 const float kVarianceThreshold = 20;
2035 const float kSNRThreshold = 20;
aluebs776593b2016-03-15 14:04:58 -07002036
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002037 // Skip frames with low energy.
aluebs776593b2016-03-15 14:04:58 -07002038 if (sqrt(variance) > kVarianceThreshold && snr < kSNRThreshold) {
2039 ++num_bad_chunks;
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002040 }
2041 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002042
2043 analog_level = fapm->gain_control()->stream_analog_level();
2044 EXPECT_EQ(apm_->gain_control()->stream_analog_level(),
2045 fapm->gain_control()->stream_analog_level());
2046 EXPECT_EQ(apm_->echo_cancellation()->stream_has_echo(),
2047 fapm->echo_cancellation()->stream_has_echo());
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002048 EXPECT_NEAR(apm_->noise_suppression()->speech_probability(),
2049 fapm->noise_suppression()->speech_probability(),
Alejandro Luebs47748742015-05-22 12:00:21 -07002050 0.01);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002051
2052 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002053 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002054 }
aluebs776593b2016-03-15 14:04:58 -07002055
2056#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2057 const size_t kMaxNumBadChunks = 0;
2058#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2059 // There are a few chunks in the fixed-point profile that give low SNR.
2060 // Listening confirmed the difference is acceptable.
2061 const size_t kMaxNumBadChunks = 60;
2062#endif
2063 EXPECT_LE(num_bad_chunks, kMaxNumBadChunks);
2064
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002065 rewind(far_file_);
2066 rewind(near_file_);
2067 }
2068}
2069
andrew@webrtc.org75f19482012-02-09 17:16:18 +00002070// TODO(andrew): Add a test to process a few frames with different combinations
2071// of enabled components.
2072
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002073TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002074 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002075 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002076
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002077 if (!write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002078 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002079 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002080 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08002081 for (size_t i = 0; i < arraysize(kChannels); i++) {
2082 for (size_t j = 0; j < arraysize(kChannels); j++) {
2083 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002084 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002085 test->set_num_reverse_channels(kChannels[i]);
2086 test->set_num_input_channels(kChannels[j]);
2087 test->set_num_output_channels(kChannels[j]);
2088 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002089 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002090 }
2091 }
2092 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002093#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2094 // To test the extended filter mode.
2095 audioproc::Test* test = ref_data.add_test();
2096 test->set_num_reverse_channels(2);
2097 test->set_num_input_channels(2);
2098 test->set_num_output_channels(2);
2099 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
2100 test->set_use_aec_extended_filter(true);
2101#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002102 }
2103
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002104 for (int i = 0; i < ref_data.test_size(); i++) {
2105 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002106
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002107 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002108 // TODO(ajm): We no longer allow different input and output channels. Skip
2109 // these tests for now, but they should be removed from the set.
2110 if (test->num_input_channels() != test->num_output_channels())
2111 continue;
2112
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002113 Config config;
2114 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02002115 config.Set<ExtendedFilter>(
2116 new ExtendedFilter(test->use_aec_extended_filter()));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002117 apm_.reset(AudioProcessing::Create(config));
2118
2119 EnableAllComponents();
2120
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002121 Init(test->sample_rate(),
2122 test->sample_rate(),
2123 test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08002124 static_cast<size_t>(test->num_input_channels()),
2125 static_cast<size_t>(test->num_output_channels()),
2126 static_cast<size_t>(test->num_reverse_channels()),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002127 true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002128
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002129 int frame_count = 0;
2130 int has_echo_count = 0;
2131 int has_voice_count = 0;
2132 int is_saturated_count = 0;
2133 int analog_level = 127;
2134 int analog_level_average = 0;
2135 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002136 float ns_speech_prob_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07002137#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2138 int stats_index = 0;
2139#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002140
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002141 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07002142 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002143
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002144 frame_->vad_activity_ = AudioFrame::kVadUnknown;
2145
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002146 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00002147 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002148 EXPECT_EQ(apm_->kNoError,
2149 apm_->gain_control()->set_stream_analog_level(analog_level));
2150
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002151 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002152
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002153 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08002154 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
2155 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002156
2157 max_output_average += MaxAudioFrame(*frame_);
2158
2159 if (apm_->echo_cancellation()->stream_has_echo()) {
2160 has_echo_count++;
2161 }
2162
2163 analog_level = apm_->gain_control()->stream_analog_level();
2164 analog_level_average += analog_level;
2165 if (apm_->gain_control()->stream_is_saturated()) {
2166 is_saturated_count++;
2167 }
2168 if (apm_->voice_detection()->stream_has_voice()) {
2169 has_voice_count++;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002170 EXPECT_EQ(AudioFrame::kVadActive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002171 } else {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002172 EXPECT_EQ(AudioFrame::kVadPassive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002173 }
2174
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002175 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
2176
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002177 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07002178 size_t write_count = fwrite(frame_->data(),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002179 sizeof(int16_t),
2180 frame_size,
2181 out_file_);
2182 ASSERT_EQ(frame_size, write_count);
2183
2184 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002185 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002186 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07002187
2188#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2189 const int kStatsAggregationFrameNum = 100; // 1 second.
2190 if (frame_count % kStatsAggregationFrameNum == 0) {
2191 // Get echo metrics.
2192 EchoCancellation::Metrics echo_metrics;
2193 EXPECT_EQ(apm_->kNoError,
2194 apm_->echo_cancellation()->GetMetrics(&echo_metrics));
2195
2196 // Get delay metrics.
2197 int median = 0;
2198 int std = 0;
2199 float fraction_poor_delays = 0;
2200 EXPECT_EQ(apm_->kNoError,
2201 apm_->echo_cancellation()->GetDelayMetrics(
2202 &median, &std, &fraction_poor_delays));
2203
2204 // Get RMS.
2205 int rms_level = apm_->level_estimator()->RMS();
2206 EXPECT_LE(0, rms_level);
2207 EXPECT_GE(127, rms_level);
2208
2209 if (!write_ref_data) {
2210 const audioproc::Test::EchoMetrics& reference =
2211 test->echo_metrics(stats_index);
2212 TestStats(echo_metrics.residual_echo_return_loss,
2213 reference.residual_echo_return_loss());
2214 TestStats(echo_metrics.echo_return_loss,
2215 reference.echo_return_loss());
2216 TestStats(echo_metrics.echo_return_loss_enhancement,
2217 reference.echo_return_loss_enhancement());
2218 TestStats(echo_metrics.a_nlp,
2219 reference.a_nlp());
2220 EXPECT_EQ(echo_metrics.divergent_filter_fraction,
2221 reference.divergent_filter_fraction());
2222
2223 const audioproc::Test::DelayMetrics& reference_delay =
2224 test->delay_metrics(stats_index);
2225 EXPECT_EQ(reference_delay.median(), median);
2226 EXPECT_EQ(reference_delay.std(), std);
2227 EXPECT_EQ(reference_delay.fraction_poor_delays(),
2228 fraction_poor_delays);
2229
2230 EXPECT_EQ(test->rms_level(stats_index), rms_level);
2231
2232 ++stats_index;
2233 } else {
2234 audioproc::Test::EchoMetrics* message =
2235 test->add_echo_metrics();
2236 WriteStatsMessage(echo_metrics.residual_echo_return_loss,
2237 message->mutable_residual_echo_return_loss());
2238 WriteStatsMessage(echo_metrics.echo_return_loss,
2239 message->mutable_echo_return_loss());
2240 WriteStatsMessage(echo_metrics.echo_return_loss_enhancement,
2241 message->mutable_echo_return_loss_enhancement());
2242 WriteStatsMessage(echo_metrics.a_nlp,
2243 message->mutable_a_nlp());
2244 message->set_divergent_filter_fraction(
2245 echo_metrics.divergent_filter_fraction);
2246
2247 audioproc::Test::DelayMetrics* message_delay =
2248 test->add_delay_metrics();
2249 message_delay->set_median(median);
2250 message_delay->set_std(std);
2251 message_delay->set_fraction_poor_delays(fraction_poor_delays);
2252
2253 test->add_rms_level(rms_level);
2254 }
2255 }
2256#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002257 }
2258 max_output_average /= frame_count;
2259 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002260 ns_speech_prob_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002261
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002262 if (!write_ref_data) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002263 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002264 // When running the test on a N7 we get a {2, 6} difference of
2265 // |has_voice_count| and |max_output_average| is up to 18 higher.
2266 // All numbers being consistently higher on N7 compare to ref_data.
2267 // TODO(bjornv): If we start getting more of these offsets on Android we
2268 // should consider a different approach. Either using one slack for all,
2269 // or generate a separate android reference.
2270#if defined(WEBRTC_ANDROID)
2271 const int kHasVoiceCountOffset = 3;
Alejandro Luebs2a5609d2016-04-05 18:16:54 -07002272 const int kHasVoiceCountNear = 4;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002273 const int kMaxOutputAverageOffset = 9;
2274 const int kMaxOutputAverageNear = 9;
2275#else
2276 const int kHasVoiceCountOffset = 0;
2277 const int kHasVoiceCountNear = kIntNear;
2278 const int kMaxOutputAverageOffset = 0;
2279 const int kMaxOutputAverageNear = kIntNear;
2280#endif
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002281 EXPECT_NEAR(test->has_echo_count(), has_echo_count, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002282 EXPECT_NEAR(test->has_voice_count(),
2283 has_voice_count - kHasVoiceCountOffset,
2284 kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002285 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002286
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002287 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002288 EXPECT_NEAR(test->max_output_average(),
2289 max_output_average - kMaxOutputAverageOffset,
2290 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002291#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002292 const double kFloatNear = 0.0005;
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002293 EXPECT_NEAR(test->ns_speech_probability_average(),
2294 ns_speech_prob_average,
2295 kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002296#endif
2297 } else {
2298 test->set_has_echo_count(has_echo_count);
2299 test->set_has_voice_count(has_voice_count);
2300 test->set_is_saturated_count(is_saturated_count);
2301
2302 test->set_analog_level_average(analog_level_average);
2303 test->set_max_output_average(max_output_average);
2304
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002305#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002306 EXPECT_LE(0.0f, ns_speech_prob_average);
2307 EXPECT_GE(1.0f, ns_speech_prob_average);
2308 test->set_ns_speech_probability_average(ns_speech_prob_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002309#endif
2310 }
2311
2312 rewind(far_file_);
2313 rewind(near_file_);
2314 }
2315
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002316 if (write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002317 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002318 }
2319}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002320
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002321TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
2322 struct ChannelFormat {
2323 AudioProcessing::ChannelLayout in_layout;
2324 AudioProcessing::ChannelLayout out_layout;
2325 };
2326 ChannelFormat cf[] = {
2327 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
2328 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
2329 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
2330 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002331
kwiberg62eaacf2016-02-17 06:39:05 -08002332 std::unique_ptr<AudioProcessing> ap(AudioProcessing::Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002333 // Enable one component just to ensure some processing takes place.
2334 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08002335 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002336 const int in_rate = 44100;
2337 const int out_rate = 48000;
2338 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
2339 TotalChannelsFromLayout(cf[i].in_layout));
2340 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
2341 ChannelsFromLayout(cf[i].out_layout));
2342
2343 // Run over a few chunks.
2344 for (int j = 0; j < 10; ++j) {
2345 EXPECT_NOERR(ap->ProcessStream(
2346 in_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002347 in_cb.num_frames(),
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002348 in_rate,
2349 cf[i].in_layout,
2350 out_rate,
2351 cf[i].out_layout,
2352 out_cb.channels()));
2353 }
2354 }
2355}
2356
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002357// Compares the reference and test arrays over a region around the expected
2358// delay. Finds the highest SNR in that region and adds the variance and squared
2359// error results to the supplied accumulators.
2360void UpdateBestSNR(const float* ref,
2361 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08002362 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002363 int expected_delay,
2364 double* variance_acc,
2365 double* sq_error_acc) {
2366 double best_snr = std::numeric_limits<double>::min();
2367 double best_variance = 0;
2368 double best_sq_error = 0;
2369 // Search over a region of eight samples around the expected delay.
2370 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
2371 ++delay) {
2372 double sq_error = 0;
2373 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08002374 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002375 double error = test[i + delay] - ref[i];
2376 sq_error += error * error;
2377 variance += ref[i] * ref[i];
2378 }
2379
2380 if (sq_error == 0) {
2381 *variance_acc += variance;
2382 return;
2383 }
2384 double snr = variance / sq_error;
2385 if (snr > best_snr) {
2386 best_snr = snr;
2387 best_variance = variance;
2388 best_sq_error = sq_error;
2389 }
2390 }
2391
2392 *variance_acc += best_variance;
2393 *sq_error_acc += best_sq_error;
2394}
2395
2396// Used to test a multitude of sample rate and channel combinations. It works
2397// by first producing a set of reference files (in SetUpTestCase) that are
2398// assumed to be correct, as the used parameters are verified by other tests
2399// in this collection. Primarily the reference files are all produced at
2400// "native" rates which do not involve any resampling.
2401
2402// Each test pass produces an output file with a particular format. The output
2403// is matched against the reference file closest to its internal processing
2404// format. If necessary the output is resampled back to its process format.
2405// Due to the resampling distortion, we don't expect identical results, but
2406// enforce SNR thresholds which vary depending on the format. 0 is a special
2407// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02002408typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002409class AudioProcessingTest
2410 : public testing::TestWithParam<AudioProcessingTestData> {
2411 public:
2412 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02002413 : input_rate_(std::get<0>(GetParam())),
2414 output_rate_(std::get<1>(GetParam())),
2415 reverse_input_rate_(std::get<2>(GetParam())),
2416 reverse_output_rate_(std::get<3>(GetParam())),
2417 expected_snr_(std::get<4>(GetParam())),
2418 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002419
2420 virtual ~AudioProcessingTest() {}
2421
2422 static void SetUpTestCase() {
2423 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07002424 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08002425 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08002426 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
2427 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
2428 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002429 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07002430 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
2431 kNativeRates[i], kNumChannels[j], kNumChannels[j],
2432 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002433 }
2434 }
2435 }
2436 }
2437
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02002438 void TearDown() {
2439 // Remove "out" files after each test.
2440 ClearTempOutFiles();
2441 }
2442
pbos@webrtc.org200ac002015-02-03 14:14:01 +00002443 static void TearDownTestCase() {
2444 ClearTempFiles();
2445 }
ekmeyerson60d9b332015-08-14 10:35:55 -07002446
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002447 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07002448 // to a file specified with |output_file_prefix|. Both forward and reverse
2449 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002450 static void ProcessFormat(int input_rate,
2451 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07002452 int reverse_input_rate,
2453 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08002454 size_t num_input_channels,
2455 size_t num_output_channels,
2456 size_t num_reverse_input_channels,
2457 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02002458 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002459 Config config;
2460 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
kwiberg62eaacf2016-02-17 06:39:05 -08002461 std::unique_ptr<AudioProcessing> ap(AudioProcessing::Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002462 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002463
ekmeyerson60d9b332015-08-14 10:35:55 -07002464 ProcessingConfig processing_config = {
2465 {{input_rate, num_input_channels},
2466 {output_rate, num_output_channels},
2467 {reverse_input_rate, num_reverse_input_channels},
2468 {reverse_output_rate, num_reverse_output_channels}}};
2469 ap->Initialize(processing_config);
2470
2471 FILE* far_file =
2472 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002473 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07002474 FILE* out_file =
2475 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2476 reverse_input_rate, reverse_output_rate,
2477 num_input_channels, num_output_channels,
2478 num_reverse_input_channels,
2479 num_reverse_output_channels, kForward).c_str(),
2480 "wb");
2481 FILE* rev_out_file =
2482 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2483 reverse_input_rate, reverse_output_rate,
2484 num_input_channels, num_output_channels,
2485 num_reverse_input_channels,
2486 num_reverse_output_channels, kReverse).c_str(),
2487 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002488 ASSERT_TRUE(far_file != NULL);
2489 ASSERT_TRUE(near_file != NULL);
2490 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07002491 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002492
2493 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
2494 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002495 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
2496 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002497 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
2498 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002499 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
2500 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002501
2502 // Temporary buffers.
2503 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07002504 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
2505 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08002506 std::unique_ptr<float[]> float_data(new float[max_length]);
2507 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002508
2509 int analog_level = 127;
2510 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
2511 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002512 EXPECT_NOERR(ap->ProcessReverseStream(
2513 rev_cb.channels(), processing_config.reverse_input_stream(),
2514 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002515
2516 EXPECT_NOERR(ap->set_stream_delay_ms(0));
2517 ap->echo_cancellation()->set_stream_drift_samples(0);
2518 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
2519
2520 EXPECT_NOERR(ap->ProcessStream(
2521 fwd_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002522 fwd_cb.num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002523 input_rate,
2524 LayoutFromChannels(num_input_channels),
2525 output_rate,
2526 LayoutFromChannels(num_output_channels),
2527 out_cb.channels()));
2528
ekmeyerson60d9b332015-08-14 10:35:55 -07002529 // Dump forward output to file.
2530 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002531 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002532 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002533
pkasting25702cb2016-01-08 13:50:27 -08002534 ASSERT_EQ(out_length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002535 fwrite(float_data.get(), sizeof(float_data[0]),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002536 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002537
ekmeyerson60d9b332015-08-14 10:35:55 -07002538 // Dump reverse output to file.
2539 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
2540 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002541 size_t rev_out_length =
2542 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002543
pkasting25702cb2016-01-08 13:50:27 -08002544 ASSERT_EQ(rev_out_length,
ekmeyerson60d9b332015-08-14 10:35:55 -07002545 fwrite(float_data.get(), sizeof(float_data[0]), rev_out_length,
2546 rev_out_file));
2547
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002548 analog_level = ap->gain_control()->stream_analog_level();
2549 }
2550 fclose(far_file);
2551 fclose(near_file);
2552 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07002553 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002554 }
2555
2556 protected:
2557 int input_rate_;
2558 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002559 int reverse_input_rate_;
2560 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002561 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002562 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002563};
2564
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00002565TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002566 struct ChannelFormat {
2567 int num_input;
2568 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07002569 int num_reverse_input;
2570 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002571 };
2572 ChannelFormat cf[] = {
ekmeyerson60d9b332015-08-14 10:35:55 -07002573 {1, 1, 1, 1},
2574 {1, 1, 2, 1},
2575 {2, 1, 1, 1},
2576 {2, 1, 2, 1},
2577 {2, 2, 1, 1},
2578 {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002579 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002580
pkasting25702cb2016-01-08 13:50:27 -08002581 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002582 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
2583 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
2584 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07002585
ekmeyerson60d9b332015-08-14 10:35:55 -07002586 // Verify output for both directions.
2587 std::vector<StreamDirection> stream_directions;
2588 stream_directions.push_back(kForward);
2589 stream_directions.push_back(kReverse);
2590 for (StreamDirection file_direction : stream_directions) {
2591 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
2592 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
2593 const int out_num =
2594 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
2595 const double expected_snr =
2596 file_direction ? expected_reverse_snr_ : expected_snr_;
2597
2598 const int min_ref_rate = std::min(in_rate, out_rate);
2599 int ref_rate;
2600
2601 if (min_ref_rate > 32000) {
2602 ref_rate = 48000;
2603 } else if (min_ref_rate > 16000) {
2604 ref_rate = 32000;
2605 } else if (min_ref_rate > 8000) {
2606 ref_rate = 16000;
2607 } else {
2608 ref_rate = 8000;
2609 }
aluebs776593b2016-03-15 14:04:58 -07002610#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08002611 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07002612 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08002613 }
2614#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07002615 FILE* out_file = fopen(
2616 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
2617 reverse_output_rate_, cf[i].num_input,
2618 cf[i].num_output, cf[i].num_reverse_input,
2619 cf[i].num_reverse_output, file_direction).c_str(),
2620 "rb");
2621 // The reference files always have matching input and output channels.
2622 FILE* ref_file = fopen(
2623 OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
2624 cf[i].num_output, cf[i].num_output,
2625 cf[i].num_reverse_output, cf[i].num_reverse_output,
2626 file_direction).c_str(),
2627 "rb");
2628 ASSERT_TRUE(out_file != NULL);
2629 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002630
pkasting25702cb2016-01-08 13:50:27 -08002631 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2632 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002633 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002634 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002635 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002636 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002637 // Data from the resampled output, in case the reference and output rates
2638 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002639 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002640
ekmeyerson60d9b332015-08-14 10:35:55 -07002641 PushResampler<float> resampler;
2642 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002643
ekmeyerson60d9b332015-08-14 10:35:55 -07002644 // Compute the resampling delay of the output relative to the reference,
2645 // to find the region over which we should search for the best SNR.
2646 float expected_delay_sec = 0;
2647 if (in_rate != ref_rate) {
2648 // Input resampling delay.
2649 expected_delay_sec +=
2650 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2651 }
2652 if (out_rate != ref_rate) {
2653 // Output resampling delay.
2654 expected_delay_sec +=
2655 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2656 // Delay of converting the output back to its processing rate for
2657 // testing.
2658 expected_delay_sec +=
2659 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2660 }
2661 int expected_delay =
2662 floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002663
ekmeyerson60d9b332015-08-14 10:35:55 -07002664 double variance = 0;
2665 double sq_error = 0;
2666 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2667 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2668 float* out_ptr = out_data.get();
2669 if (out_rate != ref_rate) {
2670 // Resample the output back to its internal processing rate if
2671 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002672 ASSERT_EQ(ref_length,
2673 static_cast<size_t>(resampler.Resample(
2674 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002675 out_ptr = cmp_data.get();
2676 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002677
ekmeyerson60d9b332015-08-14 10:35:55 -07002678 // Update the |sq_error| and |variance| accumulators with the highest
2679 // SNR of reference vs output.
2680 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2681 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002682 }
2683
ekmeyerson60d9b332015-08-14 10:35:55 -07002684 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2685 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2686 << cf[i].num_input << ", " << cf[i].num_output << ", "
2687 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2688 << ", " << file_direction << "): ";
2689 if (sq_error > 0) {
2690 double snr = 10 * log10(variance / sq_error);
2691 EXPECT_GE(snr, expected_snr);
2692 EXPECT_NE(0, expected_snr);
2693 std::cout << "SNR=" << snr << " dB" << std::endl;
2694 } else {
aluebs776593b2016-03-15 14:04:58 -07002695 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002696 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002697
ekmeyerson60d9b332015-08-14 10:35:55 -07002698 fclose(out_file);
2699 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002700 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002701 }
2702}
2703
2704#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2705INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002706 CommonFormats,
2707 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002708 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2709 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2710 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2711 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2712 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2713 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2714 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2715 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2716 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2717 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2718 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2719 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002720
Edward Lemurc5ee9872017-10-23 23:33:04 +02002721 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2722 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2723 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2724 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2725 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2726 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2727 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2728 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2729 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2730 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2731 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2732 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002733
Edward Lemurc5ee9872017-10-23 23:33:04 +02002734 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2735 std::make_tuple(32000, 48000, 32000, 48000, 35, 30),
2736 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2737 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2738 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2739 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2740 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2741 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2742 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2743 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2744 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2745 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002746
Edward Lemurc5ee9872017-10-23 23:33:04 +02002747 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2748 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2749 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2750 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2751 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2752 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2753 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2754 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2755 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2756 std::make_tuple(16000, 16000, 48000, 16000, 40, 20),
2757 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2758 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002759
2760#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2761INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002762 CommonFormats,
2763 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002764 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 20, 0),
2765 std::make_tuple(48000, 48000, 32000, 48000, 20, 30),
2766 std::make_tuple(48000, 48000, 16000, 48000, 20, 20),
2767 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2768 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2769 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
2770 std::make_tuple(48000, 32000, 48000, 32000, 20, 35),
2771 std::make_tuple(48000, 32000, 32000, 32000, 20, 0),
2772 std::make_tuple(48000, 32000, 16000, 32000, 20, 20),
2773 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2774 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2775 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002776
Edward Lemurc5ee9872017-10-23 23:33:04 +02002777 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2778 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2779 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2780 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2781 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2782 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
2783 std::make_tuple(44100, 32000, 48000, 32000, 20, 35),
2784 std::make_tuple(44100, 32000, 32000, 32000, 20, 0),
2785 std::make_tuple(44100, 32000, 16000, 32000, 20, 20),
2786 std::make_tuple(44100, 16000, 48000, 16000, 20, 20),
2787 std::make_tuple(44100, 16000, 32000, 16000, 20, 20),
2788 std::make_tuple(44100, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002789
Edward Lemurc5ee9872017-10-23 23:33:04 +02002790 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2791 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2792 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2793 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2794 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2795 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2796 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2797 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2798 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2799 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2800 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2801 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002802
Edward Lemurc5ee9872017-10-23 23:33:04 +02002803 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2804 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2805 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2806 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2807 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2808 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2809 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2810 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2811 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2812 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2813 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2814 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002815#endif
2816
niklase@google.com470e71d2011-07-07 08:21:25 +00002817} // namespace
peahc19f3122016-10-07 14:54:10 -07002818
2819TEST(ApmConfiguration, DefaultBehavior) {
2820 // Verify that the level controller is default off, it can be activated using
2821 // the config, and that the default initial level is maintained after the
2822 // config has been applied.
2823 std::unique_ptr<AudioProcessingImpl> apm(
peaha9cc40b2017-06-29 08:32:09 -07002824 new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002825 AudioProcessing::Config config;
2826 EXPECT_FALSE(apm->config_.level_controller.enabled);
2827 // TODO(peah): Add test for the existence of the level controller object once
2828 // that is created only when that is specified in the config.
2829 // TODO(peah): Remove the testing for
2830 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2831 // is instead used to activate the level controller.
2832 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2833 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2834 apm->config_.level_controller.initial_peak_level_dbfs,
2835 std::numeric_limits<float>::epsilon());
2836 config.level_controller.enabled = true;
2837 apm->ApplyConfig(config);
2838 EXPECT_TRUE(apm->config_.level_controller.enabled);
2839 // TODO(peah): Add test for the existence of the level controller object once
2840 // that is created only when the that is specified in the config.
2841 // TODO(peah): Remove the testing for
2842 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2843 // is instead used to activate the level controller.
2844 EXPECT_TRUE(apm->capture_nonlocked_.level_controller_enabled);
2845 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2846 apm->config_.level_controller.initial_peak_level_dbfs,
2847 std::numeric_limits<float>::epsilon());
2848}
2849
2850TEST(ApmConfiguration, ValidConfigBehavior) {
2851 // Verify that the initial level can be specified and is retained after the
2852 // config has been applied.
2853 std::unique_ptr<AudioProcessingImpl> apm(
peaha9cc40b2017-06-29 08:32:09 -07002854 new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002855 AudioProcessing::Config config;
2856 config.level_controller.initial_peak_level_dbfs = -50.f;
2857 apm->ApplyConfig(config);
2858 EXPECT_FALSE(apm->config_.level_controller.enabled);
2859 // TODO(peah): Add test for the existence of the level controller object once
2860 // that is created only when the that is specified in the config.
2861 // TODO(peah): Remove the testing for
2862 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2863 // is instead used to activate the level controller.
2864 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2865 EXPECT_NEAR(-50.f, apm->config_.level_controller.initial_peak_level_dbfs,
2866 std::numeric_limits<float>::epsilon());
2867}
2868
2869TEST(ApmConfiguration, InValidConfigBehavior) {
2870 // Verify that the config is properly reset when nonproper values are applied
2871 // for the initial level.
2872
2873 // Verify that the config is properly reset when the specified initial peak
2874 // level is too low.
2875 std::unique_ptr<AudioProcessingImpl> apm(
peaha9cc40b2017-06-29 08:32:09 -07002876 new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002877 AudioProcessing::Config config;
2878 config.level_controller.enabled = true;
2879 config.level_controller.initial_peak_level_dbfs = -101.f;
2880 apm->ApplyConfig(config);
2881 EXPECT_FALSE(apm->config_.level_controller.enabled);
2882 // TODO(peah): Add test for the existence of the level controller object once
2883 // that is created only when the that is specified in the config.
2884 // TODO(peah): Remove the testing for
2885 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2886 // is instead used to activate the level controller.
2887 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2888 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2889 apm->config_.level_controller.initial_peak_level_dbfs,
2890 std::numeric_limits<float>::epsilon());
2891
2892 // Verify that the config is properly reset when the specified initial peak
2893 // level is too high.
peaha9cc40b2017-06-29 08:32:09 -07002894 apm.reset(new rtc::RefCountedObject<AudioProcessingImpl>(webrtc::Config()));
peahc19f3122016-10-07 14:54:10 -07002895 config = AudioProcessing::Config();
2896 config.level_controller.enabled = true;
2897 config.level_controller.initial_peak_level_dbfs = 1.f;
2898 apm->ApplyConfig(config);
2899 EXPECT_FALSE(apm->config_.level_controller.enabled);
2900 // TODO(peah): Add test for the existence of the level controller object once
2901 // that is created only when that is specified in the config.
2902 // TODO(peah): Remove the testing for
2903 // apm->capture_nonlocked_.level_controller_enabled once the value in config_
2904 // is instead used to activate the level controller.
2905 EXPECT_FALSE(apm->capture_nonlocked_.level_controller_enabled);
2906 EXPECT_NEAR(kTargetLcPeakLeveldBFS,
2907 apm->config_.level_controller.initial_peak_level_dbfs,
2908 std::numeric_limits<float>::epsilon());
2909}
2910
Sam Zackrisson0beac582017-09-25 12:04:02 +02002911TEST(ApmConfiguration, EnablePostProcessing) {
2912 // Verify that apm uses a capture post processing module if one is provided.
2913 webrtc::Config webrtc_config;
2914 auto mock_post_processor_ptr =
2915 new testing::NiceMock<test::MockPostProcessing>();
2916 auto mock_post_processor =
2917 std::unique_ptr<PostProcessing>(mock_post_processor_ptr);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002918 rtc::scoped_refptr<AudioProcessing> apm = AudioProcessing::Create(
2919 webrtc_config, std::move(mock_post_processor), nullptr, nullptr);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002920
2921 AudioFrame audio;
2922 audio.num_channels_ = 1;
2923 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2924
2925 EXPECT_CALL(*mock_post_processor_ptr, Process(testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002926 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002927}
2928
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002929class MyEchoControlFactory : public EchoControlFactory {
2930 public:
2931 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2932 auto ec = new test::MockEchoControl();
2933 EXPECT_CALL(*ec, AnalyzeRender(testing::_)).Times(1);
2934 EXPECT_CALL(*ec, AnalyzeCapture(testing::_)).Times(2);
2935 EXPECT_CALL(*ec, ProcessCapture(testing::_, testing::_)).Times(2);
2936 return std::unique_ptr<EchoControl>(ec);
2937 }
2938};
2939
2940TEST(ApmConfiguration, EchoControlInjection) {
2941 // Verify that apm uses an injected echo controller if one is provided.
2942 webrtc::Config webrtc_config;
2943 std::unique_ptr<EchoControlFactory> echo_control_factory(
2944 new MyEchoControlFactory());
2945
2946 rtc::scoped_refptr<AudioProcessing> apm = AudioProcessing::Create(
2947 webrtc_config, nullptr, std::move(echo_control_factory), nullptr);
2948
2949 AudioFrame audio;
2950 audio.num_channels_ = 1;
2951 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2952 apm->ProcessStream(&audio);
2953 apm->ProcessReverseStream(&audio);
2954 apm->ProcessStream(&audio);
2955}
Ivo Creusenae026092017-11-20 13:07:16 +01002956
2957std::unique_ptr<AudioProcessing> CreateApm(bool use_AEC2) {
2958 Config old_config;
2959 if (use_AEC2) {
2960 old_config.Set<ExtendedFilter>(new ExtendedFilter(true));
2961 old_config.Set<DelayAgnostic>(new DelayAgnostic(true));
2962 }
2963 std::unique_ptr<AudioProcessing> apm(AudioProcessing::Create(old_config));
2964 if (!apm) {
2965 return apm;
2966 }
2967
2968 ProcessingConfig processing_config = {
2969 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2970
2971 if (apm->Initialize(processing_config) != 0) {
2972 return nullptr;
2973 }
2974
2975 // Disable all components except for an AEC and the residual echo detector.
2976 AudioProcessing::Config config;
2977 config.residual_echo_detector.enabled = true;
2978 config.echo_canceller3.enabled = false;
2979 config.high_pass_filter.enabled = false;
2980 config.gain_controller2.enabled = false;
2981 config.level_controller.enabled = false;
2982 apm->ApplyConfig(config);
2983 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
2984 EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
2985 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
2986 EXPECT_EQ(apm->voice_detection()->Enable(false), 0);
2987
2988 if (use_AEC2) {
2989 EXPECT_EQ(apm->echo_control_mobile()->Enable(false), 0);
2990 EXPECT_EQ(apm->echo_cancellation()->enable_metrics(true), 0);
2991 EXPECT_EQ(apm->echo_cancellation()->enable_delay_logging(true), 0);
2992 EXPECT_EQ(apm->echo_cancellation()->Enable(true), 0);
2993 } else {
2994 EXPECT_EQ(apm->echo_cancellation()->Enable(false), 0);
2995 EXPECT_EQ(apm->echo_control_mobile()->Enable(true), 0);
2996 }
2997 return apm;
2998}
2999
3000#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
3001#define MAYBE_ApmStatistics DISABLED_ApmStatistics
3002#else
3003#define MAYBE_ApmStatistics ApmStatistics
3004#endif
3005
3006TEST(MAYBE_ApmStatistics, AEC2EnabledTest) {
3007 // Set up APM with AEC2 and process some audio.
3008 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
3009 ASSERT_TRUE(apm);
3010
3011 // Set up an audioframe.
3012 AudioFrame frame;
3013 frame.num_channels_ = 1;
3014 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3015
3016 // Fill the audio frame with a sawtooth pattern.
3017 int16_t* ptr = frame.mutable_data();
3018 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3019 ptr[i] = 10000 * ((i % 3) - 1);
3020 }
3021
3022 // Do some processing.
3023 for (int i = 0; i < 200; i++) {
3024 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3025 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3026 EXPECT_EQ(apm->ProcessStream(&frame), 0);
3027 }
3028
3029 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01003030 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01003031 // We expect all statistics to be set and have a sensible value.
3032 ASSERT_TRUE(stats.residual_echo_likelihood);
3033 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3034 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3035 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
3036 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3037 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3038 ASSERT_TRUE(stats.echo_return_loss);
3039 EXPECT_NE(*stats.echo_return_loss, -100.0);
3040 ASSERT_TRUE(stats.echo_return_loss_enhancement);
3041 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
3042 ASSERT_TRUE(stats.divergent_filter_fraction);
3043 EXPECT_NE(*stats.divergent_filter_fraction, -1.0);
3044 ASSERT_TRUE(stats.delay_standard_deviation_ms);
3045 EXPECT_GE(*stats.delay_standard_deviation_ms, 0);
3046 // We don't check stats.delay_median_ms since it takes too long to settle to a
3047 // value. At least 20 seconds of data need to be processed before it will get
3048 // a value, which would make this test take too much time.
3049
3050 // If there are no receive streams, we expect the stats not to be set. The
3051 // 'false' argument signals to APM that no receive streams are currently
3052 // active. In that situation the statistics would get stuck at their last
3053 // calculated value (AEC and echo detection need at least one stream in each
3054 // direction), so to avoid that, they should not be set by APM.
3055 stats = apm->GetStatistics(false);
3056 EXPECT_FALSE(stats.residual_echo_likelihood);
3057 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3058 EXPECT_FALSE(stats.echo_return_loss);
3059 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3060 EXPECT_FALSE(stats.divergent_filter_fraction);
3061 EXPECT_FALSE(stats.delay_median_ms);
3062 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3063}
3064
3065TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
3066 // Set up APM with AECM and process some audio.
3067 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
3068 ASSERT_TRUE(apm);
3069
3070 // Set up an audioframe.
3071 AudioFrame frame;
3072 frame.num_channels_ = 1;
3073 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3074
3075 // Fill the audio frame with a sawtooth pattern.
3076 int16_t* ptr = frame.mutable_data();
3077 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3078 ptr[i] = 10000 * ((i % 3) - 1);
3079 }
3080
3081 // Do some processing.
3082 for (int i = 0; i < 200; i++) {
3083 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3084 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3085 EXPECT_EQ(apm->ProcessStream(&frame), 0);
3086 }
3087
3088 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01003089 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01003090 // We expect only the residual echo detector statistics to be set and have a
3091 // sensible value.
3092 EXPECT_TRUE(stats.residual_echo_likelihood);
3093 if (stats.residual_echo_likelihood) {
3094 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3095 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3096 }
3097 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
3098 if (stats.residual_echo_likelihood_recent_max) {
3099 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3100 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3101 }
3102 EXPECT_FALSE(stats.echo_return_loss);
3103 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3104 EXPECT_FALSE(stats.divergent_filter_fraction);
3105 EXPECT_FALSE(stats.delay_median_ms);
3106 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3107
3108 // If there are no receive streams, we expect the stats not to be set.
3109 stats = apm->GetStatistics(false);
3110 EXPECT_FALSE(stats.residual_echo_likelihood);
3111 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3112 EXPECT_FALSE(stats.echo_return_loss);
3113 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3114 EXPECT_FALSE(stats.divergent_filter_fraction);
3115 EXPECT_FALSE(stats.delay_median_ms);
3116 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3117}
andrew@webrtc.org27c69802014-02-18 20:24:56 +00003118} // namespace webrtc