blob: efbe3c81cea21976f043520df2d6ea9414d6d9d2 [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/test/protobuf_utils.h"
29#include "modules/audio_processing/test/test_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/arraysize.h"
31#include "rtc_base/checks.h"
32#include "rtc_base/gtest_prod_util.h"
33#include "rtc_base/ignore_wundef.h"
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +010034#include "rtc_base/numerics/safe_conversions.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010035#include "rtc_base/numerics/safe_minmax.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/protobuf_utils.h"
Niels Möller84255bb2017-10-06 13:43:23 +020037#include "rtc_base/refcountedobject.h"
Alessio Bazzicac054e782018-04-16 12:10:09 +020038#include "rtc_base/swap_queue.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/task_queue.h"
40#include "rtc_base/thread.h"
41#include "system_wrappers/include/event_wrapper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "test/gtest.h"
43#include "test/testsupport/fileutils.h"
kwiberg77eab702016-09-28 17:42:01 -070044
45RTC_PUSH_IGNORING_WUNDEF()
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000046#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000047#include "external/webrtc/webrtc/modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000048#else
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000050#endif
kwiberg77eab702016-09-28 17:42:01 -070051RTC_POP_IGNORING_WUNDEF()
niklase@google.com470e71d2011-07-07 08:21:25 +000052
andrew@webrtc.org27c69802014-02-18 20:24:56 +000053namespace webrtc {
niklase@google.com470e71d2011-07-07 08:21:25 +000054namespace {
andrew@webrtc.org17e40642014-03-04 20:58:13 +000055
ekmeyerson60d9b332015-08-14 10:35:55 -070056// TODO(ekmeyerson): Switch to using StreamConfig and ProcessingConfig where
57// applicable.
58
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +000059// TODO(bjornv): This is not feasible until the functionality has been
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +000060// re-implemented; see comment at the bottom of this file. For now, the user has
61// to hard code the |write_ref_data| value.
ajm@google.com59e41402011-07-28 17:34:04 +000062// When false, this will compare the output data with the results stored to
niklase@google.com470e71d2011-07-07 08:21:25 +000063// file. This is the typical case. When the file should be updated, it can
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +000064// be set to true with the command-line switch --write_ref_data.
65bool write_ref_data = false;
mbonadei7c2c8432017-04-07 00:59:12 -070066const int32_t kChannels[] = {1, 2};
Alejandro Luebs47748742015-05-22 12:00:21 -070067const int kSampleRates[] = {8000, 16000, 32000, 48000};
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +000068
aluebseb3603b2016-04-20 15:27:58 -070069#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
70// Android doesn't support 48kHz.
71const int kProcessSampleRates[] = {8000, 16000, 32000};
72#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Alejandro Luebs47748742015-05-22 12:00:21 -070073const int kProcessSampleRates[] = {8000, 16000, 32000, 48000};
aluebseb3603b2016-04-20 15:27:58 -070074#endif
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000075
ekmeyerson60d9b332015-08-14 10:35:55 -070076enum StreamDirection { kForward = 0, kReverse };
77
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000078void ConvertToFloat(const int16_t* int_data, ChannelBuffer<float>* cb) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000079 ChannelBuffer<int16_t> cb_int(cb->num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000080 cb->num_channels());
81 Deinterleave(int_data,
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000082 cb->num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000083 cb->num_channels(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000084 cb_int.channels());
Peter Kasting69558702016-01-12 16:26:35 -080085 for (size_t i = 0; i < cb->num_channels(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000086 S16ToFloat(cb_int.channels()[i],
87 cb->num_frames(),
88 cb->channels()[i]);
89 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000090}
andrew@webrtc.org17e40642014-03-04 20:58:13 +000091
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000092void ConvertToFloat(const AudioFrame& frame, ChannelBuffer<float>* cb) {
yujo36b1a5f2017-06-12 12:45:32 -070093 ConvertToFloat(frame.data(), cb);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000094}
95
andrew@webrtc.org103657b2014-04-24 18:28:56 +000096// Number of channels including the keyboard channel.
Peter Kasting69558702016-01-12 16:26:35 -080097size_t TotalChannelsFromLayout(AudioProcessing::ChannelLayout layout) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +000098 switch (layout) {
99 case AudioProcessing::kMono:
100 return 1;
101 case AudioProcessing::kMonoAndKeyboard:
102 case AudioProcessing::kStereo:
103 return 2;
104 case AudioProcessing::kStereoAndKeyboard:
105 return 3;
106 }
kwiberg9e2be5f2016-09-14 05:23:22 -0700107 RTC_NOTREACHED();
pkasting25702cb2016-01-08 13:50:27 -0800108 return 0;
andrew@webrtc.org103657b2014-04-24 18:28:56 +0000109}
110
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000111int TruncateToMultipleOf10(int value) {
112 return (value / 10) * 10;
113}
114
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000115void MixStereoToMono(const float* stereo, float* mono,
pkasting25702cb2016-01-08 13:50:27 -0800116 size_t samples_per_channel) {
117 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000118 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) / 2;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000119}
120
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000121void MixStereoToMono(const int16_t* stereo, int16_t* mono,
pkasting25702cb2016-01-08 13:50:27 -0800122 size_t samples_per_channel) {
123 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000124 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) >> 1;
125}
126
pkasting25702cb2016-01-08 13:50:27 -0800127void CopyLeftToRightChannel(int16_t* stereo, size_t samples_per_channel) {
128 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000129 stereo[i * 2 + 1] = stereo[i * 2];
130 }
131}
132
yujo36b1a5f2017-06-12 12:45:32 -0700133void VerifyChannelsAreEqual(const int16_t* stereo, size_t samples_per_channel) {
pkasting25702cb2016-01-08 13:50:27 -0800134 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000135 EXPECT_EQ(stereo[i * 2 + 1], stereo[i * 2]);
136 }
137}
138
139void SetFrameTo(AudioFrame* frame, int16_t value) {
yujo36b1a5f2017-06-12 12:45:32 -0700140 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700141 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
142 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700143 frame_data[i] = value;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000144 }
145}
146
147void SetFrameTo(AudioFrame* frame, int16_t left, int16_t right) {
Peter Kasting69558702016-01-12 16:26:35 -0800148 ASSERT_EQ(2u, frame->num_channels_);
yujo36b1a5f2017-06-12 12:45:32 -0700149 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700150 for (size_t i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
yujo36b1a5f2017-06-12 12:45:32 -0700151 frame_data[i] = left;
152 frame_data[i + 1] = right;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000153 }
154}
155
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000156void ScaleFrame(AudioFrame* frame, float scale) {
yujo36b1a5f2017-06-12 12:45:32 -0700157 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700158 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
159 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700160 frame_data[i] = FloatS16ToS16(frame_data[i] * scale);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000161 }
162}
163
andrew@webrtc.org81865342012-10-27 00:28:27 +0000164bool FrameDataAreEqual(const AudioFrame& frame1, const AudioFrame& frame2) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000165 if (frame1.samples_per_channel_ != frame2.samples_per_channel_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000166 return false;
167 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000168 if (frame1.num_channels_ != frame2.num_channels_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000169 return false;
170 }
yujo36b1a5f2017-06-12 12:45:32 -0700171 if (memcmp(frame1.data(), frame2.data(),
andrew@webrtc.org81865342012-10-27 00:28:27 +0000172 frame1.samples_per_channel_ * frame1.num_channels_ *
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000173 sizeof(int16_t))) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000174 return false;
175 }
176 return true;
177}
178
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000179void EnableAllAPComponents(AudioProcessing* ap) {
180#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
181 EXPECT_NOERR(ap->echo_control_mobile()->Enable(true));
182
183 EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveDigital));
184 EXPECT_NOERR(ap->gain_control()->Enable(true));
185#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
186 EXPECT_NOERR(ap->echo_cancellation()->enable_drift_compensation(true));
187 EXPECT_NOERR(ap->echo_cancellation()->enable_metrics(true));
188 EXPECT_NOERR(ap->echo_cancellation()->enable_delay_logging(true));
189 EXPECT_NOERR(ap->echo_cancellation()->Enable(true));
190
191 EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
192 EXPECT_NOERR(ap->gain_control()->set_analog_level_limits(0, 255));
193 EXPECT_NOERR(ap->gain_control()->Enable(true));
194#endif
195
peah8271d042016-11-22 07:24:52 -0800196 AudioProcessing::Config apm_config;
197 apm_config.high_pass_filter.enabled = true;
198 ap->ApplyConfig(apm_config);
199
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000200 EXPECT_NOERR(ap->level_estimator()->Enable(true));
201 EXPECT_NOERR(ap->noise_suppression()->Enable(true));
202
203 EXPECT_NOERR(ap->voice_detection()->Enable(true));
204}
205
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000206// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000207template <class T>
208T AbsValue(T a) {
209 return a > 0 ? a: -a;
210}
211
212int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800213 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700214 const int16_t* frame_data = frame.data();
215 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800216 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700217 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000218 }
219
220 return max_data;
221}
222
fischman@webrtc.orgf8be8df2013-12-17 23:46:39 +0000223#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
andrew@webrtc.org81865342012-10-27 00:28:27 +0000224void TestStats(const AudioProcessing::Statistic& test,
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000225 const audioproc::Test::Statistic& reference) {
minyue58530ed2016-05-24 05:50:12 -0700226 EXPECT_EQ(reference.instant(), test.instant);
227 EXPECT_EQ(reference.average(), test.average);
228 EXPECT_EQ(reference.maximum(), test.maximum);
229 EXPECT_EQ(reference.minimum(), test.minimum);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000230}
231
232void WriteStatsMessage(const AudioProcessing::Statistic& output,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000233 audioproc::Test::Statistic* msg) {
234 msg->set_instant(output.instant);
235 msg->set_average(output.average);
236 msg->set_maximum(output.maximum);
237 msg->set_minimum(output.minimum);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000238}
fischman@webrtc.orgf8be8df2013-12-17 23:46:39 +0000239#endif
andrew@webrtc.org81865342012-10-27 00:28:27 +0000240
Alex Loiko890988c2017-08-31 10:25:48 +0200241void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700242 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000243 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000244 ASSERT_TRUE(file != NULL);
245
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100246 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000247 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800248 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000249 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000250
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000251 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000252 ASSERT_EQ(static_cast<size_t>(size),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000253 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000254 fclose(file);
255}
256
Alex Loiko890988c2017-08-31 10:25:48 +0200257std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000258 std::ostringstream ss;
259 // Resource files are all stereo.
260 ss << name << sample_rate_hz / 1000 << "_stereo";
261 return test::ResourcePath(ss.str(), "pcm");
262}
263
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000264// Temporary filenames unique to this process. Used to be able to run these
265// tests in parallel as each process needs to be running in isolation they can't
266// have competing filenames.
267std::map<std::string, std::string> temp_filenames;
268
Alex Loiko890988c2017-08-31 10:25:48 +0200269std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000270 int input_rate,
271 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700272 int reverse_input_rate,
273 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800274 size_t num_input_channels,
275 size_t num_output_channels,
276 size_t num_reverse_input_channels,
277 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700278 StreamDirection file_direction) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000279 std::ostringstream ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700280 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
281 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000282 if (num_output_channels == 1) {
283 ss << "mono";
284 } else if (num_output_channels == 2) {
285 ss << "stereo";
286 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700287 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000288 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700289 ss << output_rate / 1000;
290 if (num_reverse_output_channels == 1) {
291 ss << "_rmono";
292 } else if (num_reverse_output_channels == 2) {
293 ss << "_rstereo";
294 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700295 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700296 }
297 ss << reverse_output_rate / 1000;
298 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000299
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000300 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700301 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000302 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
303 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000304}
305
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000306void ClearTempFiles() {
307 for (auto& kv : temp_filenames)
308 remove(kv.second.c_str());
309}
310
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200311// Only remove "out" files. Keep "ref" files.
312void ClearTempOutFiles() {
313 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
314 const std::string& filename = it->first;
315 if (filename.substr(0, 3).compare("out") == 0) {
316 remove(it->second.c_str());
317 temp_filenames.erase(it++);
318 } else {
319 it++;
320 }
321 }
322}
323
Alex Loiko890988c2017-08-31 10:25:48 +0200324void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000325 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000326 ASSERT_TRUE(file != NULL);
327 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000328 fclose(file);
329}
330
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000331// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
332// stereo) file, converts to deinterleaved float (optionally downmixing) and
333// returns the result in |cb|. Returns false if the file ended (or on error) and
334// true otherwise.
335//
336// |int_data| and |float_data| are just temporary space that must be
337// sufficiently large to hold the 10 ms chunk.
338bool ReadChunk(FILE* file, int16_t* int_data, float* float_data,
339 ChannelBuffer<float>* cb) {
340 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000341 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000342 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
343 if (read_count != frame_size) {
344 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700345 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000346 return false; // This is expected.
347 }
348
349 S16ToFloat(int_data, frame_size, float_data);
350 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000351 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000352 } else {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000353 Deinterleave(float_data, cb->num_frames(), 2,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000354 cb->channels());
355 }
356
357 return true;
358}
359
niklase@google.com470e71d2011-07-07 08:21:25 +0000360class ApmTest : public ::testing::Test {
361 protected:
362 ApmTest();
363 virtual void SetUp();
364 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000365
366 static void SetUpTestCase() {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000367 }
368
369 static void TearDownTestCase() {
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000370 ClearTempFiles();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000371 }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000372
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000373 // Used to select between int and float interface tests.
374 enum Format {
375 kIntFormat,
376 kFloatFormat
377 };
378
379 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000380 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000381 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800382 size_t num_input_channels,
383 size_t num_output_channels,
384 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000385 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000386 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000387 void EnableAllComponents();
388 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000389 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000390 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000391 void ReadFrameWithRewind(FILE* file, AudioFrame* frame,
392 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000393 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000394 void ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
395 int delay_min, int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700396 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800397 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700398 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800399 void TestChangingForwardChannels(size_t num_in_channels,
400 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700401 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800402 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700403 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000404 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
405 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000406 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000407 int ProcessStreamChooser(Format format);
408 int AnalyzeReverseStreamChooser(Format format);
409 void ProcessDebugDump(const std::string& in_filename,
410 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800411 Format format,
412 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000413 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000414
415 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000416 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800417 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000418 AudioFrame* frame_;
419 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800420 std::unique_ptr<ChannelBuffer<float> > float_cb_;
421 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000422 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800423 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000424 FILE* far_file_;
425 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000426 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000427};
428
429ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000430 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000431#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800432 ref_filename_(test::ResourcePath("audio_processing/output_data_fixed",
433 "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000434#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000435#if defined(WEBRTC_MAC)
436 // A different file for Mac is needed because on this platform the AEC
437 // constant |kFixedDelayMs| value is 20 and not 50 as it is on the rest.
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800438 ref_filename_(test::ResourcePath("audio_processing/output_data_mac",
439 "pb")),
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000440#else
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800441 ref_filename_(test::ResourcePath("audio_processing/output_data_float",
442 "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000443#endif
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000444#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000445 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000446 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000447 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000448 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000449 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000450 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000451 out_file_(NULL) {
452 Config config;
453 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100454 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000455}
niklase@google.com470e71d2011-07-07 08:21:25 +0000456
457void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000458 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000459
460 frame_ = new AudioFrame();
461 revframe_ = new AudioFrame();
462
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000463 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000464}
465
466void ApmTest::TearDown() {
467 if (frame_) {
468 delete frame_;
469 }
470 frame_ = NULL;
471
472 if (revframe_) {
473 delete revframe_;
474 }
475 revframe_ = NULL;
476
477 if (far_file_) {
478 ASSERT_EQ(0, fclose(far_file_));
479 }
480 far_file_ = NULL;
481
482 if (near_file_) {
483 ASSERT_EQ(0, fclose(near_file_));
484 }
485 near_file_ = NULL;
486
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000487 if (out_file_) {
488 ASSERT_EQ(0, fclose(out_file_));
489 }
490 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000491}
492
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000493void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000494 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700495 ap->Initialize(
496 {{{frame_->sample_rate_hz_, frame_->num_channels_},
497 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700498 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700499 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000500}
501
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000502void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000503 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000504 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800505 size_t num_input_channels,
506 size_t num_output_channels,
507 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000508 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000509 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000510 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000511 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000512
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000513 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
514 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000515 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000516
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000517 if (far_file_) {
518 ASSERT_EQ(0, fclose(far_file_));
519 }
520 std::string filename = ResourceFilePath("far", sample_rate_hz);
521 far_file_ = fopen(filename.c_str(), "rb");
522 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " <<
523 filename << "\n";
524
525 if (near_file_) {
526 ASSERT_EQ(0, fclose(near_file_));
527 }
528 filename = ResourceFilePath("near", sample_rate_hz);
529 near_file_ = fopen(filename.c_str(), "rb");
530 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " <<
531 filename << "\n";
532
533 if (open_output_file) {
534 if (out_file_) {
535 ASSERT_EQ(0, fclose(out_file_));
536 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700537 filename = OutputFilePath(
538 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
539 reverse_sample_rate_hz, num_input_channels, num_output_channels,
540 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000541 out_file_ = fopen(filename.c_str(), "wb");
542 ASSERT_TRUE(out_file_ != NULL) << "Could not open file " <<
543 filename << "\n";
544 }
545}
546
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000547void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000548 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000549}
550
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000551bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame,
552 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000553 // The files always contain stereo audio.
554 size_t frame_size = frame->samples_per_channel_ * 2;
yujo36b1a5f2017-06-12 12:45:32 -0700555 size_t read_count = fread(frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000556 sizeof(int16_t),
557 frame_size,
558 file);
559 if (read_count != frame_size) {
560 // Check that the file really ended.
561 EXPECT_NE(0, feof(file));
562 return false; // This is expected.
563 }
564
565 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700566 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000567 frame->samples_per_channel_);
568 }
569
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000570 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000571 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000572 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000573 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000574}
575
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000576bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
577 return ReadFrame(file, frame, NULL);
578}
579
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000580// If the end of the file has been reached, rewind it and attempt to read the
581// frame again.
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000582void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame,
583 ChannelBuffer<float>* cb) {
584 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000585 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000586 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000587 }
588}
589
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000590void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
591 ReadFrameWithRewind(file, frame, NULL);
592}
593
andrew@webrtc.org81865342012-10-27 00:28:27 +0000594void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
595 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000596 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000597 EXPECT_EQ(apm_->kNoError,
598 apm_->gain_control()->set_stream_analog_level(127));
599 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000600}
601
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000602int ApmTest::ProcessStreamChooser(Format format) {
603 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000604 return apm_->ProcessStream(frame_);
605 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000606 return apm_->ProcessStream(float_cb_->channels(),
607 frame_->samples_per_channel_,
608 frame_->sample_rate_hz_,
609 LayoutFromChannels(frame_->num_channels_),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000610 output_sample_rate_hz_,
611 LayoutFromChannels(num_output_channels_),
612 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000613}
614
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000615int ApmTest::AnalyzeReverseStreamChooser(Format format) {
616 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700617 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000618 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000619 return apm_->AnalyzeReverseStream(
620 revfloat_cb_->channels(),
621 revframe_->samples_per_channel_,
622 revframe_->sample_rate_hz_,
623 LayoutFromChannels(revframe_->num_channels_));
624}
625
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000626void ApmTest::ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
627 int delay_min, int delay_max) {
628 // The |revframe_| and |frame_| should include the proper frame information,
629 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000630 AudioFrame tmp_frame;
631 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000632 bool causal = true;
633
634 tmp_frame.CopyFrom(*revframe_);
635 SetFrameTo(&tmp_frame, 0);
636
637 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
638 // Initialize the |frame_queue| with empty frames.
639 int frame_delay = delay_ms / 10;
640 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000641 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000642 frame->CopyFrom(tmp_frame);
643 frame_queue.push(frame);
644 frame_delay++;
645 causal = false;
646 }
647 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000648 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000649 frame->CopyFrom(tmp_frame);
650 frame_queue.push(frame);
651 frame_delay--;
652 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000653 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
654 // need enough frames with audio to have reliable estimates, but as few as
655 // possible to keep processing time down. 4.5 seconds seemed to be a good
656 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000657 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000658 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000659 frame->CopyFrom(tmp_frame);
660 // Use the near end recording, since that has more speech in it.
661 ASSERT_TRUE(ReadFrame(near_file_, frame));
662 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000663 AudioFrame* reverse_frame = frame;
664 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000665 if (!causal) {
666 reverse_frame = frame_queue.front();
667 // When we call ProcessStream() the frame is modified, so we can't use the
668 // pointer directly when things are non-causal. Use an intermediate frame
669 // and copy the data.
670 process_frame = &tmp_frame;
671 process_frame->CopyFrom(*frame);
672 }
aluebsb0319552016-03-17 20:39:53 -0700673 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000674 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
675 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
676 frame = frame_queue.front();
677 frame_queue.pop();
678 delete frame;
679
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000680 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000681 int median;
682 int std;
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000683 float poor_fraction;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000684 // Discard the first delay metrics to avoid convergence effects.
685 EXPECT_EQ(apm_->kNoError,
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000686 apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
687 &poor_fraction));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000688 }
689 }
690
691 rewind(near_file_);
692 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000693 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000694 frame_queue.pop();
695 delete frame;
696 }
697 // Calculate expected delay estimate and acceptable regions. Further,
698 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700699 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700700 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700701 const int expected_median =
702 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
703 const int expected_median_high = rtc::SafeClamp<int>(
704 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700705 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700706 const int expected_median_low = rtc::SafeClamp<int>(
707 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700708 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000709 // Verify delay metrics.
710 int median;
711 int std;
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000712 float poor_fraction;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000713 EXPECT_EQ(apm_->kNoError,
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000714 apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
715 &poor_fraction));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000716 EXPECT_GE(expected_median_high, median);
717 EXPECT_LE(expected_median_low, median);
718}
719
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000720void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000721 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000722 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000723
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000724 // -- Missing AGC level --
niklase@google.com470e71d2011-07-07 08:21:25 +0000725 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000726 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000727 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000728
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000729 // Resets after successful ProcessStream().
niklase@google.com470e71d2011-07-07 08:21:25 +0000730 EXPECT_EQ(apm_->kNoError,
731 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000732 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000733 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000734 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000735
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000736 // Other stream parameters set correctly.
737 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
niklase@google.com470e71d2011-07-07 08:21:25 +0000738 EXPECT_EQ(apm_->kNoError,
739 apm_->echo_cancellation()->enable_drift_compensation(true));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000740 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000741 apm_->echo_cancellation()->set_stream_drift_samples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +0000742 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000743 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000744 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
745 EXPECT_EQ(apm_->kNoError,
746 apm_->echo_cancellation()->enable_drift_compensation(false));
747
748 // -- Missing delay --
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000749 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000750 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000751 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000752 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000753
754 // Resets after successful ProcessStream().
755 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000756 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000757 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000758 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000759
760 // Other stream parameters set correctly.
761 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
762 EXPECT_EQ(apm_->kNoError,
763 apm_->echo_cancellation()->enable_drift_compensation(true));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000764 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000765 EXPECT_EQ(apm_->kNoError,
766 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000767 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000768 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000769 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
770
771 // -- Missing drift --
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000772 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000773 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000774
775 // Resets after successful ProcessStream().
776 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000777 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000778 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000779 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000780 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000781
782 // Other stream parameters set correctly.
niklase@google.com470e71d2011-07-07 08:21:25 +0000783 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
784 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
785 EXPECT_EQ(apm_->kNoError,
786 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000787 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000788 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000789
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000790 // -- No stream parameters --
niklase@google.com470e71d2011-07-07 08:21:25 +0000791 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000792 AnalyzeReverseStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000793 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000794 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000795
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000796 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000797 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000798 apm_->echo_cancellation()->set_stream_drift_samples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +0000799 EXPECT_EQ(apm_->kNoError,
800 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000801 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000802}
803
804TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000805 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000806}
807
808TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000809 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000810}
811
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000812TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
813 EXPECT_EQ(0, apm_->delay_offset_ms());
814 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
815 EXPECT_EQ(50, apm_->stream_delay_ms());
816}
817
818TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
819 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000820 apm_->set_delay_offset_ms(100);
821 EXPECT_EQ(100, apm_->delay_offset_ms());
822 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000823 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000824 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
825 EXPECT_EQ(200, apm_->stream_delay_ms());
826
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000827 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000828 apm_->set_delay_offset_ms(-50);
829 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000830 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
831 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000832 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
833 EXPECT_EQ(50, apm_->stream_delay_ms());
834}
835
Michael Graczyk86c6d332015-07-23 11:41:39 -0700836void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800837 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700838 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000839 frame_->num_channels_ = num_channels;
840 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700841 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000842}
843
Michael Graczyk86c6d332015-07-23 11:41:39 -0700844void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800845 size_t num_in_channels,
846 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700847 AudioProcessing::Error expected_return) {
848 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
849 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
850
851 EXPECT_EQ(expected_return,
852 apm_->ProcessStream(float_cb_->channels(), input_stream,
853 output_stream, float_cb_->channels()));
854}
855
856void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800857 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700858 AudioProcessing::Error expected_return) {
859 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700860 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
861 {output_sample_rate_hz_, apm_->num_output_channels()},
862 {frame_->sample_rate_hz_, num_rev_channels},
863 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700864
ekmeyerson60d9b332015-08-14 10:35:55 -0700865 EXPECT_EQ(
866 expected_return,
867 apm_->ProcessReverseStream(
868 float_cb_->channels(), processing_config.reverse_input_stream(),
869 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700870}
871
872TEST_F(ApmTest, ChannelsInt16Interface) {
873 // Testing number of invalid and valid channels.
874 Init(16000, 16000, 16000, 4, 4, 4, false);
875
876 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
877
Peter Kasting69558702016-01-12 16:26:35 -0800878 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700879 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000880 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000881 }
882}
883
Michael Graczyk86c6d332015-07-23 11:41:39 -0700884TEST_F(ApmTest, Channels) {
885 // Testing number of invalid and valid channels.
886 Init(16000, 16000, 16000, 4, 4, 4, false);
887
888 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
889 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
890
Peter Kasting69558702016-01-12 16:26:35 -0800891 for (size_t i = 1; i < 4; ++i) {
892 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700893 // Output channels much be one or match input channels.
894 if (j == 1 || i == j) {
895 TestChangingForwardChannels(i, j, kNoErr);
896 TestChangingReverseChannels(i, kNoErr);
897
898 EXPECT_EQ(i, apm_->num_input_channels());
899 EXPECT_EQ(j, apm_->num_output_channels());
900 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800901 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700902 } else {
903 TestChangingForwardChannels(i, j,
904 AudioProcessing::kBadNumberChannelsError);
905 }
906 }
907 }
908}
909
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000910TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000911 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000912 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000913 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000914 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700915 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800916 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000917 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000918 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000919 }
920}
921
niklase@google.com470e71d2011-07-07 08:21:25 +0000922TEST_F(ApmTest, EchoCancellation) {
923 EXPECT_EQ(apm_->kNoError,
924 apm_->echo_cancellation()->enable_drift_compensation(true));
925 EXPECT_TRUE(apm_->echo_cancellation()->is_drift_compensation_enabled());
926 EXPECT_EQ(apm_->kNoError,
927 apm_->echo_cancellation()->enable_drift_compensation(false));
928 EXPECT_FALSE(apm_->echo_cancellation()->is_drift_compensation_enabled());
929
niklase@google.com470e71d2011-07-07 08:21:25 +0000930 EchoCancellation::SuppressionLevel level[] = {
931 EchoCancellation::kLowSuppression,
932 EchoCancellation::kModerateSuppression,
933 EchoCancellation::kHighSuppression,
934 };
pkasting25702cb2016-01-08 13:50:27 -0800935 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000936 EXPECT_EQ(apm_->kNoError,
937 apm_->echo_cancellation()->set_suppression_level(level[i]));
938 EXPECT_EQ(level[i],
939 apm_->echo_cancellation()->suppression_level());
940 }
941
942 EchoCancellation::Metrics metrics;
943 EXPECT_EQ(apm_->kNotEnabledError,
944 apm_->echo_cancellation()->GetMetrics(&metrics));
945
ivoc3e9a5372016-10-28 07:55:33 -0700946 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
947 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
948
niklase@google.com470e71d2011-07-07 08:21:25 +0000949 EXPECT_EQ(apm_->kNoError,
950 apm_->echo_cancellation()->enable_metrics(true));
951 EXPECT_TRUE(apm_->echo_cancellation()->are_metrics_enabled());
952 EXPECT_EQ(apm_->kNoError,
953 apm_->echo_cancellation()->enable_metrics(false));
954 EXPECT_FALSE(apm_->echo_cancellation()->are_metrics_enabled());
955
ivoc48dfab52016-10-28 03:29:31 -0700956 EXPECT_EQ(apm_->kNoError,
957 apm_->echo_cancellation()->enable_delay_logging(true));
958 EXPECT_TRUE(apm_->echo_cancellation()->is_delay_logging_enabled());
959 EXPECT_EQ(apm_->kNoError,
960 apm_->echo_cancellation()->enable_delay_logging(false));
961 EXPECT_FALSE(apm_->echo_cancellation()->is_delay_logging_enabled());
962
ivoc3e9a5372016-10-28 07:55:33 -0700963 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
964 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
965
966 int median = 0;
967 int std = 0;
968 float poor_fraction = 0;
969 EXPECT_EQ(apm_->kNotEnabledError, apm_->echo_cancellation()->GetDelayMetrics(
970 &median, &std, &poor_fraction));
971
niklase@google.com470e71d2011-07-07 08:21:25 +0000972 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
973 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
974 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
975 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
bjornv@webrtc.org91d11b32013-03-05 16:53:09 +0000976
977 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
978 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
979 EXPECT_TRUE(apm_->echo_cancellation()->aec_core() != NULL);
980 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
981 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
982 EXPECT_FALSE(apm_->echo_cancellation()->aec_core() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000983}
984
bjornv@webrtc.org84f8ec12014-06-19 12:14:33 +0000985TEST_F(ApmTest, DISABLED_EchoCancellationReportsCorrectDelays) {
bjornv@webrtc.orgbac00122015-01-02 09:23:49 +0000986 // TODO(bjornv): Fix this test to work with DA-AEC.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000987 // Enable AEC only.
988 EXPECT_EQ(apm_->kNoError,
989 apm_->echo_cancellation()->enable_drift_compensation(false));
990 EXPECT_EQ(apm_->kNoError,
991 apm_->echo_cancellation()->enable_metrics(false));
992 EXPECT_EQ(apm_->kNoError,
993 apm_->echo_cancellation()->enable_delay_logging(true));
994 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000995 Config config;
henrik.lundin0f133b92015-07-02 00:17:55 -0700996 config.Set<DelayAgnostic>(new DelayAgnostic(false));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000997 apm_->SetExtraOptions(config);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000998
999 // Internally in the AEC the amount of lookahead the delay estimation can
1000 // handle is 15 blocks and the maximum delay is set to 60 blocks.
1001 const int kLookaheadBlocks = 15;
1002 const int kMaxDelayBlocks = 60;
1003 // The AEC has a startup time before it actually starts to process. This
1004 // procedure can flush the internal far-end buffer, which of course affects
1005 // the delay estimation. Therefore, we set a system_delay high enough to
1006 // avoid that. The smallest system_delay you can report without flushing the
1007 // buffer is 66 ms in 8 kHz.
1008 //
1009 // It is known that for 16 kHz (and 32 kHz) sampling frequency there is an
1010 // additional stuffing of 8 ms on the fly, but it seems to have no impact on
1011 // delay estimation. This should be noted though. In case of test failure,
1012 // this could be the cause.
1013 const int kSystemDelayMs = 66;
1014 // Test a couple of corner cases and verify that the estimated delay is
1015 // within a valid region (set to +-1.5 blocks). Note that these cases are
1016 // sampling frequency dependent.
pkasting25702cb2016-01-08 13:50:27 -08001017 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001018 Init(kProcessSampleRates[i],
1019 kProcessSampleRates[i],
1020 kProcessSampleRates[i],
1021 2,
1022 2,
1023 2,
1024 false);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001025 // Sampling frequency dependent variables.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001026 const int num_ms_per_block =
1027 std::max(4, static_cast<int>(640 / frame_->samples_per_channel_));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001028 const int delay_min_ms = -kLookaheadBlocks * num_ms_per_block;
1029 const int delay_max_ms = (kMaxDelayBlocks - 1) * num_ms_per_block;
1030
1031 // 1) Verify correct delay estimate at lookahead boundary.
1032 int delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_min_ms);
1033 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1034 delay_max_ms);
1035 // 2) A delay less than maximum lookahead should give an delay estimate at
1036 // the boundary (= -kLookaheadBlocks * num_ms_per_block).
1037 delay_ms -= 20;
1038 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1039 delay_max_ms);
1040 // 3) Three values around zero delay. Note that we need to compensate for
1041 // the fake system_delay.
1042 delay_ms = TruncateToMultipleOf10(kSystemDelayMs - 10);
1043 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1044 delay_max_ms);
1045 delay_ms = TruncateToMultipleOf10(kSystemDelayMs);
1046 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1047 delay_max_ms);
1048 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + 10);
1049 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1050 delay_max_ms);
1051 // 4) Verify correct delay estimate at maximum delay boundary.
1052 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_max_ms);
1053 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1054 delay_max_ms);
1055 // 5) A delay above the maximum delay should give an estimate at the
1056 // boundary (= (kMaxDelayBlocks - 1) * num_ms_per_block).
1057 delay_ms += 20;
1058 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1059 delay_max_ms);
1060 }
1061}
1062
niklase@google.com470e71d2011-07-07 08:21:25 +00001063TEST_F(ApmTest, EchoControlMobile) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001064 // Turn AECM on (and AEC off)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001065 Init(16000, 16000, 16000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001066 EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(true));
1067 EXPECT_TRUE(apm_->echo_control_mobile()->is_enabled());
1068
niklase@google.com470e71d2011-07-07 08:21:25 +00001069 // Toggle routing modes
1070 EchoControlMobile::RoutingMode mode[] = {
1071 EchoControlMobile::kQuietEarpieceOrHeadset,
1072 EchoControlMobile::kEarpiece,
1073 EchoControlMobile::kLoudEarpiece,
1074 EchoControlMobile::kSpeakerphone,
1075 EchoControlMobile::kLoudSpeakerphone,
1076 };
pkasting25702cb2016-01-08 13:50:27 -08001077 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001078 EXPECT_EQ(apm_->kNoError,
1079 apm_->echo_control_mobile()->set_routing_mode(mode[i]));
1080 EXPECT_EQ(mode[i],
1081 apm_->echo_control_mobile()->routing_mode());
1082 }
1083 // Turn comfort noise off/on
1084 EXPECT_EQ(apm_->kNoError,
1085 apm_->echo_control_mobile()->enable_comfort_noise(false));
1086 EXPECT_FALSE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
1087 EXPECT_EQ(apm_->kNoError,
1088 apm_->echo_control_mobile()->enable_comfort_noise(true));
1089 EXPECT_TRUE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001090 // Set and get echo path
ajm@google.com22e65152011-07-18 18:03:01 +00001091 const size_t echo_path_size =
1092 apm_->echo_control_mobile()->echo_path_size_bytes();
kwiberg62eaacf2016-02-17 06:39:05 -08001093 std::unique_ptr<char[]> echo_path_in(new char[echo_path_size]);
1094 std::unique_ptr<char[]> echo_path_out(new char[echo_path_size]);
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001095 EXPECT_EQ(apm_->kNullPointerError,
1096 apm_->echo_control_mobile()->SetEchoPath(NULL, echo_path_size));
1097 EXPECT_EQ(apm_->kNullPointerError,
1098 apm_->echo_control_mobile()->GetEchoPath(NULL, echo_path_size));
1099 EXPECT_EQ(apm_->kBadParameterError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001100 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(), 1));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001101 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001102 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001103 echo_path_size));
ajm@google.com22e65152011-07-18 18:03:01 +00001104 for (size_t i = 0; i < echo_path_size; i++) {
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001105 echo_path_in[i] = echo_path_out[i] + 1;
1106 }
1107 EXPECT_EQ(apm_->kBadParameterError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001108 apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(), 1));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001109 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001110 apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(),
1111 echo_path_size));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001112 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001113 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
1114 echo_path_size));
ajm@google.com22e65152011-07-18 18:03:01 +00001115 for (size_t i = 0; i < echo_path_size; i++) {
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001116 EXPECT_EQ(echo_path_in[i], echo_path_out[i]);
1117 }
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001118
1119 // Process a few frames with NS in the default disabled state. This exercises
1120 // a different codepath than with it enabled.
1121 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1122 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1123 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1124 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1125
niklase@google.com470e71d2011-07-07 08:21:25 +00001126 // Turn AECM off
1127 EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(false));
1128 EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1129}
1130
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +00001131TEST_F(ApmTest, GainControl) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001132 // Testing gain modes
niklase@google.com470e71d2011-07-07 08:21:25 +00001133 EXPECT_EQ(apm_->kNoError,
1134 apm_->gain_control()->set_mode(
1135 apm_->gain_control()->mode()));
1136
1137 GainControl::Mode mode[] = {
1138 GainControl::kAdaptiveAnalog,
1139 GainControl::kAdaptiveDigital,
1140 GainControl::kFixedDigital
1141 };
pkasting25702cb2016-01-08 13:50:27 -08001142 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001143 EXPECT_EQ(apm_->kNoError,
1144 apm_->gain_control()->set_mode(mode[i]));
1145 EXPECT_EQ(mode[i], apm_->gain_control()->mode());
1146 }
1147 // Testing invalid target levels
1148 EXPECT_EQ(apm_->kBadParameterError,
1149 apm_->gain_control()->set_target_level_dbfs(-3));
1150 EXPECT_EQ(apm_->kBadParameterError,
1151 apm_->gain_control()->set_target_level_dbfs(-40));
1152 // Testing valid target levels
1153 EXPECT_EQ(apm_->kNoError,
1154 apm_->gain_control()->set_target_level_dbfs(
1155 apm_->gain_control()->target_level_dbfs()));
1156
1157 int level_dbfs[] = {0, 6, 31};
pkasting25702cb2016-01-08 13:50:27 -08001158 for (size_t i = 0; i < arraysize(level_dbfs); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001159 EXPECT_EQ(apm_->kNoError,
1160 apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
1161 EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
1162 }
1163
1164 // Testing invalid compression gains
1165 EXPECT_EQ(apm_->kBadParameterError,
1166 apm_->gain_control()->set_compression_gain_db(-1));
1167 EXPECT_EQ(apm_->kBadParameterError,
1168 apm_->gain_control()->set_compression_gain_db(100));
1169
1170 // Testing valid compression gains
1171 EXPECT_EQ(apm_->kNoError,
1172 apm_->gain_control()->set_compression_gain_db(
1173 apm_->gain_control()->compression_gain_db()));
1174
1175 int gain_db[] = {0, 10, 90};
pkasting25702cb2016-01-08 13:50:27 -08001176 for (size_t i = 0; i < arraysize(gain_db); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001177 EXPECT_EQ(apm_->kNoError,
1178 apm_->gain_control()->set_compression_gain_db(gain_db[i]));
1179 EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
1180 }
1181
1182 // Testing limiter off/on
1183 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
1184 EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
1185 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
1186 EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
1187
1188 // Testing invalid level limits
1189 EXPECT_EQ(apm_->kBadParameterError,
1190 apm_->gain_control()->set_analog_level_limits(-1, 512));
1191 EXPECT_EQ(apm_->kBadParameterError,
1192 apm_->gain_control()->set_analog_level_limits(100000, 512));
1193 EXPECT_EQ(apm_->kBadParameterError,
1194 apm_->gain_control()->set_analog_level_limits(512, -1));
1195 EXPECT_EQ(apm_->kBadParameterError,
1196 apm_->gain_control()->set_analog_level_limits(512, 100000));
1197 EXPECT_EQ(apm_->kBadParameterError,
1198 apm_->gain_control()->set_analog_level_limits(512, 255));
1199
1200 // Testing valid level limits
1201 EXPECT_EQ(apm_->kNoError,
1202 apm_->gain_control()->set_analog_level_limits(
1203 apm_->gain_control()->analog_level_minimum(),
1204 apm_->gain_control()->analog_level_maximum()));
1205
1206 int min_level[] = {0, 255, 1024};
pkasting25702cb2016-01-08 13:50:27 -08001207 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001208 EXPECT_EQ(apm_->kNoError,
1209 apm_->gain_control()->set_analog_level_limits(min_level[i], 1024));
1210 EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
1211 }
1212
1213 int max_level[] = {0, 1024, 65535};
pkasting25702cb2016-01-08 13:50:27 -08001214 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001215 EXPECT_EQ(apm_->kNoError,
1216 apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
1217 EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
1218 }
1219
1220 // TODO(ajm): stream_is_saturated() and stream_analog_level()
1221
1222 // Turn AGC off
1223 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
1224 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1225}
1226
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001227void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001228 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001229 EXPECT_EQ(apm_->kNoError,
1230 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1231 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1232
1233 int out_analog_level = 0;
1234 for (int i = 0; i < 2000; ++i) {
1235 ReadFrameWithRewind(near_file_, frame_);
1236 // Ensure the audio is at a low level, so the AGC will try to increase it.
1237 ScaleFrame(frame_, 0.25);
1238
1239 // Always pass in the same volume.
1240 EXPECT_EQ(apm_->kNoError,
1241 apm_->gain_control()->set_stream_analog_level(100));
1242 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1243 out_analog_level = apm_->gain_control()->stream_analog_level();
1244 }
1245
1246 // Ensure the AGC is still able to reach the maximum.
1247 EXPECT_EQ(255, out_analog_level);
1248}
1249
1250// Verifies that despite volume slider quantization, the AGC can continue to
1251// increase its volume.
1252TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -08001253 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001254 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
1255 }
1256}
1257
1258void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001259 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001260 EXPECT_EQ(apm_->kNoError,
1261 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1262 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1263
1264 int out_analog_level = 100;
1265 for (int i = 0; i < 1000; ++i) {
1266 ReadFrameWithRewind(near_file_, frame_);
1267 // Ensure the audio is at a low level, so the AGC will try to increase it.
1268 ScaleFrame(frame_, 0.25);
1269
1270 EXPECT_EQ(apm_->kNoError,
1271 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1272 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1273 out_analog_level = apm_->gain_control()->stream_analog_level();
1274 }
1275
1276 // Ensure the volume was raised.
1277 EXPECT_GT(out_analog_level, 100);
1278 int highest_level_reached = out_analog_level;
1279 // Simulate a user manual volume change.
1280 out_analog_level = 100;
1281
1282 for (int i = 0; i < 300; ++i) {
1283 ReadFrameWithRewind(near_file_, frame_);
1284 ScaleFrame(frame_, 0.25);
1285
1286 EXPECT_EQ(apm_->kNoError,
1287 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1288 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1289 out_analog_level = apm_->gain_control()->stream_analog_level();
1290 // Check that AGC respected the manually adjusted volume.
1291 EXPECT_LT(out_analog_level, highest_level_reached);
1292 }
1293 // Check that the volume was still raised.
1294 EXPECT_GT(out_analog_level, 100);
1295}
1296
1297TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001298 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001299 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1300 }
1301}
1302
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001303#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
1304TEST_F(ApmTest, AgcOnlyAdaptsWhenTargetSignalIsPresent) {
1305 const int kSampleRateHz = 16000;
pkasting25702cb2016-01-08 13:50:27 -08001306 const size_t kSamplesPerChannel =
1307 static_cast<size_t>(AudioProcessing::kChunkSizeMs * kSampleRateHz / 1000);
Peter Kasting69558702016-01-12 16:26:35 -08001308 const size_t kNumInputChannels = 2;
1309 const size_t kNumOutputChannels = 1;
pkasting25702cb2016-01-08 13:50:27 -08001310 const size_t kNumChunks = 700;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001311 const float kScaleFactor = 0.25f;
1312 Config config;
1313 std::vector<webrtc::Point> geometry;
1314 geometry.push_back(webrtc::Point(0.f, 0.f, 0.f));
1315 geometry.push_back(webrtc::Point(0.05f, 0.f, 0.f));
1316 config.Set<Beamforming>(new Beamforming(true, geometry));
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +00001317 testing::NiceMock<MockNonlinearBeamformer>* beamformer =
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001318 new testing::NiceMock<MockNonlinearBeamformer>(geometry, 1u);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001319 std::unique_ptr<AudioProcessing> apm(
Ivo Creusen62337e52018-01-09 14:17:33 +01001320 AudioProcessingBuilder()
1321 .SetNonlinearBeamformer(
1322 std::unique_ptr<webrtc::NonlinearBeamformer>(beamformer))
1323 .Create(config));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001324 EXPECT_EQ(kNoErr, apm->gain_control()->Enable(true));
1325 ChannelBuffer<float> src_buf(kSamplesPerChannel, kNumInputChannels);
1326 ChannelBuffer<float> dest_buf(kSamplesPerChannel, kNumOutputChannels);
pkasting25702cb2016-01-08 13:50:27 -08001327 const size_t max_length = kSamplesPerChannel * std::max(kNumInputChannels,
1328 kNumOutputChannels);
kwiberg62eaacf2016-02-17 06:39:05 -08001329 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
1330 std::unique_ptr<float[]> float_data(new float[max_length]);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001331 std::string filename = ResourceFilePath("far", kSampleRateHz);
1332 FILE* far_file = fopen(filename.c_str(), "rb");
1333 ASSERT_TRUE(far_file != NULL) << "Could not open file " << filename << "\n";
1334 const int kDefaultVolume = apm->gain_control()->stream_analog_level();
1335 const int kDefaultCompressionGain =
1336 apm->gain_control()->compression_gain_db();
1337 bool is_target = false;
1338 EXPECT_CALL(*beamformer, is_target_present())
1339 .WillRepeatedly(testing::ReturnPointee(&is_target));
pkasting25702cb2016-01-08 13:50:27 -08001340 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001341 ASSERT_TRUE(ReadChunk(far_file,
1342 int_data.get(),
1343 float_data.get(),
1344 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001345 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001346 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001347 src_buf.channels()[j][k] *= kScaleFactor;
1348 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001349 }
1350 EXPECT_EQ(kNoErr,
1351 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001352 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001353 kSampleRateHz,
1354 LayoutFromChannels(src_buf.num_channels()),
1355 kSampleRateHz,
1356 LayoutFromChannels(dest_buf.num_channels()),
1357 dest_buf.channels()));
1358 }
1359 EXPECT_EQ(kDefaultVolume,
1360 apm->gain_control()->stream_analog_level());
1361 EXPECT_EQ(kDefaultCompressionGain,
1362 apm->gain_control()->compression_gain_db());
1363 rewind(far_file);
1364 is_target = true;
pkasting25702cb2016-01-08 13:50:27 -08001365 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001366 ASSERT_TRUE(ReadChunk(far_file,
1367 int_data.get(),
1368 float_data.get(),
1369 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001370 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001371 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001372 src_buf.channels()[j][k] *= kScaleFactor;
1373 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001374 }
1375 EXPECT_EQ(kNoErr,
1376 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001377 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001378 kSampleRateHz,
1379 LayoutFromChannels(src_buf.num_channels()),
1380 kSampleRateHz,
1381 LayoutFromChannels(dest_buf.num_channels()),
1382 dest_buf.channels()));
1383 }
1384 EXPECT_LT(kDefaultVolume,
1385 apm->gain_control()->stream_analog_level());
1386 EXPECT_LT(kDefaultCompressionGain,
1387 apm->gain_control()->compression_gain_db());
1388 ASSERT_EQ(0, fclose(far_file));
1389}
1390#endif
1391
niklase@google.com470e71d2011-07-07 08:21:25 +00001392TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001393 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001394 NoiseSuppression::Level level[] = {
1395 NoiseSuppression::kLow,
1396 NoiseSuppression::kModerate,
1397 NoiseSuppression::kHigh,
1398 NoiseSuppression::kVeryHigh
1399 };
pkasting25702cb2016-01-08 13:50:27 -08001400 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001401 EXPECT_EQ(apm_->kNoError,
1402 apm_->noise_suppression()->set_level(level[i]));
1403 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1404 }
1405
andrew@webrtc.org648af742012-02-08 01:57:29 +00001406 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001407 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1408 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1409 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1410 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1411}
1412
1413TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001414 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001415 AudioProcessing::Config apm_config;
1416 apm_config.high_pass_filter.enabled = true;
1417 apm_->ApplyConfig(apm_config);
1418 apm_config.high_pass_filter.enabled = false;
1419 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001420}
1421
1422TEST_F(ApmTest, LevelEstimator) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001423 // Turn level estimator on/off
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001424 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001425 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001426
1427 EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1428
1429 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1430 EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1431
1432 // Run this test in wideband; in super-wb, the splitting filter distorts the
1433 // audio enough to cause deviation from the expectation for small values.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001434 frame_->samples_per_channel_ = 160;
1435 frame_->num_channels_ = 2;
1436 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001437
1438 // Min value if no frames have been processed.
1439 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1440
1441 // Min value on zero frames.
1442 SetFrameTo(frame_, 0);
1443 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1444 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1445 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1446
1447 // Try a few RMS values.
1448 // (These also test that the value resets after retrieving it.)
1449 SetFrameTo(frame_, 32767);
1450 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1451 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1452 EXPECT_EQ(0, apm_->level_estimator()->RMS());
1453
1454 SetFrameTo(frame_, 30000);
1455 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1456 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1457 EXPECT_EQ(1, apm_->level_estimator()->RMS());
1458
1459 SetFrameTo(frame_, 10000);
1460 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1461 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1462 EXPECT_EQ(10, apm_->level_estimator()->RMS());
1463
1464 SetFrameTo(frame_, 10);
1465 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1466 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1467 EXPECT_EQ(70, apm_->level_estimator()->RMS());
1468
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001469 // Verify reset after enable/disable.
1470 SetFrameTo(frame_, 32767);
1471 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1472 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1473 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1474 SetFrameTo(frame_, 1);
1475 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1476 EXPECT_EQ(90, apm_->level_estimator()->RMS());
1477
1478 // Verify reset after initialize.
1479 SetFrameTo(frame_, 32767);
1480 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1481 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1482 SetFrameTo(frame_, 1);
1483 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1484 EXPECT_EQ(90, apm_->level_estimator()->RMS());
niklase@google.com470e71d2011-07-07 08:21:25 +00001485}
1486
1487TEST_F(ApmTest, VoiceDetection) {
1488 // Test external VAD
1489 EXPECT_EQ(apm_->kNoError,
1490 apm_->voice_detection()->set_stream_has_voice(true));
1491 EXPECT_TRUE(apm_->voice_detection()->stream_has_voice());
1492 EXPECT_EQ(apm_->kNoError,
1493 apm_->voice_detection()->set_stream_has_voice(false));
1494 EXPECT_FALSE(apm_->voice_detection()->stream_has_voice());
1495
andrew@webrtc.org648af742012-02-08 01:57:29 +00001496 // Test valid likelihoods
niklase@google.com470e71d2011-07-07 08:21:25 +00001497 VoiceDetection::Likelihood likelihood[] = {
1498 VoiceDetection::kVeryLowLikelihood,
1499 VoiceDetection::kLowLikelihood,
1500 VoiceDetection::kModerateLikelihood,
1501 VoiceDetection::kHighLikelihood
1502 };
pkasting25702cb2016-01-08 13:50:27 -08001503 for (size_t i = 0; i < arraysize(likelihood); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001504 EXPECT_EQ(apm_->kNoError,
1505 apm_->voice_detection()->set_likelihood(likelihood[i]));
1506 EXPECT_EQ(likelihood[i], apm_->voice_detection()->likelihood());
1507 }
1508
1509 /* TODO(bjornv): Enable once VAD supports other frame lengths than 10 ms
andrew@webrtc.org648af742012-02-08 01:57:29 +00001510 // Test invalid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001511 EXPECT_EQ(apm_->kBadParameterError,
1512 apm_->voice_detection()->set_frame_size_ms(12));
1513
andrew@webrtc.org648af742012-02-08 01:57:29 +00001514 // Test valid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001515 for (int i = 10; i <= 30; i += 10) {
1516 EXPECT_EQ(apm_->kNoError,
1517 apm_->voice_detection()->set_frame_size_ms(i));
1518 EXPECT_EQ(i, apm_->voice_detection()->frame_size_ms());
1519 }
1520 */
1521
andrew@webrtc.org648af742012-02-08 01:57:29 +00001522 // Turn VAD on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001523 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1524 EXPECT_TRUE(apm_->voice_detection()->is_enabled());
1525 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1526 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1527
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001528 // Test that AudioFrame activity is maintained when VAD is disabled.
1529 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1530 AudioFrame::VADActivity activity[] = {
1531 AudioFrame::kVadActive,
1532 AudioFrame::kVadPassive,
1533 AudioFrame::kVadUnknown
1534 };
pkasting25702cb2016-01-08 13:50:27 -08001535 for (size_t i = 0; i < arraysize(activity); i++) {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001536 frame_->vad_activity_ = activity[i];
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001537 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001538 EXPECT_EQ(activity[i], frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001539 }
1540
1541 // Test that AudioFrame activity is set when VAD is enabled.
1542 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001543 frame_->vad_activity_ = AudioFrame::kVadUnknown;
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001544 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001545 EXPECT_NE(AudioFrame::kVadUnknown, frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001546
niklase@google.com470e71d2011-07-07 08:21:25 +00001547 // TODO(bjornv): Add tests for streamed voice; stream_has_voice()
1548}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001549
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001550TEST_F(ApmTest, AllProcessingDisabledByDefault) {
1551 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
1552 EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1553 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1554 EXPECT_FALSE(apm_->high_pass_filter()->is_enabled());
1555 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1556 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1557 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1558}
1559
1560TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001561 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001562 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001563 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001564 AudioFrame frame_copy;
1565 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001566 for (int j = 0; j < 1000; j++) {
1567 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1568 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001569 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1570 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001571 }
1572 }
1573}
1574
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001575TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1576 // Test that ProcessStream copies input to output even with no processing.
1577 const size_t kSamples = 80;
1578 const int sample_rate = 8000;
1579 const float src[kSamples] = {
1580 -1.0f, 0.0f, 1.0f
1581 };
1582 float dest[kSamples] = {};
1583
1584 auto src_channels = &src[0];
1585 auto dest_channels = &dest[0];
1586
Ivo Creusen62337e52018-01-09 14:17:33 +01001587 apm_.reset(AudioProcessingBuilder().Create());
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001588 EXPECT_NOERR(apm_->ProcessStream(
1589 &src_channels, kSamples, sample_rate, LayoutFromChannels(1),
1590 sample_rate, LayoutFromChannels(1), &dest_channels));
1591
1592 for (size_t i = 0; i < kSamples; ++i) {
1593 EXPECT_EQ(src[i], dest[i]);
1594 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001595
1596 // Same for ProcessReverseStream.
1597 float rev_dest[kSamples] = {};
1598 auto rev_dest_channels = &rev_dest[0];
1599
1600 StreamConfig input_stream = {sample_rate, 1};
1601 StreamConfig output_stream = {sample_rate, 1};
1602 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1603 output_stream, &rev_dest_channels));
1604
1605 for (size_t i = 0; i < kSamples; ++i) {
1606 EXPECT_EQ(src[i], rev_dest[i]);
1607 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001608}
1609
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001610TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1611 EnableAllComponents();
1612
pkasting25702cb2016-01-08 13:50:27 -08001613 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001614 Init(kProcessSampleRates[i],
1615 kProcessSampleRates[i],
1616 kProcessSampleRates[i],
1617 2,
1618 2,
1619 2,
1620 false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001621 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001622 ASSERT_EQ(0, feof(far_file_));
1623 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001624 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001625 CopyLeftToRightChannel(revframe_->mutable_data(),
1626 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001627
aluebsb0319552016-03-17 20:39:53 -07001628 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001629
yujo36b1a5f2017-06-12 12:45:32 -07001630 CopyLeftToRightChannel(frame_->mutable_data(),
1631 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001632 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1633
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001634 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001635 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001636 ASSERT_EQ(kNoErr,
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001637 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001638 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001639 analog_level = apm_->gain_control()->stream_analog_level();
1640
yujo36b1a5f2017-06-12 12:45:32 -07001641 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001642 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001643 rewind(far_file_);
1644 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001645 }
1646}
1647
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001648TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001649 // Verify the filter is not active through undistorted audio when:
1650 // 1. No components are enabled...
1651 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001652 AudioFrame frame_copy;
1653 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001654 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1655 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1656 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1657
1658 // 2. Only the level estimator is enabled...
1659 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001660 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001661 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1662 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1663 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1664 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1665 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1666
1667 // 3. Only VAD is enabled...
1668 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001669 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001670 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1671 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1672 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1673 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1674 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1675
1676 // 4. Both VAD and the level estimator are enabled...
1677 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001678 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001679 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1680 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1681 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1682 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1683 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1684 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1685 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1686
1687 // 5. Not using super-wb.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001688 frame_->samples_per_channel_ = 160;
1689 frame_->num_channels_ = 2;
1690 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001691 // Enable AEC, which would require the filter in super-wb. We rely on the
1692 // first few frames of data being unaffected by the AEC.
1693 // TODO(andrew): This test, and the one below, rely rather tenuously on the
1694 // behavior of the AEC. Think of something more robust.
1695 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001696 // Make sure we have extended filter enabled. This makes sure nothing is
1697 // touched until we have a farend frame.
1698 Config config;
Henrik Lundin441f6342015-06-09 16:03:13 +02001699 config.Set<ExtendedFilter>(new ExtendedFilter(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001700 apm_->SetExtraOptions(config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001701 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001702 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001703 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001704 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001705 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1706 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001707 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001708 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1709 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1710
1711 // Check the test is valid. We should have distortion from the filter
1712 // when AEC is enabled (which won't affect the audio).
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001713 frame_->samples_per_channel_ = 320;
1714 frame_->num_channels_ = 2;
1715 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001716 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001717 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001718 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001719 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001720 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1721 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1722}
1723
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001724#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1725void ApmTest::ProcessDebugDump(const std::string& in_filename,
1726 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001727 Format format,
1728 int max_size_bytes) {
aleloif4dd1912017-06-15 01:55:38 -07001729 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001730 FILE* in_file = fopen(in_filename.c_str(), "rb");
1731 ASSERT_TRUE(in_file != NULL);
1732 audioproc::Event event_msg;
1733 bool first_init = true;
1734
1735 while (ReadMessageFromFile(in_file, &event_msg)) {
1736 if (event_msg.type() == audioproc::Event::INIT) {
1737 const audioproc::Init msg = event_msg.init();
1738 int reverse_sample_rate = msg.sample_rate();
1739 if (msg.has_reverse_sample_rate()) {
1740 reverse_sample_rate = msg.reverse_sample_rate();
1741 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001742 int output_sample_rate = msg.sample_rate();
1743 if (msg.has_output_sample_rate()) {
1744 output_sample_rate = msg.output_sample_rate();
1745 }
1746
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001747 Init(msg.sample_rate(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001748 output_sample_rate,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001749 reverse_sample_rate,
1750 msg.num_input_channels(),
1751 msg.num_output_channels(),
1752 msg.num_reverse_channels(),
1753 false);
1754 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001755 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001756 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001757 auto aec_dump =
1758 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1759 EXPECT_TRUE(aec_dump);
1760 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001761 first_init = false;
1762 }
1763
1764 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1765 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1766
1767 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001768 ASSERT_EQ(revframe_->num_channels_,
1769 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001770 for (int i = 0; i < msg.channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001771 memcpy(revfloat_cb_->channels()[i],
1772 msg.channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001773 msg.channel(i).size());
1774 }
1775 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001776 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001777 if (format == kFloatFormat) {
1778 // We're using an int16 input file; convert to float.
1779 ConvertToFloat(*revframe_, revfloat_cb_.get());
1780 }
1781 }
1782 AnalyzeReverseStreamChooser(format);
1783
1784 } else if (event_msg.type() == audioproc::Event::STREAM) {
1785 const audioproc::Stream msg = event_msg.stream();
1786 // ProcessStream could have changed this for the output frame.
1787 frame_->num_channels_ = apm_->num_input_channels();
1788
1789 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1790 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
1791 apm_->echo_cancellation()->set_stream_drift_samples(msg.drift());
1792 if (msg.has_keypress()) {
1793 apm_->set_stream_key_pressed(msg.keypress());
1794 } else {
1795 apm_->set_stream_key_pressed(true);
1796 }
1797
1798 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001799 ASSERT_EQ(frame_->num_channels_,
1800 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001801 for (int i = 0; i < msg.input_channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001802 memcpy(float_cb_->channels()[i],
1803 msg.input_channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001804 msg.input_channel(i).size());
1805 }
1806 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001807 memcpy(frame_->mutable_data(), msg.input_data().data(),
1808 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001809 if (format == kFloatFormat) {
1810 // We're using an int16 input file; convert to float.
1811 ConvertToFloat(*frame_, float_cb_.get());
1812 }
1813 }
1814 ProcessStreamChooser(format);
1815 }
1816 }
aleloif4dd1912017-06-15 01:55:38 -07001817 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001818 fclose(in_file);
1819}
1820
1821void ApmTest::VerifyDebugDumpTest(Format format) {
1822 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001823 std::string format_string;
1824 switch (format) {
1825 case kIntFormat:
1826 format_string = "_int";
1827 break;
1828 case kFloatFormat:
1829 format_string = "_float";
1830 break;
1831 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001832 const std::string ref_filename = test::TempFilename(
1833 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1834 const std::string out_filename = test::TempFilename(
1835 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001836 const std::string limited_filename = test::TempFilename(
1837 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1838 const size_t logging_limit_bytes = 100000;
1839 // We expect at least this many bytes in the created logfile.
1840 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001841 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001842 ProcessDebugDump(in_filename, ref_filename, format, -1);
1843 ProcessDebugDump(ref_filename, out_filename, format, -1);
1844 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001845
1846 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1847 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001848 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001849 ASSERT_TRUE(ref_file != NULL);
1850 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001851 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001852 std::unique_ptr<uint8_t[]> ref_bytes;
1853 std::unique_ptr<uint8_t[]> out_bytes;
1854 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001855
1856 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1857 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001858 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001859 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001860 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001861 while (ref_size > 0 && out_size > 0) {
1862 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001863 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001864 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001865 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001866 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001867 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001868 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1869 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001870 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001871 }
1872 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001873 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1874 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001875 EXPECT_NE(0, feof(ref_file));
1876 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001877 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001878 ASSERT_EQ(0, fclose(ref_file));
1879 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001880 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001881 remove(ref_filename.c_str());
1882 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001883 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001884}
1885
pbosc7a65692016-05-06 12:50:04 -07001886TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001887 VerifyDebugDumpTest(kIntFormat);
1888}
1889
pbosc7a65692016-05-06 12:50:04 -07001890TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001891 VerifyDebugDumpTest(kFloatFormat);
1892}
1893#endif
1894
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001895// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001896TEST_F(ApmTest, DebugDump) {
aleloif4dd1912017-06-15 01:55:38 -07001897 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001898 const std::string filename =
1899 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001900 {
1901 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1902 EXPECT_FALSE(aec_dump);
1903 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001904
1905#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1906 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001907 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001908
aleloif4dd1912017-06-15 01:55:38 -07001909 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1910 EXPECT_TRUE(aec_dump);
1911 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001912 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001913 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001914 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001915
1916 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001917 FILE* fid = fopen(filename.c_str(), "r");
1918 ASSERT_TRUE(fid != NULL);
1919
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001920 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001921 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001922 ASSERT_EQ(0, remove(filename.c_str()));
1923#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001924 // Verify the file has NOT been written.
1925 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1926#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1927}
1928
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001929// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001930TEST_F(ApmTest, DebugDumpFromFileHandle) {
aleloif4dd1912017-06-15 01:55:38 -07001931 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1932
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001933 const std::string filename =
1934 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001935 FILE* fid = fopen(filename.c_str(), "w");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001936 ASSERT_TRUE(fid);
1937
1938#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1939 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001940 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001941
aleloif4dd1912017-06-15 01:55:38 -07001942 auto aec_dump = AecDumpFactory::Create(fid, -1, &worker_queue);
1943 EXPECT_TRUE(aec_dump);
1944 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001945 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001946 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001947 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001948
1949 // Verify the file has been written.
1950 fid = fopen(filename.c_str(), "r");
1951 ASSERT_TRUE(fid != NULL);
1952
1953 // Clean it up.
1954 ASSERT_EQ(0, fclose(fid));
1955 ASSERT_EQ(0, remove(filename.c_str()));
1956#else
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001957 ASSERT_EQ(0, fclose(fid));
1958#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1959}
1960
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001961TEST_F(ApmTest, FloatAndIntInterfacesGiveSimilarResults) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001962 audioproc::OutputData ref_data;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001963 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001964
1965 Config config;
1966 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001967 std::unique_ptr<AudioProcessing> fapm(
1968 AudioProcessingBuilder().Create(config));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001969 EnableAllComponents();
1970 EnableAllAPComponents(fapm.get());
1971 for (int i = 0; i < ref_data.test_size(); i++) {
1972 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
1973
1974 audioproc::Test* test = ref_data.mutable_test(i);
1975 // TODO(ajm): Restore downmixing test cases.
1976 if (test->num_input_channels() != test->num_output_channels())
1977 continue;
1978
Peter Kasting69558702016-01-12 16:26:35 -08001979 const size_t num_render_channels =
1980 static_cast<size_t>(test->num_reverse_channels());
1981 const size_t num_input_channels =
1982 static_cast<size_t>(test->num_input_channels());
1983 const size_t num_output_channels =
1984 static_cast<size_t>(test->num_output_channels());
pkasting25702cb2016-01-08 13:50:27 -08001985 const size_t samples_per_channel = static_cast<size_t>(
1986 test->sample_rate() * AudioProcessing::kChunkSizeMs / 1000);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001987
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001988 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
1989 num_input_channels, num_output_channels, num_render_channels, true);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001990 Init(fapm.get());
1991
1992 ChannelBuffer<int16_t> output_cb(samples_per_channel, num_input_channels);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001993 ChannelBuffer<int16_t> output_int16(samples_per_channel,
1994 num_input_channels);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001995
1996 int analog_level = 127;
aluebs776593b2016-03-15 14:04:58 -07001997 size_t num_bad_chunks = 0;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001998 while (ReadFrame(far_file_, revframe_, revfloat_cb_.get()) &&
1999 ReadFrame(near_file_, frame_, float_cb_.get())) {
2000 frame_->vad_activity_ = AudioFrame::kVadUnknown;
2001
aluebsb0319552016-03-17 20:39:53 -07002002 EXPECT_NOERR(apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002003 EXPECT_NOERR(fapm->AnalyzeReverseStream(
2004 revfloat_cb_->channels(),
2005 samples_per_channel,
2006 test->sample_rate(),
2007 LayoutFromChannels(num_render_channels)));
2008
2009 EXPECT_NOERR(apm_->set_stream_delay_ms(0));
2010 EXPECT_NOERR(fapm->set_stream_delay_ms(0));
2011 apm_->echo_cancellation()->set_stream_drift_samples(0);
2012 fapm->echo_cancellation()->set_stream_drift_samples(0);
2013 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(analog_level));
2014 EXPECT_NOERR(fapm->gain_control()->set_stream_analog_level(analog_level));
2015
2016 EXPECT_NOERR(apm_->ProcessStream(frame_));
yujo36b1a5f2017-06-12 12:45:32 -07002017 Deinterleave(frame_->data(), samples_per_channel, num_output_channels,
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002018 output_int16.channels());
2019
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002020 EXPECT_NOERR(fapm->ProcessStream(
2021 float_cb_->channels(),
2022 samples_per_channel,
2023 test->sample_rate(),
2024 LayoutFromChannels(num_input_channels),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002025 test->sample_rate(),
2026 LayoutFromChannels(num_output_channels),
2027 float_cb_->channels()));
Peter Kasting69558702016-01-12 16:26:35 -08002028 for (size_t j = 0; j < num_output_channels; ++j) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002029 FloatToS16(float_cb_->channels()[j],
2030 samples_per_channel,
2031 output_cb.channels()[j]);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002032 float variance = 0;
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002033 float snr = ComputeSNR(output_int16.channels()[j],
2034 output_cb.channels()[j],
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002035 samples_per_channel, &variance);
aluebs776593b2016-03-15 14:04:58 -07002036
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002037 const float kVarianceThreshold = 20;
2038 const float kSNRThreshold = 20;
aluebs776593b2016-03-15 14:04:58 -07002039
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002040 // Skip frames with low energy.
aluebs776593b2016-03-15 14:04:58 -07002041 if (sqrt(variance) > kVarianceThreshold && snr < kSNRThreshold) {
2042 ++num_bad_chunks;
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002043 }
2044 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002045
2046 analog_level = fapm->gain_control()->stream_analog_level();
2047 EXPECT_EQ(apm_->gain_control()->stream_analog_level(),
2048 fapm->gain_control()->stream_analog_level());
2049 EXPECT_EQ(apm_->echo_cancellation()->stream_has_echo(),
2050 fapm->echo_cancellation()->stream_has_echo());
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002051 EXPECT_NEAR(apm_->noise_suppression()->speech_probability(),
2052 fapm->noise_suppression()->speech_probability(),
Alejandro Luebs47748742015-05-22 12:00:21 -07002053 0.01);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002054
2055 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002056 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002057 }
aluebs776593b2016-03-15 14:04:58 -07002058
2059#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2060 const size_t kMaxNumBadChunks = 0;
2061#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2062 // There are a few chunks in the fixed-point profile that give low SNR.
2063 // Listening confirmed the difference is acceptable.
2064 const size_t kMaxNumBadChunks = 60;
2065#endif
2066 EXPECT_LE(num_bad_chunks, kMaxNumBadChunks);
2067
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002068 rewind(far_file_);
2069 rewind(near_file_);
2070 }
2071}
2072
andrew@webrtc.org75f19482012-02-09 17:16:18 +00002073// TODO(andrew): Add a test to process a few frames with different combinations
2074// of enabled components.
2075
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002076TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002077 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002078 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002079
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002080 if (!write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002081 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002082 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002083 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08002084 for (size_t i = 0; i < arraysize(kChannels); i++) {
2085 for (size_t j = 0; j < arraysize(kChannels); j++) {
2086 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002087 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002088 test->set_num_reverse_channels(kChannels[i]);
2089 test->set_num_input_channels(kChannels[j]);
2090 test->set_num_output_channels(kChannels[j]);
2091 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002092 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002093 }
2094 }
2095 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002096#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2097 // To test the extended filter mode.
2098 audioproc::Test* test = ref_data.add_test();
2099 test->set_num_reverse_channels(2);
2100 test->set_num_input_channels(2);
2101 test->set_num_output_channels(2);
2102 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
2103 test->set_use_aec_extended_filter(true);
2104#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002105 }
2106
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002107 for (int i = 0; i < ref_data.test_size(); i++) {
2108 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002109
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002110 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002111 // TODO(ajm): We no longer allow different input and output channels. Skip
2112 // these tests for now, but they should be removed from the set.
2113 if (test->num_input_channels() != test->num_output_channels())
2114 continue;
2115
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002116 Config config;
2117 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02002118 config.Set<ExtendedFilter>(
2119 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01002120 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002121
2122 EnableAllComponents();
2123
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002124 Init(test->sample_rate(),
2125 test->sample_rate(),
2126 test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08002127 static_cast<size_t>(test->num_input_channels()),
2128 static_cast<size_t>(test->num_output_channels()),
2129 static_cast<size_t>(test->num_reverse_channels()),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002130 true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002131
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002132 int frame_count = 0;
2133 int has_echo_count = 0;
2134 int has_voice_count = 0;
2135 int is_saturated_count = 0;
2136 int analog_level = 127;
2137 int analog_level_average = 0;
2138 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002139 float ns_speech_prob_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07002140#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2141 int stats_index = 0;
2142#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002143
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002144 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07002145 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002146
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002147 frame_->vad_activity_ = AudioFrame::kVadUnknown;
2148
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002149 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00002150 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002151 EXPECT_EQ(apm_->kNoError,
2152 apm_->gain_control()->set_stream_analog_level(analog_level));
2153
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002154 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002155
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002156 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08002157 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
2158 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002159
2160 max_output_average += MaxAudioFrame(*frame_);
2161
2162 if (apm_->echo_cancellation()->stream_has_echo()) {
2163 has_echo_count++;
2164 }
2165
2166 analog_level = apm_->gain_control()->stream_analog_level();
2167 analog_level_average += analog_level;
2168 if (apm_->gain_control()->stream_is_saturated()) {
2169 is_saturated_count++;
2170 }
2171 if (apm_->voice_detection()->stream_has_voice()) {
2172 has_voice_count++;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002173 EXPECT_EQ(AudioFrame::kVadActive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002174 } else {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002175 EXPECT_EQ(AudioFrame::kVadPassive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002176 }
2177
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002178 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
2179
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002180 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07002181 size_t write_count = fwrite(frame_->data(),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002182 sizeof(int16_t),
2183 frame_size,
2184 out_file_);
2185 ASSERT_EQ(frame_size, write_count);
2186
2187 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002188 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002189 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07002190
2191#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2192 const int kStatsAggregationFrameNum = 100; // 1 second.
2193 if (frame_count % kStatsAggregationFrameNum == 0) {
2194 // Get echo metrics.
2195 EchoCancellation::Metrics echo_metrics;
2196 EXPECT_EQ(apm_->kNoError,
2197 apm_->echo_cancellation()->GetMetrics(&echo_metrics));
2198
2199 // Get delay metrics.
2200 int median = 0;
2201 int std = 0;
2202 float fraction_poor_delays = 0;
2203 EXPECT_EQ(apm_->kNoError,
2204 apm_->echo_cancellation()->GetDelayMetrics(
2205 &median, &std, &fraction_poor_delays));
2206
2207 // Get RMS.
2208 int rms_level = apm_->level_estimator()->RMS();
2209 EXPECT_LE(0, rms_level);
2210 EXPECT_GE(127, rms_level);
2211
2212 if (!write_ref_data) {
2213 const audioproc::Test::EchoMetrics& reference =
2214 test->echo_metrics(stats_index);
2215 TestStats(echo_metrics.residual_echo_return_loss,
2216 reference.residual_echo_return_loss());
2217 TestStats(echo_metrics.echo_return_loss,
2218 reference.echo_return_loss());
2219 TestStats(echo_metrics.echo_return_loss_enhancement,
2220 reference.echo_return_loss_enhancement());
2221 TestStats(echo_metrics.a_nlp,
2222 reference.a_nlp());
2223 EXPECT_EQ(echo_metrics.divergent_filter_fraction,
2224 reference.divergent_filter_fraction());
2225
2226 const audioproc::Test::DelayMetrics& reference_delay =
2227 test->delay_metrics(stats_index);
2228 EXPECT_EQ(reference_delay.median(), median);
2229 EXPECT_EQ(reference_delay.std(), std);
2230 EXPECT_EQ(reference_delay.fraction_poor_delays(),
2231 fraction_poor_delays);
2232
2233 EXPECT_EQ(test->rms_level(stats_index), rms_level);
2234
2235 ++stats_index;
2236 } else {
2237 audioproc::Test::EchoMetrics* message =
2238 test->add_echo_metrics();
2239 WriteStatsMessage(echo_metrics.residual_echo_return_loss,
2240 message->mutable_residual_echo_return_loss());
2241 WriteStatsMessage(echo_metrics.echo_return_loss,
2242 message->mutable_echo_return_loss());
2243 WriteStatsMessage(echo_metrics.echo_return_loss_enhancement,
2244 message->mutable_echo_return_loss_enhancement());
2245 WriteStatsMessage(echo_metrics.a_nlp,
2246 message->mutable_a_nlp());
2247 message->set_divergent_filter_fraction(
2248 echo_metrics.divergent_filter_fraction);
2249
2250 audioproc::Test::DelayMetrics* message_delay =
2251 test->add_delay_metrics();
2252 message_delay->set_median(median);
2253 message_delay->set_std(std);
2254 message_delay->set_fraction_poor_delays(fraction_poor_delays);
2255
2256 test->add_rms_level(rms_level);
2257 }
2258 }
2259#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002260 }
2261 max_output_average /= frame_count;
2262 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002263 ns_speech_prob_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002264
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002265 if (!write_ref_data) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002266 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002267 // When running the test on a N7 we get a {2, 6} difference of
2268 // |has_voice_count| and |max_output_average| is up to 18 higher.
2269 // All numbers being consistently higher on N7 compare to ref_data.
2270 // TODO(bjornv): If we start getting more of these offsets on Android we
2271 // should consider a different approach. Either using one slack for all,
2272 // or generate a separate android reference.
2273#if defined(WEBRTC_ANDROID)
2274 const int kHasVoiceCountOffset = 3;
Alejandro Luebs2a5609d2016-04-05 18:16:54 -07002275 const int kHasVoiceCountNear = 4;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002276 const int kMaxOutputAverageOffset = 9;
2277 const int kMaxOutputAverageNear = 9;
2278#else
2279 const int kHasVoiceCountOffset = 0;
2280 const int kHasVoiceCountNear = kIntNear;
2281 const int kMaxOutputAverageOffset = 0;
2282 const int kMaxOutputAverageNear = kIntNear;
2283#endif
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002284 EXPECT_NEAR(test->has_echo_count(), has_echo_count, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002285 EXPECT_NEAR(test->has_voice_count(),
2286 has_voice_count - kHasVoiceCountOffset,
2287 kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002288 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002289
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002290 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002291 EXPECT_NEAR(test->max_output_average(),
2292 max_output_average - kMaxOutputAverageOffset,
2293 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002294#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002295 const double kFloatNear = 0.0005;
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002296 EXPECT_NEAR(test->ns_speech_probability_average(),
2297 ns_speech_prob_average,
2298 kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002299#endif
2300 } else {
2301 test->set_has_echo_count(has_echo_count);
2302 test->set_has_voice_count(has_voice_count);
2303 test->set_is_saturated_count(is_saturated_count);
2304
2305 test->set_analog_level_average(analog_level_average);
2306 test->set_max_output_average(max_output_average);
2307
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002308#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002309 EXPECT_LE(0.0f, ns_speech_prob_average);
2310 EXPECT_GE(1.0f, ns_speech_prob_average);
2311 test->set_ns_speech_probability_average(ns_speech_prob_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002312#endif
2313 }
2314
2315 rewind(far_file_);
2316 rewind(near_file_);
2317 }
2318
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002319 if (write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002320 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002321 }
2322}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002323
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002324TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
2325 struct ChannelFormat {
2326 AudioProcessing::ChannelLayout in_layout;
2327 AudioProcessing::ChannelLayout out_layout;
2328 };
2329 ChannelFormat cf[] = {
2330 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
2331 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
2332 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
2333 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002334
Ivo Creusen62337e52018-01-09 14:17:33 +01002335 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002336 // Enable one component just to ensure some processing takes place.
2337 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08002338 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002339 const int in_rate = 44100;
2340 const int out_rate = 48000;
2341 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
2342 TotalChannelsFromLayout(cf[i].in_layout));
2343 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
2344 ChannelsFromLayout(cf[i].out_layout));
2345
2346 // Run over a few chunks.
2347 for (int j = 0; j < 10; ++j) {
2348 EXPECT_NOERR(ap->ProcessStream(
2349 in_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002350 in_cb.num_frames(),
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002351 in_rate,
2352 cf[i].in_layout,
2353 out_rate,
2354 cf[i].out_layout,
2355 out_cb.channels()));
2356 }
2357 }
2358}
2359
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002360// Compares the reference and test arrays over a region around the expected
2361// delay. Finds the highest SNR in that region and adds the variance and squared
2362// error results to the supplied accumulators.
2363void UpdateBestSNR(const float* ref,
2364 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08002365 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002366 int expected_delay,
2367 double* variance_acc,
2368 double* sq_error_acc) {
2369 double best_snr = std::numeric_limits<double>::min();
2370 double best_variance = 0;
2371 double best_sq_error = 0;
2372 // Search over a region of eight samples around the expected delay.
2373 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
2374 ++delay) {
2375 double sq_error = 0;
2376 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08002377 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002378 double error = test[i + delay] - ref[i];
2379 sq_error += error * error;
2380 variance += ref[i] * ref[i];
2381 }
2382
2383 if (sq_error == 0) {
2384 *variance_acc += variance;
2385 return;
2386 }
2387 double snr = variance / sq_error;
2388 if (snr > best_snr) {
2389 best_snr = snr;
2390 best_variance = variance;
2391 best_sq_error = sq_error;
2392 }
2393 }
2394
2395 *variance_acc += best_variance;
2396 *sq_error_acc += best_sq_error;
2397}
2398
2399// Used to test a multitude of sample rate and channel combinations. It works
2400// by first producing a set of reference files (in SetUpTestCase) that are
2401// assumed to be correct, as the used parameters are verified by other tests
2402// in this collection. Primarily the reference files are all produced at
2403// "native" rates which do not involve any resampling.
2404
2405// Each test pass produces an output file with a particular format. The output
2406// is matched against the reference file closest to its internal processing
2407// format. If necessary the output is resampled back to its process format.
2408// Due to the resampling distortion, we don't expect identical results, but
2409// enforce SNR thresholds which vary depending on the format. 0 is a special
2410// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02002411typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002412class AudioProcessingTest
2413 : public testing::TestWithParam<AudioProcessingTestData> {
2414 public:
2415 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02002416 : input_rate_(std::get<0>(GetParam())),
2417 output_rate_(std::get<1>(GetParam())),
2418 reverse_input_rate_(std::get<2>(GetParam())),
2419 reverse_output_rate_(std::get<3>(GetParam())),
2420 expected_snr_(std::get<4>(GetParam())),
2421 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002422
2423 virtual ~AudioProcessingTest() {}
2424
2425 static void SetUpTestCase() {
2426 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07002427 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08002428 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08002429 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
2430 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
2431 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002432 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07002433 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
2434 kNativeRates[i], kNumChannels[j], kNumChannels[j],
2435 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002436 }
2437 }
2438 }
2439 }
2440
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02002441 void TearDown() {
2442 // Remove "out" files after each test.
2443 ClearTempOutFiles();
2444 }
2445
pbos@webrtc.org200ac002015-02-03 14:14:01 +00002446 static void TearDownTestCase() {
2447 ClearTempFiles();
2448 }
ekmeyerson60d9b332015-08-14 10:35:55 -07002449
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002450 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07002451 // to a file specified with |output_file_prefix|. Both forward and reverse
2452 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002453 static void ProcessFormat(int input_rate,
2454 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07002455 int reverse_input_rate,
2456 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08002457 size_t num_input_channels,
2458 size_t num_output_channels,
2459 size_t num_reverse_input_channels,
2460 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02002461 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002462 Config config;
2463 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01002464 std::unique_ptr<AudioProcessing> ap(
2465 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002466 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002467
ekmeyerson60d9b332015-08-14 10:35:55 -07002468 ProcessingConfig processing_config = {
2469 {{input_rate, num_input_channels},
2470 {output_rate, num_output_channels},
2471 {reverse_input_rate, num_reverse_input_channels},
2472 {reverse_output_rate, num_reverse_output_channels}}};
2473 ap->Initialize(processing_config);
2474
2475 FILE* far_file =
2476 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002477 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07002478 FILE* out_file =
2479 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2480 reverse_input_rate, reverse_output_rate,
2481 num_input_channels, num_output_channels,
2482 num_reverse_input_channels,
2483 num_reverse_output_channels, kForward).c_str(),
2484 "wb");
2485 FILE* rev_out_file =
2486 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2487 reverse_input_rate, reverse_output_rate,
2488 num_input_channels, num_output_channels,
2489 num_reverse_input_channels,
2490 num_reverse_output_channels, kReverse).c_str(),
2491 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002492 ASSERT_TRUE(far_file != NULL);
2493 ASSERT_TRUE(near_file != NULL);
2494 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07002495 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002496
2497 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
2498 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002499 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
2500 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002501 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
2502 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002503 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
2504 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002505
2506 // Temporary buffers.
2507 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07002508 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
2509 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08002510 std::unique_ptr<float[]> float_data(new float[max_length]);
2511 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002512
2513 int analog_level = 127;
2514 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
2515 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002516 EXPECT_NOERR(ap->ProcessReverseStream(
2517 rev_cb.channels(), processing_config.reverse_input_stream(),
2518 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002519
2520 EXPECT_NOERR(ap->set_stream_delay_ms(0));
2521 ap->echo_cancellation()->set_stream_drift_samples(0);
2522 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
2523
2524 EXPECT_NOERR(ap->ProcessStream(
2525 fwd_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002526 fwd_cb.num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002527 input_rate,
2528 LayoutFromChannels(num_input_channels),
2529 output_rate,
2530 LayoutFromChannels(num_output_channels),
2531 out_cb.channels()));
2532
ekmeyerson60d9b332015-08-14 10:35:55 -07002533 // Dump forward output to file.
2534 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002535 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002536 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002537
pkasting25702cb2016-01-08 13:50:27 -08002538 ASSERT_EQ(out_length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002539 fwrite(float_data.get(), sizeof(float_data[0]),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002540 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002541
ekmeyerson60d9b332015-08-14 10:35:55 -07002542 // Dump reverse output to file.
2543 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
2544 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002545 size_t rev_out_length =
2546 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002547
pkasting25702cb2016-01-08 13:50:27 -08002548 ASSERT_EQ(rev_out_length,
ekmeyerson60d9b332015-08-14 10:35:55 -07002549 fwrite(float_data.get(), sizeof(float_data[0]), rev_out_length,
2550 rev_out_file));
2551
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002552 analog_level = ap->gain_control()->stream_analog_level();
2553 }
2554 fclose(far_file);
2555 fclose(near_file);
2556 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07002557 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002558 }
2559
2560 protected:
2561 int input_rate_;
2562 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002563 int reverse_input_rate_;
2564 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002565 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002566 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002567};
2568
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00002569TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002570 struct ChannelFormat {
2571 int num_input;
2572 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07002573 int num_reverse_input;
2574 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002575 };
2576 ChannelFormat cf[] = {
ekmeyerson60d9b332015-08-14 10:35:55 -07002577 {1, 1, 1, 1},
2578 {1, 1, 2, 1},
2579 {2, 1, 1, 1},
2580 {2, 1, 2, 1},
2581 {2, 2, 1, 1},
2582 {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002583 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002584
pkasting25702cb2016-01-08 13:50:27 -08002585 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002586 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
2587 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
2588 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07002589
ekmeyerson60d9b332015-08-14 10:35:55 -07002590 // Verify output for both directions.
2591 std::vector<StreamDirection> stream_directions;
2592 stream_directions.push_back(kForward);
2593 stream_directions.push_back(kReverse);
2594 for (StreamDirection file_direction : stream_directions) {
2595 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
2596 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
2597 const int out_num =
2598 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
2599 const double expected_snr =
2600 file_direction ? expected_reverse_snr_ : expected_snr_;
2601
2602 const int min_ref_rate = std::min(in_rate, out_rate);
2603 int ref_rate;
2604
2605 if (min_ref_rate > 32000) {
2606 ref_rate = 48000;
2607 } else if (min_ref_rate > 16000) {
2608 ref_rate = 32000;
2609 } else if (min_ref_rate > 8000) {
2610 ref_rate = 16000;
2611 } else {
2612 ref_rate = 8000;
2613 }
aluebs776593b2016-03-15 14:04:58 -07002614#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08002615 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07002616 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08002617 }
2618#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07002619 FILE* out_file = fopen(
2620 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
2621 reverse_output_rate_, cf[i].num_input,
2622 cf[i].num_output, cf[i].num_reverse_input,
2623 cf[i].num_reverse_output, file_direction).c_str(),
2624 "rb");
2625 // The reference files always have matching input and output channels.
2626 FILE* ref_file = fopen(
2627 OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
2628 cf[i].num_output, cf[i].num_output,
2629 cf[i].num_reverse_output, cf[i].num_reverse_output,
2630 file_direction).c_str(),
2631 "rb");
2632 ASSERT_TRUE(out_file != NULL);
2633 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002634
pkasting25702cb2016-01-08 13:50:27 -08002635 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2636 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002637 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002638 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002639 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002640 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002641 // Data from the resampled output, in case the reference and output rates
2642 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002643 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002644
ekmeyerson60d9b332015-08-14 10:35:55 -07002645 PushResampler<float> resampler;
2646 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002647
ekmeyerson60d9b332015-08-14 10:35:55 -07002648 // Compute the resampling delay of the output relative to the reference,
2649 // to find the region over which we should search for the best SNR.
2650 float expected_delay_sec = 0;
2651 if (in_rate != ref_rate) {
2652 // Input resampling delay.
2653 expected_delay_sec +=
2654 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2655 }
2656 if (out_rate != ref_rate) {
2657 // Output resampling delay.
2658 expected_delay_sec +=
2659 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2660 // Delay of converting the output back to its processing rate for
2661 // testing.
2662 expected_delay_sec +=
2663 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2664 }
2665 int expected_delay =
2666 floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002667
ekmeyerson60d9b332015-08-14 10:35:55 -07002668 double variance = 0;
2669 double sq_error = 0;
2670 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2671 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2672 float* out_ptr = out_data.get();
2673 if (out_rate != ref_rate) {
2674 // Resample the output back to its internal processing rate if
2675 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002676 ASSERT_EQ(ref_length,
2677 static_cast<size_t>(resampler.Resample(
2678 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002679 out_ptr = cmp_data.get();
2680 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002681
ekmeyerson60d9b332015-08-14 10:35:55 -07002682 // Update the |sq_error| and |variance| accumulators with the highest
2683 // SNR of reference vs output.
2684 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2685 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002686 }
2687
ekmeyerson60d9b332015-08-14 10:35:55 -07002688 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2689 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2690 << cf[i].num_input << ", " << cf[i].num_output << ", "
2691 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2692 << ", " << file_direction << "): ";
2693 if (sq_error > 0) {
2694 double snr = 10 * log10(variance / sq_error);
2695 EXPECT_GE(snr, expected_snr);
2696 EXPECT_NE(0, expected_snr);
2697 std::cout << "SNR=" << snr << " dB" << std::endl;
2698 } else {
aluebs776593b2016-03-15 14:04:58 -07002699 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002700 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002701
ekmeyerson60d9b332015-08-14 10:35:55 -07002702 fclose(out_file);
2703 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002704 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002705 }
2706}
2707
2708#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2709INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002710 CommonFormats,
2711 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002712 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2713 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2714 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2715 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2716 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2717 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2718 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2719 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2720 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2721 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2722 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2723 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002724
Edward Lemurc5ee9872017-10-23 23:33:04 +02002725 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2726 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2727 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2728 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2729 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2730 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2731 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2732 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2733 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2734 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2735 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2736 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002737
Edward Lemurc5ee9872017-10-23 23:33:04 +02002738 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2739 std::make_tuple(32000, 48000, 32000, 48000, 35, 30),
2740 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2741 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2742 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2743 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2744 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2745 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2746 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2747 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2748 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2749 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002750
Edward Lemurc5ee9872017-10-23 23:33:04 +02002751 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2752 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2753 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2754 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2755 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2756 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2757 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2758 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2759 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2760 std::make_tuple(16000, 16000, 48000, 16000, 40, 20),
2761 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2762 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002763
2764#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2765INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002766 CommonFormats,
2767 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002768 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 20, 0),
2769 std::make_tuple(48000, 48000, 32000, 48000, 20, 30),
2770 std::make_tuple(48000, 48000, 16000, 48000, 20, 20),
2771 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2772 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2773 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
2774 std::make_tuple(48000, 32000, 48000, 32000, 20, 35),
2775 std::make_tuple(48000, 32000, 32000, 32000, 20, 0),
2776 std::make_tuple(48000, 32000, 16000, 32000, 20, 20),
2777 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2778 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2779 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002780
Edward Lemurc5ee9872017-10-23 23:33:04 +02002781 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2782 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2783 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2784 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2785 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2786 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
2787 std::make_tuple(44100, 32000, 48000, 32000, 20, 35),
2788 std::make_tuple(44100, 32000, 32000, 32000, 20, 0),
2789 std::make_tuple(44100, 32000, 16000, 32000, 20, 20),
2790 std::make_tuple(44100, 16000, 48000, 16000, 20, 20),
2791 std::make_tuple(44100, 16000, 32000, 16000, 20, 20),
2792 std::make_tuple(44100, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002793
Edward Lemurc5ee9872017-10-23 23:33:04 +02002794 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2795 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2796 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2797 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2798 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2799 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2800 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2801 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2802 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2803 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2804 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2805 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002806
Edward Lemurc5ee9872017-10-23 23:33:04 +02002807 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2808 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2809 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2810 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2811 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2812 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2813 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2814 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2815 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2816 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2817 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2818 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002819#endif
2820
niklase@google.com470e71d2011-07-07 08:21:25 +00002821} // namespace
peahc19f3122016-10-07 14:54:10 -07002822
Alessio Bazzicac054e782018-04-16 12:10:09 +02002823TEST(RuntimeSettingTest, TestDefaultCtor) {
2824 auto s = AudioProcessing::RuntimeSetting();
2825 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2826}
2827
2828TEST(RuntimeSettingTest, TestCapturePreGain) {
2829 using Type = AudioProcessing::RuntimeSetting::Type;
2830 {
2831 auto s = AudioProcessing::RuntimeSetting::CreateCapturePreGain(1.25f);
2832 EXPECT_EQ(Type::kCapturePreGain, s.type());
2833 float v;
2834 s.GetFloat(&v);
2835 EXPECT_EQ(1.25f, v);
2836 }
2837
2838#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
2839 EXPECT_DEATH(AudioProcessing::RuntimeSetting::CreateCapturePreGain(0.1f), "");
2840#endif
2841}
2842
2843TEST(RuntimeSettingTest, TestUsageWithSwapQueue) {
2844 SwapQueue<AudioProcessing::RuntimeSetting> q(1);
2845 auto s = AudioProcessing::RuntimeSetting();
2846 ASSERT_TRUE(q.Insert(&s));
2847 ASSERT_TRUE(q.Remove(&s));
2848 EXPECT_EQ(AudioProcessing::RuntimeSetting::Type::kNotSpecified, s.type());
2849}
2850
Sam Zackrisson0beac582017-09-25 12:04:02 +02002851TEST(ApmConfiguration, EnablePostProcessing) {
2852 // Verify that apm uses a capture post processing module if one is provided.
Sam Zackrisson0beac582017-09-25 12:04:02 +02002853 auto mock_post_processor_ptr =
Alex Loiko5825aa62017-12-18 16:02:40 +01002854 new testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002855 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002856 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002857 rtc::scoped_refptr<AudioProcessing> apm =
2858 AudioProcessingBuilder()
2859 .SetCapturePostProcessing(std::move(mock_post_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002860 .Create();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002861
2862 AudioFrame audio;
2863 audio.num_channels_ = 1;
2864 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2865
2866 EXPECT_CALL(*mock_post_processor_ptr, Process(testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002867 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002868}
2869
Alex Loiko5825aa62017-12-18 16:02:40 +01002870TEST(ApmConfiguration, EnablePreProcessing) {
2871 // Verify that apm uses a capture post processing module if one is provided.
Alex Loiko5825aa62017-12-18 16:02:40 +01002872 auto mock_pre_processor_ptr =
2873 new testing::NiceMock<test::MockCustomProcessing>();
2874 auto mock_pre_processor =
2875 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002876 rtc::scoped_refptr<AudioProcessing> apm =
2877 AudioProcessingBuilder()
2878 .SetRenderPreProcessing(std::move(mock_pre_processor))
Alex Loiko73ec0192018-05-15 10:52:28 +02002879 .Create();
Alex Loiko5825aa62017-12-18 16:02:40 +01002880
2881 AudioFrame audio;
2882 audio.num_channels_ = 1;
2883 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2884
2885 EXPECT_CALL(*mock_pre_processor_ptr, Process(testing::_)).Times(1);
2886 apm->ProcessReverseStream(&audio);
2887}
2888
Alex Loiko73ec0192018-05-15 10:52:28 +02002889TEST(ApmConfiguration, PreProcessingReceivesRuntimeSettings) {
2890 auto mock_pre_processor_ptr =
2891 new testing::NiceMock<test::MockCustomProcessing>();
2892 auto mock_pre_processor =
2893 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
2894 rtc::scoped_refptr<AudioProcessing> apm =
2895 AudioProcessingBuilder()
2896 .SetRenderPreProcessing(std::move(mock_pre_processor))
2897 .Create();
2898 apm->SetRuntimeSetting(
2899 AudioProcessing::RuntimeSetting::CreateCustomRenderSetting(0));
2900
2901 // RuntimeSettings forwarded during 'Process*Stream' calls.
2902 // Therefore we have to make one such call.
2903 AudioFrame audio;
2904 audio.num_channels_ = 1;
2905 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2906
2907 EXPECT_CALL(*mock_pre_processor_ptr, SetRuntimeSetting(testing::_)).Times(1);
2908 apm->ProcessReverseStream(&audio);
2909}
2910
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002911class MyEchoControlFactory : public EchoControlFactory {
2912 public:
2913 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2914 auto ec = new test::MockEchoControl();
2915 EXPECT_CALL(*ec, AnalyzeRender(testing::_)).Times(1);
2916 EXPECT_CALL(*ec, AnalyzeCapture(testing::_)).Times(2);
2917 EXPECT_CALL(*ec, ProcessCapture(testing::_, testing::_)).Times(2);
2918 return std::unique_ptr<EchoControl>(ec);
2919 }
2920};
2921
2922TEST(ApmConfiguration, EchoControlInjection) {
2923 // Verify that apm uses an injected echo controller if one is provided.
2924 webrtc::Config webrtc_config;
2925 std::unique_ptr<EchoControlFactory> echo_control_factory(
2926 new MyEchoControlFactory());
2927
Alex Loiko5825aa62017-12-18 16:02:40 +01002928 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002929 AudioProcessingBuilder()
2930 .SetEchoControlFactory(std::move(echo_control_factory))
2931 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002932
2933 AudioFrame audio;
2934 audio.num_channels_ = 1;
2935 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2936 apm->ProcessStream(&audio);
2937 apm->ProcessReverseStream(&audio);
2938 apm->ProcessStream(&audio);
2939}
Ivo Creusenae026092017-11-20 13:07:16 +01002940
2941std::unique_ptr<AudioProcessing> CreateApm(bool use_AEC2) {
2942 Config old_config;
2943 if (use_AEC2) {
2944 old_config.Set<ExtendedFilter>(new ExtendedFilter(true));
2945 old_config.Set<DelayAgnostic>(new DelayAgnostic(true));
2946 }
Ivo Creusen62337e52018-01-09 14:17:33 +01002947 std::unique_ptr<AudioProcessing> apm(
2948 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002949 if (!apm) {
2950 return apm;
2951 }
2952
2953 ProcessingConfig processing_config = {
2954 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2955
2956 if (apm->Initialize(processing_config) != 0) {
2957 return nullptr;
2958 }
2959
2960 // Disable all components except for an AEC and the residual echo detector.
2961 AudioProcessing::Config config;
2962 config.residual_echo_detector.enabled = true;
Ivo Creusenae026092017-11-20 13:07:16 +01002963 config.high_pass_filter.enabled = false;
2964 config.gain_controller2.enabled = false;
Ivo Creusenae026092017-11-20 13:07:16 +01002965 apm->ApplyConfig(config);
2966 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
2967 EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
2968 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
2969 EXPECT_EQ(apm->voice_detection()->Enable(false), 0);
2970
2971 if (use_AEC2) {
2972 EXPECT_EQ(apm->echo_control_mobile()->Enable(false), 0);
2973 EXPECT_EQ(apm->echo_cancellation()->enable_metrics(true), 0);
2974 EXPECT_EQ(apm->echo_cancellation()->enable_delay_logging(true), 0);
2975 EXPECT_EQ(apm->echo_cancellation()->Enable(true), 0);
2976 } else {
2977 EXPECT_EQ(apm->echo_cancellation()->Enable(false), 0);
2978 EXPECT_EQ(apm->echo_control_mobile()->Enable(true), 0);
2979 }
2980 return apm;
2981}
2982
2983#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
2984#define MAYBE_ApmStatistics DISABLED_ApmStatistics
2985#else
2986#define MAYBE_ApmStatistics ApmStatistics
2987#endif
2988
2989TEST(MAYBE_ApmStatistics, AEC2EnabledTest) {
2990 // Set up APM with AEC2 and process some audio.
2991 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
2992 ASSERT_TRUE(apm);
2993
2994 // Set up an audioframe.
2995 AudioFrame frame;
2996 frame.num_channels_ = 1;
2997 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
2998
2999 // Fill the audio frame with a sawtooth pattern.
3000 int16_t* ptr = frame.mutable_data();
3001 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3002 ptr[i] = 10000 * ((i % 3) - 1);
3003 }
3004
3005 // Do some processing.
3006 for (int i = 0; i < 200; i++) {
3007 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3008 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3009 EXPECT_EQ(apm->ProcessStream(&frame), 0);
3010 }
3011
3012 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01003013 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01003014 // We expect all statistics to be set and have a sensible value.
3015 ASSERT_TRUE(stats.residual_echo_likelihood);
3016 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3017 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3018 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
3019 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3020 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3021 ASSERT_TRUE(stats.echo_return_loss);
3022 EXPECT_NE(*stats.echo_return_loss, -100.0);
3023 ASSERT_TRUE(stats.echo_return_loss_enhancement);
3024 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
3025 ASSERT_TRUE(stats.divergent_filter_fraction);
3026 EXPECT_NE(*stats.divergent_filter_fraction, -1.0);
3027 ASSERT_TRUE(stats.delay_standard_deviation_ms);
3028 EXPECT_GE(*stats.delay_standard_deviation_ms, 0);
3029 // We don't check stats.delay_median_ms since it takes too long to settle to a
3030 // value. At least 20 seconds of data need to be processed before it will get
3031 // a value, which would make this test take too much time.
3032
3033 // If there are no receive streams, we expect the stats not to be set. The
3034 // 'false' argument signals to APM that no receive streams are currently
3035 // active. In that situation the statistics would get stuck at their last
3036 // calculated value (AEC and echo detection need at least one stream in each
3037 // direction), so to avoid that, they should not be set by APM.
3038 stats = apm->GetStatistics(false);
3039 EXPECT_FALSE(stats.residual_echo_likelihood);
3040 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3041 EXPECT_FALSE(stats.echo_return_loss);
3042 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3043 EXPECT_FALSE(stats.divergent_filter_fraction);
3044 EXPECT_FALSE(stats.delay_median_ms);
3045 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3046}
3047
3048TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
3049 // Set up APM with AECM and process some audio.
3050 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
3051 ASSERT_TRUE(apm);
3052
3053 // Set up an audioframe.
3054 AudioFrame frame;
3055 frame.num_channels_ = 1;
3056 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3057
3058 // Fill the audio frame with a sawtooth pattern.
3059 int16_t* ptr = frame.mutable_data();
3060 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3061 ptr[i] = 10000 * ((i % 3) - 1);
3062 }
3063
3064 // Do some processing.
3065 for (int i = 0; i < 200; i++) {
3066 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3067 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3068 EXPECT_EQ(apm->ProcessStream(&frame), 0);
3069 }
3070
3071 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01003072 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01003073 // We expect only the residual echo detector statistics to be set and have a
3074 // sensible value.
3075 EXPECT_TRUE(stats.residual_echo_likelihood);
3076 if (stats.residual_echo_likelihood) {
3077 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3078 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3079 }
3080 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
3081 if (stats.residual_echo_likelihood_recent_max) {
3082 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3083 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3084 }
3085 EXPECT_FALSE(stats.echo_return_loss);
3086 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3087 EXPECT_FALSE(stats.divergent_filter_fraction);
3088 EXPECT_FALSE(stats.delay_median_ms);
3089 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3090
3091 // If there are no receive streams, we expect the stats not to be set.
3092 stats = apm->GetStatistics(false);
3093 EXPECT_FALSE(stats.residual_echo_likelihood);
3094 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3095 EXPECT_FALSE(stats.echo_return_loss);
3096 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3097 EXPECT_FALSE(stats.divergent_filter_fraction);
3098 EXPECT_FALSE(stats.delay_median_ms);
3099 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3100}
andrew@webrtc.org27c69802014-02-18 20:24:56 +00003101} // namespace webrtc