tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

sinc_resampler.cc (13992B)


      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 #include "common_audio/resampler/sinc_resampler.h"
     86 
     87 #include <cmath>
     88 #include <cstdint>
     89 #include <cstring>
     90 #include <limits>
     91 #include <numbers>
     92 
     93 #include "rtc_base/checks.h"
     94 #include "rtc_base/cpu_info.h"
     95 #include "rtc_base/memory/aligned_malloc.h"
     96 #include "rtc_base/system/arch.h"
     97 
     98 namespace webrtc {
     99 
    100 namespace {
    101 
    102 double SincScaleFactor(double io_ratio) {
    103  // `sinc_scale_factor` is basically the normalized cutoff frequency of the
    104  // low-pass filter.
    105  double sinc_scale_factor = io_ratio > 1.0 ? 1.0 / io_ratio : 1.0;
    106 
    107  // The sinc function is an idealized brick-wall filter, but since we're
    108  // windowing it the transition from pass to stop does not happen right away.
    109  // So we should adjust the low pass filter cutoff slightly downward to avoid
    110  // some aliasing at the very high-end.
    111  // TODO(crogers): this value is empirical and to be more exact should vary
    112  // depending on kKernelSize.
    113  sinc_scale_factor *= 0.9;
    114 
    115  return sinc_scale_factor;
    116 }
    117 
    118 }  // namespace
    119 
    120 const size_t SincResampler::kKernelSize;
    121 
    122 // If we know the minimum architecture at compile time, avoid CPU detection.
    123 void SincResampler::InitializeCPUSpecificFeatures() {
    124 #if defined(WEBRTC_HAS_NEON)
    125  convolve_proc_ = Convolve_NEON;
    126 #elif defined(WEBRTC_ARCH_X86_FAMILY)
    127  // Using AVX2 instead of SSE2 when AVX2/FMA3 supported.
    128  if (cpu_info::Supports(cpu_info::ISA::kAVX2) &&
    129      cpu_info::Supports(cpu_info::ISA::kFMA3))
    130    convolve_proc_ = Convolve_AVX2;
    131  else if (cpu_info::Supports(cpu_info::ISA::kSSE2))
    132    convolve_proc_ = Convolve_SSE;
    133  else
    134    convolve_proc_ = Convolve_C;
    135 #else
    136  // Unknown architecture.
    137  convolve_proc_ = Convolve_C;
    138 #endif
    139 }
    140 
    141 SincResampler::SincResampler(double io_sample_rate_ratio,
    142                             size_t request_frames,
    143                             SincResamplerCallback* read_cb)
    144    : io_sample_rate_ratio_(io_sample_rate_ratio),
    145      read_cb_(read_cb),
    146      request_frames_(request_frames),
    147      input_buffer_size_(request_frames_ + kKernelSize),
    148      // Create input buffers with a 32-byte alignment for SIMD optimizations.
    149      kernel_storage_(static_cast<float*>(
    150          AlignedMalloc(sizeof(float) * kKernelStorageSize, 32))),
    151      kernel_pre_sinc_storage_(static_cast<float*>(
    152          AlignedMalloc(sizeof(float) * kKernelStorageSize, 32))),
    153      kernel_window_storage_(static_cast<float*>(
    154          AlignedMalloc(sizeof(float) * kKernelStorageSize, 32))),
    155      input_buffer_(static_cast<float*>(
    156          AlignedMalloc(sizeof(float) * input_buffer_size_, 32))),
    157      convolve_proc_(nullptr),
    158      r1_(input_buffer_.get()),
    159      r2_(input_buffer_.get() + kKernelSize / 2) {
    160  InitializeCPUSpecificFeatures();
    161  RTC_DCHECK(convolve_proc_);
    162  RTC_DCHECK_GT(request_frames_, 0);
    163  Flush();
    164  RTC_DCHECK_GT(block_size_, kKernelSize);
    165 
    166  memset(kernel_storage_.get(), 0,
    167         sizeof(*kernel_storage_.get()) * kKernelStorageSize);
    168  memset(kernel_pre_sinc_storage_.get(), 0,
    169         sizeof(*kernel_pre_sinc_storage_.get()) * kKernelStorageSize);
    170  memset(kernel_window_storage_.get(), 0,
    171         sizeof(*kernel_window_storage_.get()) * kKernelStorageSize);
    172 
    173  InitializeKernel();
    174 }
    175 
    176 SincResampler::~SincResampler() {}
    177 
    178 void SincResampler::UpdateRegions(bool second_load) {
    179  // Setup various region pointers in the buffer (see diagram above).  If we're
    180  // on the second load we need to slide r0_ to the right by kKernelSize / 2.
    181  r0_ = input_buffer_.get() + (second_load ? kKernelSize : kKernelSize / 2);
    182  r3_ = r0_ + request_frames_ - kKernelSize;
    183  r4_ = r0_ + request_frames_ - kKernelSize / 2;
    184  block_size_ = r4_ - r2_;
    185 
    186  // r1_ at the beginning of the buffer.
    187  RTC_DCHECK_EQ(r1_, input_buffer_.get());
    188  // r1_ left of r2_, r4_ left of r3_ and size correct.
    189  RTC_DCHECK_EQ(r2_ - r1_, r4_ - r3_);
    190  // r2_ left of r3.
    191  RTC_DCHECK_LT(r2_, r3_);
    192 }
    193 
    194 void SincResampler::InitializeKernel() {
    195  // Blackman window parameters.
    196  static const double kAlpha = 0.16;
    197  static const double kA0 = 0.5 * (1.0 - kAlpha);
    198  static const double kA1 = 0.5;
    199  static const double kA2 = 0.5 * kAlpha;
    200 
    201  // Generates a set of windowed sinc() kernels.
    202  // We generate a range of sub-sample offsets from 0.0 to 1.0.
    203  const double sinc_scale_factor = SincScaleFactor(io_sample_rate_ratio_);
    204  for (size_t offset_idx = 0; offset_idx <= kKernelOffsetCount; ++offset_idx) {
    205    const float subsample_offset =
    206        static_cast<float>(offset_idx) / kKernelOffsetCount;
    207 
    208    for (size_t i = 0; i < kKernelSize; ++i) {
    209      const size_t idx = i + offset_idx * kKernelSize;
    210      const float pre_sinc = static_cast<float>(
    211          std::numbers::pi *
    212          (static_cast<int>(i) - static_cast<int>(kKernelSize / 2) -
    213           subsample_offset));
    214      kernel_pre_sinc_storage_[idx] = pre_sinc;
    215 
    216      // Compute Blackman window, matching the offset of the sinc().
    217      const float x = (i - subsample_offset) / kKernelSize;
    218      const float window =
    219          static_cast<float>(kA0 - kA1 * cos(2.0 * std::numbers::pi * x) +
    220                             kA2 * cos(4.0 * std::numbers::pi * x));
    221      kernel_window_storage_[idx] = window;
    222 
    223      // Compute the sinc with offset, then window the sinc() function and store
    224      // at the correct offset.
    225      kernel_storage_[idx] = static_cast<float>(
    226          window * ((pre_sinc == 0)
    227                        ? sinc_scale_factor
    228                        : (sin(sinc_scale_factor * pre_sinc) / pre_sinc)));
    229    }
    230  }
    231 }
    232 
    233 void SincResampler::SetRatio(double io_sample_rate_ratio) {
    234  if (fabs(io_sample_rate_ratio_ - io_sample_rate_ratio) <
    235      std::numeric_limits<double>::epsilon()) {
    236    return;
    237  }
    238 
    239  io_sample_rate_ratio_ = io_sample_rate_ratio;
    240 
    241  // Optimize reinitialization by reusing values which are independent of
    242  // `sinc_scale_factor`.  Provides a 3x speedup.
    243  const double sinc_scale_factor = SincScaleFactor(io_sample_rate_ratio_);
    244  for (size_t offset_idx = 0; offset_idx <= kKernelOffsetCount; ++offset_idx) {
    245    for (size_t i = 0; i < kKernelSize; ++i) {
    246      const size_t idx = i + offset_idx * kKernelSize;
    247      const float window = kernel_window_storage_[idx];
    248      const float pre_sinc = kernel_pre_sinc_storage_[idx];
    249 
    250      kernel_storage_[idx] = static_cast<float>(
    251          window * ((pre_sinc == 0)
    252                        ? sinc_scale_factor
    253                        : (sin(sinc_scale_factor * pre_sinc) / pre_sinc)));
    254    }
    255  }
    256 }
    257 
    258 void SincResampler::Resample(size_t frames, float* destination) {
    259  size_t remaining_frames = frames;
    260 
    261  // Step (1) -- Prime the input buffer at the start of the input stream.
    262  if (!buffer_primed_ && remaining_frames) {
    263    read_cb_->Run(request_frames_, r0_);
    264    buffer_primed_ = true;
    265  }
    266 
    267  // Step (2) -- Resample!  const what we can outside of the loop for speed.  It
    268  // actually has an impact on ARM performance.  See inner loop comment below.
    269  const double current_io_ratio = io_sample_rate_ratio_;
    270  const float* const kernel_ptr = kernel_storage_.get();
    271  while (remaining_frames) {
    272    // `i` may be negative if the last Resample() call ended on an iteration
    273    // that put `virtual_source_idx_` over the limit.
    274    //
    275    // Note: The loop construct here can severely impact performance on ARM
    276    // or when built with clang.  See https://codereview.chromium.org/18566009/
    277    for (int i = static_cast<int>(
    278             ceil((block_size_ - virtual_source_idx_) / current_io_ratio));
    279         i > 0; --i) {
    280      RTC_DCHECK_LT(virtual_source_idx_, block_size_);
    281 
    282      // `virtual_source_idx_` lies in between two kernel offsets so figure out
    283      // what they are.
    284      const int source_idx = static_cast<int>(virtual_source_idx_);
    285      const double subsample_remainder = virtual_source_idx_ - source_idx;
    286 
    287      const double virtual_offset_idx =
    288          subsample_remainder * kKernelOffsetCount;
    289      const int offset_idx = static_cast<int>(virtual_offset_idx);
    290 
    291      // We'll compute "convolutions" for the two kernels which straddle
    292      // `virtual_source_idx_`.
    293      const float* const k1 = kernel_ptr + offset_idx * kKernelSize;
    294      const float* const k2 = k1 + kKernelSize;
    295 
    296      // Ensure `k1`, `k2` are 32-byte aligned for SIMD usage.  Should always be
    297      // true so long as kKernelSize is a multiple of 32.
    298      RTC_DCHECK_EQ(0, reinterpret_cast<uintptr_t>(k1) % 32);
    299      RTC_DCHECK_EQ(0, reinterpret_cast<uintptr_t>(k2) % 32);
    300 
    301      // Initialize input pointer based on quantized `virtual_source_idx_`.
    302      const float* const input_ptr = r1_ + source_idx;
    303 
    304      // Figure out how much to weight each kernel's "convolution".
    305      const double kernel_interpolation_factor =
    306          virtual_offset_idx - offset_idx;
    307      *destination++ =
    308          convolve_proc_(input_ptr, k1, k2, kernel_interpolation_factor);
    309 
    310      // Advance the virtual index.
    311      virtual_source_idx_ += current_io_ratio;
    312 
    313      if (!--remaining_frames)
    314        return;
    315    }
    316 
    317    // Wrap back around to the start.
    318    virtual_source_idx_ -= block_size_;
    319 
    320    // Step (3) -- Copy r3_, r4_ to r1_, r2_.
    321    // This wraps the last input frames back to the start of the buffer.
    322    memcpy(r1_, r3_, sizeof(*input_buffer_.get()) * kKernelSize);
    323 
    324    // Step (4) -- Reinitialize regions if necessary.
    325    if (r0_ == r2_)
    326      UpdateRegions(true);
    327 
    328    // Step (5) -- Refresh the buffer with more input.
    329    read_cb_->Run(request_frames_, r0_);
    330  }
    331 }
    332 
    333 #undef CONVOLVE_FUNC
    334 
    335 size_t SincResampler::ChunkSize() const {
    336  return static_cast<size_t>(block_size_ / io_sample_rate_ratio_);
    337 }
    338 
    339 void SincResampler::Flush() {
    340  virtual_source_idx_ = 0;
    341  buffer_primed_ = false;
    342  memset(input_buffer_.get(), 0,
    343         sizeof(*input_buffer_.get()) * input_buffer_size_);
    344  UpdateRegions(false);
    345 }
    346 
    347 float SincResampler::Convolve_C(const float* input_ptr,
    348                                const float* k1,
    349                                const float* k2,
    350                                double kernel_interpolation_factor) {
    351  float sum1 = 0;
    352  float sum2 = 0;
    353 
    354  // Generate a single output sample.  Unrolling this loop hurt performance in
    355  // local testing.
    356  size_t n = kKernelSize;
    357  while (n--) {
    358    sum1 += *input_ptr * *k1++;
    359    sum2 += *input_ptr++ * *k2++;
    360  }
    361 
    362  // Linearly interpolate the two "convolutions".
    363  return static_cast<float>((1.0 - kernel_interpolation_factor) * sum1 +
    364                            kernel_interpolation_factor * sum2);
    365 }
    366 
    367 }  // namespace webrtc