DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
dspark::Resampler< T > Class Template Reference

Windowed-sinc sample rate converter optimized for real-time DSP. More...

#include <Resampler.h>

Public Types

enum class  Quality { Draft , Normal , High , Ultra }
 
enum class  OfflineEngine { Direct , TwoStage }
 How process() and processRange() compute (setOfflineEngine()). More...
 

Public Member Functions

void setOfflineEngine (OfflineEngine engine) noexcept
 Chooses the offline engine (the streaming path is unaffected).
 
OfflineEngine getOfflineEngine () const noexcept
 The offline engine in force (Direct by default).
 
void prepare (double sourceRate, double targetRate, Quality quality=Quality::Normal)
 Prepares the resampler for a given rate conversion.
 
void prepare (const AudioSpec &spec, double targetRate, Quality quality=Quality::Normal)
 Prepares the resampler using AudioSpec (unified API).
 
void reset () noexcept
 Resets the internal state (delay lines, all channels) to zero.
 
std::vector< T > process (const T *input, int inputLength)
 Resamples an entire buffer (offline batch processing).
 
int64_t process (const T *input, int inputLength, T *output, int64_t outputCapacity)
 process() into caller storage.
 
std::vector< T > processRange (const T *input, int inputLength, int64_t firstOutput, int64_t count)
 Offline, time-aligned conversion of any span of output samples.
 
int64_t getReach () const noexcept
 How far, in output samples, the kernel reaches before an input sample and after it: processRange() over [-getReach(), ceil(inputLength * getRatio()) + getReach()) holds the whole converted signal. It is the reach of the offline engine in force (setOfflineEngine()).
 
int processBlock (const T *input, int inputLength, T *output) noexcept
 Resamples a block of audio in single-channel streaming mode.
 
int processBlock (AudioBufferView< T > input, AudioBufferView< T > output) noexcept
 Resamples multi-channel audio using AudioBufferView (streaming).
 
int getMaxOutputSamples (int inputLength) const noexcept
 Returns the maximum number of output samples for a given input length.
 
double getRatio () const noexcept
 Returns the conversion ratio (targetRate / sourceRate).
 
int getFilterLength () const noexcept
 Kernel length in input samples (1 at a ratio of exactly 1).
 
int getLatency () const noexcept
 Returns the streaming latency in output samples.
 

Static Public Attributes

static constexpr int kMaxTaps = 8192
 Longest kernel, in input samples (see the class note).
 
static constexpr double kMaxRatio = 16777216.0
 Largest target/source ratio prepare() accepts. Output per input sample follows the ratio, so past this no caller's buffer holds it.
 
static constexpr int kMaxTwoStageOrder = 1 << 16
 Longest stage-1 kernel order of the TwoStage offline engine (see setOfflineEngine()).
 

Detailed Description

template<typename T>
class dspark::Resampler< T >

Windowed-sinc sample rate converter optimized for real-time DSP.

Quality tiers are filter specifications; the kernel length follows from them and from the ratio (a downsampler's kernel is longer by the ratio, since its band edge is lower relative to the input rate):

Quality Passband edge Stopband Taps, 44.1 <-> 48 kHz
Draft 0.80 Nyquist 60 dB 38 / 40
Normal 0.90 Nyquist 100 dB 130 / 140
High 0.91 Nyquist 140 dB 206 / 224
Ultra 0.915 Nyquist 210 dB 332 / 362

"Nyquist" is the lower of the two rates' Nyquist frequencies; Ultra's passband reaches 20.2 kHz at 44.1 kHz. The float instantiation is limited by float arithmetic to roughly -140 dB; the double one reaches the table. Kernels are capped at kMaxTaps taps, which binds only for downsampling beyond about 25:1 at Ultra: past it the transition band widens.

Template Parameters
TSample type (float or double).

Definition at line 99 of file Resampler.h.

Member Enumeration Documentation

◆ OfflineEngine

template<typename T >
enum class dspark::Resampler::OfflineEngine
strong

How process() and processRange() compute (setOfflineEngine()).

Enumerator
Direct 

The streaming kernels: process() is processBlock() shifted by getLatency(), bit for bit.

TwoStage 

FFT band-limiting, then a short interpolator: the same tier specification, cheaper.

Definition at line 122 of file Resampler.h.

◆ Quality

template<typename T >
enum class dspark::Resampler::Quality
strong
Enumerator
Draft 

Passband 0.80 of Nyquist, 60 dB stopband: previews.

Normal 

Passband 0.90 of Nyquist, 100 dB stopband.

High 

Passband 0.91 of Nyquist (20 kHz at 44.1), 140 dB stopband.

Ultra 

Passband 0.915 of Nyquist, 210 dB stopband: mastering.

Definition at line 102 of file Resampler.h.

Member Function Documentation

◆ getFilterLength()

template<typename T >
int dspark::Resampler< T >::getFilterLength ( ) const
inlinenoexcept

Kernel length in input samples (1 at a ratio of exactly 1).

Definition at line 443 of file Resampler.h.

◆ getLatency()

template<typename T >
int dspark::Resampler< T >::getLatency ( ) const
inlinenoexcept

Returns the streaming latency in output samples.

The streaming path (processBlock) delays the signal by exactly half the kernel length in input samples – the kernel's group delay – which this getter reports rounded to the nearest output sample. The offline process() path is already time-aligned and has zero latency.

Definition at line 453 of file Resampler.h.

◆ getMaxOutputSamples()

template<typename T >
int dspark::Resampler< T >::getMaxOutputSamples ( int  inputLength) const
inlinenoexcept

Returns the maximum number of output samples for a given input length.

Parameters
inputLengthNumber of input samples.
Returns
Maximum possible output samples.

Definition at line 431 of file Resampler.h.

◆ getOfflineEngine()

template<typename T >
OfflineEngine dspark::Resampler< T >::getOfflineEngine ( ) const
inlinenoexcept

The offline engine in force (Direct by default).

Definition at line 179 of file Resampler.h.

◆ getRatio()

template<typename T >
double dspark::Resampler< T >::getRatio ( ) const
inlinenoexcept

Returns the conversion ratio (targetRate / sourceRate).

Definition at line 440 of file Resampler.h.

◆ getReach()

template<typename T >
int64_t dspark::Resampler< T >::getReach ( ) const
inlinenoexcept

How far, in output samples, the kernel reaches before an input sample and after it: processRange() over [-getReach(), ceil(inputLength * getRatio()) + getReach()) holds the whole converted signal. It is the reach of the offline engine in force (setOfflineEngine()).

Definition at line 369 of file Resampler.h.

◆ prepare() [1/2]

template<typename T >
void dspark::Resampler< T >::prepare ( const AudioSpec &  spec,
double  targetRate,
Quality  quality = Quality::Normal 
)
inline

Prepares the resampler using AudioSpec (unified API).

Pre-allocates multi-channel states. MUST be called outside the audio thread.

Parameters
specAudio environment (sampleRate, numChannels used).
targetRateTarget sample rate in Hz.
qualityFilter specification (default: Normal).

Definition at line 208 of file Resampler.h.

◆ prepare() [2/2]

template<typename T >
void dspark::Resampler< T >::prepare ( double  sourceRate,
double  targetRate,
Quality  quality = Quality::Normal 
)
inline

Prepares the resampler for a given rate conversion.

Allocates internal buffers. MUST be called outside the audio thread. A non-finite rate, or a ratio above kMaxRatio, is ignored and the current conversion stays in force. Rates below 1 Hz are raised to 1 Hz.

Parameters
sourceRateSource sample rate in Hz.
targetRateTarget sample rate in Hz.
qualityFilter specification (default: Normal).

Definition at line 192 of file Resampler.h.

◆ process() [1/2]

template<typename T >
std::vector< T > dspark::Resampler< T >::process ( const T *  input,
int  inputLength 
)
inline

Resamples an entire buffer (offline batch processing).

Stateless and time-aligned: output sample k interpolates the input at position k / getRatio() exactly (no latency; the buffer edges are zero-padded). Allocates the output vector – offline use only; the overload that writes into caller storage does not.

Parameters
inputSource audio samples.
inputLengthNumber of input samples.
Returns
Vector of resampled output samples (ceil(inputLength * ratio)); empty when not prepared, for a null input or a length below 1.

Definition at line 244 of file Resampler.h.

◆ process() [2/2]

template<typename T >
int64_t dspark::Resampler< T >::process ( const T *  input,
int  inputLength,
T *  output,
int64_t  outputCapacity 
)
inline

process() into caller storage.

Writes the first min(outputCapacity, ceil(inputLength * getRatio())) samples of process()'s result, bit for bit. It allocates nothing once the offline engine is designed (the first offline call after prepare() or setOfflineEngine() designs it), so a converter that reuses its output buffer pays no allocation per call.

Parameters
inputSource audio samples.
inputLengthNumber of input samples.
outputDestination for the converted samples.
outputCapacitySamples the destination holds.
Returns
Samples written: 0 when not prepared, for a null pointer, or for a length or capacity below 1.

Definition at line 268 of file Resampler.h.

◆ processBlock() [1/2]

template<typename T >
int dspark::Resampler< T >::processBlock ( AudioBufferView< T >  input,
AudioBufferView< T >  output 
)
inlinenoexcept

Resamples multi-channel audio using AudioBufferView (streaming).

Processes each channel sequentially with its independent state.

Parameters
inputInput audio buffer view.
outputOutput audio buffer view (pre-allocated).
Returns
Number of output samples produced per channel.

Definition at line 404 of file Resampler.h.

◆ processBlock() [2/2]

template<typename T >
int dspark::Resampler< T >::processBlock ( const T *  input,
int  inputLength,
T *  output 
)
inlinenoexcept

Resamples a block of audio in single-channel streaming mode.

Parameters
inputInput audio samples.
inputLengthNumber of input samples.
outputOutput buffer (must hold at least getMaxOutputSamples()).
Returns
Number of output samples produced.

Definition at line 390 of file Resampler.h.

◆ processRange()

template<typename T >
std::vector< T > dspark::Resampler< T >::processRange ( const T *  input,
int  inputLength,
int64_t  firstOutput,
int64_t  count 
)
inline

Offline, time-aligned conversion of any span of output samples.

Output sample k, for k in [firstOutput, firstOutput + count), is the input interpolated at position k / getRatio(), with the input taken as zero outside [0, inputLength). Unlike process(), which stops at the input's last sample, the span may start before 0 and run past the end, so it can hold the kernel's whole response to the signal: the ringing before its first sample and after its last. For an impulse response, whose first sample is often its loudest, that ringing is part of the converted response. getReach() gives the span that holds all of it. Allocates the output vector – offline use only.

Definition at line 322 of file Resampler.h.

◆ reset()

template<typename T >
void dspark::Resampler< T >::reset ( )
inlinenoexcept

Resets the internal state (delay lines, all channels) to zero.

Safe to call from the audio thread after prepare(): it only fills storage that prepare() already sized and never allocates.

Definition at line 224 of file Resampler.h.

◆ setOfflineEngine()

template<typename T >
void dspark::Resampler< T >::setOfflineEngine ( OfflineEngine  engine)
inlinenoexcept

Chooses the offline engine (the streaming path is unaffected).

Direct (the default) evaluates one streaming kernel per output. TwoStage first low-pass filters the input by overlap-save FFT convolution, at the input rate or, when the lower Nyquist lies above a quarter of the input rate, at twice it (zero-stuffed): the tier's passband edge and stopband edge, 12 dB more attenuation. The band-limited signal is then oversampled at least 2:1 over its band, so the rate change needs only a short kernel whose stopband starts at the band's first image: 24 taps at High, 32 or 36 at Ultra (the length is a multiple of four, so a product has no scalar tail at any vector width), 40 dB above the tier (the images of in-band tones fall there, and Direct's longer kernel has decayed that far at those distances). When the output rate is an integer fraction of that rate (48 <-> 96 kHz) the output is read straight from the band-limited signal. Both stages run in double, for both instantiations, so the float output is limited by its own rounding only. Outputs one cycle of phases apart share their stage-2 kernel row and their windows lie a fixed step apart, so up to eight of them are computed together (simd::dotProductStrided(), whose results do not depend on how a set is split).

Measured against Direct (MSVC x64, AVX2 dispatch, double, ns per input sample once prepared, into caller storage) at 96 -> 44.1 / 48 -> 44.1 / 44.1 -> 48 / 44.1 -> 96 kHz: High 2.1 / 3.4 / 3.4 / 5.1 instead of 16.4 / 16.6 / 20.4 / 42.1; Ultra 2.3 / 3.6 / 4.0 / 6.0 instead of 26.2 / 26.9 / 27.7 / 60.3. Stage 1 reads a double input straight from the caller's buffer, and its filter product and inverse are one transform. At 2:1 (96 -> 48 kHz) the inverse runs at half the length on the folded spectrum: High 1.2, Ultra 1.3 instead of 14.6 and 23.9. The vector-returning process() adds the vector: Ultra 2.6 / 4.5 / 5.1 / 8.2. Passband edge, image and alias rejection and the residual of in-band tones are those of Direct or better; on in-band material the two engines agree to -152 dB at High and -222 dB at Ultra.

The transforms sit on a fixed grid, so processRange() spans agree with one another and with process() bit for bit; getReach() follows the engine in force. A non-finite input sample reaches every output of the transforms that read it (up to the transform length, a few thousand samples), not only the kernel's reach. The first offline call after prepare() or after this setter designs the stages (0.1 to 0.6 ms and a few hundred kB at common ratios; prepare() itself still designs the streaming kernels). Stage 1 is capped at kMaxTwoStageOrder: past about 190:1 downsampling at Ultra its transition band widens, as Direct's does past 25:1.

Definition at line 176 of file Resampler.h.

Member Data Documentation

◆ kMaxRatio

template<typename T >
constexpr double dspark::Resampler< T >::kMaxRatio = 16777216.0
staticconstexpr

Largest target/source ratio prepare() accepts. Output per input sample follows the ratio, so past this no caller's buffer holds it.

Definition at line 115 of file Resampler.h.

◆ kMaxTaps

template<typename T >
constexpr int dspark::Resampler< T >::kMaxTaps = 8192
staticconstexpr

Longest kernel, in input samples (see the class note).

Definition at line 111 of file Resampler.h.

◆ kMaxTwoStageOrder

template<typename T >
constexpr int dspark::Resampler< T >::kMaxTwoStageOrder = 1 << 16
staticconstexpr

Longest stage-1 kernel order of the TwoStage offline engine (see setOfflineEngine()).

Definition at line 119 of file Resampler.h.


The documentation for this class was generated from the following file: