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 // Initial input buffer layout, dividing into regions r0_ to r4_ (note: r0_, r3_
6 // and r4_ will move after the first load):
8 // |----------------|-----------------------------------------|----------------|
11 // <--------------------------------------------------------->
12 // r0_ (during first load)
14 // kKernelSize / 2 kKernelSize / 2 kKernelSize / 2 kKernelSize / 2
15 // <---------------> <---------------> <---------------> <--------------->
18 // block_size_ == r4_ - r2_
19 // <--------------------------------------->
22 // <------------------ ... ----------------->
23 // r0_ (during second load)
25 // On the second request r0_ slides to the right by kKernelSize / 2 and r3_, r4_
26 // and block_size_ are reinitialized via step (3) in the algorithm below.
28 // These new regions remain constant until a Flush() occurs. While complicated,
29 // this allows us to reduce jitter by always requesting the same amount from the
34 // 1) Allocate input_buffer of size: request_frames_ + kKernelSize; this ensures
35 // there's enough room to read request_frames_ from the callback into region
36 // r0_ (which will move between the first and subsequent passes).
38 // 2) Let r1_, r2_ each represent half the kernel centered around r0_:
40 // r0_ = input_buffer_ + kKernelSize / 2
41 // r1_ = input_buffer_
44 // r0_ is always request_frames_ in size. r1_, r2_ are kKernelSize / 2 in
45 // size. r1_ must be zero initialized to avoid convolution with garbage (see
48 // 3) Let r3_, r4_ each represent half the kernel right aligned with the end of
49 // r0_ and choose block_size_ as the distance in frames between r4_ and r2_:
51 // r3_ = r0_ + request_frames_ - kKernelSize
52 // r4_ = r0_ + request_frames_ - kKernelSize / 2
53 // block_size_ = r4_ - r2_ = request_frames_ - kKernelSize / 2
55 // 4) Consume request_frames_ frames into r0_.
57 // 5) Position kernel centered at start of r2_ and generate output frames until
58 // the kernel is centered at the start of r4_ or we've finished generating
59 // all the output frames.
61 // 6) Wrap left over data from the r3_ to r1_ and r4_ to r2_.
63 // 7) If we're on the second load, in order to avoid overwriting the frames we
64 // just wrapped from r4_ we need to slide r0_ to the right by the size of
65 // r4_, which is kKernelSize / 2:
67 // r0_ = r0_ + kKernelSize / 2 = input_buffer_ + kKernelSize
69 // r3_, r4_, and block_size_ then need to be reinitialized, so goto (3).
71 // 8) Else, if we're not on the second load, goto (4).
73 // Note: we're glossing over how the sub-sample handling works with
74 // |virtual_source_idx_|, etc.
76 // MSVC++ requires this to be set before any other includes to get M_PI.
77 #define _USE_MATH_DEFINES
79 #include "media/base/sinc_resampler.h"
85 #include "base/logging.h"
87 #if defined(ARCH_CPU_ARM_FAMILY) && defined(USE_NEON)
93 static double SincScaleFactor(double io_ratio
) {
94 // |sinc_scale_factor| is basically the normalized cutoff frequency of the
96 double sinc_scale_factor
= io_ratio
> 1.0 ? 1.0 / io_ratio
: 1.0;
98 // The sinc function is an idealized brick-wall filter, but since we're
99 // windowing it the transition from pass to stop does not happen right away.
100 // So we should adjust the low pass filter cutoff slightly downward to avoid
101 // some aliasing at the very high-end.
102 // TODO(crogers): this value is empirical and to be more exact should vary
103 // depending on kKernelSize.
104 sinc_scale_factor
*= 0.9;
106 return sinc_scale_factor
;
109 // If we know the minimum architecture at compile time, avoid CPU detection.
110 // Force NaCl code to use C routines since (at present) nothing there uses these
111 // methods and plumbing the -msse built library is non-trivial.
112 #if defined(ARCH_CPU_X86_FAMILY) && !defined(OS_NACL)
114 #define CONVOLVE_FUNC Convolve_SSE
115 void SincResampler::InitializeCPUSpecificFeatures() {}
117 // X86 CPU detection required. Functions will be set by
118 // InitializeCPUSpecificFeatures().
119 // TODO(dalecurtis): Once Chrome moves to an SSE baseline this can be removed.
120 #define CONVOLVE_FUNC g_convolve_proc_
122 typedef float (*ConvolveProc
)(const float*, const float*, const float*, double);
123 static ConvolveProc g_convolve_proc_
= NULL
;
125 void SincResampler::InitializeCPUSpecificFeatures() {
126 CHECK(!g_convolve_proc_
);
127 g_convolve_proc_
= base::CPU().has_sse() ? Convolve_SSE
: Convolve_C
;
130 #elif defined(ARCH_CPU_ARM_FAMILY) && defined(USE_NEON)
131 #define CONVOLVE_FUNC Convolve_NEON
132 void SincResampler::InitializeCPUSpecificFeatures() {}
134 // Unknown architecture.
135 #define CONVOLVE_FUNC Convolve_C
136 void SincResampler::InitializeCPUSpecificFeatures() {}
139 SincResampler::SincResampler(double io_sample_rate_ratio
,
141 const ReadCB
& read_cb
)
142 : io_sample_rate_ratio_(io_sample_rate_ratio
),
144 request_frames_(request_frames
),
145 input_buffer_size_(request_frames_
+ kKernelSize
),
146 // Create input buffers with a 16-byte alignment for SSE optimizations.
147 kernel_storage_(static_cast<float*>(
148 base::AlignedAlloc(sizeof(float) * kKernelStorageSize
, 16))),
149 kernel_pre_sinc_storage_(static_cast<float*>(
150 base::AlignedAlloc(sizeof(float) * kKernelStorageSize
, 16))),
151 kernel_window_storage_(static_cast<float*>(
152 base::AlignedAlloc(sizeof(float) * kKernelStorageSize
, 16))),
153 input_buffer_(static_cast<float*>(
154 base::AlignedAlloc(sizeof(float) * input_buffer_size_
, 16))),
155 r1_(input_buffer_
.get()),
156 r2_(input_buffer_
.get() + kKernelSize
/ 2) {
157 CHECK_GT(request_frames_
, 0);
159 CHECK_GT(block_size_
, kKernelSize
)
160 << "block_size must be greater than kKernelSize!";
162 memset(kernel_storage_
.get(), 0,
163 sizeof(*kernel_storage_
.get()) * kKernelStorageSize
);
164 memset(kernel_pre_sinc_storage_
.get(), 0,
165 sizeof(*kernel_pre_sinc_storage_
.get()) * kKernelStorageSize
);
166 memset(kernel_window_storage_
.get(), 0,
167 sizeof(*kernel_window_storage_
.get()) * kKernelStorageSize
);
172 SincResampler::~SincResampler() {}
174 void SincResampler::UpdateRegions(bool second_load
) {
175 // Setup various region pointers in the buffer (see diagram above). If we're
176 // on the second load we need to slide r0_ to the right by kKernelSize / 2.
177 r0_
= input_buffer_
.get() + (second_load
? kKernelSize
: kKernelSize
/ 2);
178 r3_
= r0_
+ request_frames_
- kKernelSize
;
179 r4_
= r0_
+ request_frames_
- kKernelSize
/ 2;
180 block_size_
= r4_
- r2_
;
182 // r1_ at the beginning of the buffer.
183 CHECK_EQ(r1_
, input_buffer_
.get());
184 // r1_ left of r2_, r4_ left of r3_ and size correct.
185 CHECK_EQ(r2_
- r1_
, r4_
- r3_
);
190 void SincResampler::InitializeKernel() {
191 // Blackman window parameters.
192 static const double kAlpha
= 0.16;
193 static const double kA0
= 0.5 * (1.0 - kAlpha
);
194 static const double kA1
= 0.5;
195 static const double kA2
= 0.5 * kAlpha
;
197 // Generates a set of windowed sinc() kernels.
198 // We generate a range of sub-sample offsets from 0.0 to 1.0.
199 const double sinc_scale_factor
= SincScaleFactor(io_sample_rate_ratio_
);
200 for (int offset_idx
= 0; offset_idx
<= kKernelOffsetCount
; ++offset_idx
) {
201 const float subsample_offset
=
202 static_cast<float>(offset_idx
) / kKernelOffsetCount
;
204 for (int i
= 0; i
< kKernelSize
; ++i
) {
205 const int idx
= i
+ offset_idx
* kKernelSize
;
206 const float pre_sinc
= M_PI
* (i
- kKernelSize
/ 2 - subsample_offset
);
207 kernel_pre_sinc_storage_
[idx
] = pre_sinc
;
209 // Compute Blackman window, matching the offset of the sinc().
210 const float x
= (i
- subsample_offset
) / kKernelSize
;
212 kA0
- kA1
* cos(2.0 * M_PI
* x
) + kA2
* cos(4.0 * M_PI
* x
);
213 kernel_window_storage_
[idx
] = window
;
215 // Compute the sinc with offset, then window the sinc() function and store
216 // at the correct offset.
218 kernel_storage_
[idx
] = sinc_scale_factor
* window
;
220 kernel_storage_
[idx
] =
221 window
* sin(sinc_scale_factor
* pre_sinc
) / pre_sinc
;
227 void SincResampler::SetRatio(double io_sample_rate_ratio
) {
228 if (fabs(io_sample_rate_ratio_
- io_sample_rate_ratio
) <
229 std::numeric_limits
<double>::epsilon()) {
233 io_sample_rate_ratio_
= io_sample_rate_ratio
;
235 // Optimize reinitialization by reusing values which are independent of
236 // |sinc_scale_factor|. Provides a 3x speedup.
237 const double sinc_scale_factor
= SincScaleFactor(io_sample_rate_ratio_
);
238 for (int offset_idx
= 0; offset_idx
<= kKernelOffsetCount
; ++offset_idx
) {
239 for (int i
= 0; i
< kKernelSize
; ++i
) {
240 const int idx
= i
+ offset_idx
* kKernelSize
;
241 const float window
= kernel_window_storage_
[idx
];
242 const float pre_sinc
= kernel_pre_sinc_storage_
[idx
];
245 kernel_storage_
[idx
] = sinc_scale_factor
* window
;
247 kernel_storage_
[idx
] =
248 window
* sin(sinc_scale_factor
* pre_sinc
) / pre_sinc
;
254 void SincResampler::Resample(int frames
, float* destination
) {
255 int remaining_frames
= frames
;
257 // Step (1) -- Prime the input buffer at the start of the input stream.
258 if (!buffer_primed_
&& remaining_frames
) {
259 read_cb_
.Run(request_frames_
, r0_
);
260 buffer_primed_
= true;
263 // Step (2) -- Resample! const what we can outside of the loop for speed. It
264 // actually has an impact on ARM performance. See inner loop comment below.
265 const double current_io_ratio
= io_sample_rate_ratio_
;
266 const float* const kernel_ptr
= kernel_storage_
.get();
267 while (remaining_frames
) {
268 // Note: The loop construct here can severely impact performance on ARM
269 // or when built with clang. See https://codereview.chromium.org/18566009/
270 int source_idx
= virtual_source_idx_
;
271 while (source_idx
< block_size_
) {
272 // |virtual_source_idx_| lies in between two kernel offsets so figure out
274 const double subsample_remainder
= virtual_source_idx_
- source_idx
;
276 const double virtual_offset_idx
=
277 subsample_remainder
* kKernelOffsetCount
;
278 const int offset_idx
= virtual_offset_idx
;
280 // We'll compute "convolutions" for the two kernels which straddle
281 // |virtual_source_idx_|.
282 const float* const k1
= kernel_ptr
+ offset_idx
* kKernelSize
;
283 const float* const k2
= k1
+ kKernelSize
;
285 // Ensure |k1|, |k2| are 16-byte aligned for SIMD usage. Should always be
286 // true so long as kKernelSize is a multiple of 16.
287 DCHECK_EQ(0u, reinterpret_cast<uintptr_t>(k1
) & 0x0F);
288 DCHECK_EQ(0u, reinterpret_cast<uintptr_t>(k2
) & 0x0F);
290 // Initialize input pointer based on quantized |virtual_source_idx_|.
291 const float* const input_ptr
= r1_
+ source_idx
;
293 // Figure out how much to weight each kernel's "convolution".
294 const double kernel_interpolation_factor
=
295 virtual_offset_idx
- offset_idx
;
296 *destination
++ = CONVOLVE_FUNC(
297 input_ptr
, k1
, k2
, kernel_interpolation_factor
);
299 // Advance the virtual index.
300 virtual_source_idx_
+= current_io_ratio
;
301 source_idx
= virtual_source_idx_
;
303 if (!--remaining_frames
)
307 // Wrap back around to the start.
308 DCHECK_GE(virtual_source_idx_
, block_size_
);
309 virtual_source_idx_
-= block_size_
;
311 // Step (3) -- Copy r3_, r4_ to r1_, r2_.
312 // This wraps the last input frames back to the start of the buffer.
313 memcpy(r1_
, r3_
, sizeof(*input_buffer_
.get()) * kKernelSize
);
315 // Step (4) -- Reinitialize regions if necessary.
319 // Step (5) -- Refresh the buffer with more input.
320 read_cb_
.Run(request_frames_
, r0_
);
326 int SincResampler::ChunkSize() const {
327 return block_size_
/ io_sample_rate_ratio_
;
330 void SincResampler::Flush() {
331 virtual_source_idx_
= 0;
332 buffer_primed_
= false;
333 memset(input_buffer_
.get(), 0,
334 sizeof(*input_buffer_
.get()) * input_buffer_size_
);
335 UpdateRegions(false);
338 float SincResampler::Convolve_C(const float* input_ptr
, const float* k1
,
340 double kernel_interpolation_factor
) {
344 // Generate a single output sample. Unrolling this loop hurt performance in
348 sum1
+= *input_ptr
* *k1
++;
349 sum2
+= *input_ptr
++ * *k2
++;
352 // Linearly interpolate the two "convolutions".
353 return (1.0 - kernel_interpolation_factor
) * sum1
354 + kernel_interpolation_factor
* sum2
;
357 #if defined(ARCH_CPU_ARM_FAMILY) && defined(USE_NEON)
358 float SincResampler::Convolve_NEON(const float* input_ptr
, const float* k1
,
360 double kernel_interpolation_factor
) {
362 float32x4_t m_sums1
= vmovq_n_f32(0);
363 float32x4_t m_sums2
= vmovq_n_f32(0);
365 const float* upper
= input_ptr
+ kKernelSize
;
366 for (; input_ptr
< upper
; ) {
367 m_input
= vld1q_f32(input_ptr
);
369 m_sums1
= vmlaq_f32(m_sums1
, m_input
, vld1q_f32(k1
));
371 m_sums2
= vmlaq_f32(m_sums2
, m_input
, vld1q_f32(k2
));
375 // Linearly interpolate the two "convolutions".
377 vmulq_f32(m_sums1
, vmovq_n_f32(1.0 - kernel_interpolation_factor
)),
378 m_sums2
, vmovq_n_f32(kernel_interpolation_factor
));
380 // Sum components together.
381 float32x2_t m_half
= vadd_f32(vget_high_f32(m_sums1
), vget_low_f32(m_sums1
));
382 return vget_lane_f32(vpadd_f32(m_half
, m_half
), 0);