2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
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.
11 // Modified from the Chromium original:
12 // src/media/base/sinc_resampler.cc
14 // Initial input buffer layout, dividing into regions r0_ to r4_ (note: r0_, r3_
15 // and r4_ will move after the first load):
17 // |----------------|-----------------------------------------|----------------|
20 // <--------------------------------------------------------->
21 // r0_ (during first load)
23 // kKernelSize / 2 kKernelSize / 2 kKernelSize / 2 kKernelSize / 2
24 // <---------------> <---------------> <---------------> <--------------->
27 // block_size_ == r4_ - r2_
28 // <--------------------------------------->
31 // <------------------ ... ----------------->
32 // r0_ (during second load)
34 // On the second request r0_ slides to the right by kKernelSize / 2 and r3_, r4_
35 // and block_size_ are reinitialized via step (3) in the algorithm below.
37 // These new regions remain constant until a Flush() occurs. While complicated,
38 // this allows us to reduce jitter by always requesting the same amount from the
43 // 1) Allocate input_buffer of size: request_frames_ + kKernelSize; this ensures
44 // there's enough room to read request_frames_ from the callback into region
45 // r0_ (which will move between the first and subsequent passes).
47 // 2) Let r1_, r2_ each represent half the kernel centered around r0_:
49 // r0_ = input_buffer_ + kKernelSize / 2
50 // r1_ = input_buffer_
53 // r0_ is always request_frames_ in size. r1_, r2_ are kKernelSize / 2 in
54 // size. r1_ must be zero initialized to avoid convolution with garbage (see
57 // 3) Let r3_, r4_ each represent half the kernel right aligned with the end of
58 // r0_ and choose block_size_ as the distance in frames between r4_ and r2_:
60 // r3_ = r0_ + request_frames_ - kKernelSize
61 // r4_ = r0_ + request_frames_ - kKernelSize / 2
62 // block_size_ = r4_ - r2_ = request_frames_ - kKernelSize / 2
64 // 4) Consume request_frames_ frames into r0_.
66 // 5) Position kernel centered at start of r2_ and generate output frames until
67 // the kernel is centered at the start of r4_ or we've finished generating
68 // all the output frames.
70 // 6) Wrap left over data from the r3_ to r1_ and r4_ to r2_.
72 // 7) If we're on the second load, in order to avoid overwriting the frames we
73 // just wrapped from r4_ we need to slide r0_ to the right by the size of
74 // r4_, which is kKernelSize / 2:
76 // r0_ = r0_ + kKernelSize / 2 = input_buffer_ + kKernelSize
78 // r3_, r4_, and block_size_ then need to be reinitialized, so goto (3).
80 // 8) Else, if we're not on the second load, goto (4).
82 // Note: we're glossing over how the sub-sample handling works with
83 // |virtual_source_idx_|, etc.
85 // MSVC++ requires this to be set before any other includes to get M_PI.
86 #define _USE_MATH_DEFINES
88 #include "webrtc/common_audio/resampler/sinc_resampler.h"
89 #include "webrtc/system_wrappers/interface/compile_assert.h"
90 #include "webrtc/system_wrappers/interface/cpu_features_wrapper.h"
91 #include "webrtc/typedefs.h"
101 static double SincScaleFactor(double io_ratio) {
102 // |sinc_scale_factor| is basically the normalized cutoff frequency of the
104 double sinc_scale_factor = io_ratio > 1.0 ? 1.0 / io_ratio : 1.0;
106 // The sinc function is an idealized brick-wall filter, but since we're
107 // windowing it the transition from pass to stop does not happen right away.
108 // So we should adjust the low pass filter cutoff slightly downward to avoid
109 // some aliasing at the very high-end.
110 // TODO(crogers): this value is empirical and to be more exact should vary
111 // depending on kKernelSize.
112 sinc_scale_factor *= 0.9;
114 return sinc_scale_factor;
117 // If we know the minimum architecture at compile time, avoid CPU detection.
118 #if defined(WEBRTC_ARCH_X86_FAMILY)
119 #if defined(__SSE2__)
120 #define CONVOLVE_FUNC Convolve_SSE
121 void SincResampler::InitializeCPUSpecificFeatures() {}
123 // x86 CPU detection required. Function will be set by
124 // InitializeCPUSpecificFeatures().
125 // TODO(dalecurtis): Once Chrome moves to an SSE baseline this can be removed.
126 #define CONVOLVE_FUNC convolve_proc_
128 void SincResampler::InitializeCPUSpecificFeatures() {
129 convolve_proc_ = WebRtc_GetCPUInfo(kSSE2) ? Convolve_SSE : Convolve_C;
132 #elif defined(WEBRTC_ARCH_ARM_V7)
133 #if defined(WEBRTC_ARCH_ARM_NEON)
134 #define CONVOLVE_FUNC Convolve_NEON
135 void SincResampler::InitializeCPUSpecificFeatures() {}
137 // ARM CPU detection required. Function will be set by
138 // InitializeCPUSpecificFeatures().
139 #define CONVOLVE_FUNC convolve_proc_
141 void SincResampler::InitializeCPUSpecificFeatures() {
142 convolve_proc_ = WebRtc_GetCPUFeaturesARM() & kCPUFeatureNEON ?
143 Convolve_NEON : Convolve_C;
147 // Unknown architecture.
148 #define CONVOLVE_FUNC Convolve_C
149 void SincResampler::InitializeCPUSpecificFeatures() {}
152 SincResampler::SincResampler(double io_sample_rate_ratio,
154 SincResamplerCallback* read_cb)
155 : io_sample_rate_ratio_(io_sample_rate_ratio),
157 request_frames_(request_frames),
158 input_buffer_size_(request_frames_ + kKernelSize),
159 // Create input buffers with a 16-byte alignment for SSE optimizations.
160 kernel_storage_(static_cast<float*>(
161 AlignedMalloc(sizeof(float) * kKernelStorageSize, 16))),
162 kernel_pre_sinc_storage_(static_cast<float*>(
163 AlignedMalloc(sizeof(float) * kKernelStorageSize, 16))),
164 kernel_window_storage_(static_cast<float*>(
165 AlignedMalloc(sizeof(float) * kKernelStorageSize, 16))),
166 input_buffer_(static_cast<float*>(
167 AlignedMalloc(sizeof(float) * input_buffer_size_, 16))),
168 #if defined(WEBRTC_CPU_DETECTION)
169 convolve_proc_(NULL),
171 r1_(input_buffer_.get()),
172 r2_(input_buffer_.get() + kKernelSize / 2) {
173 #if defined(WEBRTC_CPU_DETECTION)
174 InitializeCPUSpecificFeatures();
175 assert(convolve_proc_);
177 assert(request_frames_ > 0);
179 assert(block_size_ > kKernelSize);
181 memset(kernel_storage_.get(), 0,
182 sizeof(*kernel_storage_.get()) * kKernelStorageSize);
183 memset(kernel_pre_sinc_storage_.get(), 0,
184 sizeof(*kernel_pre_sinc_storage_.get()) * kKernelStorageSize);
185 memset(kernel_window_storage_.get(), 0,
186 sizeof(*kernel_window_storage_.get()) * kKernelStorageSize);
191 SincResampler::~SincResampler() {}
193 void SincResampler::UpdateRegions(bool second_load) {
194 // Setup various region pointers in the buffer (see diagram above). If we're
195 // on the second load we need to slide r0_ to the right by kKernelSize / 2.
196 r0_ = input_buffer_.get() + (second_load ? kKernelSize : kKernelSize / 2);
197 r3_ = r0_ + request_frames_ - kKernelSize;
198 r4_ = r0_ + request_frames_ - kKernelSize / 2;
199 block_size_ = r4_ - r2_;
201 // r1_ at the beginning of the buffer.
202 assert(r1_ == input_buffer_.get());
203 // r1_ left of r2_, r4_ left of r3_ and size correct.
204 assert(r2_ - r1_ == r4_ - r3_);
209 void SincResampler::InitializeKernel() {
210 // Blackman window parameters.
211 static const double kAlpha = 0.16;
212 static const double kA0 = 0.5 * (1.0 - kAlpha);
213 static const double kA1 = 0.5;
214 static const double kA2 = 0.5 * kAlpha;
216 // Generates a set of windowed sinc() kernels.
217 // We generate a range of sub-sample offsets from 0.0 to 1.0.
218 const double sinc_scale_factor = SincScaleFactor(io_sample_rate_ratio_);
219 for (int offset_idx = 0; offset_idx <= kKernelOffsetCount; ++offset_idx) {
220 const float subsample_offset =
221 static_cast<float>(offset_idx) / kKernelOffsetCount;
223 for (int i = 0; i < kKernelSize; ++i) {
224 const int idx = i + offset_idx * kKernelSize;
225 const float pre_sinc = M_PI * (i - kKernelSize / 2 - subsample_offset);
226 kernel_pre_sinc_storage_[idx] = pre_sinc;
228 // Compute Blackman window, matching the offset of the sinc().
229 const float x = (i - subsample_offset) / kKernelSize;
230 const float window = kA0 - kA1 * cos(2.0 * M_PI * x) + kA2
231 * cos(4.0 * M_PI * x);
232 kernel_window_storage_[idx] = window;
234 // Compute the sinc with offset, then window the sinc() function and store
235 // at the correct offset.
237 kernel_storage_[idx] = sinc_scale_factor * window;
239 kernel_storage_[idx] =
240 window * sin(sinc_scale_factor * pre_sinc) / pre_sinc;
246 void SincResampler::SetRatio(double io_sample_rate_ratio) {
247 if (fabs(io_sample_rate_ratio_ - io_sample_rate_ratio) <
248 std::numeric_limits<double>::epsilon()) {
252 io_sample_rate_ratio_ = io_sample_rate_ratio;
254 // Optimize reinitialization by reusing values which are independent of
255 // |sinc_scale_factor|. Provides a 3x speedup.
256 const double sinc_scale_factor = SincScaleFactor(io_sample_rate_ratio_);
257 for (int offset_idx = 0; offset_idx <= kKernelOffsetCount; ++offset_idx) {
258 for (int i = 0; i < kKernelSize; ++i) {
259 const int idx = i + offset_idx * kKernelSize;
260 const float window = kernel_window_storage_[idx];
261 const float pre_sinc = kernel_pre_sinc_storage_[idx];
264 kernel_storage_[idx] = sinc_scale_factor * window;
266 kernel_storage_[idx] =
267 window * sin(sinc_scale_factor * pre_sinc) / pre_sinc;
273 void SincResampler::Resample(int frames, float* destination) {
274 int remaining_frames = frames;
276 // Step (1) -- Prime the input buffer at the start of the input stream.
277 if (!buffer_primed_ && remaining_frames) {
278 read_cb_->Run(request_frames_, r0_);
279 buffer_primed_ = true;
282 // Step (2) -- Resample! const what we can outside of the loop for speed. It
283 // actually has an impact on ARM performance. See inner loop comment below.
284 const double current_io_ratio = io_sample_rate_ratio_;
285 const float* const kernel_ptr = kernel_storage_.get();
286 while (remaining_frames) {
287 // |i| may be negative if the last Resample() call ended on an iteration
288 // that put |virtual_source_idx_| over the limit.
290 // Note: The loop construct here can severely impact performance on ARM
291 // or when built with clang. See https://codereview.chromium.org/18566009/
292 for (int i = ceil((block_size_ - virtual_source_idx_) / current_io_ratio);
294 assert(virtual_source_idx_ < block_size_);
296 // |virtual_source_idx_| lies in between two kernel offsets so figure out
298 const int source_idx = virtual_source_idx_;
299 const double subsample_remainder = virtual_source_idx_ - source_idx;
301 const double virtual_offset_idx =
302 subsample_remainder * kKernelOffsetCount;
303 const int offset_idx = virtual_offset_idx;
305 // We'll compute "convolutions" for the two kernels which straddle
306 // |virtual_source_idx_|.
307 const float* const k1 = kernel_ptr + offset_idx * kKernelSize;
308 const float* const k2 = k1 + kKernelSize;
310 // Ensure |k1|, |k2| are 16-byte aligned for SIMD usage. Should always be
311 // true so long as kKernelSize is a multiple of 16.
312 assert(0u == (reinterpret_cast<uintptr_t>(k1) & 0x0F));
313 assert(0u == (reinterpret_cast<uintptr_t>(k2) & 0x0F));
315 // Initialize input pointer based on quantized |virtual_source_idx_|.
316 const float* const input_ptr = r1_ + source_idx;
318 // Figure out how much to weight each kernel's "convolution".
319 const double kernel_interpolation_factor =
320 virtual_offset_idx - offset_idx;
321 *destination++ = CONVOLVE_FUNC(
322 input_ptr, k1, k2, kernel_interpolation_factor);
324 // Advance the virtual index.
325 virtual_source_idx_ += current_io_ratio;
327 if (!--remaining_frames)
331 // Wrap back around to the start.
332 virtual_source_idx_ -= block_size_;
334 // Step (3) -- Copy r3_, r4_ to r1_, r2_.
335 // This wraps the last input frames back to the start of the buffer.
336 memcpy(r1_, r3_, sizeof(*input_buffer_.get()) * kKernelSize);
338 // Step (4) -- Reinitialize regions if necessary.
342 // Step (5) -- Refresh the buffer with more input.
343 read_cb_->Run(request_frames_, r0_);
349 int SincResampler::ChunkSize() const {
350 return block_size_ / io_sample_rate_ratio_;
353 void SincResampler::Flush() {
354 virtual_source_idx_ = 0;
355 buffer_primed_ = false;
356 memset(input_buffer_.get(), 0,
357 sizeof(*input_buffer_.get()) * input_buffer_size_);
358 UpdateRegions(false);
361 float SincResampler::Convolve_C(const float* input_ptr, const float* k1,
363 double kernel_interpolation_factor) {
367 // Generate a single output sample. Unrolling this loop hurt performance in
371 sum1 += *input_ptr * *k1++;
372 sum2 += *input_ptr++ * *k2++;
375 // Linearly interpolate the two "convolutions".
376 return (1.0 - kernel_interpolation_factor) * sum1
377 + kernel_interpolation_factor * sum2;
380 } // namespace webrtc