blob: 6993da59b1fccb2e4fe09be0f55e3d493935587e [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/task_queue.h"
39#include "rtc_base/thread.h"
40#include "system_wrappers/include/event_wrapper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "test/gtest.h"
42#include "test/testsupport/fileutils.h"
kwiberg77eab702016-09-28 17:42:01 -070043
44RTC_PUSH_IGNORING_WUNDEF()
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000045#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
leozwang@webrtc.org534e4952012-10-22 21:21:52 +000046#include "external/webrtc/webrtc/modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000047#else
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "modules/audio_processing/test/unittest.pb.h"
leozwang@webrtc.orga3736342012-03-16 21:36:00 +000049#endif
kwiberg77eab702016-09-28 17:42:01 -070050RTC_POP_IGNORING_WUNDEF()
niklase@google.com470e71d2011-07-07 08:21:25 +000051
andrew@webrtc.org27c69802014-02-18 20:24:56 +000052namespace webrtc {
niklase@google.com470e71d2011-07-07 08:21:25 +000053namespace {
andrew@webrtc.org17e40642014-03-04 20:58:13 +000054
ekmeyerson60d9b332015-08-14 10:35:55 -070055// TODO(ekmeyerson): Switch to using StreamConfig and ProcessingConfig where
56// applicable.
57
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +000058// TODO(bjornv): This is not feasible until the functionality has been
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +000059// re-implemented; see comment at the bottom of this file. For now, the user has
60// to hard code the |write_ref_data| value.
ajm@google.com59e41402011-07-28 17:34:04 +000061// When false, this will compare the output data with the results stored to
niklase@google.com470e71d2011-07-07 08:21:25 +000062// file. This is the typical case. When the file should be updated, it can
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +000063// be set to true with the command-line switch --write_ref_data.
64bool write_ref_data = false;
mbonadei7c2c8432017-04-07 00:59:12 -070065const int32_t kChannels[] = {1, 2};
Alejandro Luebs47748742015-05-22 12:00:21 -070066const int kSampleRates[] = {8000, 16000, 32000, 48000};
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +000067
aluebseb3603b2016-04-20 15:27:58 -070068#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
69// Android doesn't support 48kHz.
70const int kProcessSampleRates[] = {8000, 16000, 32000};
71#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
Alejandro Luebs47748742015-05-22 12:00:21 -070072const int kProcessSampleRates[] = {8000, 16000, 32000, 48000};
aluebseb3603b2016-04-20 15:27:58 -070073#endif
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +000074
ekmeyerson60d9b332015-08-14 10:35:55 -070075enum StreamDirection { kForward = 0, kReverse };
76
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000077void ConvertToFloat(const int16_t* int_data, ChannelBuffer<float>* cb) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000078 ChannelBuffer<int16_t> cb_int(cb->num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000079 cb->num_channels());
80 Deinterleave(int_data,
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000081 cb->num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000082 cb->num_channels(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000083 cb_int.channels());
Peter Kasting69558702016-01-12 16:26:35 -080084 for (size_t i = 0; i < cb->num_channels(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +000085 S16ToFloat(cb_int.channels()[i],
86 cb->num_frames(),
87 cb->channels()[i]);
88 }
andrew@webrtc.orga8b97372014-03-10 22:26:12 +000089}
andrew@webrtc.org17e40642014-03-04 20:58:13 +000090
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000091void ConvertToFloat(const AudioFrame& frame, ChannelBuffer<float>* cb) {
yujo36b1a5f2017-06-12 12:45:32 -070092 ConvertToFloat(frame.data(), cb);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +000093}
94
andrew@webrtc.org103657b2014-04-24 18:28:56 +000095// Number of channels including the keyboard channel.
Peter Kasting69558702016-01-12 16:26:35 -080096size_t TotalChannelsFromLayout(AudioProcessing::ChannelLayout layout) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +000097 switch (layout) {
98 case AudioProcessing::kMono:
99 return 1;
100 case AudioProcessing::kMonoAndKeyboard:
101 case AudioProcessing::kStereo:
102 return 2;
103 case AudioProcessing::kStereoAndKeyboard:
104 return 3;
105 }
kwiberg9e2be5f2016-09-14 05:23:22 -0700106 RTC_NOTREACHED();
pkasting25702cb2016-01-08 13:50:27 -0800107 return 0;
andrew@webrtc.org103657b2014-04-24 18:28:56 +0000108}
109
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000110int TruncateToMultipleOf10(int value) {
111 return (value / 10) * 10;
112}
113
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000114void MixStereoToMono(const float* stereo, float* mono,
pkasting25702cb2016-01-08 13:50:27 -0800115 size_t samples_per_channel) {
116 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000117 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) / 2;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000118}
119
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000120void MixStereoToMono(const int16_t* stereo, int16_t* mono,
pkasting25702cb2016-01-08 13:50:27 -0800121 size_t samples_per_channel) {
122 for (size_t i = 0; i < samples_per_channel; ++i)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000123 mono[i] = (stereo[i * 2] + stereo[i * 2 + 1]) >> 1;
124}
125
pkasting25702cb2016-01-08 13:50:27 -0800126void CopyLeftToRightChannel(int16_t* stereo, size_t samples_per_channel) {
127 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000128 stereo[i * 2 + 1] = stereo[i * 2];
129 }
130}
131
yujo36b1a5f2017-06-12 12:45:32 -0700132void VerifyChannelsAreEqual(const int16_t* stereo, size_t samples_per_channel) {
pkasting25702cb2016-01-08 13:50:27 -0800133 for (size_t i = 0; i < samples_per_channel; i++) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000134 EXPECT_EQ(stereo[i * 2 + 1], stereo[i * 2]);
135 }
136}
137
138void SetFrameTo(AudioFrame* frame, int16_t value) {
yujo36b1a5f2017-06-12 12:45:32 -0700139 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700140 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
141 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700142 frame_data[i] = value;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000143 }
144}
145
146void SetFrameTo(AudioFrame* frame, int16_t left, int16_t right) {
Peter Kasting69558702016-01-12 16:26:35 -0800147 ASSERT_EQ(2u, frame->num_channels_);
yujo36b1a5f2017-06-12 12:45:32 -0700148 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700149 for (size_t i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
yujo36b1a5f2017-06-12 12:45:32 -0700150 frame_data[i] = left;
151 frame_data[i + 1] = right;
andrew@webrtc.org81865342012-10-27 00:28:27 +0000152 }
153}
154
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000155void ScaleFrame(AudioFrame* frame, float scale) {
yujo36b1a5f2017-06-12 12:45:32 -0700156 int16_t* frame_data = frame->mutable_data();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700157 for (size_t i = 0; i < frame->samples_per_channel_ * frame->num_channels_;
158 ++i) {
yujo36b1a5f2017-06-12 12:45:32 -0700159 frame_data[i] = FloatS16ToS16(frame_data[i] * scale);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000160 }
161}
162
andrew@webrtc.org81865342012-10-27 00:28:27 +0000163bool FrameDataAreEqual(const AudioFrame& frame1, const AudioFrame& frame2) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000164 if (frame1.samples_per_channel_ != frame2.samples_per_channel_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000165 return false;
166 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000167 if (frame1.num_channels_ != frame2.num_channels_) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000168 return false;
169 }
yujo36b1a5f2017-06-12 12:45:32 -0700170 if (memcmp(frame1.data(), frame2.data(),
andrew@webrtc.org81865342012-10-27 00:28:27 +0000171 frame1.samples_per_channel_ * frame1.num_channels_ *
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000172 sizeof(int16_t))) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000173 return false;
174 }
175 return true;
176}
177
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000178void EnableAllAPComponents(AudioProcessing* ap) {
179#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
180 EXPECT_NOERR(ap->echo_control_mobile()->Enable(true));
181
182 EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveDigital));
183 EXPECT_NOERR(ap->gain_control()->Enable(true));
184#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
185 EXPECT_NOERR(ap->echo_cancellation()->enable_drift_compensation(true));
186 EXPECT_NOERR(ap->echo_cancellation()->enable_metrics(true));
187 EXPECT_NOERR(ap->echo_cancellation()->enable_delay_logging(true));
188 EXPECT_NOERR(ap->echo_cancellation()->Enable(true));
189
190 EXPECT_NOERR(ap->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
191 EXPECT_NOERR(ap->gain_control()->set_analog_level_limits(0, 255));
192 EXPECT_NOERR(ap->gain_control()->Enable(true));
193#endif
194
peah8271d042016-11-22 07:24:52 -0800195 AudioProcessing::Config apm_config;
196 apm_config.high_pass_filter.enabled = true;
197 ap->ApplyConfig(apm_config);
198
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000199 EXPECT_NOERR(ap->level_estimator()->Enable(true));
200 EXPECT_NOERR(ap->noise_suppression()->Enable(true));
201
202 EXPECT_NOERR(ap->voice_detection()->Enable(true));
203}
204
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +0000205// These functions are only used by ApmTest.Process.
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000206template <class T>
207T AbsValue(T a) {
208 return a > 0 ? a: -a;
209}
210
211int16_t MaxAudioFrame(const AudioFrame& frame) {
pkasting25702cb2016-01-08 13:50:27 -0800212 const size_t length = frame.samples_per_channel_ * frame.num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -0700213 const int16_t* frame_data = frame.data();
214 int16_t max_data = AbsValue(frame_data[0]);
pkasting25702cb2016-01-08 13:50:27 -0800215 for (size_t i = 1; i < length; i++) {
yujo36b1a5f2017-06-12 12:45:32 -0700216 max_data = std::max(max_data, AbsValue(frame_data[i]));
andrew@webrtc.orgd7696c42013-12-03 23:39:16 +0000217 }
218
219 return max_data;
220}
221
fischman@webrtc.orgf8be8df2013-12-17 23:46:39 +0000222#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
andrew@webrtc.org81865342012-10-27 00:28:27 +0000223void TestStats(const AudioProcessing::Statistic& test,
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000224 const audioproc::Test::Statistic& reference) {
minyue58530ed2016-05-24 05:50:12 -0700225 EXPECT_EQ(reference.instant(), test.instant);
226 EXPECT_EQ(reference.average(), test.average);
227 EXPECT_EQ(reference.maximum(), test.maximum);
228 EXPECT_EQ(reference.minimum(), test.minimum);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000229}
230
231void WriteStatsMessage(const AudioProcessing::Statistic& output,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000232 audioproc::Test::Statistic* msg) {
233 msg->set_instant(output.instant);
234 msg->set_average(output.average);
235 msg->set_maximum(output.maximum);
236 msg->set_minimum(output.minimum);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000237}
fischman@webrtc.orgf8be8df2013-12-17 23:46:39 +0000238#endif
andrew@webrtc.org81865342012-10-27 00:28:27 +0000239
Alex Loiko890988c2017-08-31 10:25:48 +0200240void OpenFileAndWriteMessage(const std::string& filename,
mbonadei7c2c8432017-04-07 00:59:12 -0700241 const MessageLite& msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000242 FILE* file = fopen(filename.c_str(), "wb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000243 ASSERT_TRUE(file != NULL);
244
Mirko Bonadei5b86f0a2017-11-29 15:20:26 +0100245 int32_t size = rtc::checked_cast<int32_t>(msg.ByteSizeLong());
andrew@webrtc.org81865342012-10-27 00:28:27 +0000246 ASSERT_GT(size, 0);
kwiberg62eaacf2016-02-17 06:39:05 -0800247 std::unique_ptr<uint8_t[]> array(new uint8_t[size]);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000248 ASSERT_TRUE(msg.SerializeToArray(array.get(), size));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000249
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000250 ASSERT_EQ(1u, fwrite(&size, sizeof(size), 1, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000251 ASSERT_EQ(static_cast<size_t>(size),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000252 fwrite(array.get(), sizeof(array[0]), size, file));
andrew@webrtc.org81865342012-10-27 00:28:27 +0000253 fclose(file);
254}
255
Alex Loiko890988c2017-08-31 10:25:48 +0200256std::string ResourceFilePath(const std::string& name, int sample_rate_hz) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000257 std::ostringstream ss;
258 // Resource files are all stereo.
259 ss << name << sample_rate_hz / 1000 << "_stereo";
260 return test::ResourcePath(ss.str(), "pcm");
261}
262
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000263// Temporary filenames unique to this process. Used to be able to run these
264// tests in parallel as each process needs to be running in isolation they can't
265// have competing filenames.
266std::map<std::string, std::string> temp_filenames;
267
Alex Loiko890988c2017-08-31 10:25:48 +0200268std::string OutputFilePath(const std::string& name,
andrew@webrtc.orgf26c9e82014-04-24 03:46:46 +0000269 int input_rate,
270 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -0700271 int reverse_input_rate,
272 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800273 size_t num_input_channels,
274 size_t num_output_channels,
275 size_t num_reverse_input_channels,
276 size_t num_reverse_output_channels,
ekmeyerson60d9b332015-08-14 10:35:55 -0700277 StreamDirection file_direction) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000278 std::ostringstream ss;
ekmeyerson60d9b332015-08-14 10:35:55 -0700279 ss << name << "_i" << num_input_channels << "_" << input_rate / 1000 << "_ir"
280 << num_reverse_input_channels << "_" << reverse_input_rate / 1000 << "_";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000281 if (num_output_channels == 1) {
282 ss << "mono";
283 } else if (num_output_channels == 2) {
284 ss << "stereo";
285 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700286 RTC_NOTREACHED();
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000287 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700288 ss << output_rate / 1000;
289 if (num_reverse_output_channels == 1) {
290 ss << "_rmono";
291 } else if (num_reverse_output_channels == 2) {
292 ss << "_rstereo";
293 } else {
kwiberg9e2be5f2016-09-14 05:23:22 -0700294 RTC_NOTREACHED();
ekmeyerson60d9b332015-08-14 10:35:55 -0700295 }
296 ss << reverse_output_rate / 1000;
297 ss << "_d" << file_direction << "_pcm";
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000298
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000299 std::string filename = ss.str();
pbosbb36fdf2015-07-09 07:48:14 -0700300 if (temp_filenames[filename].empty())
pbos@webrtc.orga525c982015-01-12 17:31:18 +0000301 temp_filenames[filename] = test::TempFilename(test::OutputPath(), filename);
302 return temp_filenames[filename];
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000303}
304
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000305void ClearTempFiles() {
306 for (auto& kv : temp_filenames)
307 remove(kv.second.c_str());
308}
309
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +0200310// Only remove "out" files. Keep "ref" files.
311void ClearTempOutFiles() {
312 for (auto it = temp_filenames.begin(); it != temp_filenames.end();) {
313 const std::string& filename = it->first;
314 if (filename.substr(0, 3).compare("out") == 0) {
315 remove(it->second.c_str());
316 temp_filenames.erase(it++);
317 } else {
318 it++;
319 }
320 }
321}
322
Alex Loiko890988c2017-08-31 10:25:48 +0200323void OpenFileAndReadMessage(const std::string& filename, MessageLite* msg) {
andrew@webrtc.org81865342012-10-27 00:28:27 +0000324 FILE* file = fopen(filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000325 ASSERT_TRUE(file != NULL);
326 ReadMessageFromFile(file, msg);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000327 fclose(file);
328}
329
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000330// Reads a 10 ms chunk of int16 interleaved audio from the given (assumed
331// stereo) file, converts to deinterleaved float (optionally downmixing) and
332// returns the result in |cb|. Returns false if the file ended (or on error) and
333// true otherwise.
334//
335// |int_data| and |float_data| are just temporary space that must be
336// sufficiently large to hold the 10 ms chunk.
337bool ReadChunk(FILE* file, int16_t* int_data, float* float_data,
338 ChannelBuffer<float>* cb) {
339 // The files always contain stereo audio.
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000340 size_t frame_size = cb->num_frames() * 2;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000341 size_t read_count = fread(int_data, sizeof(int16_t), frame_size, file);
342 if (read_count != frame_size) {
343 // Check that the file really ended.
kwiberg9e2be5f2016-09-14 05:23:22 -0700344 RTC_DCHECK(feof(file));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000345 return false; // This is expected.
346 }
347
348 S16ToFloat(int_data, frame_size, float_data);
349 if (cb->num_channels() == 1) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000350 MixStereoToMono(float_data, cb->channels()[0], cb->num_frames());
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000351 } else {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +0000352 Deinterleave(float_data, cb->num_frames(), 2,
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +0000353 cb->channels());
354 }
355
356 return true;
357}
358
niklase@google.com470e71d2011-07-07 08:21:25 +0000359class ApmTest : public ::testing::Test {
360 protected:
361 ApmTest();
362 virtual void SetUp();
363 virtual void TearDown();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000364
365 static void SetUpTestCase() {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000366 }
367
368 static void TearDownTestCase() {
pbos@webrtc.org200ac002015-02-03 14:14:01 +0000369 ClearTempFiles();
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000370 }
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000371
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000372 // Used to select between int and float interface tests.
373 enum Format {
374 kIntFormat,
375 kFloatFormat
376 };
377
378 void Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000379 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000380 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800381 size_t num_input_channels,
382 size_t num_output_channels,
383 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000384 bool open_output_file);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000385 void Init(AudioProcessing* ap);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000386 void EnableAllComponents();
387 bool ReadFrame(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000388 bool ReadFrame(FILE* file, AudioFrame* frame, ChannelBuffer<float>* cb);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000389 void ReadFrameWithRewind(FILE* file, AudioFrame* frame);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000390 void ReadFrameWithRewind(FILE* file, AudioFrame* frame,
391 ChannelBuffer<float>* cb);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000392 void ProcessWithDefaultStreamParameters(AudioFrame* frame);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000393 void ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
394 int delay_min, int delay_max);
Michael Graczyk86c6d332015-07-23 11:41:39 -0700395 void TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800396 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700397 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800398 void TestChangingForwardChannels(size_t num_in_channels,
399 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700400 AudioProcessing::Error expected_return);
Peter Kasting69558702016-01-12 16:26:35 -0800401 void TestChangingReverseChannels(size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700402 AudioProcessing::Error expected_return);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000403 void RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate);
404 void RunManualVolumeChangeIsPossibleTest(int sample_rate);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000405 void StreamParametersTest(Format format);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000406 int ProcessStreamChooser(Format format);
407 int AnalyzeReverseStreamChooser(Format format);
408 void ProcessDebugDump(const std::string& in_filename,
409 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -0800410 Format format,
411 int max_size_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000412 void VerifyDebugDumpTest(Format format);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000413
414 const std::string output_path_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000415 const std::string ref_filename_;
kwiberg62eaacf2016-02-17 06:39:05 -0800416 std::unique_ptr<AudioProcessing> apm_;
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000417 AudioFrame* frame_;
418 AudioFrame* revframe_;
kwiberg62eaacf2016-02-17 06:39:05 -0800419 std::unique_ptr<ChannelBuffer<float> > float_cb_;
420 std::unique_ptr<ChannelBuffer<float> > revfloat_cb_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000421 int output_sample_rate_hz_;
Peter Kasting69558702016-01-12 16:26:35 -0800422 size_t num_output_channels_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000423 FILE* far_file_;
424 FILE* near_file_;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000425 FILE* out_file_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000426};
427
428ApmTest::ApmTest()
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000429 : output_path_(test::OutputPath()),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000430#if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800431 ref_filename_(test::ResourcePath("audio_processing/output_data_fixed",
432 "pb")),
andrew@webrtc.org293d22b2012-01-30 22:04:26 +0000433#elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000434#if defined(WEBRTC_MAC)
435 // A different file for Mac is needed because on this platform the AEC
436 // constant |kFixedDelayMs| value is 20 and not 50 as it is on the rest.
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800437 ref_filename_(test::ResourcePath("audio_processing/output_data_mac",
438 "pb")),
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000439#else
ehmaldonadodedaf1c2016-11-18 04:52:22 -0800440 ref_filename_(test::ResourcePath("audio_processing/output_data_float",
441 "pb")),
kjellander@webrtc.org61f07c32011-10-18 06:54:58 +0000442#endif
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +0000443#endif
niklase@google.com470e71d2011-07-07 08:21:25 +0000444 frame_(NULL),
ajm@google.com22e65152011-07-18 18:03:01 +0000445 revframe_(NULL),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000446 output_sample_rate_hz_(0),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000447 num_output_channels_(0),
ajm@google.com22e65152011-07-18 18:03:01 +0000448 far_file_(NULL),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000449 near_file_(NULL),
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000450 out_file_(NULL) {
451 Config config;
452 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +0100453 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +0000454}
niklase@google.com470e71d2011-07-07 08:21:25 +0000455
456void ApmTest::SetUp() {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +0000457 ASSERT_TRUE(apm_.get() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000458
459 frame_ = new AudioFrame();
460 revframe_ = new AudioFrame();
461
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000462 Init(32000, 32000, 32000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000463}
464
465void ApmTest::TearDown() {
466 if (frame_) {
467 delete frame_;
468 }
469 frame_ = NULL;
470
471 if (revframe_) {
472 delete revframe_;
473 }
474 revframe_ = NULL;
475
476 if (far_file_) {
477 ASSERT_EQ(0, fclose(far_file_));
478 }
479 far_file_ = NULL;
480
481 if (near_file_) {
482 ASSERT_EQ(0, fclose(near_file_));
483 }
484 near_file_ = NULL;
485
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000486 if (out_file_) {
487 ASSERT_EQ(0, fclose(out_file_));
488 }
489 out_file_ = NULL;
niklase@google.com470e71d2011-07-07 08:21:25 +0000490}
491
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000492void ApmTest::Init(AudioProcessing* ap) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000493 ASSERT_EQ(kNoErr,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700494 ap->Initialize(
495 {{{frame_->sample_rate_hz_, frame_->num_channels_},
496 {output_sample_rate_hz_, num_output_channels_},
ekmeyerson60d9b332015-08-14 10:35:55 -0700497 {revframe_->sample_rate_hz_, revframe_->num_channels_},
Michael Graczyk86c6d332015-07-23 11:41:39 -0700498 {revframe_->sample_rate_hz_, revframe_->num_channels_}}}));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000499}
500
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000501void ApmTest::Init(int sample_rate_hz,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000502 int output_sample_rate_hz,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000503 int reverse_sample_rate_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800504 size_t num_input_channels,
505 size_t num_output_channels,
506 size_t num_reverse_channels,
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000507 bool open_output_file) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000508 SetContainerFormat(sample_rate_hz, num_input_channels, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000509 output_sample_rate_hz_ = output_sample_rate_hz;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000510 num_output_channels_ = num_output_channels;
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000511
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000512 SetContainerFormat(reverse_sample_rate_hz, num_reverse_channels, revframe_,
513 &revfloat_cb_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000514 Init(apm_.get());
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000515
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000516 if (far_file_) {
517 ASSERT_EQ(0, fclose(far_file_));
518 }
519 std::string filename = ResourceFilePath("far", sample_rate_hz);
520 far_file_ = fopen(filename.c_str(), "rb");
521 ASSERT_TRUE(far_file_ != NULL) << "Could not open file " <<
522 filename << "\n";
523
524 if (near_file_) {
525 ASSERT_EQ(0, fclose(near_file_));
526 }
527 filename = ResourceFilePath("near", sample_rate_hz);
528 near_file_ = fopen(filename.c_str(), "rb");
529 ASSERT_TRUE(near_file_ != NULL) << "Could not open file " <<
530 filename << "\n";
531
532 if (open_output_file) {
533 if (out_file_) {
534 ASSERT_EQ(0, fclose(out_file_));
535 }
ekmeyerson60d9b332015-08-14 10:35:55 -0700536 filename = OutputFilePath(
537 "out", sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz,
538 reverse_sample_rate_hz, num_input_channels, num_output_channels,
539 num_reverse_channels, num_reverse_channels, kForward);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +0000540 out_file_ = fopen(filename.c_str(), "wb");
541 ASSERT_TRUE(out_file_ != NULL) << "Could not open file " <<
542 filename << "\n";
543 }
544}
545
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000546void ApmTest::EnableAllComponents() {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000547 EnableAllAPComponents(apm_.get());
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000548}
549
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000550bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame,
551 ChannelBuffer<float>* cb) {
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000552 // The files always contain stereo audio.
553 size_t frame_size = frame->samples_per_channel_ * 2;
yujo36b1a5f2017-06-12 12:45:32 -0700554 size_t read_count = fread(frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000555 sizeof(int16_t),
556 frame_size,
557 file);
558 if (read_count != frame_size) {
559 // Check that the file really ended.
560 EXPECT_NE(0, feof(file));
561 return false; // This is expected.
562 }
563
564 if (frame->num_channels_ == 1) {
yujo36b1a5f2017-06-12 12:45:32 -0700565 MixStereoToMono(frame->data(), frame->mutable_data(),
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000566 frame->samples_per_channel_);
567 }
568
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000569 if (cb) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000570 ConvertToFloat(*frame, cb);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000571 }
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +0000572 return true;
ajm@google.coma769fa52011-07-13 21:57:58 +0000573}
574
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000575bool ApmTest::ReadFrame(FILE* file, AudioFrame* frame) {
576 return ReadFrame(file, frame, NULL);
577}
578
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000579// If the end of the file has been reached, rewind it and attempt to read the
580// frame again.
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000581void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame,
582 ChannelBuffer<float>* cb) {
583 if (!ReadFrame(near_file_, frame_, cb)) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000584 rewind(near_file_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000585 ASSERT_TRUE(ReadFrame(near_file_, frame_, cb));
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000586 }
587}
588
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000589void ApmTest::ReadFrameWithRewind(FILE* file, AudioFrame* frame) {
590 ReadFrameWithRewind(file, frame, NULL);
591}
592
andrew@webrtc.org81865342012-10-27 00:28:27 +0000593void ApmTest::ProcessWithDefaultStreamParameters(AudioFrame* frame) {
594 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000595 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org81865342012-10-27 00:28:27 +0000596 EXPECT_EQ(apm_->kNoError,
597 apm_->gain_control()->set_stream_analog_level(127));
598 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +0000599}
600
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000601int ApmTest::ProcessStreamChooser(Format format) {
602 if (format == kIntFormat) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000603 return apm_->ProcessStream(frame_);
604 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000605 return apm_->ProcessStream(float_cb_->channels(),
606 frame_->samples_per_channel_,
607 frame_->sample_rate_hz_,
608 LayoutFromChannels(frame_->num_channels_),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000609 output_sample_rate_hz_,
610 LayoutFromChannels(num_output_channels_),
611 float_cb_->channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000612}
613
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000614int ApmTest::AnalyzeReverseStreamChooser(Format format) {
615 if (format == kIntFormat) {
aluebsb0319552016-03-17 20:39:53 -0700616 return apm_->ProcessReverseStream(revframe_);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000617 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000618 return apm_->AnalyzeReverseStream(
619 revfloat_cb_->channels(),
620 revframe_->samples_per_channel_,
621 revframe_->sample_rate_hz_,
622 LayoutFromChannels(revframe_->num_channels_));
623}
624
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000625void ApmTest::ProcessDelayVerificationTest(int delay_ms, int system_delay_ms,
626 int delay_min, int delay_max) {
627 // The |revframe_| and |frame_| should include the proper frame information,
628 // hence can be used for extracting information.
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000629 AudioFrame tmp_frame;
630 std::queue<AudioFrame*> frame_queue;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000631 bool causal = true;
632
633 tmp_frame.CopyFrom(*revframe_);
634 SetFrameTo(&tmp_frame, 0);
635
636 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
637 // Initialize the |frame_queue| with empty frames.
638 int frame_delay = delay_ms / 10;
639 while (frame_delay < 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000640 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000641 frame->CopyFrom(tmp_frame);
642 frame_queue.push(frame);
643 frame_delay++;
644 causal = false;
645 }
646 while (frame_delay > 0) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000647 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000648 frame->CopyFrom(tmp_frame);
649 frame_queue.push(frame);
650 frame_delay--;
651 }
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000652 // Run for 4.5 seconds, skipping statistics from the first 2.5 seconds. We
653 // need enough frames with audio to have reliable estimates, but as few as
654 // possible to keep processing time down. 4.5 seconds seemed to be a good
655 // compromise for this recording.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000656 for (int frame_count = 0; frame_count < 450; ++frame_count) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000657 AudioFrame* frame = new AudioFrame();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000658 frame->CopyFrom(tmp_frame);
659 // Use the near end recording, since that has more speech in it.
660 ASSERT_TRUE(ReadFrame(near_file_, frame));
661 frame_queue.push(frame);
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000662 AudioFrame* reverse_frame = frame;
663 AudioFrame* process_frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000664 if (!causal) {
665 reverse_frame = frame_queue.front();
666 // When we call ProcessStream() the frame is modified, so we can't use the
667 // pointer directly when things are non-causal. Use an intermediate frame
668 // and copy the data.
669 process_frame = &tmp_frame;
670 process_frame->CopyFrom(*frame);
671 }
aluebsb0319552016-03-17 20:39:53 -0700672 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(reverse_frame));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000673 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(system_delay_ms));
674 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(process_frame));
675 frame = frame_queue.front();
676 frame_queue.pop();
677 delete frame;
678
bjornv@webrtc.orgbbd47fc2014-01-13 08:54:34 +0000679 if (frame_count == 250) {
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000680 int median;
681 int std;
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000682 float poor_fraction;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000683 // Discard the first delay metrics to avoid convergence effects.
684 EXPECT_EQ(apm_->kNoError,
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000685 apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
686 &poor_fraction));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000687 }
688 }
689
690 rewind(near_file_);
691 while (!frame_queue.empty()) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +0000692 AudioFrame* frame = frame_queue.front();
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000693 frame_queue.pop();
694 delete frame;
695 }
696 // Calculate expected delay estimate and acceptable regions. Further,
697 // limit them w.r.t. AEC delay estimation support.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700698 const size_t samples_per_ms =
kwiberg7885d3f2017-04-25 12:35:07 -0700699 rtc::SafeMin<size_t>(16u, frame_->samples_per_channel_ / 10);
kwiberg07038562017-06-12 11:40:47 -0700700 const int expected_median =
701 rtc::SafeClamp<int>(delay_ms - system_delay_ms, delay_min, delay_max);
702 const int expected_median_high = rtc::SafeClamp<int>(
703 expected_median + rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700704 delay_max);
kwiberg07038562017-06-12 11:40:47 -0700705 const int expected_median_low = rtc::SafeClamp<int>(
706 expected_median - rtc::dchecked_cast<int>(96 / samples_per_ms), delay_min,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700707 delay_max);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000708 // Verify delay metrics.
709 int median;
710 int std;
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000711 float poor_fraction;
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000712 EXPECT_EQ(apm_->kNoError,
bjornv@webrtc.orgb1786db2015-02-03 06:06:26 +0000713 apm_->echo_cancellation()->GetDelayMetrics(&median, &std,
714 &poor_fraction));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000715 EXPECT_GE(expected_median_high, median);
716 EXPECT_LE(expected_median_low, median);
717}
718
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000719void ApmTest::StreamParametersTest(Format format) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000720 // No errors when the components are disabled.
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000721 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000722
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000723 // -- Missing AGC level --
niklase@google.com470e71d2011-07-07 08:21:25 +0000724 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000725 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000726 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000727
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000728 // Resets after successful ProcessStream().
niklase@google.com470e71d2011-07-07 08:21:25 +0000729 EXPECT_EQ(apm_->kNoError,
730 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000731 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000732 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000733 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000734
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000735 // Other stream parameters set correctly.
736 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
niklase@google.com470e71d2011-07-07 08:21:25 +0000737 EXPECT_EQ(apm_->kNoError,
738 apm_->echo_cancellation()->enable_drift_compensation(true));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000739 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000740 apm_->echo_cancellation()->set_stream_drift_samples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +0000741 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000742 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000743 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
744 EXPECT_EQ(apm_->kNoError,
745 apm_->echo_cancellation()->enable_drift_compensation(false));
746
747 // -- Missing delay --
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000748 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000749 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000750 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000751 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000752
753 // Resets after successful ProcessStream().
754 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000755 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000756 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000757 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000758
759 // Other stream parameters set correctly.
760 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
761 EXPECT_EQ(apm_->kNoError,
762 apm_->echo_cancellation()->enable_drift_compensation(true));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000763 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000764 EXPECT_EQ(apm_->kNoError,
765 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000766 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000767 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000768 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
769
770 // -- Missing drift --
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000771 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000772 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000773
774 // Resets after successful ProcessStream().
775 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000776 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000777 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000778 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000779 ProcessStreamChooser(format));
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000780
781 // Other stream parameters set correctly.
niklase@google.com470e71d2011-07-07 08:21:25 +0000782 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
783 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
784 EXPECT_EQ(apm_->kNoError,
785 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000786 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000787 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000788
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000789 // -- No stream parameters --
niklase@google.com470e71d2011-07-07 08:21:25 +0000790 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000791 AnalyzeReverseStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000792 EXPECT_EQ(apm_->kStreamParameterNotSetError,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000793 ProcessStreamChooser(format));
niklase@google.com470e71d2011-07-07 08:21:25 +0000794
andrew@webrtc.org1e916932011-11-29 18:28:57 +0000795 // -- All there --
niklase@google.com470e71d2011-07-07 08:21:25 +0000796 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +0000797 apm_->echo_cancellation()->set_stream_drift_samples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +0000798 EXPECT_EQ(apm_->kNoError,
799 apm_->gain_control()->set_stream_analog_level(127));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000800 EXPECT_EQ(apm_->kNoError, ProcessStreamChooser(format));
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000801}
802
803TEST_F(ApmTest, StreamParametersInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000804 StreamParametersTest(kIntFormat);
andrew@webrtc.org17e40642014-03-04 20:58:13 +0000805}
806
807TEST_F(ApmTest, StreamParametersFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000808 StreamParametersTest(kFloatFormat);
niklase@google.com470e71d2011-07-07 08:21:25 +0000809}
810
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000811TEST_F(ApmTest, DefaultDelayOffsetIsZero) {
812 EXPECT_EQ(0, apm_->delay_offset_ms());
813 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(50));
814 EXPECT_EQ(50, apm_->stream_delay_ms());
815}
816
817TEST_F(ApmTest, DelayOffsetWithLimitsIsSetProperly) {
818 // High limit of 500 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000819 apm_->set_delay_offset_ms(100);
820 EXPECT_EQ(100, apm_->delay_offset_ms());
821 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(450));
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000822 EXPECT_EQ(500, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000823 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
824 EXPECT_EQ(200, apm_->stream_delay_ms());
825
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000826 // Low limit of 0 ms.
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000827 apm_->set_delay_offset_ms(-50);
828 EXPECT_EQ(-50, apm_->delay_offset_ms());
andrew@webrtc.org5f23d642012-05-29 21:14:06 +0000829 EXPECT_EQ(apm_->kBadStreamParameterWarning, apm_->set_stream_delay_ms(20));
830 EXPECT_EQ(0, apm_->stream_delay_ms());
andrew@webrtc.org6f9f8172012-03-06 19:03:39 +0000831 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(100));
832 EXPECT_EQ(50, apm_->stream_delay_ms());
833}
834
Michael Graczyk86c6d332015-07-23 11:41:39 -0700835void ApmTest::TestChangingChannelsInt16Interface(
Peter Kasting69558702016-01-12 16:26:35 -0800836 size_t num_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700837 AudioProcessing::Error expected_return) {
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000838 frame_->num_channels_ = num_channels;
839 EXPECT_EQ(expected_return, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -0700840 EXPECT_EQ(expected_return, apm_->ProcessReverseStream(frame_));
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000841}
842
Michael Graczyk86c6d332015-07-23 11:41:39 -0700843void ApmTest::TestChangingForwardChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800844 size_t num_in_channels,
845 size_t num_out_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700846 AudioProcessing::Error expected_return) {
847 const StreamConfig input_stream = {frame_->sample_rate_hz_, num_in_channels};
848 const StreamConfig output_stream = {output_sample_rate_hz_, num_out_channels};
849
850 EXPECT_EQ(expected_return,
851 apm_->ProcessStream(float_cb_->channels(), input_stream,
852 output_stream, float_cb_->channels()));
853}
854
855void ApmTest::TestChangingReverseChannels(
Peter Kasting69558702016-01-12 16:26:35 -0800856 size_t num_rev_channels,
Michael Graczyk86c6d332015-07-23 11:41:39 -0700857 AudioProcessing::Error expected_return) {
858 const ProcessingConfig processing_config = {
ekmeyerson60d9b332015-08-14 10:35:55 -0700859 {{frame_->sample_rate_hz_, apm_->num_input_channels()},
860 {output_sample_rate_hz_, apm_->num_output_channels()},
861 {frame_->sample_rate_hz_, num_rev_channels},
862 {frame_->sample_rate_hz_, num_rev_channels}}};
Michael Graczyk86c6d332015-07-23 11:41:39 -0700863
ekmeyerson60d9b332015-08-14 10:35:55 -0700864 EXPECT_EQ(
865 expected_return,
866 apm_->ProcessReverseStream(
867 float_cb_->channels(), processing_config.reverse_input_stream(),
868 processing_config.reverse_output_stream(), float_cb_->channels()));
Michael Graczyk86c6d332015-07-23 11:41:39 -0700869}
870
871TEST_F(ApmTest, ChannelsInt16Interface) {
872 // Testing number of invalid and valid channels.
873 Init(16000, 16000, 16000, 4, 4, 4, false);
874
875 TestChangingChannelsInt16Interface(0, apm_->kBadNumberChannelsError);
876
Peter Kasting69558702016-01-12 16:26:35 -0800877 for (size_t i = 1; i < 4; i++) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700878 TestChangingChannelsInt16Interface(i, kNoErr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000879 EXPECT_EQ(i, apm_->num_input_channels());
niklase@google.com470e71d2011-07-07 08:21:25 +0000880 }
881}
882
Michael Graczyk86c6d332015-07-23 11:41:39 -0700883TEST_F(ApmTest, Channels) {
884 // Testing number of invalid and valid channels.
885 Init(16000, 16000, 16000, 4, 4, 4, false);
886
887 TestChangingForwardChannels(0, 1, apm_->kBadNumberChannelsError);
888 TestChangingReverseChannels(0, apm_->kBadNumberChannelsError);
889
Peter Kasting69558702016-01-12 16:26:35 -0800890 for (size_t i = 1; i < 4; ++i) {
891 for (size_t j = 0; j < 1; ++j) {
Michael Graczyk86c6d332015-07-23 11:41:39 -0700892 // Output channels much be one or match input channels.
893 if (j == 1 || i == j) {
894 TestChangingForwardChannels(i, j, kNoErr);
895 TestChangingReverseChannels(i, kNoErr);
896
897 EXPECT_EQ(i, apm_->num_input_channels());
898 EXPECT_EQ(j, apm_->num_output_channels());
899 // The number of reverse channels used for processing to is always 1.
Peter Kasting69558702016-01-12 16:26:35 -0800900 EXPECT_EQ(1u, apm_->num_reverse_channels());
Michael Graczyk86c6d332015-07-23 11:41:39 -0700901 } else {
902 TestChangingForwardChannels(i, j,
903 AudioProcessing::kBadNumberChannelsError);
904 }
905 }
906 }
907}
908
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000909TEST_F(ApmTest, SampleRatesInt) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000910 // Testing invalid sample rates
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000911 SetContainerFormat(10000, 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000912 EXPECT_EQ(apm_->kBadSampleRateError, ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000913 // Testing valid sample rates
Alejandro Luebs47748742015-05-22 12:00:21 -0700914 int fs[] = {8000, 16000, 32000, 48000};
pkasting25702cb2016-01-08 13:50:27 -0800915 for (size_t i = 0; i < arraysize(fs); i++) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +0000916 SetContainerFormat(fs[i], 2, frame_, &float_cb_);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +0000917 EXPECT_NOERR(ProcessStreamChooser(kIntFormat));
niklase@google.com470e71d2011-07-07 08:21:25 +0000918 }
919}
920
niklase@google.com470e71d2011-07-07 08:21:25 +0000921TEST_F(ApmTest, EchoCancellation) {
922 EXPECT_EQ(apm_->kNoError,
923 apm_->echo_cancellation()->enable_drift_compensation(true));
924 EXPECT_TRUE(apm_->echo_cancellation()->is_drift_compensation_enabled());
925 EXPECT_EQ(apm_->kNoError,
926 apm_->echo_cancellation()->enable_drift_compensation(false));
927 EXPECT_FALSE(apm_->echo_cancellation()->is_drift_compensation_enabled());
928
niklase@google.com470e71d2011-07-07 08:21:25 +0000929 EchoCancellation::SuppressionLevel level[] = {
930 EchoCancellation::kLowSuppression,
931 EchoCancellation::kModerateSuppression,
932 EchoCancellation::kHighSuppression,
933 };
pkasting25702cb2016-01-08 13:50:27 -0800934 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000935 EXPECT_EQ(apm_->kNoError,
936 apm_->echo_cancellation()->set_suppression_level(level[i]));
937 EXPECT_EQ(level[i],
938 apm_->echo_cancellation()->suppression_level());
939 }
940
941 EchoCancellation::Metrics metrics;
942 EXPECT_EQ(apm_->kNotEnabledError,
943 apm_->echo_cancellation()->GetMetrics(&metrics));
944
ivoc3e9a5372016-10-28 07:55:33 -0700945 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
946 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
947
niklase@google.com470e71d2011-07-07 08:21:25 +0000948 EXPECT_EQ(apm_->kNoError,
949 apm_->echo_cancellation()->enable_metrics(true));
950 EXPECT_TRUE(apm_->echo_cancellation()->are_metrics_enabled());
951 EXPECT_EQ(apm_->kNoError,
952 apm_->echo_cancellation()->enable_metrics(false));
953 EXPECT_FALSE(apm_->echo_cancellation()->are_metrics_enabled());
954
ivoc48dfab52016-10-28 03:29:31 -0700955 EXPECT_EQ(apm_->kNoError,
956 apm_->echo_cancellation()->enable_delay_logging(true));
957 EXPECT_TRUE(apm_->echo_cancellation()->is_delay_logging_enabled());
958 EXPECT_EQ(apm_->kNoError,
959 apm_->echo_cancellation()->enable_delay_logging(false));
960 EXPECT_FALSE(apm_->echo_cancellation()->is_delay_logging_enabled());
961
ivoc3e9a5372016-10-28 07:55:33 -0700962 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
963 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
964
965 int median = 0;
966 int std = 0;
967 float poor_fraction = 0;
968 EXPECT_EQ(apm_->kNotEnabledError, apm_->echo_cancellation()->GetDelayMetrics(
969 &median, &std, &poor_fraction));
970
niklase@google.com470e71d2011-07-07 08:21:25 +0000971 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
972 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
973 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
974 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
bjornv@webrtc.org91d11b32013-03-05 16:53:09 +0000975
976 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
977 EXPECT_TRUE(apm_->echo_cancellation()->is_enabled());
978 EXPECT_TRUE(apm_->echo_cancellation()->aec_core() != NULL);
979 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(false));
980 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
981 EXPECT_FALSE(apm_->echo_cancellation()->aec_core() != NULL);
niklase@google.com470e71d2011-07-07 08:21:25 +0000982}
983
bjornv@webrtc.org84f8ec12014-06-19 12:14:33 +0000984TEST_F(ApmTest, DISABLED_EchoCancellationReportsCorrectDelays) {
bjornv@webrtc.orgbac00122015-01-02 09:23:49 +0000985 // TODO(bjornv): Fix this test to work with DA-AEC.
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000986 // Enable AEC only.
987 EXPECT_EQ(apm_->kNoError,
988 apm_->echo_cancellation()->enable_drift_compensation(false));
989 EXPECT_EQ(apm_->kNoError,
990 apm_->echo_cancellation()->enable_metrics(false));
991 EXPECT_EQ(apm_->kNoError,
992 apm_->echo_cancellation()->enable_delay_logging(true));
993 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000994 Config config;
henrik.lundin0f133b92015-07-02 00:17:55 -0700995 config.Set<DelayAgnostic>(new DelayAgnostic(false));
bjornv@webrtc.org5c3f4e32014-06-19 09:51:29 +0000996 apm_->SetExtraOptions(config);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +0000997
998 // Internally in the AEC the amount of lookahead the delay estimation can
999 // handle is 15 blocks and the maximum delay is set to 60 blocks.
1000 const int kLookaheadBlocks = 15;
1001 const int kMaxDelayBlocks = 60;
1002 // The AEC has a startup time before it actually starts to process. This
1003 // procedure can flush the internal far-end buffer, which of course affects
1004 // the delay estimation. Therefore, we set a system_delay high enough to
1005 // avoid that. The smallest system_delay you can report without flushing the
1006 // buffer is 66 ms in 8 kHz.
1007 //
1008 // It is known that for 16 kHz (and 32 kHz) sampling frequency there is an
1009 // additional stuffing of 8 ms on the fly, but it seems to have no impact on
1010 // delay estimation. This should be noted though. In case of test failure,
1011 // this could be the cause.
1012 const int kSystemDelayMs = 66;
1013 // Test a couple of corner cases and verify that the estimated delay is
1014 // within a valid region (set to +-1.5 blocks). Note that these cases are
1015 // sampling frequency dependent.
pkasting25702cb2016-01-08 13:50:27 -08001016 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001017 Init(kProcessSampleRates[i],
1018 kProcessSampleRates[i],
1019 kProcessSampleRates[i],
1020 2,
1021 2,
1022 2,
1023 false);
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001024 // Sampling frequency dependent variables.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001025 const int num_ms_per_block =
1026 std::max(4, static_cast<int>(640 / frame_->samples_per_channel_));
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001027 const int delay_min_ms = -kLookaheadBlocks * num_ms_per_block;
1028 const int delay_max_ms = (kMaxDelayBlocks - 1) * num_ms_per_block;
1029
1030 // 1) Verify correct delay estimate at lookahead boundary.
1031 int delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_min_ms);
1032 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1033 delay_max_ms);
1034 // 2) A delay less than maximum lookahead should give an delay estimate at
1035 // the boundary (= -kLookaheadBlocks * num_ms_per_block).
1036 delay_ms -= 20;
1037 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1038 delay_max_ms);
1039 // 3) Three values around zero delay. Note that we need to compensate for
1040 // the fake system_delay.
1041 delay_ms = TruncateToMultipleOf10(kSystemDelayMs - 10);
1042 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1043 delay_max_ms);
1044 delay_ms = TruncateToMultipleOf10(kSystemDelayMs);
1045 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1046 delay_max_ms);
1047 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + 10);
1048 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1049 delay_max_ms);
1050 // 4) Verify correct delay estimate at maximum delay boundary.
1051 delay_ms = TruncateToMultipleOf10(kSystemDelayMs + delay_max_ms);
1052 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1053 delay_max_ms);
1054 // 5) A delay above the maximum delay should give an estimate at the
1055 // boundary (= (kMaxDelayBlocks - 1) * num_ms_per_block).
1056 delay_ms += 20;
1057 ProcessDelayVerificationTest(delay_ms, kSystemDelayMs, delay_min_ms,
1058 delay_max_ms);
1059 }
1060}
1061
niklase@google.com470e71d2011-07-07 08:21:25 +00001062TEST_F(ApmTest, EchoControlMobile) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001063 // Turn AECM on (and AEC off)
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001064 Init(16000, 16000, 16000, 2, 2, 2, false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001065 EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(true));
1066 EXPECT_TRUE(apm_->echo_control_mobile()->is_enabled());
1067
niklase@google.com470e71d2011-07-07 08:21:25 +00001068 // Toggle routing modes
1069 EchoControlMobile::RoutingMode mode[] = {
1070 EchoControlMobile::kQuietEarpieceOrHeadset,
1071 EchoControlMobile::kEarpiece,
1072 EchoControlMobile::kLoudEarpiece,
1073 EchoControlMobile::kSpeakerphone,
1074 EchoControlMobile::kLoudSpeakerphone,
1075 };
pkasting25702cb2016-01-08 13:50:27 -08001076 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001077 EXPECT_EQ(apm_->kNoError,
1078 apm_->echo_control_mobile()->set_routing_mode(mode[i]));
1079 EXPECT_EQ(mode[i],
1080 apm_->echo_control_mobile()->routing_mode());
1081 }
1082 // Turn comfort noise off/on
1083 EXPECT_EQ(apm_->kNoError,
1084 apm_->echo_control_mobile()->enable_comfort_noise(false));
1085 EXPECT_FALSE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
1086 EXPECT_EQ(apm_->kNoError,
1087 apm_->echo_control_mobile()->enable_comfort_noise(true));
1088 EXPECT_TRUE(apm_->echo_control_mobile()->is_comfort_noise_enabled());
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001089 // Set and get echo path
ajm@google.com22e65152011-07-18 18:03:01 +00001090 const size_t echo_path_size =
1091 apm_->echo_control_mobile()->echo_path_size_bytes();
kwiberg62eaacf2016-02-17 06:39:05 -08001092 std::unique_ptr<char[]> echo_path_in(new char[echo_path_size]);
1093 std::unique_ptr<char[]> echo_path_out(new char[echo_path_size]);
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001094 EXPECT_EQ(apm_->kNullPointerError,
1095 apm_->echo_control_mobile()->SetEchoPath(NULL, echo_path_size));
1096 EXPECT_EQ(apm_->kNullPointerError,
1097 apm_->echo_control_mobile()->GetEchoPath(NULL, echo_path_size));
1098 EXPECT_EQ(apm_->kBadParameterError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001099 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(), 1));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001100 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001101 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001102 echo_path_size));
ajm@google.com22e65152011-07-18 18:03:01 +00001103 for (size_t i = 0; i < echo_path_size; i++) {
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001104 echo_path_in[i] = echo_path_out[i] + 1;
1105 }
1106 EXPECT_EQ(apm_->kBadParameterError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001107 apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(), 1));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001108 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001109 apm_->echo_control_mobile()->SetEchoPath(echo_path_in.get(),
1110 echo_path_size));
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001111 EXPECT_EQ(apm_->kNoError,
andrew@webrtc.org3119ecf2011-11-01 17:00:18 +00001112 apm_->echo_control_mobile()->GetEchoPath(echo_path_out.get(),
1113 echo_path_size));
ajm@google.com22e65152011-07-18 18:03:01 +00001114 for (size_t i = 0; i < echo_path_size; i++) {
bjornv@google.comc4b939c2011-07-13 08:09:56 +00001115 EXPECT_EQ(echo_path_in[i], echo_path_out[i]);
1116 }
andrew@webrtc.org75f19482012-02-09 17:16:18 +00001117
1118 // Process a few frames with NS in the default disabled state. This exercises
1119 // a different codepath than with it enabled.
1120 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1121 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1122 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
1123 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1124
niklase@google.com470e71d2011-07-07 08:21:25 +00001125 // Turn AECM off
1126 EXPECT_EQ(apm_->kNoError, apm_->echo_control_mobile()->Enable(false));
1127 EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1128}
1129
aluebs@webrtc.orgc9ee4122014-02-03 14:41:57 +00001130TEST_F(ApmTest, GainControl) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001131 // Testing gain modes
niklase@google.com470e71d2011-07-07 08:21:25 +00001132 EXPECT_EQ(apm_->kNoError,
1133 apm_->gain_control()->set_mode(
1134 apm_->gain_control()->mode()));
1135
1136 GainControl::Mode mode[] = {
1137 GainControl::kAdaptiveAnalog,
1138 GainControl::kAdaptiveDigital,
1139 GainControl::kFixedDigital
1140 };
pkasting25702cb2016-01-08 13:50:27 -08001141 for (size_t i = 0; i < arraysize(mode); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001142 EXPECT_EQ(apm_->kNoError,
1143 apm_->gain_control()->set_mode(mode[i]));
1144 EXPECT_EQ(mode[i], apm_->gain_control()->mode());
1145 }
1146 // Testing invalid target levels
1147 EXPECT_EQ(apm_->kBadParameterError,
1148 apm_->gain_control()->set_target_level_dbfs(-3));
1149 EXPECT_EQ(apm_->kBadParameterError,
1150 apm_->gain_control()->set_target_level_dbfs(-40));
1151 // Testing valid target levels
1152 EXPECT_EQ(apm_->kNoError,
1153 apm_->gain_control()->set_target_level_dbfs(
1154 apm_->gain_control()->target_level_dbfs()));
1155
1156 int level_dbfs[] = {0, 6, 31};
pkasting25702cb2016-01-08 13:50:27 -08001157 for (size_t i = 0; i < arraysize(level_dbfs); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001158 EXPECT_EQ(apm_->kNoError,
1159 apm_->gain_control()->set_target_level_dbfs(level_dbfs[i]));
1160 EXPECT_EQ(level_dbfs[i], apm_->gain_control()->target_level_dbfs());
1161 }
1162
1163 // Testing invalid compression gains
1164 EXPECT_EQ(apm_->kBadParameterError,
1165 apm_->gain_control()->set_compression_gain_db(-1));
1166 EXPECT_EQ(apm_->kBadParameterError,
1167 apm_->gain_control()->set_compression_gain_db(100));
1168
1169 // Testing valid compression gains
1170 EXPECT_EQ(apm_->kNoError,
1171 apm_->gain_control()->set_compression_gain_db(
1172 apm_->gain_control()->compression_gain_db()));
1173
1174 int gain_db[] = {0, 10, 90};
pkasting25702cb2016-01-08 13:50:27 -08001175 for (size_t i = 0; i < arraysize(gain_db); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001176 EXPECT_EQ(apm_->kNoError,
1177 apm_->gain_control()->set_compression_gain_db(gain_db[i]));
1178 EXPECT_EQ(gain_db[i], apm_->gain_control()->compression_gain_db());
1179 }
1180
1181 // Testing limiter off/on
1182 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(false));
1183 EXPECT_FALSE(apm_->gain_control()->is_limiter_enabled());
1184 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->enable_limiter(true));
1185 EXPECT_TRUE(apm_->gain_control()->is_limiter_enabled());
1186
1187 // Testing invalid level limits
1188 EXPECT_EQ(apm_->kBadParameterError,
1189 apm_->gain_control()->set_analog_level_limits(-1, 512));
1190 EXPECT_EQ(apm_->kBadParameterError,
1191 apm_->gain_control()->set_analog_level_limits(100000, 512));
1192 EXPECT_EQ(apm_->kBadParameterError,
1193 apm_->gain_control()->set_analog_level_limits(512, -1));
1194 EXPECT_EQ(apm_->kBadParameterError,
1195 apm_->gain_control()->set_analog_level_limits(512, 100000));
1196 EXPECT_EQ(apm_->kBadParameterError,
1197 apm_->gain_control()->set_analog_level_limits(512, 255));
1198
1199 // Testing valid level limits
1200 EXPECT_EQ(apm_->kNoError,
1201 apm_->gain_control()->set_analog_level_limits(
1202 apm_->gain_control()->analog_level_minimum(),
1203 apm_->gain_control()->analog_level_maximum()));
1204
1205 int min_level[] = {0, 255, 1024};
pkasting25702cb2016-01-08 13:50:27 -08001206 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001207 EXPECT_EQ(apm_->kNoError,
1208 apm_->gain_control()->set_analog_level_limits(min_level[i], 1024));
1209 EXPECT_EQ(min_level[i], apm_->gain_control()->analog_level_minimum());
1210 }
1211
1212 int max_level[] = {0, 1024, 65535};
pkasting25702cb2016-01-08 13:50:27 -08001213 for (size_t i = 0; i < arraysize(min_level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001214 EXPECT_EQ(apm_->kNoError,
1215 apm_->gain_control()->set_analog_level_limits(0, max_level[i]));
1216 EXPECT_EQ(max_level[i], apm_->gain_control()->analog_level_maximum());
1217 }
1218
1219 // TODO(ajm): stream_is_saturated() and stream_analog_level()
1220
1221 // Turn AGC off
1222 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(false));
1223 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1224}
1225
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001226void ApmTest::RunQuantizedVolumeDoesNotGetStuckTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001227 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001228 EXPECT_EQ(apm_->kNoError,
1229 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1230 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1231
1232 int out_analog_level = 0;
1233 for (int i = 0; i < 2000; ++i) {
1234 ReadFrameWithRewind(near_file_, frame_);
1235 // Ensure the audio is at a low level, so the AGC will try to increase it.
1236 ScaleFrame(frame_, 0.25);
1237
1238 // Always pass in the same volume.
1239 EXPECT_EQ(apm_->kNoError,
1240 apm_->gain_control()->set_stream_analog_level(100));
1241 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1242 out_analog_level = apm_->gain_control()->stream_analog_level();
1243 }
1244
1245 // Ensure the AGC is still able to reach the maximum.
1246 EXPECT_EQ(255, out_analog_level);
1247}
1248
1249// Verifies that despite volume slider quantization, the AGC can continue to
1250// increase its volume.
1251TEST_F(ApmTest, QuantizedVolumeDoesNotGetStuck) {
pkasting25702cb2016-01-08 13:50:27 -08001252 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001253 RunQuantizedVolumeDoesNotGetStuckTest(kSampleRates[i]);
1254 }
1255}
1256
1257void ApmTest::RunManualVolumeChangeIsPossibleTest(int sample_rate) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001258 Init(sample_rate, sample_rate, sample_rate, 2, 2, 2, false);
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001259 EXPECT_EQ(apm_->kNoError,
1260 apm_->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
1261 EXPECT_EQ(apm_->kNoError, apm_->gain_control()->Enable(true));
1262
1263 int out_analog_level = 100;
1264 for (int i = 0; i < 1000; ++i) {
1265 ReadFrameWithRewind(near_file_, frame_);
1266 // Ensure the audio is at a low level, so the AGC will try to increase it.
1267 ScaleFrame(frame_, 0.25);
1268
1269 EXPECT_EQ(apm_->kNoError,
1270 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1271 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1272 out_analog_level = apm_->gain_control()->stream_analog_level();
1273 }
1274
1275 // Ensure the volume was raised.
1276 EXPECT_GT(out_analog_level, 100);
1277 int highest_level_reached = out_analog_level;
1278 // Simulate a user manual volume change.
1279 out_analog_level = 100;
1280
1281 for (int i = 0; i < 300; ++i) {
1282 ReadFrameWithRewind(near_file_, frame_);
1283 ScaleFrame(frame_, 0.25);
1284
1285 EXPECT_EQ(apm_->kNoError,
1286 apm_->gain_control()->set_stream_analog_level(out_analog_level));
1287 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1288 out_analog_level = apm_->gain_control()->stream_analog_level();
1289 // Check that AGC respected the manually adjusted volume.
1290 EXPECT_LT(out_analog_level, highest_level_reached);
1291 }
1292 // Check that the volume was still raised.
1293 EXPECT_GT(out_analog_level, 100);
1294}
1295
1296TEST_F(ApmTest, ManualVolumeChangeIsPossible) {
pkasting25702cb2016-01-08 13:50:27 -08001297 for (size_t i = 0; i < arraysize(kSampleRates); ++i) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00001298 RunManualVolumeChangeIsPossibleTest(kSampleRates[i]);
1299 }
1300}
1301
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001302#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
1303TEST_F(ApmTest, AgcOnlyAdaptsWhenTargetSignalIsPresent) {
1304 const int kSampleRateHz = 16000;
pkasting25702cb2016-01-08 13:50:27 -08001305 const size_t kSamplesPerChannel =
1306 static_cast<size_t>(AudioProcessing::kChunkSizeMs * kSampleRateHz / 1000);
Peter Kasting69558702016-01-12 16:26:35 -08001307 const size_t kNumInputChannels = 2;
1308 const size_t kNumOutputChannels = 1;
pkasting25702cb2016-01-08 13:50:27 -08001309 const size_t kNumChunks = 700;
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001310 const float kScaleFactor = 0.25f;
1311 Config config;
1312 std::vector<webrtc::Point> geometry;
1313 geometry.push_back(webrtc::Point(0.f, 0.f, 0.f));
1314 geometry.push_back(webrtc::Point(0.05f, 0.f, 0.f));
1315 config.Set<Beamforming>(new Beamforming(true, geometry));
mgraczyk@chromium.org0f663de2015-03-13 00:13:32 +00001316 testing::NiceMock<MockNonlinearBeamformer>* beamformer =
Alejandro Luebsf4022ff2016-07-01 17:19:09 -07001317 new testing::NiceMock<MockNonlinearBeamformer>(geometry, 1u);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02001318 std::unique_ptr<AudioProcessing> apm(
Ivo Creusen62337e52018-01-09 14:17:33 +01001319 AudioProcessingBuilder()
1320 .SetNonlinearBeamformer(
1321 std::unique_ptr<webrtc::NonlinearBeamformer>(beamformer))
1322 .Create(config));
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001323 EXPECT_EQ(kNoErr, apm->gain_control()->Enable(true));
1324 ChannelBuffer<float> src_buf(kSamplesPerChannel, kNumInputChannels);
1325 ChannelBuffer<float> dest_buf(kSamplesPerChannel, kNumOutputChannels);
pkasting25702cb2016-01-08 13:50:27 -08001326 const size_t max_length = kSamplesPerChannel * std::max(kNumInputChannels,
1327 kNumOutputChannels);
kwiberg62eaacf2016-02-17 06:39:05 -08001328 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
1329 std::unique_ptr<float[]> float_data(new float[max_length]);
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001330 std::string filename = ResourceFilePath("far", kSampleRateHz);
1331 FILE* far_file = fopen(filename.c_str(), "rb");
1332 ASSERT_TRUE(far_file != NULL) << "Could not open file " << filename << "\n";
1333 const int kDefaultVolume = apm->gain_control()->stream_analog_level();
1334 const int kDefaultCompressionGain =
1335 apm->gain_control()->compression_gain_db();
1336 bool is_target = false;
1337 EXPECT_CALL(*beamformer, is_target_present())
1338 .WillRepeatedly(testing::ReturnPointee(&is_target));
pkasting25702cb2016-01-08 13:50:27 -08001339 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001340 ASSERT_TRUE(ReadChunk(far_file,
1341 int_data.get(),
1342 float_data.get(),
1343 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001344 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001345 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001346 src_buf.channels()[j][k] *= kScaleFactor;
1347 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001348 }
1349 EXPECT_EQ(kNoErr,
1350 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001351 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001352 kSampleRateHz,
1353 LayoutFromChannels(src_buf.num_channels()),
1354 kSampleRateHz,
1355 LayoutFromChannels(dest_buf.num_channels()),
1356 dest_buf.channels()));
1357 }
1358 EXPECT_EQ(kDefaultVolume,
1359 apm->gain_control()->stream_analog_level());
1360 EXPECT_EQ(kDefaultCompressionGain,
1361 apm->gain_control()->compression_gain_db());
1362 rewind(far_file);
1363 is_target = true;
pkasting25702cb2016-01-08 13:50:27 -08001364 for (size_t i = 0; i < kNumChunks; ++i) {
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001365 ASSERT_TRUE(ReadChunk(far_file,
1366 int_data.get(),
1367 float_data.get(),
1368 &src_buf));
Peter Kasting69558702016-01-12 16:26:35 -08001369 for (size_t j = 0; j < kNumInputChannels; ++j) {
pkasting25702cb2016-01-08 13:50:27 -08001370 for (size_t k = 0; k < kSamplesPerChannel; ++k) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001371 src_buf.channels()[j][k] *= kScaleFactor;
1372 }
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001373 }
1374 EXPECT_EQ(kNoErr,
1375 apm->ProcessStream(src_buf.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001376 src_buf.num_frames(),
aluebs@webrtc.orgd82f55d2015-01-15 18:07:21 +00001377 kSampleRateHz,
1378 LayoutFromChannels(src_buf.num_channels()),
1379 kSampleRateHz,
1380 LayoutFromChannels(dest_buf.num_channels()),
1381 dest_buf.channels()));
1382 }
1383 EXPECT_LT(kDefaultVolume,
1384 apm->gain_control()->stream_analog_level());
1385 EXPECT_LT(kDefaultCompressionGain,
1386 apm->gain_control()->compression_gain_db());
1387 ASSERT_EQ(0, fclose(far_file));
1388}
1389#endif
1390
niklase@google.com470e71d2011-07-07 08:21:25 +00001391TEST_F(ApmTest, NoiseSuppression) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001392 // Test valid suppression levels.
niklase@google.com470e71d2011-07-07 08:21:25 +00001393 NoiseSuppression::Level level[] = {
1394 NoiseSuppression::kLow,
1395 NoiseSuppression::kModerate,
1396 NoiseSuppression::kHigh,
1397 NoiseSuppression::kVeryHigh
1398 };
pkasting25702cb2016-01-08 13:50:27 -08001399 for (size_t i = 0; i < arraysize(level); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001400 EXPECT_EQ(apm_->kNoError,
1401 apm_->noise_suppression()->set_level(level[i]));
1402 EXPECT_EQ(level[i], apm_->noise_suppression()->level());
1403 }
1404
andrew@webrtc.org648af742012-02-08 01:57:29 +00001405 // Turn NS on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001406 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(true));
1407 EXPECT_TRUE(apm_->noise_suppression()->is_enabled());
1408 EXPECT_EQ(apm_->kNoError, apm_->noise_suppression()->Enable(false));
1409 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1410}
1411
1412TEST_F(ApmTest, HighPassFilter) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001413 // Turn HP filter on/off
peah8271d042016-11-22 07:24:52 -08001414 AudioProcessing::Config apm_config;
1415 apm_config.high_pass_filter.enabled = true;
1416 apm_->ApplyConfig(apm_config);
1417 apm_config.high_pass_filter.enabled = false;
1418 apm_->ApplyConfig(apm_config);
niklase@google.com470e71d2011-07-07 08:21:25 +00001419}
1420
1421TEST_F(ApmTest, LevelEstimator) {
andrew@webrtc.org648af742012-02-08 01:57:29 +00001422 // Turn level estimator on/off
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001423 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
niklase@google.com470e71d2011-07-07 08:21:25 +00001424 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001425
1426 EXPECT_EQ(apm_->kNotEnabledError, apm_->level_estimator()->RMS());
1427
1428 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1429 EXPECT_TRUE(apm_->level_estimator()->is_enabled());
1430
1431 // Run this test in wideband; in super-wb, the splitting filter distorts the
1432 // audio enough to cause deviation from the expectation for small values.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001433 frame_->samples_per_channel_ = 160;
1434 frame_->num_channels_ = 2;
1435 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001436
1437 // Min value if no frames have been processed.
1438 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1439
1440 // Min value on zero frames.
1441 SetFrameTo(frame_, 0);
1442 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1443 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1444 EXPECT_EQ(127, apm_->level_estimator()->RMS());
1445
1446 // Try a few RMS values.
1447 // (These also test that the value resets after retrieving it.)
1448 SetFrameTo(frame_, 32767);
1449 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1450 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1451 EXPECT_EQ(0, apm_->level_estimator()->RMS());
1452
1453 SetFrameTo(frame_, 30000);
1454 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1455 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1456 EXPECT_EQ(1, apm_->level_estimator()->RMS());
1457
1458 SetFrameTo(frame_, 10000);
1459 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1460 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1461 EXPECT_EQ(10, apm_->level_estimator()->RMS());
1462
1463 SetFrameTo(frame_, 10);
1464 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1465 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1466 EXPECT_EQ(70, apm_->level_estimator()->RMS());
1467
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001468 // Verify reset after enable/disable.
1469 SetFrameTo(frame_, 32767);
1470 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1471 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1472 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1473 SetFrameTo(frame_, 1);
1474 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1475 EXPECT_EQ(90, apm_->level_estimator()->RMS());
1476
1477 // Verify reset after initialize.
1478 SetFrameTo(frame_, 32767);
1479 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1480 EXPECT_EQ(apm_->kNoError, apm_->Initialize());
1481 SetFrameTo(frame_, 1);
1482 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1483 EXPECT_EQ(90, apm_->level_estimator()->RMS());
niklase@google.com470e71d2011-07-07 08:21:25 +00001484}
1485
1486TEST_F(ApmTest, VoiceDetection) {
1487 // Test external VAD
1488 EXPECT_EQ(apm_->kNoError,
1489 apm_->voice_detection()->set_stream_has_voice(true));
1490 EXPECT_TRUE(apm_->voice_detection()->stream_has_voice());
1491 EXPECT_EQ(apm_->kNoError,
1492 apm_->voice_detection()->set_stream_has_voice(false));
1493 EXPECT_FALSE(apm_->voice_detection()->stream_has_voice());
1494
andrew@webrtc.org648af742012-02-08 01:57:29 +00001495 // Test valid likelihoods
niklase@google.com470e71d2011-07-07 08:21:25 +00001496 VoiceDetection::Likelihood likelihood[] = {
1497 VoiceDetection::kVeryLowLikelihood,
1498 VoiceDetection::kLowLikelihood,
1499 VoiceDetection::kModerateLikelihood,
1500 VoiceDetection::kHighLikelihood
1501 };
pkasting25702cb2016-01-08 13:50:27 -08001502 for (size_t i = 0; i < arraysize(likelihood); i++) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001503 EXPECT_EQ(apm_->kNoError,
1504 apm_->voice_detection()->set_likelihood(likelihood[i]));
1505 EXPECT_EQ(likelihood[i], apm_->voice_detection()->likelihood());
1506 }
1507
1508 /* TODO(bjornv): Enable once VAD supports other frame lengths than 10 ms
andrew@webrtc.org648af742012-02-08 01:57:29 +00001509 // Test invalid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001510 EXPECT_EQ(apm_->kBadParameterError,
1511 apm_->voice_detection()->set_frame_size_ms(12));
1512
andrew@webrtc.org648af742012-02-08 01:57:29 +00001513 // Test valid frame sizes
niklase@google.com470e71d2011-07-07 08:21:25 +00001514 for (int i = 10; i <= 30; i += 10) {
1515 EXPECT_EQ(apm_->kNoError,
1516 apm_->voice_detection()->set_frame_size_ms(i));
1517 EXPECT_EQ(i, apm_->voice_detection()->frame_size_ms());
1518 }
1519 */
1520
andrew@webrtc.org648af742012-02-08 01:57:29 +00001521 // Turn VAD on/off
niklase@google.com470e71d2011-07-07 08:21:25 +00001522 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1523 EXPECT_TRUE(apm_->voice_detection()->is_enabled());
1524 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1525 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1526
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001527 // Test that AudioFrame activity is maintained when VAD is disabled.
1528 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1529 AudioFrame::VADActivity activity[] = {
1530 AudioFrame::kVadActive,
1531 AudioFrame::kVadPassive,
1532 AudioFrame::kVadUnknown
1533 };
pkasting25702cb2016-01-08 13:50:27 -08001534 for (size_t i = 0; i < arraysize(activity); i++) {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001535 frame_->vad_activity_ = activity[i];
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001536 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001537 EXPECT_EQ(activity[i], frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001538 }
1539
1540 // Test that AudioFrame activity is set when VAD is enabled.
1541 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001542 frame_->vad_activity_ = AudioFrame::kVadUnknown;
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001543 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001544 EXPECT_NE(AudioFrame::kVadUnknown, frame_->vad_activity_);
andrew@webrtc.orged083d42011-09-19 15:28:51 +00001545
niklase@google.com470e71d2011-07-07 08:21:25 +00001546 // TODO(bjornv): Add tests for streamed voice; stream_has_voice()
1547}
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001548
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001549TEST_F(ApmTest, AllProcessingDisabledByDefault) {
1550 EXPECT_FALSE(apm_->echo_cancellation()->is_enabled());
1551 EXPECT_FALSE(apm_->echo_control_mobile()->is_enabled());
1552 EXPECT_FALSE(apm_->gain_control()->is_enabled());
1553 EXPECT_FALSE(apm_->high_pass_filter()->is_enabled());
1554 EXPECT_FALSE(apm_->level_estimator()->is_enabled());
1555 EXPECT_FALSE(apm_->noise_suppression()->is_enabled());
1556 EXPECT_FALSE(apm_->voice_detection()->is_enabled());
1557}
1558
1559TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabled) {
pkasting25702cb2016-01-08 13:50:27 -08001560 for (size_t i = 0; i < arraysize(kSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001561 Init(kSampleRates[i], kSampleRates[i], kSampleRates[i], 2, 2, 2, false);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001562 SetFrameTo(frame_, 1000, 2000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001563 AudioFrame frame_copy;
1564 frame_copy.CopyFrom(*frame_);
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001565 for (int j = 0; j < 1000; j++) {
1566 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1567 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
ekmeyerson60d9b332015-08-14 10:35:55 -07001568 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(frame_));
1569 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
andrew@webrtc.orgecac9b72012-05-02 00:04:10 +00001570 }
1571 }
1572}
1573
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001574TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) {
1575 // Test that ProcessStream copies input to output even with no processing.
1576 const size_t kSamples = 80;
1577 const int sample_rate = 8000;
1578 const float src[kSamples] = {
1579 -1.0f, 0.0f, 1.0f
1580 };
1581 float dest[kSamples] = {};
1582
1583 auto src_channels = &src[0];
1584 auto dest_channels = &dest[0];
1585
Ivo Creusen62337e52018-01-09 14:17:33 +01001586 apm_.reset(AudioProcessingBuilder().Create());
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001587 EXPECT_NOERR(apm_->ProcessStream(
1588 &src_channels, kSamples, sample_rate, LayoutFromChannels(1),
1589 sample_rate, LayoutFromChannels(1), &dest_channels));
1590
1591 for (size_t i = 0; i < kSamples; ++i) {
1592 EXPECT_EQ(src[i], dest[i]);
1593 }
ekmeyerson60d9b332015-08-14 10:35:55 -07001594
1595 // Same for ProcessReverseStream.
1596 float rev_dest[kSamples] = {};
1597 auto rev_dest_channels = &rev_dest[0];
1598
1599 StreamConfig input_stream = {sample_rate, 1};
1600 StreamConfig output_stream = {sample_rate, 1};
1601 EXPECT_NOERR(apm_->ProcessReverseStream(&src_channels, input_stream,
1602 output_stream, &rev_dest_channels));
1603
1604 for (size_t i = 0; i < kSamples; ++i) {
1605 EXPECT_EQ(src[i], rev_dest[i]);
1606 }
mgraczyk@chromium.orgd6e84d92015-01-14 01:33:54 +00001607}
1608
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001609TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) {
1610 EnableAllComponents();
1611
pkasting25702cb2016-01-08 13:50:27 -08001612 for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001613 Init(kProcessSampleRates[i],
1614 kProcessSampleRates[i],
1615 kProcessSampleRates[i],
1616 2,
1617 2,
1618 2,
1619 false);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001620 int analog_level = 127;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001621 ASSERT_EQ(0, feof(far_file_));
1622 ASSERT_EQ(0, feof(near_file_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001623 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
yujo36b1a5f2017-06-12 12:45:32 -07001624 CopyLeftToRightChannel(revframe_->mutable_data(),
1625 revframe_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001626
aluebsb0319552016-03-17 20:39:53 -07001627 ASSERT_EQ(kNoErr, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001628
yujo36b1a5f2017-06-12 12:45:32 -07001629 CopyLeftToRightChannel(frame_->mutable_data(),
1630 frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001631 frame_->vad_activity_ = AudioFrame::kVadUnknown;
1632
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001633 ASSERT_EQ(kNoErr, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001634 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001635 ASSERT_EQ(kNoErr,
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001636 apm_->gain_control()->set_stream_analog_level(analog_level));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001637 ASSERT_EQ(kNoErr, apm_->ProcessStream(frame_));
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001638 analog_level = apm_->gain_control()->stream_analog_level();
1639
yujo36b1a5f2017-06-12 12:45:32 -07001640 VerifyChannelsAreEqual(frame_->data(), frame_->samples_per_channel_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001641 }
bjornv@webrtc.org3e102492013-02-14 15:29:09 +00001642 rewind(far_file_);
1643 rewind(near_file_);
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00001644 }
1645}
1646
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001647TEST_F(ApmTest, SplittingFilter) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001648 // Verify the filter is not active through undistorted audio when:
1649 // 1. No components are enabled...
1650 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001651 AudioFrame frame_copy;
1652 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001653 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1654 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1655 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1656
1657 // 2. Only the level estimator is enabled...
1658 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001659 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001660 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1661 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1662 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1663 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1664 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1665
1666 // 3. Only VAD is enabled...
1667 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001668 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001669 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1670 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1671 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1672 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1673 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1674
1675 // 4. Both VAD and the level estimator are enabled...
1676 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001677 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001678 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(true));
1679 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(true));
1680 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1681 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1682 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1683 EXPECT_EQ(apm_->kNoError, apm_->level_estimator()->Enable(false));
1684 EXPECT_EQ(apm_->kNoError, apm_->voice_detection()->Enable(false));
1685
1686 // 5. Not using super-wb.
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001687 frame_->samples_per_channel_ = 160;
1688 frame_->num_channels_ = 2;
1689 frame_->sample_rate_hz_ = 16000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001690 // Enable AEC, which would require the filter in super-wb. We rely on the
1691 // first few frames of data being unaffected by the AEC.
1692 // TODO(andrew): This test, and the one below, rely rather tenuously on the
1693 // behavior of the AEC. Think of something more robust.
1694 EXPECT_EQ(apm_->kNoError, apm_->echo_cancellation()->Enable(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001695 // Make sure we have extended filter enabled. This makes sure nothing is
1696 // touched until we have a farend frame.
1697 Config config;
Henrik Lundin441f6342015-06-09 16:03:13 +02001698 config.Set<ExtendedFilter>(new ExtendedFilter(true));
bjornv@webrtc.orgcb0ea432014-06-09 08:21:52 +00001699 apm_->SetExtraOptions(config);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001700 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001701 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001702 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001703 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001704 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1705 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001706 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001707 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1708 EXPECT_TRUE(FrameDataAreEqual(*frame_, frame_copy));
1709
1710 // Check the test is valid. We should have distortion from the filter
1711 // when AEC is enabled (which won't affect the audio).
andrew@webrtc.org63a50982012-05-02 23:56:37 +00001712 frame_->samples_per_channel_ = 320;
1713 frame_->num_channels_ = 2;
1714 frame_->sample_rate_hz_ = 32000;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001715 SetFrameTo(frame_, 1000);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +00001716 frame_copy.CopyFrom(*frame_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001717 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00001718 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00001719 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
1720 EXPECT_FALSE(FrameDataAreEqual(*frame_, frame_copy));
1721}
1722
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001723#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1724void ApmTest::ProcessDebugDump(const std::string& in_filename,
1725 const std::string& out_filename,
ivocd66b44d2016-01-15 03:06:36 -08001726 Format format,
1727 int max_size_bytes) {
aleloif4dd1912017-06-15 01:55:38 -07001728 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001729 FILE* in_file = fopen(in_filename.c_str(), "rb");
1730 ASSERT_TRUE(in_file != NULL);
1731 audioproc::Event event_msg;
1732 bool first_init = true;
1733
1734 while (ReadMessageFromFile(in_file, &event_msg)) {
1735 if (event_msg.type() == audioproc::Event::INIT) {
1736 const audioproc::Init msg = event_msg.init();
1737 int reverse_sample_rate = msg.sample_rate();
1738 if (msg.has_reverse_sample_rate()) {
1739 reverse_sample_rate = msg.reverse_sample_rate();
1740 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001741 int output_sample_rate = msg.sample_rate();
1742 if (msg.has_output_sample_rate()) {
1743 output_sample_rate = msg.output_sample_rate();
1744 }
1745
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001746 Init(msg.sample_rate(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001747 output_sample_rate,
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001748 reverse_sample_rate,
1749 msg.num_input_channels(),
1750 msg.num_output_channels(),
1751 msg.num_reverse_channels(),
1752 false);
1753 if (first_init) {
aleloif4dd1912017-06-15 01:55:38 -07001754 // AttachAecDump() writes an additional init message. Don't start
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001755 // recording until after the first init to avoid the extra message.
aleloif4dd1912017-06-15 01:55:38 -07001756 auto aec_dump =
1757 AecDumpFactory::Create(out_filename, max_size_bytes, &worker_queue);
1758 EXPECT_TRUE(aec_dump);
1759 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001760 first_init = false;
1761 }
1762
1763 } else if (event_msg.type() == audioproc::Event::REVERSE_STREAM) {
1764 const audioproc::ReverseStream msg = event_msg.reverse_stream();
1765
1766 if (msg.channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001767 ASSERT_EQ(revframe_->num_channels_,
1768 static_cast<size_t>(msg.channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001769 for (int i = 0; i < msg.channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001770 memcpy(revfloat_cb_->channels()[i],
1771 msg.channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001772 msg.channel(i).size());
1773 }
1774 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001775 memcpy(revframe_->mutable_data(), msg.data().data(), msg.data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001776 if (format == kFloatFormat) {
1777 // We're using an int16 input file; convert to float.
1778 ConvertToFloat(*revframe_, revfloat_cb_.get());
1779 }
1780 }
1781 AnalyzeReverseStreamChooser(format);
1782
1783 } else if (event_msg.type() == audioproc::Event::STREAM) {
1784 const audioproc::Stream msg = event_msg.stream();
1785 // ProcessStream could have changed this for the output frame.
1786 frame_->num_channels_ = apm_->num_input_channels();
1787
1788 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(msg.level()));
1789 EXPECT_NOERR(apm_->set_stream_delay_ms(msg.delay()));
1790 apm_->echo_cancellation()->set_stream_drift_samples(msg.drift());
1791 if (msg.has_keypress()) {
1792 apm_->set_stream_key_pressed(msg.keypress());
1793 } else {
1794 apm_->set_stream_key_pressed(true);
1795 }
1796
1797 if (msg.input_channel_size() > 0) {
Peter Kasting69558702016-01-12 16:26:35 -08001798 ASSERT_EQ(frame_->num_channels_,
1799 static_cast<size_t>(msg.input_channel_size()));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001800 for (int i = 0; i < msg.input_channel_size(); ++i) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00001801 memcpy(float_cb_->channels()[i],
1802 msg.input_channel(i).data(),
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001803 msg.input_channel(i).size());
1804 }
1805 } else {
yujo36b1a5f2017-06-12 12:45:32 -07001806 memcpy(frame_->mutable_data(), msg.input_data().data(),
1807 msg.input_data().size());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001808 if (format == kFloatFormat) {
1809 // We're using an int16 input file; convert to float.
1810 ConvertToFloat(*frame_, float_cb_.get());
1811 }
1812 }
1813 ProcessStreamChooser(format);
1814 }
1815 }
aleloif4dd1912017-06-15 01:55:38 -07001816 apm_->DetachAecDump();
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001817 fclose(in_file);
1818}
1819
1820void ApmTest::VerifyDebugDumpTest(Format format) {
1821 const std::string in_filename = test::ResourcePath("ref03", "aecdump");
henrik.lundin@webrtc.org1092ea02014-04-02 07:46:49 +00001822 std::string format_string;
1823 switch (format) {
1824 case kIntFormat:
1825 format_string = "_int";
1826 break;
1827 case kFloatFormat:
1828 format_string = "_float";
1829 break;
1830 }
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001831 const std::string ref_filename = test::TempFilename(
1832 test::OutputPath(), std::string("ref") + format_string + "_aecdump");
1833 const std::string out_filename = test::TempFilename(
1834 test::OutputPath(), std::string("out") + format_string + "_aecdump");
ivocd66b44d2016-01-15 03:06:36 -08001835 const std::string limited_filename = test::TempFilename(
1836 test::OutputPath(), std::string("limited") + format_string + "_aecdump");
1837 const size_t logging_limit_bytes = 100000;
1838 // We expect at least this many bytes in the created logfile.
1839 const size_t logging_expected_bytes = 95000;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001840 EnableAllComponents();
ivocd66b44d2016-01-15 03:06:36 -08001841 ProcessDebugDump(in_filename, ref_filename, format, -1);
1842 ProcessDebugDump(ref_filename, out_filename, format, -1);
1843 ProcessDebugDump(ref_filename, limited_filename, format, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001844
1845 FILE* ref_file = fopen(ref_filename.c_str(), "rb");
1846 FILE* out_file = fopen(out_filename.c_str(), "rb");
ivocd66b44d2016-01-15 03:06:36 -08001847 FILE* limited_file = fopen(limited_filename.c_str(), "rb");
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001848 ASSERT_TRUE(ref_file != NULL);
1849 ASSERT_TRUE(out_file != NULL);
ivocd66b44d2016-01-15 03:06:36 -08001850 ASSERT_TRUE(limited_file != NULL);
kwiberg62eaacf2016-02-17 06:39:05 -08001851 std::unique_ptr<uint8_t[]> ref_bytes;
1852 std::unique_ptr<uint8_t[]> out_bytes;
1853 std::unique_ptr<uint8_t[]> limited_bytes;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001854
1855 size_t ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1856 size_t out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001857 size_t limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001858 size_t bytes_read = 0;
ivocd66b44d2016-01-15 03:06:36 -08001859 size_t bytes_read_limited = 0;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001860 while (ref_size > 0 && out_size > 0) {
1861 bytes_read += ref_size;
ivocd66b44d2016-01-15 03:06:36 -08001862 bytes_read_limited += limited_size;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001863 EXPECT_EQ(ref_size, out_size);
ivocd66b44d2016-01-15 03:06:36 -08001864 EXPECT_GE(ref_size, limited_size);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001865 EXPECT_EQ(0, memcmp(ref_bytes.get(), out_bytes.get(), ref_size));
ivocd66b44d2016-01-15 03:06:36 -08001866 EXPECT_EQ(0, memcmp(ref_bytes.get(), limited_bytes.get(), limited_size));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001867 ref_size = ReadMessageBytesFromFile(ref_file, &ref_bytes);
1868 out_size = ReadMessageBytesFromFile(out_file, &out_bytes);
ivocd66b44d2016-01-15 03:06:36 -08001869 limited_size = ReadMessageBytesFromFile(limited_file, &limited_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001870 }
1871 EXPECT_GT(bytes_read, 0u);
ivocd66b44d2016-01-15 03:06:36 -08001872 EXPECT_GT(bytes_read_limited, logging_expected_bytes);
1873 EXPECT_LE(bytes_read_limited, logging_limit_bytes);
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001874 EXPECT_NE(0, feof(ref_file));
1875 EXPECT_NE(0, feof(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001876 EXPECT_NE(0, feof(limited_file));
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001877 ASSERT_EQ(0, fclose(ref_file));
1878 ASSERT_EQ(0, fclose(out_file));
ivocd66b44d2016-01-15 03:06:36 -08001879 ASSERT_EQ(0, fclose(limited_file));
Peter Boströmfade1792015-05-12 10:44:11 +02001880 remove(ref_filename.c_str());
1881 remove(out_filename.c_str());
ivocd66b44d2016-01-15 03:06:36 -08001882 remove(limited_filename.c_str());
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001883}
1884
pbosc7a65692016-05-06 12:50:04 -07001885TEST_F(ApmTest, VerifyDebugDumpInt) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001886 VerifyDebugDumpTest(kIntFormat);
1887}
1888
pbosc7a65692016-05-06 12:50:04 -07001889TEST_F(ApmTest, VerifyDebugDumpFloat) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001890 VerifyDebugDumpTest(kFloatFormat);
1891}
1892#endif
1893
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001894// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001895TEST_F(ApmTest, DebugDump) {
aleloif4dd1912017-06-15 01:55:38 -07001896 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001897 const std::string filename =
1898 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001899 {
1900 auto aec_dump = AecDumpFactory::Create("", -1, &worker_queue);
1901 EXPECT_FALSE(aec_dump);
1902 }
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001903
1904#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1905 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001906 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001907
aleloif4dd1912017-06-15 01:55:38 -07001908 auto aec_dump = AecDumpFactory::Create(filename, -1, &worker_queue);
1909 EXPECT_TRUE(aec_dump);
1910 apm_->AttachAecDump(std::move(aec_dump));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001911 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aluebsb0319552016-03-17 20:39:53 -07001912 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
aleloif4dd1912017-06-15 01:55:38 -07001913 apm_->DetachAecDump();
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001914
1915 // Verify the file has been written.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001916 FILE* fid = fopen(filename.c_str(), "r");
1917 ASSERT_TRUE(fid != NULL);
1918
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001919 // Clean it up.
andrew@webrtc.orgf5d8c3b2012-01-24 21:35:39 +00001920 ASSERT_EQ(0, fclose(fid));
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001921 ASSERT_EQ(0, remove(filename.c_str()));
1922#else
andrew@webrtc.org7bf26462011-12-03 00:03:31 +00001923 // Verify the file has NOT been written.
1924 ASSERT_TRUE(fopen(filename.c_str(), "r") == NULL);
1925#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1926}
1927
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001928// TODO(andrew): expand test to verify output.
pbosc7a65692016-05-06 12:50:04 -07001929TEST_F(ApmTest, DebugDumpFromFileHandle) {
aleloif4dd1912017-06-15 01:55:38 -07001930 rtc::TaskQueue worker_queue("ApmTest_worker_queue");
1931
pbos@webrtc.orga525c982015-01-12 17:31:18 +00001932 const std::string filename =
1933 test::TempFilename(test::OutputPath(), "debug_aec");
aleloif4dd1912017-06-15 01:55:38 -07001934 FILE* fid = fopen(filename.c_str(), "w");
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001935 ASSERT_TRUE(fid);
1936
1937#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
1938 // Stopping without having started should be OK.
aleloif4dd1912017-06-15 01:55:38 -07001939 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001940
aleloif4dd1912017-06-15 01:55:38 -07001941 auto aec_dump = AecDumpFactory::Create(fid, -1, &worker_queue);
1942 EXPECT_TRUE(aec_dump);
1943 apm_->AttachAecDump(std::move(aec_dump));
aluebsb0319552016-03-17 20:39:53 -07001944 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001945 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
aleloif4dd1912017-06-15 01:55:38 -07001946 apm_->DetachAecDump();
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001947
1948 // Verify the file has been written.
1949 fid = fopen(filename.c_str(), "r");
1950 ASSERT_TRUE(fid != NULL);
1951
1952 // Clean it up.
1953 ASSERT_EQ(0, fclose(fid));
1954 ASSERT_EQ(0, remove(filename.c_str()));
1955#else
henrikg@webrtc.org863b5362013-12-06 16:05:17 +00001956 ASSERT_EQ(0, fclose(fid));
1957#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
1958}
1959
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001960TEST_F(ApmTest, FloatAndIntInterfacesGiveSimilarResults) {
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001961 audioproc::OutputData ref_data;
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00001962 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001963
1964 Config config;
1965 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01001966 std::unique_ptr<AudioProcessing> fapm(
1967 AudioProcessingBuilder().Create(config));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001968 EnableAllComponents();
1969 EnableAllAPComponents(fapm.get());
1970 for (int i = 0; i < ref_data.test_size(); i++) {
1971 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
1972
1973 audioproc::Test* test = ref_data.mutable_test(i);
1974 // TODO(ajm): Restore downmixing test cases.
1975 if (test->num_input_channels() != test->num_output_channels())
1976 continue;
1977
Peter Kasting69558702016-01-12 16:26:35 -08001978 const size_t num_render_channels =
1979 static_cast<size_t>(test->num_reverse_channels());
1980 const size_t num_input_channels =
1981 static_cast<size_t>(test->num_input_channels());
1982 const size_t num_output_channels =
1983 static_cast<size_t>(test->num_output_channels());
pkasting25702cb2016-01-08 13:50:27 -08001984 const size_t samples_per_channel = static_cast<size_t>(
1985 test->sample_rate() * AudioProcessing::kChunkSizeMs / 1000);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001986
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00001987 Init(test->sample_rate(), test->sample_rate(), test->sample_rate(),
1988 num_input_channels, num_output_channels, num_render_channels, true);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001989 Init(fapm.get());
1990
1991 ChannelBuffer<int16_t> output_cb(samples_per_channel, num_input_channels);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00001992 ChannelBuffer<int16_t> output_int16(samples_per_channel,
1993 num_input_channels);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001994
1995 int analog_level = 127;
aluebs776593b2016-03-15 14:04:58 -07001996 size_t num_bad_chunks = 0;
andrew@webrtc.org17e40642014-03-04 20:58:13 +00001997 while (ReadFrame(far_file_, revframe_, revfloat_cb_.get()) &&
1998 ReadFrame(near_file_, frame_, float_cb_.get())) {
1999 frame_->vad_activity_ = AudioFrame::kVadUnknown;
2000
aluebsb0319552016-03-17 20:39:53 -07002001 EXPECT_NOERR(apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002002 EXPECT_NOERR(fapm->AnalyzeReverseStream(
2003 revfloat_cb_->channels(),
2004 samples_per_channel,
2005 test->sample_rate(),
2006 LayoutFromChannels(num_render_channels)));
2007
2008 EXPECT_NOERR(apm_->set_stream_delay_ms(0));
2009 EXPECT_NOERR(fapm->set_stream_delay_ms(0));
2010 apm_->echo_cancellation()->set_stream_drift_samples(0);
2011 fapm->echo_cancellation()->set_stream_drift_samples(0);
2012 EXPECT_NOERR(apm_->gain_control()->set_stream_analog_level(analog_level));
2013 EXPECT_NOERR(fapm->gain_control()->set_stream_analog_level(analog_level));
2014
2015 EXPECT_NOERR(apm_->ProcessStream(frame_));
yujo36b1a5f2017-06-12 12:45:32 -07002016 Deinterleave(frame_->data(), samples_per_channel, num_output_channels,
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002017 output_int16.channels());
2018
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002019 EXPECT_NOERR(fapm->ProcessStream(
2020 float_cb_->channels(),
2021 samples_per_channel,
2022 test->sample_rate(),
2023 LayoutFromChannels(num_input_channels),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002024 test->sample_rate(),
2025 LayoutFromChannels(num_output_channels),
2026 float_cb_->channels()));
Peter Kasting69558702016-01-12 16:26:35 -08002027 for (size_t j = 0; j < num_output_channels; ++j) {
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002028 FloatToS16(float_cb_->channels()[j],
2029 samples_per_channel,
2030 output_cb.channels()[j]);
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002031 float variance = 0;
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002032 float snr = ComputeSNR(output_int16.channels()[j],
2033 output_cb.channels()[j],
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002034 samples_per_channel, &variance);
aluebs776593b2016-03-15 14:04:58 -07002035
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002036 const float kVarianceThreshold = 20;
2037 const float kSNRThreshold = 20;
aluebs776593b2016-03-15 14:04:58 -07002038
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002039 // Skip frames with low energy.
aluebs776593b2016-03-15 14:04:58 -07002040 if (sqrt(variance) > kVarianceThreshold && snr < kSNRThreshold) {
2041 ++num_bad_chunks;
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002042 }
2043 }
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002044
2045 analog_level = fapm->gain_control()->stream_analog_level();
2046 EXPECT_EQ(apm_->gain_control()->stream_analog_level(),
2047 fapm->gain_control()->stream_analog_level());
2048 EXPECT_EQ(apm_->echo_cancellation()->stream_has_echo(),
2049 fapm->echo_cancellation()->stream_has_echo());
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002050 EXPECT_NEAR(apm_->noise_suppression()->speech_probability(),
2051 fapm->noise_suppression()->speech_probability(),
Alejandro Luebs47748742015-05-22 12:00:21 -07002052 0.01);
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002053
2054 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002055 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002056 }
aluebs776593b2016-03-15 14:04:58 -07002057
2058#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2059 const size_t kMaxNumBadChunks = 0;
2060#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2061 // There are a few chunks in the fixed-point profile that give low SNR.
2062 // Listening confirmed the difference is acceptable.
2063 const size_t kMaxNumBadChunks = 60;
2064#endif
2065 EXPECT_LE(num_bad_chunks, kMaxNumBadChunks);
2066
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002067 rewind(far_file_);
2068 rewind(near_file_);
2069 }
2070}
2071
andrew@webrtc.org75f19482012-02-09 17:16:18 +00002072// TODO(andrew): Add a test to process a few frames with different combinations
2073// of enabled components.
2074
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002075TEST_F(ApmTest, Process) {
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002076 GOOGLE_PROTOBUF_VERIFY_VERSION;
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002077 audioproc::OutputData ref_data;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002078
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002079 if (!write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002080 OpenFileAndReadMessage(ref_filename_, &ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002081 } else {
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002082 // Write the desired tests to the protobuf reference file.
pkasting25702cb2016-01-08 13:50:27 -08002083 for (size_t i = 0; i < arraysize(kChannels); i++) {
2084 for (size_t j = 0; j < arraysize(kChannels); j++) {
2085 for (size_t l = 0; l < arraysize(kProcessSampleRates); l++) {
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002086 audioproc::Test* test = ref_data.add_test();
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002087 test->set_num_reverse_channels(kChannels[i]);
2088 test->set_num_input_channels(kChannels[j]);
2089 test->set_num_output_channels(kChannels[j]);
2090 test->set_sample_rate(kProcessSampleRates[l]);
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002091 test->set_use_aec_extended_filter(false);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002092 }
2093 }
2094 }
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002095#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2096 // To test the extended filter mode.
2097 audioproc::Test* test = ref_data.add_test();
2098 test->set_num_reverse_channels(2);
2099 test->set_num_input_channels(2);
2100 test->set_num_output_channels(2);
2101 test->set_sample_rate(AudioProcessing::kSampleRate32kHz);
2102 test->set_use_aec_extended_filter(true);
2103#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002104 }
2105
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002106 for (int i = 0; i < ref_data.test_size(); i++) {
2107 printf("Running test %d of %d...\n", i + 1, ref_data.test_size());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002108
andrew@webrtc.org27c69802014-02-18 20:24:56 +00002109 audioproc::Test* test = ref_data.mutable_test(i);
andrew@webrtc.org60730cf2014-01-07 17:45:09 +00002110 // TODO(ajm): We no longer allow different input and output channels. Skip
2111 // these tests for now, but they should be removed from the set.
2112 if (test->num_input_channels() != test->num_output_channels())
2113 continue;
2114
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002115 Config config;
2116 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Henrik Lundin441f6342015-06-09 16:03:13 +02002117 config.Set<ExtendedFilter>(
2118 new ExtendedFilter(test->use_aec_extended_filter()));
Ivo Creusen62337e52018-01-09 14:17:33 +01002119 apm_.reset(AudioProcessingBuilder().Create(config));
aluebs@webrtc.orgf17ee9c2015-01-29 00:03:53 +00002120
2121 EnableAllComponents();
2122
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002123 Init(test->sample_rate(),
2124 test->sample_rate(),
2125 test->sample_rate(),
Peter Kasting69558702016-01-12 16:26:35 -08002126 static_cast<size_t>(test->num_input_channels()),
2127 static_cast<size_t>(test->num_output_channels()),
2128 static_cast<size_t>(test->num_reverse_channels()),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002129 true);
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002130
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002131 int frame_count = 0;
2132 int has_echo_count = 0;
2133 int has_voice_count = 0;
2134 int is_saturated_count = 0;
2135 int analog_level = 127;
2136 int analog_level_average = 0;
2137 int max_output_average = 0;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002138 float ns_speech_prob_average = 0.0f;
minyue58530ed2016-05-24 05:50:12 -07002139#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2140 int stats_index = 0;
2141#endif
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002142
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002143 while (ReadFrame(far_file_, revframe_) && ReadFrame(near_file_, frame_)) {
aluebsb0319552016-03-17 20:39:53 -07002144 EXPECT_EQ(apm_->kNoError, apm_->ProcessReverseStream(revframe_));
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002145
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002146 frame_->vad_activity_ = AudioFrame::kVadUnknown;
2147
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002148 EXPECT_EQ(apm_->kNoError, apm_->set_stream_delay_ms(0));
andrew@webrtc.org6be1e932013-03-01 18:47:28 +00002149 apm_->echo_cancellation()->set_stream_drift_samples(0);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002150 EXPECT_EQ(apm_->kNoError,
2151 apm_->gain_control()->set_stream_analog_level(analog_level));
2152
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002153 EXPECT_EQ(apm_->kNoError, apm_->ProcessStream(frame_));
andrew@webrtc.org17e40642014-03-04 20:58:13 +00002154
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002155 // Ensure the frame was downmixed properly.
Peter Kasting69558702016-01-12 16:26:35 -08002156 EXPECT_EQ(static_cast<size_t>(test->num_output_channels()),
2157 frame_->num_channels_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002158
2159 max_output_average += MaxAudioFrame(*frame_);
2160
2161 if (apm_->echo_cancellation()->stream_has_echo()) {
2162 has_echo_count++;
2163 }
2164
2165 analog_level = apm_->gain_control()->stream_analog_level();
2166 analog_level_average += analog_level;
2167 if (apm_->gain_control()->stream_is_saturated()) {
2168 is_saturated_count++;
2169 }
2170 if (apm_->voice_detection()->stream_has_voice()) {
2171 has_voice_count++;
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002172 EXPECT_EQ(AudioFrame::kVadActive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002173 } else {
andrew@webrtc.org63a50982012-05-02 23:56:37 +00002174 EXPECT_EQ(AudioFrame::kVadPassive, frame_->vad_activity_);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002175 }
2176
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002177 ns_speech_prob_average += apm_->noise_suppression()->speech_probability();
2178
andrew@webrtc.org07bf9a02012-05-05 00:32:00 +00002179 size_t frame_size = frame_->samples_per_channel_ * frame_->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07002180 size_t write_count = fwrite(frame_->data(),
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002181 sizeof(int16_t),
2182 frame_size,
2183 out_file_);
2184 ASSERT_EQ(frame_size, write_count);
2185
2186 // Reset in case of downmixing.
Peter Kasting69558702016-01-12 16:26:35 -08002187 frame_->num_channels_ = static_cast<size_t>(test->num_input_channels());
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002188 frame_count++;
minyue58530ed2016-05-24 05:50:12 -07002189
2190#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2191 const int kStatsAggregationFrameNum = 100; // 1 second.
2192 if (frame_count % kStatsAggregationFrameNum == 0) {
2193 // Get echo metrics.
2194 EchoCancellation::Metrics echo_metrics;
2195 EXPECT_EQ(apm_->kNoError,
2196 apm_->echo_cancellation()->GetMetrics(&echo_metrics));
2197
2198 // Get delay metrics.
2199 int median = 0;
2200 int std = 0;
2201 float fraction_poor_delays = 0;
2202 EXPECT_EQ(apm_->kNoError,
2203 apm_->echo_cancellation()->GetDelayMetrics(
2204 &median, &std, &fraction_poor_delays));
2205
2206 // Get RMS.
2207 int rms_level = apm_->level_estimator()->RMS();
2208 EXPECT_LE(0, rms_level);
2209 EXPECT_GE(127, rms_level);
2210
2211 if (!write_ref_data) {
2212 const audioproc::Test::EchoMetrics& reference =
2213 test->echo_metrics(stats_index);
2214 TestStats(echo_metrics.residual_echo_return_loss,
2215 reference.residual_echo_return_loss());
2216 TestStats(echo_metrics.echo_return_loss,
2217 reference.echo_return_loss());
2218 TestStats(echo_metrics.echo_return_loss_enhancement,
2219 reference.echo_return_loss_enhancement());
2220 TestStats(echo_metrics.a_nlp,
2221 reference.a_nlp());
2222 EXPECT_EQ(echo_metrics.divergent_filter_fraction,
2223 reference.divergent_filter_fraction());
2224
2225 const audioproc::Test::DelayMetrics& reference_delay =
2226 test->delay_metrics(stats_index);
2227 EXPECT_EQ(reference_delay.median(), median);
2228 EXPECT_EQ(reference_delay.std(), std);
2229 EXPECT_EQ(reference_delay.fraction_poor_delays(),
2230 fraction_poor_delays);
2231
2232 EXPECT_EQ(test->rms_level(stats_index), rms_level);
2233
2234 ++stats_index;
2235 } else {
2236 audioproc::Test::EchoMetrics* message =
2237 test->add_echo_metrics();
2238 WriteStatsMessage(echo_metrics.residual_echo_return_loss,
2239 message->mutable_residual_echo_return_loss());
2240 WriteStatsMessage(echo_metrics.echo_return_loss,
2241 message->mutable_echo_return_loss());
2242 WriteStatsMessage(echo_metrics.echo_return_loss_enhancement,
2243 message->mutable_echo_return_loss_enhancement());
2244 WriteStatsMessage(echo_metrics.a_nlp,
2245 message->mutable_a_nlp());
2246 message->set_divergent_filter_fraction(
2247 echo_metrics.divergent_filter_fraction);
2248
2249 audioproc::Test::DelayMetrics* message_delay =
2250 test->add_delay_metrics();
2251 message_delay->set_median(median);
2252 message_delay->set_std(std);
2253 message_delay->set_fraction_poor_delays(fraction_poor_delays);
2254
2255 test->add_rms_level(rms_level);
2256 }
2257 }
2258#endif // defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE).
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002259 }
2260 max_output_average /= frame_count;
2261 analog_level_average /= frame_count;
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002262 ns_speech_prob_average /= frame_count;
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002263
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002264 if (!write_ref_data) {
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002265 const int kIntNear = 1;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002266 // When running the test on a N7 we get a {2, 6} difference of
2267 // |has_voice_count| and |max_output_average| is up to 18 higher.
2268 // All numbers being consistently higher on N7 compare to ref_data.
2269 // TODO(bjornv): If we start getting more of these offsets on Android we
2270 // should consider a different approach. Either using one slack for all,
2271 // or generate a separate android reference.
2272#if defined(WEBRTC_ANDROID)
2273 const int kHasVoiceCountOffset = 3;
Alejandro Luebs2a5609d2016-04-05 18:16:54 -07002274 const int kHasVoiceCountNear = 4;
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002275 const int kMaxOutputAverageOffset = 9;
2276 const int kMaxOutputAverageNear = 9;
2277#else
2278 const int kHasVoiceCountOffset = 0;
2279 const int kHasVoiceCountNear = kIntNear;
2280 const int kMaxOutputAverageOffset = 0;
2281 const int kMaxOutputAverageNear = kIntNear;
2282#endif
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002283 EXPECT_NEAR(test->has_echo_count(), has_echo_count, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002284 EXPECT_NEAR(test->has_voice_count(),
2285 has_voice_count - kHasVoiceCountOffset,
2286 kHasVoiceCountNear);
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002287 EXPECT_NEAR(test->is_saturated_count(), is_saturated_count, kIntNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002288
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002289 EXPECT_NEAR(test->analog_level_average(), analog_level_average, kIntNear);
bjornv@webrtc.orgdc0b37d2014-09-23 05:03:44 +00002290 EXPECT_NEAR(test->max_output_average(),
2291 max_output_average - kMaxOutputAverageOffset,
2292 kMaxOutputAverageNear);
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002293#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002294 const double kFloatNear = 0.0005;
bjornv@webrtc.org8dd60cc2014-09-11 08:36:35 +00002295 EXPECT_NEAR(test->ns_speech_probability_average(),
2296 ns_speech_prob_average,
2297 kFloatNear);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002298#endif
2299 } else {
2300 test->set_has_echo_count(has_echo_count);
2301 test->set_has_voice_count(has_voice_count);
2302 test->set_is_saturated_count(is_saturated_count);
2303
2304 test->set_analog_level_average(analog_level_average);
2305 test->set_max_output_average(max_output_average);
2306
andrew@webrtc.org293d22b2012-01-30 22:04:26 +00002307#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
bjornv@webrtc.org08329f42012-07-12 21:00:43 +00002308 EXPECT_LE(0.0f, ns_speech_prob_average);
2309 EXPECT_GE(1.0f, ns_speech_prob_average);
2310 test->set_ns_speech_probability_average(ns_speech_prob_average);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002311#endif
2312 }
2313
2314 rewind(far_file_);
2315 rewind(near_file_);
2316 }
2317
andrew@webrtc.orgdaacee82012-02-07 00:01:04 +00002318 if (write_ref_data) {
andrew@webrtc.orga8b97372014-03-10 22:26:12 +00002319 OpenFileAndWriteMessage(ref_filename_, ref_data);
andrew@webrtc.org755b04a2011-11-15 16:57:56 +00002320 }
2321}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002322
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002323TEST_F(ApmTest, NoErrorsWithKeyboardChannel) {
2324 struct ChannelFormat {
2325 AudioProcessing::ChannelLayout in_layout;
2326 AudioProcessing::ChannelLayout out_layout;
2327 };
2328 ChannelFormat cf[] = {
2329 {AudioProcessing::kMonoAndKeyboard, AudioProcessing::kMono},
2330 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kMono},
2331 {AudioProcessing::kStereoAndKeyboard, AudioProcessing::kStereo},
2332 };
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002333
Ivo Creusen62337e52018-01-09 14:17:33 +01002334 std::unique_ptr<AudioProcessing> ap(AudioProcessingBuilder().Create());
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002335 // Enable one component just to ensure some processing takes place.
2336 ap->noise_suppression()->Enable(true);
pkasting25702cb2016-01-08 13:50:27 -08002337 for (size_t i = 0; i < arraysize(cf); ++i) {
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002338 const int in_rate = 44100;
2339 const int out_rate = 48000;
2340 ChannelBuffer<float> in_cb(SamplesFromRate(in_rate),
2341 TotalChannelsFromLayout(cf[i].in_layout));
2342 ChannelBuffer<float> out_cb(SamplesFromRate(out_rate),
2343 ChannelsFromLayout(cf[i].out_layout));
2344
2345 // Run over a few chunks.
2346 for (int j = 0; j < 10; ++j) {
2347 EXPECT_NOERR(ap->ProcessStream(
2348 in_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002349 in_cb.num_frames(),
andrew@webrtc.org103657b2014-04-24 18:28:56 +00002350 in_rate,
2351 cf[i].in_layout,
2352 out_rate,
2353 cf[i].out_layout,
2354 out_cb.channels()));
2355 }
2356 }
2357}
2358
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002359// Compares the reference and test arrays over a region around the expected
2360// delay. Finds the highest SNR in that region and adds the variance and squared
2361// error results to the supplied accumulators.
2362void UpdateBestSNR(const float* ref,
2363 const float* test,
pkasting25702cb2016-01-08 13:50:27 -08002364 size_t length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002365 int expected_delay,
2366 double* variance_acc,
2367 double* sq_error_acc) {
2368 double best_snr = std::numeric_limits<double>::min();
2369 double best_variance = 0;
2370 double best_sq_error = 0;
2371 // Search over a region of eight samples around the expected delay.
2372 for (int delay = std::max(expected_delay - 4, 0); delay <= expected_delay + 4;
2373 ++delay) {
2374 double sq_error = 0;
2375 double variance = 0;
pkasting25702cb2016-01-08 13:50:27 -08002376 for (size_t i = 0; i < length - delay; ++i) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002377 double error = test[i + delay] - ref[i];
2378 sq_error += error * error;
2379 variance += ref[i] * ref[i];
2380 }
2381
2382 if (sq_error == 0) {
2383 *variance_acc += variance;
2384 return;
2385 }
2386 double snr = variance / sq_error;
2387 if (snr > best_snr) {
2388 best_snr = snr;
2389 best_variance = variance;
2390 best_sq_error = sq_error;
2391 }
2392 }
2393
2394 *variance_acc += best_variance;
2395 *sq_error_acc += best_sq_error;
2396}
2397
2398// Used to test a multitude of sample rate and channel combinations. It works
2399// by first producing a set of reference files (in SetUpTestCase) that are
2400// assumed to be correct, as the used parameters are verified by other tests
2401// in this collection. Primarily the reference files are all produced at
2402// "native" rates which do not involve any resampling.
2403
2404// Each test pass produces an output file with a particular format. The output
2405// is matched against the reference file closest to its internal processing
2406// format. If necessary the output is resampled back to its process format.
2407// Due to the resampling distortion, we don't expect identical results, but
2408// enforce SNR thresholds which vary depending on the format. 0 is a special
2409// case SNR which corresponds to inf, or zero error.
Edward Lemurc5ee9872017-10-23 23:33:04 +02002410typedef std::tuple<int, int, int, int, double, double> AudioProcessingTestData;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002411class AudioProcessingTest
2412 : public testing::TestWithParam<AudioProcessingTestData> {
2413 public:
2414 AudioProcessingTest()
Edward Lemurc5ee9872017-10-23 23:33:04 +02002415 : input_rate_(std::get<0>(GetParam())),
2416 output_rate_(std::get<1>(GetParam())),
2417 reverse_input_rate_(std::get<2>(GetParam())),
2418 reverse_output_rate_(std::get<3>(GetParam())),
2419 expected_snr_(std::get<4>(GetParam())),
2420 expected_reverse_snr_(std::get<5>(GetParam())) {}
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002421
2422 virtual ~AudioProcessingTest() {}
2423
2424 static void SetUpTestCase() {
2425 // Create all needed output reference files.
Alejandro Luebs47748742015-05-22 12:00:21 -07002426 const int kNativeRates[] = {8000, 16000, 32000, 48000};
Peter Kasting69558702016-01-12 16:26:35 -08002427 const size_t kNumChannels[] = {1, 2};
pkasting25702cb2016-01-08 13:50:27 -08002428 for (size_t i = 0; i < arraysize(kNativeRates); ++i) {
2429 for (size_t j = 0; j < arraysize(kNumChannels); ++j) {
2430 for (size_t k = 0; k < arraysize(kNumChannels); ++k) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002431 // The reference files always have matching input and output channels.
ekmeyerson60d9b332015-08-14 10:35:55 -07002432 ProcessFormat(kNativeRates[i], kNativeRates[i], kNativeRates[i],
2433 kNativeRates[i], kNumChannels[j], kNumChannels[j],
2434 kNumChannels[k], kNumChannels[k], "ref");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002435 }
2436 }
2437 }
2438 }
2439
Gustaf Ullberg8ffeeb22017-10-11 11:42:38 +02002440 void TearDown() {
2441 // Remove "out" files after each test.
2442 ClearTempOutFiles();
2443 }
2444
pbos@webrtc.org200ac002015-02-03 14:14:01 +00002445 static void TearDownTestCase() {
2446 ClearTempFiles();
2447 }
ekmeyerson60d9b332015-08-14 10:35:55 -07002448
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002449 // Runs a process pass on files with the given parameters and dumps the output
ekmeyerson60d9b332015-08-14 10:35:55 -07002450 // to a file specified with |output_file_prefix|. Both forward and reverse
2451 // output streams are dumped.
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002452 static void ProcessFormat(int input_rate,
2453 int output_rate,
ekmeyerson60d9b332015-08-14 10:35:55 -07002454 int reverse_input_rate,
2455 int reverse_output_rate,
Peter Kasting69558702016-01-12 16:26:35 -08002456 size_t num_input_channels,
2457 size_t num_output_channels,
2458 size_t num_reverse_input_channels,
2459 size_t num_reverse_output_channels,
Alex Loiko890988c2017-08-31 10:25:48 +02002460 const std::string& output_file_prefix) {
andrew@webrtc.org8328e7c2014-10-31 04:58:14 +00002461 Config config;
2462 config.Set<ExperimentalAgc>(new ExperimentalAgc(false));
Ivo Creusen62337e52018-01-09 14:17:33 +01002463 std::unique_ptr<AudioProcessing> ap(
2464 AudioProcessingBuilder().Create(config));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002465 EnableAllAPComponents(ap.get());
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002466
ekmeyerson60d9b332015-08-14 10:35:55 -07002467 ProcessingConfig processing_config = {
2468 {{input_rate, num_input_channels},
2469 {output_rate, num_output_channels},
2470 {reverse_input_rate, num_reverse_input_channels},
2471 {reverse_output_rate, num_reverse_output_channels}}};
2472 ap->Initialize(processing_config);
2473
2474 FILE* far_file =
2475 fopen(ResourceFilePath("far", reverse_input_rate).c_str(), "rb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002476 FILE* near_file = fopen(ResourceFilePath("near", input_rate).c_str(), "rb");
ekmeyerson60d9b332015-08-14 10:35:55 -07002477 FILE* out_file =
2478 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2479 reverse_input_rate, reverse_output_rate,
2480 num_input_channels, num_output_channels,
2481 num_reverse_input_channels,
2482 num_reverse_output_channels, kForward).c_str(),
2483 "wb");
2484 FILE* rev_out_file =
2485 fopen(OutputFilePath(output_file_prefix, input_rate, output_rate,
2486 reverse_input_rate, reverse_output_rate,
2487 num_input_channels, num_output_channels,
2488 num_reverse_input_channels,
2489 num_reverse_output_channels, kReverse).c_str(),
2490 "wb");
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002491 ASSERT_TRUE(far_file != NULL);
2492 ASSERT_TRUE(near_file != NULL);
2493 ASSERT_TRUE(out_file != NULL);
ekmeyerson60d9b332015-08-14 10:35:55 -07002494 ASSERT_TRUE(rev_out_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002495
2496 ChannelBuffer<float> fwd_cb(SamplesFromRate(input_rate),
2497 num_input_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002498 ChannelBuffer<float> rev_cb(SamplesFromRate(reverse_input_rate),
2499 num_reverse_input_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002500 ChannelBuffer<float> out_cb(SamplesFromRate(output_rate),
2501 num_output_channels);
ekmeyerson60d9b332015-08-14 10:35:55 -07002502 ChannelBuffer<float> rev_out_cb(SamplesFromRate(reverse_output_rate),
2503 num_reverse_output_channels);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002504
2505 // Temporary buffers.
2506 const int max_length =
ekmeyerson60d9b332015-08-14 10:35:55 -07002507 2 * std::max(std::max(out_cb.num_frames(), rev_out_cb.num_frames()),
2508 std::max(fwd_cb.num_frames(), rev_cb.num_frames()));
kwiberg62eaacf2016-02-17 06:39:05 -08002509 std::unique_ptr<float[]> float_data(new float[max_length]);
2510 std::unique_ptr<int16_t[]> int_data(new int16_t[max_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002511
2512 int analog_level = 127;
2513 while (ReadChunk(far_file, int_data.get(), float_data.get(), &rev_cb) &&
2514 ReadChunk(near_file, int_data.get(), float_data.get(), &fwd_cb)) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002515 EXPECT_NOERR(ap->ProcessReverseStream(
2516 rev_cb.channels(), processing_config.reverse_input_stream(),
2517 processing_config.reverse_output_stream(), rev_out_cb.channels()));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002518
2519 EXPECT_NOERR(ap->set_stream_delay_ms(0));
2520 ap->echo_cancellation()->set_stream_drift_samples(0);
2521 EXPECT_NOERR(ap->gain_control()->set_stream_analog_level(analog_level));
2522
2523 EXPECT_NOERR(ap->ProcessStream(
2524 fwd_cb.channels(),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002525 fwd_cb.num_frames(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002526 input_rate,
2527 LayoutFromChannels(num_input_channels),
2528 output_rate,
2529 LayoutFromChannels(num_output_channels),
2530 out_cb.channels()));
2531
ekmeyerson60d9b332015-08-14 10:35:55 -07002532 // Dump forward output to file.
2533 Interleave(out_cb.channels(), out_cb.num_frames(), out_cb.num_channels(),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002534 float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002535 size_t out_length = out_cb.num_channels() * out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002536
pkasting25702cb2016-01-08 13:50:27 -08002537 ASSERT_EQ(out_length,
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002538 fwrite(float_data.get(), sizeof(float_data[0]),
aluebs@webrtc.orgd35a5c32015-02-10 22:52:15 +00002539 out_length, out_file));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002540
ekmeyerson60d9b332015-08-14 10:35:55 -07002541 // Dump reverse output to file.
2542 Interleave(rev_out_cb.channels(), rev_out_cb.num_frames(),
2543 rev_out_cb.num_channels(), float_data.get());
pkasting25702cb2016-01-08 13:50:27 -08002544 size_t rev_out_length =
2545 rev_out_cb.num_channels() * rev_out_cb.num_frames();
ekmeyerson60d9b332015-08-14 10:35:55 -07002546
pkasting25702cb2016-01-08 13:50:27 -08002547 ASSERT_EQ(rev_out_length,
ekmeyerson60d9b332015-08-14 10:35:55 -07002548 fwrite(float_data.get(), sizeof(float_data[0]), rev_out_length,
2549 rev_out_file));
2550
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002551 analog_level = ap->gain_control()->stream_analog_level();
2552 }
2553 fclose(far_file);
2554 fclose(near_file);
2555 fclose(out_file);
ekmeyerson60d9b332015-08-14 10:35:55 -07002556 fclose(rev_out_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002557 }
2558
2559 protected:
2560 int input_rate_;
2561 int output_rate_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002562 int reverse_input_rate_;
2563 int reverse_output_rate_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002564 double expected_snr_;
ekmeyerson60d9b332015-08-14 10:35:55 -07002565 double expected_reverse_snr_;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002566};
2567
bjornv@webrtc.org2812b592014-06-02 11:27:29 +00002568TEST_P(AudioProcessingTest, Formats) {
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002569 struct ChannelFormat {
2570 int num_input;
2571 int num_output;
ekmeyerson60d9b332015-08-14 10:35:55 -07002572 int num_reverse_input;
2573 int num_reverse_output;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002574 };
2575 ChannelFormat cf[] = {
ekmeyerson60d9b332015-08-14 10:35:55 -07002576 {1, 1, 1, 1},
2577 {1, 1, 2, 1},
2578 {2, 1, 1, 1},
2579 {2, 1, 2, 1},
2580 {2, 2, 1, 1},
2581 {2, 2, 2, 2},
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002582 };
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002583
pkasting25702cb2016-01-08 13:50:27 -08002584 for (size_t i = 0; i < arraysize(cf); ++i) {
ekmeyerson60d9b332015-08-14 10:35:55 -07002585 ProcessFormat(input_rate_, output_rate_, reverse_input_rate_,
2586 reverse_output_rate_, cf[i].num_input, cf[i].num_output,
2587 cf[i].num_reverse_input, cf[i].num_reverse_output, "out");
Alejandro Luebs47748742015-05-22 12:00:21 -07002588
ekmeyerson60d9b332015-08-14 10:35:55 -07002589 // Verify output for both directions.
2590 std::vector<StreamDirection> stream_directions;
2591 stream_directions.push_back(kForward);
2592 stream_directions.push_back(kReverse);
2593 for (StreamDirection file_direction : stream_directions) {
2594 const int in_rate = file_direction ? reverse_input_rate_ : input_rate_;
2595 const int out_rate = file_direction ? reverse_output_rate_ : output_rate_;
2596 const int out_num =
2597 file_direction ? cf[i].num_reverse_output : cf[i].num_output;
2598 const double expected_snr =
2599 file_direction ? expected_reverse_snr_ : expected_snr_;
2600
2601 const int min_ref_rate = std::min(in_rate, out_rate);
2602 int ref_rate;
2603
2604 if (min_ref_rate > 32000) {
2605 ref_rate = 48000;
2606 } else if (min_ref_rate > 16000) {
2607 ref_rate = 32000;
2608 } else if (min_ref_rate > 8000) {
2609 ref_rate = 16000;
2610 } else {
2611 ref_rate = 8000;
2612 }
aluebs776593b2016-03-15 14:04:58 -07002613#ifdef WEBRTC_ARCH_ARM_FAMILY
perkjdfc28702016-03-09 16:23:23 -08002614 if (file_direction == kForward) {
aluebs776593b2016-03-15 14:04:58 -07002615 ref_rate = std::min(ref_rate, 32000);
perkjdfc28702016-03-09 16:23:23 -08002616 }
2617#endif
ekmeyerson60d9b332015-08-14 10:35:55 -07002618 FILE* out_file = fopen(
2619 OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_,
2620 reverse_output_rate_, cf[i].num_input,
2621 cf[i].num_output, cf[i].num_reverse_input,
2622 cf[i].num_reverse_output, file_direction).c_str(),
2623 "rb");
2624 // The reference files always have matching input and output channels.
2625 FILE* ref_file = fopen(
2626 OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate,
2627 cf[i].num_output, cf[i].num_output,
2628 cf[i].num_reverse_output, cf[i].num_reverse_output,
2629 file_direction).c_str(),
2630 "rb");
2631 ASSERT_TRUE(out_file != NULL);
2632 ASSERT_TRUE(ref_file != NULL);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002633
pkasting25702cb2016-01-08 13:50:27 -08002634 const size_t ref_length = SamplesFromRate(ref_rate) * out_num;
2635 const size_t out_length = SamplesFromRate(out_rate) * out_num;
ekmeyerson60d9b332015-08-14 10:35:55 -07002636 // Data from the reference file.
kwiberg62eaacf2016-02-17 06:39:05 -08002637 std::unique_ptr<float[]> ref_data(new float[ref_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002638 // Data from the output file.
kwiberg62eaacf2016-02-17 06:39:05 -08002639 std::unique_ptr<float[]> out_data(new float[out_length]);
ekmeyerson60d9b332015-08-14 10:35:55 -07002640 // Data from the resampled output, in case the reference and output rates
2641 // don't match.
kwiberg62eaacf2016-02-17 06:39:05 -08002642 std::unique_ptr<float[]> cmp_data(new float[ref_length]);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002643
ekmeyerson60d9b332015-08-14 10:35:55 -07002644 PushResampler<float> resampler;
2645 resampler.InitializeIfNeeded(out_rate, ref_rate, out_num);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002646
ekmeyerson60d9b332015-08-14 10:35:55 -07002647 // Compute the resampling delay of the output relative to the reference,
2648 // to find the region over which we should search for the best SNR.
2649 float expected_delay_sec = 0;
2650 if (in_rate != ref_rate) {
2651 // Input resampling delay.
2652 expected_delay_sec +=
2653 PushSincResampler::AlgorithmicDelaySeconds(in_rate);
2654 }
2655 if (out_rate != ref_rate) {
2656 // Output resampling delay.
2657 expected_delay_sec +=
2658 PushSincResampler::AlgorithmicDelaySeconds(ref_rate);
2659 // Delay of converting the output back to its processing rate for
2660 // testing.
2661 expected_delay_sec +=
2662 PushSincResampler::AlgorithmicDelaySeconds(out_rate);
2663 }
2664 int expected_delay =
2665 floor(expected_delay_sec * ref_rate + 0.5f) * out_num;
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002666
ekmeyerson60d9b332015-08-14 10:35:55 -07002667 double variance = 0;
2668 double sq_error = 0;
2669 while (fread(out_data.get(), sizeof(out_data[0]), out_length, out_file) &&
2670 fread(ref_data.get(), sizeof(ref_data[0]), ref_length, ref_file)) {
2671 float* out_ptr = out_data.get();
2672 if (out_rate != ref_rate) {
2673 // Resample the output back to its internal processing rate if
2674 // necssary.
pkasting25702cb2016-01-08 13:50:27 -08002675 ASSERT_EQ(ref_length,
2676 static_cast<size_t>(resampler.Resample(
2677 out_ptr, out_length, cmp_data.get(), ref_length)));
ekmeyerson60d9b332015-08-14 10:35:55 -07002678 out_ptr = cmp_data.get();
2679 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002680
ekmeyerson60d9b332015-08-14 10:35:55 -07002681 // Update the |sq_error| and |variance| accumulators with the highest
2682 // SNR of reference vs output.
2683 UpdateBestSNR(ref_data.get(), out_ptr, ref_length, expected_delay,
2684 &variance, &sq_error);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002685 }
2686
ekmeyerson60d9b332015-08-14 10:35:55 -07002687 std::cout << "(" << input_rate_ << ", " << output_rate_ << ", "
2688 << reverse_input_rate_ << ", " << reverse_output_rate_ << ", "
2689 << cf[i].num_input << ", " << cf[i].num_output << ", "
2690 << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output
2691 << ", " << file_direction << "): ";
2692 if (sq_error > 0) {
2693 double snr = 10 * log10(variance / sq_error);
2694 EXPECT_GE(snr, expected_snr);
2695 EXPECT_NE(0, expected_snr);
2696 std::cout << "SNR=" << snr << " dB" << std::endl;
2697 } else {
aluebs776593b2016-03-15 14:04:58 -07002698 std::cout << "SNR=inf dB" << std::endl;
ekmeyerson60d9b332015-08-14 10:35:55 -07002699 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002700
ekmeyerson60d9b332015-08-14 10:35:55 -07002701 fclose(out_file);
2702 fclose(ref_file);
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002703 }
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002704 }
2705}
2706
2707#if defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE)
2708INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002709 CommonFormats,
2710 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002711 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 0, 0),
2712 std::make_tuple(48000, 48000, 32000, 48000, 40, 30),
2713 std::make_tuple(48000, 48000, 16000, 48000, 40, 20),
2714 std::make_tuple(48000, 44100, 48000, 44100, 20, 20),
2715 std::make_tuple(48000, 44100, 32000, 44100, 20, 15),
2716 std::make_tuple(48000, 44100, 16000, 44100, 20, 15),
2717 std::make_tuple(48000, 32000, 48000, 32000, 30, 35),
2718 std::make_tuple(48000, 32000, 32000, 32000, 30, 0),
2719 std::make_tuple(48000, 32000, 16000, 32000, 30, 20),
2720 std::make_tuple(48000, 16000, 48000, 16000, 25, 20),
2721 std::make_tuple(48000, 16000, 32000, 16000, 25, 20),
2722 std::make_tuple(48000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002723
Edward Lemurc5ee9872017-10-23 23:33:04 +02002724 std::make_tuple(44100, 48000, 48000, 48000, 30, 0),
2725 std::make_tuple(44100, 48000, 32000, 48000, 30, 30),
2726 std::make_tuple(44100, 48000, 16000, 48000, 30, 20),
2727 std::make_tuple(44100, 44100, 48000, 44100, 20, 20),
2728 std::make_tuple(44100, 44100, 32000, 44100, 20, 15),
2729 std::make_tuple(44100, 44100, 16000, 44100, 20, 15),
2730 std::make_tuple(44100, 32000, 48000, 32000, 30, 35),
2731 std::make_tuple(44100, 32000, 32000, 32000, 30, 0),
2732 std::make_tuple(44100, 32000, 16000, 32000, 30, 20),
2733 std::make_tuple(44100, 16000, 48000, 16000, 25, 20),
2734 std::make_tuple(44100, 16000, 32000, 16000, 25, 20),
2735 std::make_tuple(44100, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002736
Edward Lemurc5ee9872017-10-23 23:33:04 +02002737 std::make_tuple(32000, 48000, 48000, 48000, 30, 0),
2738 std::make_tuple(32000, 48000, 32000, 48000, 35, 30),
2739 std::make_tuple(32000, 48000, 16000, 48000, 30, 20),
2740 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2741 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2742 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2743 std::make_tuple(32000, 32000, 48000, 32000, 40, 35),
2744 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2745 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2746 std::make_tuple(32000, 16000, 48000, 16000, 25, 20),
2747 std::make_tuple(32000, 16000, 32000, 16000, 25, 20),
2748 std::make_tuple(32000, 16000, 16000, 16000, 25, 0),
Alejandro Luebs47748742015-05-22 12:00:21 -07002749
Edward Lemurc5ee9872017-10-23 23:33:04 +02002750 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2751 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2752 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2753 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2754 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2755 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2756 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2757 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2758 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2759 std::make_tuple(16000, 16000, 48000, 16000, 40, 20),
2760 std::make_tuple(16000, 16000, 32000, 16000, 40, 20),
2761 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
Alejandro Luebs47748742015-05-22 12:00:21 -07002762
2763#elif defined(WEBRTC_AUDIOPROC_FIXED_PROFILE)
2764INSTANTIATE_TEST_CASE_P(
ekmeyerson60d9b332015-08-14 10:35:55 -07002765 CommonFormats,
2766 AudioProcessingTest,
Edward Lemurc5ee9872017-10-23 23:33:04 +02002767 testing::Values(std::make_tuple(48000, 48000, 48000, 48000, 20, 0),
2768 std::make_tuple(48000, 48000, 32000, 48000, 20, 30),
2769 std::make_tuple(48000, 48000, 16000, 48000, 20, 20),
2770 std::make_tuple(48000, 44100, 48000, 44100, 15, 20),
2771 std::make_tuple(48000, 44100, 32000, 44100, 15, 15),
2772 std::make_tuple(48000, 44100, 16000, 44100, 15, 15),
2773 std::make_tuple(48000, 32000, 48000, 32000, 20, 35),
2774 std::make_tuple(48000, 32000, 32000, 32000, 20, 0),
2775 std::make_tuple(48000, 32000, 16000, 32000, 20, 20),
2776 std::make_tuple(48000, 16000, 48000, 16000, 20, 20),
2777 std::make_tuple(48000, 16000, 32000, 16000, 20, 20),
2778 std::make_tuple(48000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002779
Edward Lemurc5ee9872017-10-23 23:33:04 +02002780 std::make_tuple(44100, 48000, 48000, 48000, 15, 0),
2781 std::make_tuple(44100, 48000, 32000, 48000, 15, 30),
2782 std::make_tuple(44100, 48000, 16000, 48000, 15, 20),
2783 std::make_tuple(44100, 44100, 48000, 44100, 15, 20),
2784 std::make_tuple(44100, 44100, 32000, 44100, 15, 15),
2785 std::make_tuple(44100, 44100, 16000, 44100, 15, 15),
2786 std::make_tuple(44100, 32000, 48000, 32000, 20, 35),
2787 std::make_tuple(44100, 32000, 32000, 32000, 20, 0),
2788 std::make_tuple(44100, 32000, 16000, 32000, 20, 20),
2789 std::make_tuple(44100, 16000, 48000, 16000, 20, 20),
2790 std::make_tuple(44100, 16000, 32000, 16000, 20, 20),
2791 std::make_tuple(44100, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002792
Edward Lemurc5ee9872017-10-23 23:33:04 +02002793 std::make_tuple(32000, 48000, 48000, 48000, 35, 0),
2794 std::make_tuple(32000, 48000, 32000, 48000, 65, 30),
2795 std::make_tuple(32000, 48000, 16000, 48000, 40, 20),
2796 std::make_tuple(32000, 44100, 48000, 44100, 20, 20),
2797 std::make_tuple(32000, 44100, 32000, 44100, 20, 15),
2798 std::make_tuple(32000, 44100, 16000, 44100, 20, 15),
2799 std::make_tuple(32000, 32000, 48000, 32000, 35, 35),
2800 std::make_tuple(32000, 32000, 32000, 32000, 0, 0),
2801 std::make_tuple(32000, 32000, 16000, 32000, 40, 20),
2802 std::make_tuple(32000, 16000, 48000, 16000, 20, 20),
2803 std::make_tuple(32000, 16000, 32000, 16000, 20, 20),
2804 std::make_tuple(32000, 16000, 16000, 16000, 20, 0),
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002805
Edward Lemurc5ee9872017-10-23 23:33:04 +02002806 std::make_tuple(16000, 48000, 48000, 48000, 25, 0),
2807 std::make_tuple(16000, 48000, 32000, 48000, 25, 30),
2808 std::make_tuple(16000, 48000, 16000, 48000, 25, 20),
2809 std::make_tuple(16000, 44100, 48000, 44100, 15, 20),
2810 std::make_tuple(16000, 44100, 32000, 44100, 15, 15),
2811 std::make_tuple(16000, 44100, 16000, 44100, 15, 15),
2812 std::make_tuple(16000, 32000, 48000, 32000, 25, 35),
2813 std::make_tuple(16000, 32000, 32000, 32000, 25, 0),
2814 std::make_tuple(16000, 32000, 16000, 32000, 25, 20),
2815 std::make_tuple(16000, 16000, 48000, 16000, 35, 20),
2816 std::make_tuple(16000, 16000, 32000, 16000, 35, 20),
2817 std::make_tuple(16000, 16000, 16000, 16000, 0, 0)));
andrew@webrtc.orgddbb8a22014-04-22 21:00:04 +00002818#endif
2819
niklase@google.com470e71d2011-07-07 08:21:25 +00002820} // namespace
peahc19f3122016-10-07 14:54:10 -07002821
Sam Zackrisson0beac582017-09-25 12:04:02 +02002822TEST(ApmConfiguration, EnablePostProcessing) {
2823 // Verify that apm uses a capture post processing module if one is provided.
2824 webrtc::Config webrtc_config;
2825 auto mock_post_processor_ptr =
Alex Loiko5825aa62017-12-18 16:02:40 +01002826 new testing::NiceMock<test::MockCustomProcessing>();
Sam Zackrisson0beac582017-09-25 12:04:02 +02002827 auto mock_post_processor =
Alex Loiko5825aa62017-12-18 16:02:40 +01002828 std::unique_ptr<CustomProcessing>(mock_post_processor_ptr);
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002829 rtc::scoped_refptr<AudioProcessing> apm =
2830 AudioProcessingBuilder()
2831 .SetCapturePostProcessing(std::move(mock_post_processor))
2832 .Create(webrtc_config);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002833
2834 AudioFrame audio;
2835 audio.num_channels_ = 1;
2836 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2837
2838 EXPECT_CALL(*mock_post_processor_ptr, Process(testing::_)).Times(1);
Gustaf Ullbergd8579e02017-10-11 16:29:02 +02002839 apm->ProcessStream(&audio);
Sam Zackrisson0beac582017-09-25 12:04:02 +02002840}
2841
Alex Loiko5825aa62017-12-18 16:02:40 +01002842TEST(ApmConfiguration, EnablePreProcessing) {
2843 // Verify that apm uses a capture post processing module if one is provided.
2844 webrtc::Config webrtc_config;
2845 auto mock_pre_processor_ptr =
2846 new testing::NiceMock<test::MockCustomProcessing>();
2847 auto mock_pre_processor =
2848 std::unique_ptr<CustomProcessing>(mock_pre_processor_ptr);
Ivo Creusen62337e52018-01-09 14:17:33 +01002849 rtc::scoped_refptr<AudioProcessing> apm =
2850 AudioProcessingBuilder()
2851 .SetRenderPreProcessing(std::move(mock_pre_processor))
2852 .Create(webrtc_config);
Alex Loiko5825aa62017-12-18 16:02:40 +01002853
2854 AudioFrame audio;
2855 audio.num_channels_ = 1;
2856 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2857
2858 EXPECT_CALL(*mock_pre_processor_ptr, Process(testing::_)).Times(1);
2859 apm->ProcessReverseStream(&audio);
2860}
2861
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002862class MyEchoControlFactory : public EchoControlFactory {
2863 public:
2864 std::unique_ptr<EchoControl> Create(int sample_rate_hz) {
2865 auto ec = new test::MockEchoControl();
2866 EXPECT_CALL(*ec, AnalyzeRender(testing::_)).Times(1);
2867 EXPECT_CALL(*ec, AnalyzeCapture(testing::_)).Times(2);
2868 EXPECT_CALL(*ec, ProcessCapture(testing::_, testing::_)).Times(2);
2869 return std::unique_ptr<EchoControl>(ec);
2870 }
2871};
2872
2873TEST(ApmConfiguration, EchoControlInjection) {
2874 // Verify that apm uses an injected echo controller if one is provided.
2875 webrtc::Config webrtc_config;
2876 std::unique_ptr<EchoControlFactory> echo_control_factory(
2877 new MyEchoControlFactory());
2878
Alex Loiko5825aa62017-12-18 16:02:40 +01002879 rtc::scoped_refptr<AudioProcessing> apm =
Ivo Creusen5ec7e122017-12-22 11:35:59 +01002880 AudioProcessingBuilder()
2881 .SetEchoControlFactory(std::move(echo_control_factory))
2882 .Create(webrtc_config);
Gustaf Ullberg002ef282017-10-12 15:13:17 +02002883
2884 AudioFrame audio;
2885 audio.num_channels_ = 1;
2886 SetFrameSampleRate(&audio, AudioProcessing::NativeRate::kSampleRate16kHz);
2887 apm->ProcessStream(&audio);
2888 apm->ProcessReverseStream(&audio);
2889 apm->ProcessStream(&audio);
2890}
Ivo Creusenae026092017-11-20 13:07:16 +01002891
2892std::unique_ptr<AudioProcessing> CreateApm(bool use_AEC2) {
2893 Config old_config;
2894 if (use_AEC2) {
2895 old_config.Set<ExtendedFilter>(new ExtendedFilter(true));
2896 old_config.Set<DelayAgnostic>(new DelayAgnostic(true));
2897 }
Ivo Creusen62337e52018-01-09 14:17:33 +01002898 std::unique_ptr<AudioProcessing> apm(
2899 AudioProcessingBuilder().Create(old_config));
Ivo Creusenae026092017-11-20 13:07:16 +01002900 if (!apm) {
2901 return apm;
2902 }
2903
2904 ProcessingConfig processing_config = {
2905 {{32000, 1}, {32000, 1}, {32000, 1}, {32000, 1}}};
2906
2907 if (apm->Initialize(processing_config) != 0) {
2908 return nullptr;
2909 }
2910
2911 // Disable all components except for an AEC and the residual echo detector.
2912 AudioProcessing::Config config;
2913 config.residual_echo_detector.enabled = true;
Ivo Creusenae026092017-11-20 13:07:16 +01002914 config.high_pass_filter.enabled = false;
2915 config.gain_controller2.enabled = false;
Ivo Creusenae026092017-11-20 13:07:16 +01002916 apm->ApplyConfig(config);
2917 EXPECT_EQ(apm->gain_control()->Enable(false), 0);
2918 EXPECT_EQ(apm->level_estimator()->Enable(false), 0);
2919 EXPECT_EQ(apm->noise_suppression()->Enable(false), 0);
2920 EXPECT_EQ(apm->voice_detection()->Enable(false), 0);
2921
2922 if (use_AEC2) {
2923 EXPECT_EQ(apm->echo_control_mobile()->Enable(false), 0);
2924 EXPECT_EQ(apm->echo_cancellation()->enable_metrics(true), 0);
2925 EXPECT_EQ(apm->echo_cancellation()->enable_delay_logging(true), 0);
2926 EXPECT_EQ(apm->echo_cancellation()->Enable(true), 0);
2927 } else {
2928 EXPECT_EQ(apm->echo_cancellation()->Enable(false), 0);
2929 EXPECT_EQ(apm->echo_control_mobile()->Enable(true), 0);
2930 }
2931 return apm;
2932}
2933
2934#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_MAC)
2935#define MAYBE_ApmStatistics DISABLED_ApmStatistics
2936#else
2937#define MAYBE_ApmStatistics ApmStatistics
2938#endif
2939
2940TEST(MAYBE_ApmStatistics, AEC2EnabledTest) {
2941 // Set up APM with AEC2 and process some audio.
2942 std::unique_ptr<AudioProcessing> apm = CreateApm(true);
2943 ASSERT_TRUE(apm);
2944
2945 // Set up an audioframe.
2946 AudioFrame frame;
2947 frame.num_channels_ = 1;
2948 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
2949
2950 // Fill the audio frame with a sawtooth pattern.
2951 int16_t* ptr = frame.mutable_data();
2952 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
2953 ptr[i] = 10000 * ((i % 3) - 1);
2954 }
2955
2956 // Do some processing.
2957 for (int i = 0; i < 200; i++) {
2958 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
2959 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
2960 EXPECT_EQ(apm->ProcessStream(&frame), 0);
2961 }
2962
2963 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01002964 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01002965 // We expect all statistics to be set and have a sensible value.
2966 ASSERT_TRUE(stats.residual_echo_likelihood);
2967 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
2968 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
2969 ASSERT_TRUE(stats.residual_echo_likelihood_recent_max);
2970 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
2971 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
2972 ASSERT_TRUE(stats.echo_return_loss);
2973 EXPECT_NE(*stats.echo_return_loss, -100.0);
2974 ASSERT_TRUE(stats.echo_return_loss_enhancement);
2975 EXPECT_NE(*stats.echo_return_loss_enhancement, -100.0);
2976 ASSERT_TRUE(stats.divergent_filter_fraction);
2977 EXPECT_NE(*stats.divergent_filter_fraction, -1.0);
2978 ASSERT_TRUE(stats.delay_standard_deviation_ms);
2979 EXPECT_GE(*stats.delay_standard_deviation_ms, 0);
2980 // We don't check stats.delay_median_ms since it takes too long to settle to a
2981 // value. At least 20 seconds of data need to be processed before it will get
2982 // a value, which would make this test take too much time.
2983
2984 // If there are no receive streams, we expect the stats not to be set. The
2985 // 'false' argument signals to APM that no receive streams are currently
2986 // active. In that situation the statistics would get stuck at their last
2987 // calculated value (AEC and echo detection need at least one stream in each
2988 // direction), so to avoid that, they should not be set by APM.
2989 stats = apm->GetStatistics(false);
2990 EXPECT_FALSE(stats.residual_echo_likelihood);
2991 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
2992 EXPECT_FALSE(stats.echo_return_loss);
2993 EXPECT_FALSE(stats.echo_return_loss_enhancement);
2994 EXPECT_FALSE(stats.divergent_filter_fraction);
2995 EXPECT_FALSE(stats.delay_median_ms);
2996 EXPECT_FALSE(stats.delay_standard_deviation_ms);
2997}
2998
2999TEST(MAYBE_ApmStatistics, AECMEnabledTest) {
3000 // Set up APM with AECM and process some audio.
3001 std::unique_ptr<AudioProcessing> apm = CreateApm(false);
3002 ASSERT_TRUE(apm);
3003
3004 // Set up an audioframe.
3005 AudioFrame frame;
3006 frame.num_channels_ = 1;
3007 SetFrameSampleRate(&frame, AudioProcessing::NativeRate::kSampleRate48kHz);
3008
3009 // Fill the audio frame with a sawtooth pattern.
3010 int16_t* ptr = frame.mutable_data();
3011 for (size_t i = 0; i < frame.kMaxDataSizeSamples; i++) {
3012 ptr[i] = 10000 * ((i % 3) - 1);
3013 }
3014
3015 // Do some processing.
3016 for (int i = 0; i < 200; i++) {
3017 EXPECT_EQ(apm->ProcessReverseStream(&frame), 0);
3018 EXPECT_EQ(apm->set_stream_delay_ms(0), 0);
3019 EXPECT_EQ(apm->ProcessStream(&frame), 0);
3020 }
3021
3022 // Test statistics interface.
Ivo Creusen56d46092017-11-24 17:29:59 +01003023 AudioProcessingStats stats = apm->GetStatistics(true);
Ivo Creusenae026092017-11-20 13:07:16 +01003024 // We expect only the residual echo detector statistics to be set and have a
3025 // sensible value.
3026 EXPECT_TRUE(stats.residual_echo_likelihood);
3027 if (stats.residual_echo_likelihood) {
3028 EXPECT_GE(*stats.residual_echo_likelihood, 0.0);
3029 EXPECT_LE(*stats.residual_echo_likelihood, 1.0);
3030 }
3031 EXPECT_TRUE(stats.residual_echo_likelihood_recent_max);
3032 if (stats.residual_echo_likelihood_recent_max) {
3033 EXPECT_GE(*stats.residual_echo_likelihood_recent_max, 0.0);
3034 EXPECT_LE(*stats.residual_echo_likelihood_recent_max, 1.0);
3035 }
3036 EXPECT_FALSE(stats.echo_return_loss);
3037 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3038 EXPECT_FALSE(stats.divergent_filter_fraction);
3039 EXPECT_FALSE(stats.delay_median_ms);
3040 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3041
3042 // If there are no receive streams, we expect the stats not to be set.
3043 stats = apm->GetStatistics(false);
3044 EXPECT_FALSE(stats.residual_echo_likelihood);
3045 EXPECT_FALSE(stats.residual_echo_likelihood_recent_max);
3046 EXPECT_FALSE(stats.echo_return_loss);
3047 EXPECT_FALSE(stats.echo_return_loss_enhancement);
3048 EXPECT_FALSE(stats.divergent_filter_fraction);
3049 EXPECT_FALSE(stats.delay_median_ms);
3050 EXPECT_FALSE(stats.delay_standard_deviation_ms);
3051}
andrew@webrtc.org27c69802014-02-18 20:24:56 +00003052} // namespace webrtc