sinc_resampler.cc revision 073dd7b423157020846872ca2398cc86d3ca9508
1/*
2 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3 *
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 */
10
11// Modified from the Chromium original:
12// src/media/base/sinc_resampler.cc
13
14// Initial input buffer layout, dividing into regions r0_ to r4_ (note: r0_, r3_
15// and r4_ will move after the first load):
16//
17// |----------------|-----------------------------------------|----------------|
18//
19//                                        request_frames_
20//                   <--------------------------------------------------------->
21//                                    r0_ (during first load)
22//
23//  kKernelSize / 2   kKernelSize / 2         kKernelSize / 2   kKernelSize / 2
24// <---------------> <--------------->       <---------------> <--------------->
25//        r1_               r2_                     r3_               r4_
26//
27//                             block_size_ == r4_ - r2_
28//                   <--------------------------------------->
29//
30//                                                  request_frames_
31//                                    <------------------ ... ----------------->
32//                                               r0_ (during second load)
33//
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.
36//
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
39// provided callback.
40//
41// The algorithm:
42//
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).
46//
47// 2) Let r1_, r2_ each represent half the kernel centered around r0_:
48//
49//        r0_ = input_buffer_ + kKernelSize / 2
50//        r1_ = input_buffer_
51//        r2_ = r0_
52//
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
55//    step (5) for why).
56//
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_:
59//
60//        r3_ = r0_ + request_frames_ - kKernelSize
61//        r4_ = r0_ + request_frames_ - kKernelSize / 2
62//        block_size_ = r4_ - r2_ = request_frames_ - kKernelSize / 2
63//
64// 4) Consume request_frames_ frames into r0_.
65//
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.
69//
70// 6) Wrap left over data from the r3_ to r1_ and r4_ to r2_.
71//
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:
75//
76//        r0_ = r0_ + kKernelSize / 2 = input_buffer_ + kKernelSize
77//
78//    r3_, r4_, and block_size_ then need to be reinitialized, so goto (3).
79//
80// 8) Else, if we're not on the second load, goto (4).
81//
82// Note: we're glossing over how the sub-sample handling works with
83// |virtual_source_idx_|, etc.
84
85// MSVC++ requires this to be set before any other includes to get M_PI.
86#define _USE_MATH_DEFINES
87
88#include "webrtc/common_audio/resampler/sinc_resampler.h"
89#include "webrtc/system_wrappers/interface/cpu_features_wrapper.h"
90#include "webrtc/typedefs.h"
91
92#include <assert.h>
93#include <math.h>
94#include <string.h>
95
96#include <limits>
97
98namespace webrtc {
99
100static double SincScaleFactor(double io_ratio) {
101  // |sinc_scale_factor| is basically the normalized cutoff frequency of the
102  // low-pass filter.
103  double sinc_scale_factor = io_ratio > 1.0 ? 1.0 / io_ratio : 1.0;
104
105  // The sinc function is an idealized brick-wall filter, but since we're
106  // windowing it the transition from pass to stop does not happen right away.
107  // So we should adjust the low pass filter cutoff slightly downward to avoid
108  // some aliasing at the very high-end.
109  // TODO(crogers): this value is empirical and to be more exact should vary
110  // depending on kKernelSize.
111  sinc_scale_factor *= 0.9;
112
113  return sinc_scale_factor;
114}
115
116// If we know the minimum architecture at compile time, avoid CPU detection.
117#if defined(WEBRTC_ARCH_X86_FAMILY)
118#if defined(__SSE2__)
119#define CONVOLVE_FUNC Convolve_SSE
120void SincResampler::InitializeCPUSpecificFeatures() {}
121#else
122// x86 CPU detection required.  Function will be set by
123// InitializeCPUSpecificFeatures().
124// TODO(dalecurtis): Once Chrome moves to an SSE baseline this can be removed.
125#define CONVOLVE_FUNC convolve_proc_
126
127void SincResampler::InitializeCPUSpecificFeatures() {
128  convolve_proc_ = WebRtc_GetCPUInfo(kSSE2) ? Convolve_SSE : Convolve_C;
129}
130#endif
131#elif defined(WEBRTC_DETECT_ARM_NEON) || defined(WEBRTC_ARCH_ARM_NEON)
132#if defined(WEBRTC_ARCH_ARM_NEON)
133#define CONVOLVE_FUNC Convolve_NEON
134void SincResampler::InitializeCPUSpecificFeatures() {}
135#else
136// ARM CPU detection required.  Function will be set by
137// InitializeCPUSpecificFeatures().
138#define CONVOLVE_FUNC convolve_proc_
139
140void SincResampler::InitializeCPUSpecificFeatures() {
141  convolve_proc_ = WebRtc_GetCPUFeaturesARM() & kCPUFeatureNEON ?
142      Convolve_NEON : Convolve_C;
143}
144#endif
145#else
146// Unknown architecture.
147#define CONVOLVE_FUNC Convolve_C
148void SincResampler::InitializeCPUSpecificFeatures() {}
149#endif
150
151SincResampler::SincResampler(double io_sample_rate_ratio,
152                             int request_frames,
153                             SincResamplerCallback* read_cb)
154    : io_sample_rate_ratio_(io_sample_rate_ratio),
155      read_cb_(read_cb),
156      request_frames_(request_frames),
157      input_buffer_size_(request_frames_ + kKernelSize),
158      // Create input buffers with a 16-byte alignment for SSE optimizations.
159      kernel_storage_(static_cast<float*>(
160          AlignedMalloc(sizeof(float) * kKernelStorageSize, 16))),
161      kernel_pre_sinc_storage_(static_cast<float*>(
162          AlignedMalloc(sizeof(float) * kKernelStorageSize, 16))),
163      kernel_window_storage_(static_cast<float*>(
164          AlignedMalloc(sizeof(float) * kKernelStorageSize, 16))),
165      input_buffer_(static_cast<float*>(
166          AlignedMalloc(sizeof(float) * input_buffer_size_, 16))),
167#if defined(WEBRTC_CPU_DETECTION)
168      convolve_proc_(NULL),
169#endif
170      r1_(input_buffer_.get()),
171      r2_(input_buffer_.get() + kKernelSize / 2) {
172#if defined(WEBRTC_CPU_DETECTION)
173  InitializeCPUSpecificFeatures();
174  assert(convolve_proc_);
175#endif
176  assert(request_frames_ > 0);
177  Flush();
178  assert(block_size_ > kKernelSize);
179
180  memset(kernel_storage_.get(), 0,
181         sizeof(*kernel_storage_.get()) * kKernelStorageSize);
182  memset(kernel_pre_sinc_storage_.get(), 0,
183         sizeof(*kernel_pre_sinc_storage_.get()) * kKernelStorageSize);
184  memset(kernel_window_storage_.get(), 0,
185         sizeof(*kernel_window_storage_.get()) * kKernelStorageSize);
186
187  InitializeKernel();
188}
189
190SincResampler::~SincResampler() {}
191
192void SincResampler::UpdateRegions(bool second_load) {
193  // Setup various region pointers in the buffer (see diagram above).  If we're
194  // on the second load we need to slide r0_ to the right by kKernelSize / 2.
195  r0_ = input_buffer_.get() + (second_load ? kKernelSize : kKernelSize / 2);
196  r3_ = r0_ + request_frames_ - kKernelSize;
197  r4_ = r0_ + request_frames_ - kKernelSize / 2;
198  block_size_ = r4_ - r2_;
199
200  // r1_ at the beginning of the buffer.
201  assert(r1_ == input_buffer_.get());
202  // r1_ left of r2_, r4_ left of r3_ and size correct.
203  assert(r2_ - r1_ == r4_ - r3_);
204  // r2_ left of r3.
205  assert(r2_ < r3_);
206}
207
208void SincResampler::InitializeKernel() {
209  // Blackman window parameters.
210  static const double kAlpha = 0.16;
211  static const double kA0 = 0.5 * (1.0 - kAlpha);
212  static const double kA1 = 0.5;
213  static const double kA2 = 0.5 * kAlpha;
214
215  // Generates a set of windowed sinc() kernels.
216  // We generate a range of sub-sample offsets from 0.0 to 1.0.
217  const double sinc_scale_factor = SincScaleFactor(io_sample_rate_ratio_);
218  for (int offset_idx = 0; offset_idx <= kKernelOffsetCount; ++offset_idx) {
219    const float subsample_offset =
220        static_cast<float>(offset_idx) / kKernelOffsetCount;
221
222    for (int i = 0; i < kKernelSize; ++i) {
223      const int idx = i + offset_idx * kKernelSize;
224      const float pre_sinc =
225          static_cast<float>(M_PI * (i - kKernelSize / 2 - subsample_offset));
226      kernel_pre_sinc_storage_[idx] = pre_sinc;
227
228      // Compute Blackman window, matching the offset of the sinc().
229      const float x = (i - subsample_offset) / kKernelSize;
230      const float window = static_cast<float>(kA0 - kA1 * cos(2.0 * M_PI * x) +
231          kA2 * cos(4.0 * M_PI * x));
232      kernel_window_storage_[idx] = window;
233
234      // Compute the sinc with offset, then window the sinc() function and store
235      // at the correct offset.
236      kernel_storage_[idx] = static_cast<float>(window *
237          ((pre_sinc == 0) ?
238              sinc_scale_factor :
239              (sin(sinc_scale_factor * pre_sinc) / pre_sinc)));
240    }
241  }
242}
243
244void SincResampler::SetRatio(double io_sample_rate_ratio) {
245  if (fabs(io_sample_rate_ratio_ - io_sample_rate_ratio) <
246      std::numeric_limits<double>::epsilon()) {
247    return;
248  }
249
250  io_sample_rate_ratio_ = io_sample_rate_ratio;
251
252  // Optimize reinitialization by reusing values which are independent of
253  // |sinc_scale_factor|.  Provides a 3x speedup.
254  const double sinc_scale_factor = SincScaleFactor(io_sample_rate_ratio_);
255  for (int offset_idx = 0; offset_idx <= kKernelOffsetCount; ++offset_idx) {
256    for (int i = 0; i < kKernelSize; ++i) {
257      const int idx = i + offset_idx * kKernelSize;
258      const float window = kernel_window_storage_[idx];
259      const float pre_sinc = kernel_pre_sinc_storage_[idx];
260
261      kernel_storage_[idx] = static_cast<float>(window *
262          ((pre_sinc == 0) ?
263              sinc_scale_factor :
264              (sin(sinc_scale_factor * pre_sinc) / pre_sinc)));
265    }
266  }
267}
268
269void SincResampler::Resample(int frames, float* destination) {
270  int remaining_frames = frames;
271
272  // Step (1) -- Prime the input buffer at the start of the input stream.
273  if (!buffer_primed_ && remaining_frames) {
274    read_cb_->Run(request_frames_, r0_);
275    buffer_primed_ = true;
276  }
277
278  // Step (2) -- Resample!  const what we can outside of the loop for speed.  It
279  // actually has an impact on ARM performance.  See inner loop comment below.
280  const double current_io_ratio = io_sample_rate_ratio_;
281  const float* const kernel_ptr = kernel_storage_.get();
282  while (remaining_frames) {
283    // |i| may be negative if the last Resample() call ended on an iteration
284    // that put |virtual_source_idx_| over the limit.
285    //
286    // Note: The loop construct here can severely impact performance on ARM
287    // or when built with clang.  See https://codereview.chromium.org/18566009/
288    for (int i = static_cast<int>(
289             ceil((block_size_ - virtual_source_idx_) / current_io_ratio));
290         i > 0; --i) {
291      assert(virtual_source_idx_ < block_size_);
292
293      // |virtual_source_idx_| lies in between two kernel offsets so figure out
294      // what they are.
295      const int source_idx = static_cast<int>(virtual_source_idx_);
296      const double subsample_remainder = virtual_source_idx_ - source_idx;
297
298      const double virtual_offset_idx =
299          subsample_remainder * kKernelOffsetCount;
300      const int offset_idx = static_cast<int>(virtual_offset_idx);
301
302      // We'll compute "convolutions" for the two kernels which straddle
303      // |virtual_source_idx_|.
304      const float* const k1 = kernel_ptr + offset_idx * kKernelSize;
305      const float* const k2 = k1 + kKernelSize;
306
307      // Ensure |k1|, |k2| are 16-byte aligned for SIMD usage.  Should always be
308      // true so long as kKernelSize is a multiple of 16.
309      assert(0u == (reinterpret_cast<uintptr_t>(k1) & 0x0F));
310      assert(0u == (reinterpret_cast<uintptr_t>(k2) & 0x0F));
311
312      // Initialize input pointer based on quantized |virtual_source_idx_|.
313      const float* const input_ptr = r1_ + source_idx;
314
315      // Figure out how much to weight each kernel's "convolution".
316      const double kernel_interpolation_factor =
317          virtual_offset_idx - offset_idx;
318      *destination++ = CONVOLVE_FUNC(
319          input_ptr, k1, k2, kernel_interpolation_factor);
320
321      // Advance the virtual index.
322      virtual_source_idx_ += current_io_ratio;
323
324      if (!--remaining_frames)
325        return;
326    }
327
328    // Wrap back around to the start.
329    virtual_source_idx_ -= block_size_;
330
331    // Step (3) -- Copy r3_, r4_ to r1_, r2_.
332    // This wraps the last input frames back to the start of the buffer.
333    memcpy(r1_, r3_, sizeof(*input_buffer_.get()) * kKernelSize);
334
335    // Step (4) -- Reinitialize regions if necessary.
336    if (r0_ == r2_)
337      UpdateRegions(true);
338
339    // Step (5) -- Refresh the buffer with more input.
340    read_cb_->Run(request_frames_, r0_);
341  }
342}
343
344#undef CONVOLVE_FUNC
345
346int SincResampler::ChunkSize() const {
347  return static_cast<int>(block_size_ / io_sample_rate_ratio_);
348}
349
350void SincResampler::Flush() {
351  virtual_source_idx_ = 0;
352  buffer_primed_ = false;
353  memset(input_buffer_.get(), 0,
354         sizeof(*input_buffer_.get()) * input_buffer_size_);
355  UpdateRegions(false);
356}
357
358float SincResampler::Convolve_C(const float* input_ptr, const float* k1,
359                                const float* k2,
360                                double kernel_interpolation_factor) {
361  float sum1 = 0;
362  float sum2 = 0;
363
364  // Generate a single output sample.  Unrolling this loop hurt performance in
365  // local testing.
366  int n = kKernelSize;
367  while (n--) {
368    sum1 += *input_ptr * *k1++;
369    sum2 += *input_ptr++ * *k2++;
370  }
371
372  // Linearly interpolate the two "convolutions".
373  return static_cast<float>((1.0 - kernel_interpolation_factor) * sum1 +
374      kernel_interpolation_factor * sum2);
375}
376
377}  // namespace webrtc
378