Delete unused downloads page asset.
[chromium-blink-merge.git] / media / base / sinc_resampler_unittest.cc
blobf3f45c472fbf3e697604501925f71cc7ebca39c7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // MSVC++ requires this to be set before any other includes to get M_PI.
6 #define _USE_MATH_DEFINES
8 #include <cmath>
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/time/time.h"
14 #include "build/build_config.h"
15 #include "media/base/sinc_resampler.h"
16 #include "testing/gmock/include/gmock/gmock.h"
17 #include "testing/gtest/include/gtest/gtest.h"
19 using testing::_;
21 namespace media {
23 static const double kSampleRateRatio = 192000.0 / 44100.0;
25 // Helper class to ensure ChunkedResample() functions properly.
26 class MockSource {
27 public:
28 MOCK_METHOD2(ProvideInput, void(int frames, float* destination));
31 ACTION(ClearBuffer) {
32 memset(arg1, 0, arg0 * sizeof(float));
35 ACTION(FillBuffer) {
36 // Value chosen arbitrarily such that SincResampler resamples it to something
37 // easily representable on all platforms; e.g., using kSampleRateRatio this
38 // becomes 1.81219.
39 memset(arg1, 64, arg0 * sizeof(float));
42 // Test requesting multiples of ChunkSize() frames results in the proper number
43 // of callbacks.
44 TEST(SincResamplerTest, ChunkedResample) {
45 MockSource mock_source;
47 // Choose a high ratio of input to output samples which will result in quick
48 // exhaustion of SincResampler's internal buffers.
49 SincResampler resampler(
50 kSampleRateRatio, SincResampler::kDefaultRequestSize,
51 base::Bind(&MockSource::ProvideInput, base::Unretained(&mock_source)));
53 static const int kChunks = 2;
54 int max_chunk_size = resampler.ChunkSize() * kChunks;
55 scoped_ptr<float[]> resampled_destination(new float[max_chunk_size]);
57 // Verify requesting ChunkSize() frames causes a single callback.
58 EXPECT_CALL(mock_source, ProvideInput(_, _))
59 .Times(1).WillOnce(ClearBuffer());
60 resampler.Resample(resampler.ChunkSize(), resampled_destination.get());
62 // Verify requesting kChunks * ChunkSize() frames causes kChunks callbacks.
63 testing::Mock::VerifyAndClear(&mock_source);
64 EXPECT_CALL(mock_source, ProvideInput(_, _))
65 .Times(kChunks).WillRepeatedly(ClearBuffer());
66 resampler.Resample(max_chunk_size, resampled_destination.get());
69 // Verify priming the resampler avoids changes to ChunkSize() between calls.
70 TEST(SincResamplerTest, PrimedResample) {
71 MockSource mock_source;
73 // Choose a high ratio of input to output samples which will result in quick
74 // exhaustion of SincResampler's internal buffers.
75 SincResampler resampler(
76 kSampleRateRatio, SincResampler::kDefaultRequestSize,
77 base::Bind(&MockSource::ProvideInput, base::Unretained(&mock_source)));
79 // Verify the priming adjusts the chunk size within reasonable limits.
80 const int first_chunk_size = resampler.ChunkSize();
81 resampler.PrimeWithSilence();
82 const int max_chunk_size = resampler.ChunkSize();
84 EXPECT_NE(first_chunk_size, max_chunk_size);
85 EXPECT_LE(
86 max_chunk_size,
87 static_cast<int>(first_chunk_size + std::ceil(SincResampler::kKernelSize /
88 (2 * kSampleRateRatio))));
90 // Verify Flush() resets to an unprimed state.
91 resampler.Flush();
92 EXPECT_EQ(first_chunk_size, resampler.ChunkSize());
93 resampler.PrimeWithSilence();
94 EXPECT_EQ(max_chunk_size, resampler.ChunkSize());
96 const int kChunks = 2;
97 const int kMaxFrames = max_chunk_size * kChunks;
98 scoped_ptr<float[]> resampled_destination(new float[kMaxFrames]);
100 // Verify requesting ChunkSize() frames causes a single callback.
101 EXPECT_CALL(mock_source, ProvideInput(_, _))
102 .Times(1).WillOnce(ClearBuffer());
103 resampler.Resample(max_chunk_size, resampled_destination.get());
104 EXPECT_EQ(max_chunk_size, resampler.ChunkSize());
106 // Verify requesting kChunks * ChunkSize() frames causes kChunks callbacks.
107 testing::Mock::VerifyAndClear(&mock_source);
108 EXPECT_CALL(mock_source, ProvideInput(_, _))
109 .Times(kChunks).WillRepeatedly(ClearBuffer());
110 resampler.Resample(kMaxFrames, resampled_destination.get());
111 EXPECT_EQ(max_chunk_size, resampler.ChunkSize());
114 // Test flush resets the internal state properly.
115 TEST(SincResamplerTest, Flush) {
116 MockSource mock_source;
117 SincResampler resampler(
118 kSampleRateRatio, SincResampler::kDefaultRequestSize,
119 base::Bind(&MockSource::ProvideInput, base::Unretained(&mock_source)));
120 scoped_ptr<float[]> resampled_destination(new float[resampler.ChunkSize()]);
122 // Fill the resampler with junk data.
123 EXPECT_CALL(mock_source, ProvideInput(_, _))
124 .Times(1).WillOnce(FillBuffer());
125 resampler.Resample(resampler.ChunkSize() / 2, resampled_destination.get());
126 ASSERT_NE(resampled_destination[0], 0);
128 // Flush and request more data, which should all be zeros now.
129 resampler.Flush();
130 testing::Mock::VerifyAndClear(&mock_source);
131 EXPECT_CALL(mock_source, ProvideInput(_, _))
132 .Times(1).WillOnce(ClearBuffer());
133 resampler.Resample(resampler.ChunkSize() / 2, resampled_destination.get());
134 for (int i = 0; i < resampler.ChunkSize() / 2; ++i)
135 ASSERT_FLOAT_EQ(resampled_destination[i], 0);
138 TEST(SincResamplerTest, DISABLED_SetRatioBench) {
139 MockSource mock_source;
140 SincResampler resampler(
141 kSampleRateRatio, SincResampler::kDefaultRequestSize,
142 base::Bind(&MockSource::ProvideInput, base::Unretained(&mock_source)));
144 base::TimeTicks start = base::TimeTicks::Now();
145 for (int i = 1; i < 10000; ++i)
146 resampler.SetRatio(1.0 / i);
147 double total_time_c_ms = (base::TimeTicks::Now() - start).InMillisecondsF();
148 printf("SetRatio() took %.2fms.\n", total_time_c_ms);
152 // Define platform independent function name for Convolve* tests.
153 #if defined(ARCH_CPU_X86_FAMILY)
154 #define CONVOLVE_FUNC Convolve_SSE
155 #elif defined(ARCH_CPU_ARM_FAMILY) && defined(USE_NEON)
156 #define CONVOLVE_FUNC Convolve_NEON
157 #endif
159 // Ensure various optimized Convolve() methods return the same value. Only run
160 // this test if other optimized methods exist, otherwise the default Convolve()
161 // will be tested by the parameterized SincResampler tests below.
162 #if defined(CONVOLVE_FUNC)
163 static const double kKernelInterpolationFactor = 0.5;
165 TEST(SincResamplerTest, Convolve) {
166 // Initialize a dummy resampler.
167 MockSource mock_source;
168 SincResampler resampler(
169 kSampleRateRatio, SincResampler::kDefaultRequestSize,
170 base::Bind(&MockSource::ProvideInput, base::Unretained(&mock_source)));
172 // The optimized Convolve methods are slightly more precise than Convolve_C(),
173 // so comparison must be done using an epsilon.
174 static const double kEpsilon = 0.00000005;
176 // Use a kernel from SincResampler as input and kernel data, this has the
177 // benefit of already being properly sized and aligned for Convolve_SSE().
178 double result = resampler.Convolve_C(
179 resampler.kernel_storage_.get(), resampler.kernel_storage_.get(),
180 resampler.kernel_storage_.get(), kKernelInterpolationFactor);
181 double result2 = resampler.CONVOLVE_FUNC(
182 resampler.kernel_storage_.get(), resampler.kernel_storage_.get(),
183 resampler.kernel_storage_.get(), kKernelInterpolationFactor);
184 EXPECT_NEAR(result2, result, kEpsilon);
186 // Test Convolve() w/ unaligned input pointer.
187 result = resampler.Convolve_C(
188 resampler.kernel_storage_.get() + 1, resampler.kernel_storage_.get(),
189 resampler.kernel_storage_.get(), kKernelInterpolationFactor);
190 result2 = resampler.CONVOLVE_FUNC(
191 resampler.kernel_storage_.get() + 1, resampler.kernel_storage_.get(),
192 resampler.kernel_storage_.get(), kKernelInterpolationFactor);
193 EXPECT_NEAR(result2, result, kEpsilon);
195 #endif
197 // Fake audio source for testing the resampler. Generates a sinusoidal linear
198 // chirp (http://en.wikipedia.org/wiki/Chirp) which can be tuned to stress the
199 // resampler for the specific sample rate conversion being used.
200 class SinusoidalLinearChirpSource {
201 public:
202 SinusoidalLinearChirpSource(int sample_rate,
203 int samples,
204 double max_frequency)
205 : sample_rate_(sample_rate),
206 total_samples_(samples),
207 max_frequency_(max_frequency),
208 current_index_(0) {
209 // Chirp rate.
210 double duration = static_cast<double>(total_samples_) / sample_rate_;
211 k_ = (max_frequency_ - kMinFrequency) / duration;
214 virtual ~SinusoidalLinearChirpSource() {}
216 void ProvideInput(int frames, float* destination) {
217 for (int i = 0; i < frames; ++i, ++current_index_) {
218 // Filter out frequencies higher than Nyquist.
219 if (Frequency(current_index_) > 0.5 * sample_rate_) {
220 destination[i] = 0;
221 } else {
222 // Calculate time in seconds.
223 double t = static_cast<double>(current_index_) / sample_rate_;
225 // Sinusoidal linear chirp.
226 destination[i] = sin(2 * M_PI * (kMinFrequency * t + (k_ / 2) * t * t));
231 double Frequency(int position) {
232 return kMinFrequency + position * (max_frequency_ - kMinFrequency)
233 / total_samples_;
236 private:
237 enum {
238 kMinFrequency = 5
241 double sample_rate_;
242 int total_samples_;
243 double max_frequency_;
244 double k_;
245 int current_index_;
247 DISALLOW_COPY_AND_ASSIGN(SinusoidalLinearChirpSource);
250 typedef std::tr1::tuple<int, int, double, double> SincResamplerTestData;
251 class SincResamplerTest
252 : public testing::TestWithParam<SincResamplerTestData> {
253 public:
254 SincResamplerTest()
255 : input_rate_(std::tr1::get<0>(GetParam())),
256 output_rate_(std::tr1::get<1>(GetParam())),
257 rms_error_(std::tr1::get<2>(GetParam())),
258 low_freq_error_(std::tr1::get<3>(GetParam())) {
261 virtual ~SincResamplerTest() {}
263 protected:
264 int input_rate_;
265 int output_rate_;
266 double rms_error_;
267 double low_freq_error_;
270 // Tests resampling using a given input and output sample rate.
271 TEST_P(SincResamplerTest, Resample) {
272 // Make comparisons using one second of data.
273 static const double kTestDurationSecs = 1;
274 int input_samples = kTestDurationSecs * input_rate_;
275 int output_samples = kTestDurationSecs * output_rate_;
277 // Nyquist frequency for the input sampling rate.
278 double input_nyquist_freq = 0.5 * input_rate_;
280 // Source for data to be resampled.
281 SinusoidalLinearChirpSource resampler_source(
282 input_rate_, input_samples, input_nyquist_freq);
284 const double io_ratio = input_rate_ / static_cast<double>(output_rate_);
285 SincResampler resampler(
286 io_ratio, SincResampler::kDefaultRequestSize,
287 base::Bind(&SinusoidalLinearChirpSource::ProvideInput,
288 base::Unretained(&resampler_source)));
290 // Force an update to the sample rate ratio to ensure dyanmic sample rate
291 // changes are working correctly.
292 scoped_ptr<float[]> kernel(new float[SincResampler::kKernelStorageSize]);
293 memcpy(kernel.get(), resampler.get_kernel_for_testing(),
294 SincResampler::kKernelStorageSize);
295 resampler.SetRatio(M_PI);
296 ASSERT_NE(0, memcmp(kernel.get(), resampler.get_kernel_for_testing(),
297 SincResampler::kKernelStorageSize));
298 resampler.SetRatio(io_ratio);
299 ASSERT_EQ(0, memcmp(kernel.get(), resampler.get_kernel_for_testing(),
300 SincResampler::kKernelStorageSize));
302 // TODO(dalecurtis): If we switch to AVX/SSE optimization, we'll need to
303 // allocate these on 32-byte boundaries and ensure they're sized % 32 bytes.
304 scoped_ptr<float[]> resampled_destination(new float[output_samples]);
305 scoped_ptr<float[]> pure_destination(new float[output_samples]);
307 // Generate resampled signal.
308 resampler.Resample(output_samples, resampled_destination.get());
310 // Generate pure signal.
311 SinusoidalLinearChirpSource pure_source(
312 output_rate_, output_samples, input_nyquist_freq);
313 pure_source.ProvideInput(output_samples, pure_destination.get());
315 // Range of the Nyquist frequency (0.5 * min(input rate, output_rate)) which
316 // we refer to as low and high.
317 static const double kLowFrequencyNyquistRange = 0.7;
318 static const double kHighFrequencyNyquistRange = 0.9;
320 // Calculate Root-Mean-Square-Error and maximum error for the resampling.
321 double sum_of_squares = 0;
322 double low_freq_max_error = 0;
323 double high_freq_max_error = 0;
324 int minimum_rate = std::min(input_rate_, output_rate_);
325 double low_frequency_range = kLowFrequencyNyquistRange * 0.5 * minimum_rate;
326 double high_frequency_range = kHighFrequencyNyquistRange * 0.5 * minimum_rate;
327 for (int i = 0; i < output_samples; ++i) {
328 double error = fabs(resampled_destination[i] - pure_destination[i]);
330 if (pure_source.Frequency(i) < low_frequency_range) {
331 if (error > low_freq_max_error)
332 low_freq_max_error = error;
333 } else if (pure_source.Frequency(i) < high_frequency_range) {
334 if (error > high_freq_max_error)
335 high_freq_max_error = error;
337 // TODO(dalecurtis): Sanity check frequencies > kHighFrequencyNyquistRange.
339 sum_of_squares += error * error;
342 double rms_error = sqrt(sum_of_squares / output_samples);
344 // Convert each error to dbFS.
345 #define DBFS(x) 20 * log10(x)
346 rms_error = DBFS(rms_error);
347 low_freq_max_error = DBFS(low_freq_max_error);
348 high_freq_max_error = DBFS(high_freq_max_error);
350 EXPECT_LE(rms_error, rms_error_);
351 EXPECT_LE(low_freq_max_error, low_freq_error_);
353 // All conversions currently have a high frequency error around -6 dbFS.
354 static const double kHighFrequencyMaxError = -6.02;
355 EXPECT_LE(high_freq_max_error, kHighFrequencyMaxError);
358 // Almost all conversions have an RMS error of around -14 dbFS.
359 static const double kResamplingRMSError = -14.58;
361 // Thresholds chosen arbitrarily based on what each resampling reported during
362 // testing. All thresholds are in dbFS, http://en.wikipedia.org/wiki/DBFS.
363 INSTANTIATE_TEST_CASE_P(
364 SincResamplerTest, SincResamplerTest, testing::Values(
365 // To 44.1kHz
366 std::tr1::make_tuple(8000, 44100, kResamplingRMSError, -62.73),
367 std::tr1::make_tuple(11025, 44100, kResamplingRMSError, -72.19),
368 std::tr1::make_tuple(16000, 44100, kResamplingRMSError, -62.54),
369 std::tr1::make_tuple(22050, 44100, kResamplingRMSError, -73.53),
370 std::tr1::make_tuple(32000, 44100, kResamplingRMSError, -63.32),
371 std::tr1::make_tuple(44100, 44100, kResamplingRMSError, -73.53),
372 std::tr1::make_tuple(48000, 44100, -15.01, -64.04),
373 std::tr1::make_tuple(96000, 44100, -18.49, -25.51),
374 std::tr1::make_tuple(192000, 44100, -20.50, -13.31),
376 // To 48kHz
377 std::tr1::make_tuple(8000, 48000, kResamplingRMSError, -63.43),
378 std::tr1::make_tuple(11025, 48000, kResamplingRMSError, -62.61),
379 std::tr1::make_tuple(16000, 48000, kResamplingRMSError, -63.96),
380 std::tr1::make_tuple(22050, 48000, kResamplingRMSError, -62.42),
381 std::tr1::make_tuple(32000, 48000, kResamplingRMSError, -64.04),
382 std::tr1::make_tuple(44100, 48000, kResamplingRMSError, -62.63),
383 std::tr1::make_tuple(48000, 48000, kResamplingRMSError, -73.52),
384 std::tr1::make_tuple(96000, 48000, -18.40, -28.44),
385 std::tr1::make_tuple(192000, 48000, -20.43, -14.11),
387 // To 96kHz
388 std::tr1::make_tuple(8000, 96000, kResamplingRMSError, -63.19),
389 std::tr1::make_tuple(11025, 96000, kResamplingRMSError, -62.61),
390 std::tr1::make_tuple(16000, 96000, kResamplingRMSError, -63.39),
391 std::tr1::make_tuple(22050, 96000, kResamplingRMSError, -62.42),
392 std::tr1::make_tuple(32000, 96000, kResamplingRMSError, -63.95),
393 std::tr1::make_tuple(44100, 96000, kResamplingRMSError, -62.63),
394 std::tr1::make_tuple(48000, 96000, kResamplingRMSError, -73.52),
395 std::tr1::make_tuple(96000, 96000, kResamplingRMSError, -73.52),
396 std::tr1::make_tuple(192000, 96000, kResamplingRMSError, -28.41),
398 // To 192kHz
399 std::tr1::make_tuple(8000, 192000, kResamplingRMSError, -63.10),
400 std::tr1::make_tuple(11025, 192000, kResamplingRMSError, -62.61),
401 std::tr1::make_tuple(16000, 192000, kResamplingRMSError, -63.14),
402 std::tr1::make_tuple(22050, 192000, kResamplingRMSError, -62.42),
403 std::tr1::make_tuple(32000, 192000, kResamplingRMSError, -63.38),
404 std::tr1::make_tuple(44100, 192000, kResamplingRMSError, -62.63),
405 std::tr1::make_tuple(48000, 192000, kResamplingRMSError, -73.44),
406 std::tr1::make_tuple(96000, 192000, kResamplingRMSError, -73.52),
407 std::tr1::make_tuple(192000, 192000, kResamplingRMSError, -73.52)));
409 } // namespace media