07. Resampling

Speech models are trained at 16 kHz, CDs are 44.1 kHz, video is 48 kHz: almost every audio pipeline converts sample rates somewhere. Without filtering, downsampling folds high frequencies back into the band as aliases and upsampling leaves spectral images. This notebook measures both effects on the library’s three quality tiers, compares them with scipy.signal.resample_poly, and rebuilds a windowed-sinc decimator by hand.

Learning outcomes. After this notebook you can

  • predict where an out-of-band component lands after downsampling (\(f_a = |f - k f_{out}|\));

  • measure alias and image rejection in dB with a single DFT bin;

  • explain why naive decimation aliases, and how the fast, medium and high tiers trade bandwidth and rejection for speed;

  • build a windowed-sinc decimator in NumPy and check it against the library and SciPy.

import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as ss
import audio_samples as aus

rng = np.random.default_rng(0)
F64 = np.dtype("float64")  # the generators take a numpy dtype instance
Q = aus.ResamplingQuality


def amplitude(x, f, fs):
    # Amplitude of the component at f Hz from one DFT bin (exact for whole periods).
    n = np.arange(len(x))
    return 2 * np.abs(np.sum(x * np.exp(-2j * np.pi * f * n / fs))) / len(x)


def level_db(x, f, fs, ref):
    return 20 * np.log10(amplitude(x, f, fs) / ref)

Concept

Ratio. Converting from \(f_{in}\) to \(f_{out}\) (both in Hz) has the dimensionless ratio

\[r = f_{out} / f_{in}\]

The output can only represent frequencies below its Nyquist frequency \(f_{out}/2\).

Downsampling and aliasing. Keeping every \(q\)-th sample (\(r = 1/q\)) samples the signal again at \(f_{out}\). A component at \(f\) Hz above \(f_{out}/2\) reappears at

\[f_a = |f - k f_{out}|\]

where \(k\) is the integer that brings \(f_a\) into \([0, f_{out}/2]\) (notebook 01). Once folded it is indistinguishable from real content, so a resampler must low-pass filter before decimating, with a cutoff at or below \(\min(f_{in}, f_{out})/2\).

Upsampling and imaging. Raising the rate by \(L\) can be modelled as inserting \(L - 1\) zeros between samples, which leaves copies (images) of the spectrum at \(k f_{in} \pm f\), followed by a low-pass interpolation filter that removes them.

Ideal band-limited interpolation. A band-limited signal is fully described by its samples; its value at time \(t\) (seconds) is

\[x(t) = \sum_n x[n]\, \mathrm{sinc}(f_{in} t - n), \qquad \mathrm{sinc}(u) = \frac{\sin(\pi u)}{\pi u}\]

A practical resampler truncates and windows the sinc and scales it so that its cutoff is \(f_c = \min(f_{in}, f_{out})/2\) (slightly less, to leave room for the transition band). One formula then does both jobs: interpolation and anti-aliasing.

Linear interpolation uses a triangular kernel instead. For integer upsampling by \(L = 3\) it equals zero-stuffing followed by the FIR \([1, 2, 3, 2, 1]/3\), whose gain at \(f\) (Hz) is

\[G(f) = \frac{3 + 4\cos\omega + 2\cos 2\omega}{9}, \qquad \omega = 2\pi f / f_{out}\]

(the extra \(1/3\) undoes the kernel’s gain of 3 at DC). \(G\) is neither flat in the pass band nor zero at the images.

Alias (or image) rejection is the level of the unwanted component relative to the input component that produced it:

\[R = 20 \log_{10}(A_{alias} / A_{in})\ \text{dB}\]

where \(A\) is a sinusoid’s amplitude. 0 dB means no rejection.

The library’s tiers (aus.ResamplingQuality). Every tier except fast upsampling is a Kaiser-windowed sinc low-pass whose cut-off is set relative to the lower Nyquist frequency \(f_N = \min(f_{in}, f_{out})/2\); the stop band starts at \(f_N\):

  • fast (the default of AudioSamples.resample): when downsampling, a short filter with its pass band to \(0.80 f_N\) and 70 dB of stop-band attenuation; when upsampling, linear interpolation (no anti-imaging filter).

  • medium: pass band to \(0.90 f_N\), 100 dB.

  • high: pass band to \(0.913 f_N\), 125 dB.

The filter is computed in the buffer’s float type: float32 for float32, int16 and uint8 buffers, float64 for float64 and int32 ones.

Time alignment. Output sample \(m\) is the band-limited reconstruction of the input at the exact input position \(m/r = m f_{in}/f_{out}\): the sinc is centred on that position, so the filter is symmetric (linear phase) and adds no delay. Input before the start and after the end counts as zeros, and the output has exactly \(\lceil N r \rceil\) samples for \(N\) input samples.

With the library

Mix a 1 kHz tone (to keep) with a 10 kHz tone (to remove), both at amplitude 0.5, and convert 48 kHz to 16 kHz by naive decimation (keep every third sample, written by hand) and with each tier. The 10 kHz tone should fold to \(|10\,000 - 16\,000| = 6\,000\) Hz. We measure each component with one DFT bin over the middle 1600 output samples (whole periods of both 1 kHz and 6 kHz, so there is no leakage).

fs_in, fs_out = 48_000, 16_000
n = np.arange(12_000)  # 250 ms
x = 0.5 * np.sin(2 * np.pi * 1_000 * n / fs_in) + 0.5 * np.sin(2 * np.pi * 10_000 * n / fs_in)
signal = aus.AudioSamples.new_mono(x, fs_in)

mid = slice(1_200, 2_800)  # middle 100 ms of the 16 kHz output
results = {}
outputs = {"naive": x[::3]}  # naive decimation, by hand: keep every third sample
results["naive"] = (level_db(x[::3][mid], 1_000, fs_out, 0.5), level_db(x[::3][mid], 6_000, fs_out, 0.5))
for name in ("fast", "medium", "high"):
    y = signal.resample(fs_out, getattr(Q, name)).to_numpy()
    assert len(y) == 4_000  # ceil(12000 / 3)
    outputs[name] = y
    results[name] = (level_db(y[mid], 1_000, fs_out, 0.5), level_db(y[mid], 6_000, fs_out, 0.5))
for name, (p, a) in results.items():
    print(f"{name:6s}: 1 kHz {p:+.4f} dB, alias at 6 kHz {a:+.1f} dB")

# Every tier passes 1 kHz unchanged (better than 0.001 dB).
assert all(abs(p) < 1e-3 for p, _ in results.values())
# Naive decimation: the alias arrives at full level, 0 dB.
assert abs(results["naive"][1]) < 1e-9
# Every tier removes it: for this 1 : 3 ratio the resampler drops everything above the output's
# Nyquist frequency in the frequency domain, so what is left is float64 round-off.
assert all(results[name][1] < -180 for name in ("fast", "medium", "high"))
naive : 1 kHz -0.0000 dB, alias at 6 kHz -0.0 dB
fast  : 1 kHz -0.0002 dB, alias at 6 kHz -299.3 dB
medium: 1 kHz -0.0000 dB, alias at 6 kHz -189.9 dB
high  : 1 kHz +0.0000 dB, alias at 6 kHz -214.5 dB
fig, ax = plt.subplots(figsize=(8, 3))
win = np.hanning(1_600)
freqs = np.fft.rfftfreq(1_600, 1 / fs_out)
for name, y in outputs.items():
    spec = np.abs(np.fft.rfft(y[mid] * win)) / win.sum() * 2
    ax.plot(freqs, 20 * np.log10(spec / 0.5 + 1e-12), label=name, lw=1)
ax.set(xlabel="Frequency (Hz)", ylabel="Level re input (dB)", ylim=(-170, 10),
       title="48 kHz -> 16 kHz: 1 kHz kept, 10 kHz aliases to 6 kHz unless filtered")
ax.legend(fontsize=8)
plt.show()
../_images/a7362f3e60541ee1fe2953ae29957799695a1eaf0bf58bb14bff0d2fd2f5780c.png

Compare with SciPy. scipy.signal.resample_poly(x, 1, 3) uses a polyphase FIR designed by firwin with a Kaiser window (\(\beta = 5\)) and \(2 \cdot 10 \cdot \max(\text{up}, \text{down}) + 1 = 61\) taps. It is exactly time-aligned (zero phase), like the library, but with its default filter it rejects the alias by about 57 dB. This is a different design choice, not an error.

y_poly = ss.resample_poly(x, 1, 3)
assert len(y_poly) == 4_000
pass_poly, alias_poly = level_db(y_poly[mid], 1_000, fs_out, 0.5), level_db(y_poly[mid], 6_000, fs_out, 0.5)
print(f"resample_poly: 1 kHz {pass_poly:+.4f} dB, alias {alias_poly:+.1f} dB")
assert abs(pass_poly) < 0.01  # pass band intact (0.01 dB)
assert abs(alias_poly + 57.3) < 0.5  # about 57 dB of rejection
# Every tier rejects the alias more than SciPy's default filter here: fast by more than 30 dB, medium and high by
# more than 40 dB.
assert results["fast"][1] < alias_poly - 30
assert results["medium"][1] < alias_poly - 40 and results["high"][1] < alias_poly - 40
resample_poly: 1 kHz +0.0085 dB, alias -57.3 dB

Time alignment. An impulse at input sample 3000 (48 kHz) peaks at output sample \(3000/3 = 1000\) (16 kHz) for every tier, and its response is symmetric about the peak. The phase of a 1 kHz tone measures any sub-sample shift: it is zero to rounding error for every tier.

imp = np.zeros(12_000)
imp[3_000] = 1.0
for name in ("fast", "medium", "high"):
    y = aus.AudioSamples.new_mono(imp, fs_in).resample(fs_out, getattr(Q, name)).to_numpy()
    assert np.argmax(np.abs(y)) == 1_000
    assert abs(y[999] - y[1_001]) < 1e-12  # symmetric (linear-phase) filter

tone = aus.sine_wave(1_000.0, 0.25, sample_rate=fs_in, amplitude=0.5, dtype=F64)
k = np.arange(1_200, 2_800)
shift = {}
for name in ("fast", "medium", "high"):
    y = tone.resample(fs_out, getattr(Q, name)).to_numpy()[k]
    phase = np.angle(np.sum(y * np.exp(-2j * np.pi * 1_000 * k / fs_out))) + np.pi / 2
    shift[name] = phase / (2 * np.pi * 1_000 / fs_out)  # in output frames; > 0 means early
print({k_: float(f"{v:.1e}") for k_, v in shift.items()})
# No delay: zero shift to rounding error, for every tier.
assert all(abs(v) < 1e-9 for v in shift.values())
{'fast': -4.4e-14, 'medium': -3.4e-11, 'high': 1.4e-14}

How it works

Naive decimation is plain sampling. With \(r = 1/3\), keeping every third sample returns \(x[3m]\), and \(\sin(2\pi\, 10\,000\, m / 16\,000) = -\sin(2\pi\, 6\,000\, m / 16\,000)\) for every integer \(m\): the 10 kHz tone is a 6 kHz tone on the 16 kHz grid. No filter afterwards can tell the two apart, which is why every tier filters first.

x10 = aus.sine_wave(10_000.0, 0.1, sample_rate=fs_in, amplitude=0.5, dtype=F64)
y10 = x10.to_numpy()[::3]  # naive decimation: 1600 samples at 16 kHz
m = np.arange(len(y10))
# Tolerance: sin of arguments up to ~6e3 rad carries ~1e-12 of rounding.
assert np.allclose(y10, -0.5 * np.sin(2 * np.pi * 6_000 * m / fs_out), rtol=0, atol=1e-9)

A windowed-sinc decimator, written out. Low-pass with a 193-tap Blackman-windowed sinc whose cutoff is \(0.95 \times 8\) kHz \(= 7.6\) kHz, then keep every third sample. The filter is centred (no delay), so the 1 kHz output matches the ideal 16 kHz sine, and the 6 kHz alias is 107.5 dB down: this filter’s stopband, folded back (the library drops that part of the spectrum for this ratio). Since the library adds no delay either, its high output and ours agree sample by sample.

half = 96
fc = 0.95 * (fs_out / 2) / fs_in  # cutoff as a fraction of fs_in
t = np.arange(-half, half + 1)
h = 2 * fc * np.sinc(2 * fc * t) * np.blackman(2 * half + 1)  # np.sinc(u) = sin(pi u)/(pi u)

# y[m] = sum_k h[k] x[3m + half - k]: full convolution, then keep the centred samples.
y_mine = np.convolve(x, h)[half::3][:4_000]

assert abs(level_db(y_mine[mid], 1_000, fs_out, 0.5)) < 1e-3  # pass band intact
assert abs(level_db(y_mine[mid], 6_000, fs_out, 0.5) + 107.5) < 0.1  # alias 107.5 dB down
ideal = 0.5 * np.sin(2 * np.pi * 1_000 * np.arange(4_000) / fs_out)
# Matches the ideal 16 kHz sine to 1e-5 (window ripple in the pass band) ...
assert np.max(np.abs(y_mine[mid] - ideal[mid])) < 1e-5
# ... and the library's high tier, also centred, to 1e-5.
assert np.max(np.abs(y_mine[mid] - outputs["high"][mid])) < 1e-5

fig, ax = plt.subplots(figsize=(8, 3))
H = np.fft.rfft(h, 8192)
ax.plot(np.fft.rfftfreq(8192, 1 / fs_in), 20 * np.log10(np.abs(H) + 1e-12))
ax.axvline(8_000, color="grey", ls=":", lw=0.8)
ax.set(xlim=(0, 24_000), ylim=(-160, 5), xlabel="Frequency (Hz)", ylabel="Gain (dB)",
       title="193-tap Blackman-windowed sinc, cutoff 7.6 kHz (output Nyquist dotted)")
plt.show()
../_images/8da26eb04c9a87df30c421289a7c01762b7dafdf2a48fc90e63694683fa366c0.png

Linear interpolation is a poor interpolation filter. Upsampling a 6 kHz tone from 16 kHz to 48 kHz with fast should, by \(G(f)\), droop the tone to \(G(6\,000) = -3.77\) dB and leave an image at \(16\,000 - 6\,000 = 10\,000\) Hz at \(G(10\,000) = -11.8\) dB. The sinc tiers pass the tone flat (to 0.0001 dB) and remove the image: for 1 : 3 every bin above 8 kHz is zero before the inverse transform, so what is left is float64 round-off.

def G_db(f, fs=48_000):
    w = 2 * np.pi * f / fs
    return 20 * np.log10(abs((3 + 4 * np.cos(w) + 2 * np.cos(2 * w)) / 9))

assert abs(G_db(6_000) + 3.77) < 0.01 and abs(G_db(10_000) + 11.8) < 0.05

x6 = aus.sine_wave(6_000.0, 0.25, sample_rate=16_000, amplitude=0.5, dtype=F64)
seg = slice(3_600, 8_400)  # 100 ms: whole periods of 6 and 10 kHz
up = {name: x6.resample(48_000, getattr(Q, name)).to_numpy()[seg] for name in ("fast", "medium", "high")}
lv = {name: (level_db(y, 6_000, 48_000, 0.5), level_db(y, 10_000, 48_000, 0.5)) for name, y in up.items()}
print({name: tuple(round(float(v), 2) for v in vals) for name, vals in lv.items()})
# Measured equals predicted to 1e-6 dB (this buffer is float64, so the resampler computes in float64).
assert abs(lv["fast"][0] - G_db(6_000)) < 1e-6 and abs(lv["fast"][1] - G_db(10_000)) < 1e-6
# The sinc tiers: tone flat to 0.0001 dB, image strongly attenuated.
assert abs(lv["medium"][0]) < 1e-4 and abs(lv["high"][0]) < 1e-4
assert lv["medium"][1] < -180 and lv["high"][1] < -180
{'fast': (-3.77, -11.84), 'medium': (0.0, -181.47), 'high': (-0.0, -207.91)}

Ask the library to explain

aus.explain.resampling(from_rate, to_rate) summarises a conversion: ratio, both Nyquist frequencies, the pass-band edge of the sinc tiers, a table of the three tiers, and a warning when you downsample.

doc = aus.explain.resampling(48_000.0, 16_000.0)
doc

Resampling

Converting 48000 Hz to 16000 Hz (ratio 0.333333) discards bandwidth, so content above the new Nyquist frequency must be filtered out first. The output can represent frequencies up to 8000 Hz.

Formulas

Conversion ratio:

$$ r = \frac{f_{out}}{f_{in}} $$

Anti-aliasing / anti-imaging cut-off must not exceed the lower Nyquist frequency:

$$ f_{c} \le \frac{\min(f_{in}, f_{out})}{2} $$

Band-limited interpolation with a windowed-sinc kernel h (every tier except Fast upsampling, which interpolates linearly):

$$ y[m] = \sum_{n} x[n] , h\left(\frac{m}{r} - n\right) $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $f_{in}$ | input rate | 48000 Hz | | $f_{out}$ | output rate | 16000 Hz |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Ratio | $r$ = 0.333333 | $f_{out} / f_{in}$ | | Input Nyquist | $f_{in}/2$ = 24000 Hz | $f_{in} / 2$ | | Output Nyquist | $f_{out}/2$ = 8000 Hz | $f_{out} / 2$ | | Sinc pass-band edge | $f_c$ = 7200 Hz | $\text{pass} \cdot \min(f_{in}, f_{out})/2$ |

Quality presets (ResamplingQuality)

| Quality | Method | Pass-band edge (Hz) | |—|—|—| | Fast | Kaiser-windowed sinc, pass-band to 0.8 x Nyquist, 70 dB stop-band | 6400 | | Medium | Kaiser-windowed sinc, pass-band to 0.9 x Nyquist, 100 dB stop-band | 7200 | | High | Kaiser-windowed sinc, pass-band to 0.913 x Nyquist, 125 dB stop-band | 7304 |

Trade-offs

  • Longer sinc kernels give a sharper transition band and better stop-band rejection at a higher computational cost per sample.

  • The pass-band edge is slightly below the lower Nyquist frequency to leave room for the transition band.

Warnings

  • Caution: Downsampling: anything between 8000 Hz and 24000 Hz must be removed before decimation or it folds back (e.g. 24000 Hz would appear at 8000 Hz). Hint: Every ResamplingQuality low-passes before decimating (Fast with a short 70 dB filter); naive decimation (keeping every N-th sample) does not and aliases.

See also

  • Offline: audio_samples::resample

  • Offline (Python): audio_samples.AudioSamples.resample

  • Streaming: audio_samples::StreamingResampler

  • Aliasing: audio_samples::educational::topics::aliasing

  • Aliasing (Python): audio_samples.explain.aliasing

assert abs(doc.quantity("Ratio") - 1 / 3) < 1e-12
assert doc.quantity("Output Nyquist") == 8_000.0
# medium's pass band ends at 0.90 x 8 kHz.
assert abs(doc.quantity("Sinc pass-band edge") - 7_200.0) < 1e-9
assert doc.has_warning_containing("Downsampling")
# Upsampling discards nothing, so there is no such warning.
assert not aus.explain.resampling(16_000.0, 48_000.0).has_warning_containing("Downsampling")

Exercises

1. Where does 13 kHz go? A 13 kHz tone (amplitude 0.5) is converted from 48 kHz to 16 kHz by keeping every third sample. Predict the output frequency, confirm it with aus.explain.aliasing, and measure the output amplitude at that frequency. How much of it does each tier of resample leave in the middle 50 ms? Put the alias frequency in Hz in answer.

answer = None  # TODO
# Solution
answer = abs(13_000 - 16_000)
assert aus.explain.aliasing(13_000.0, 16_000.0).quantity("Alias frequency") == answer == 3_000
x13 = aus.sine_wave(13_000.0, 0.1, sample_rate=48_000, amplitude=0.5, dtype=F64)
naive13 = x13.to_numpy()[::3]  # 1600 samples = 300 periods of 3 kHz
assert abs(amplitude(naive13, 3_000, 16_000) - 0.5) < 1e-9  # full level
# Every tier removes it: below -150 dB (fast) and -220 dB (medium, high) in the middle 50 ms
# (150 periods); over the whole 100 ms all read about -74 dB, set by the edge clicks.
for name, below in (("fast", -150), ("medium", -220), ("high", -220)):
    y13 = x13.resample(16_000, getattr(Q, name)).to_numpy()
    assert level_db(y13[400:1_200], 3_000, 16_000, 0.5) < below
    assert abs(level_db(y13, 3_000, 16_000, 0.5) + 74.0) < 0.5

2. Droop at 2 kHz. Predict the gain (dB) of fast upsampling 16 kHz to 48 kHz at 2 kHz from \(G(f)\), then measure it. Put the measured gain in answer.

answer = None  # TODO
# Solution
# w = 2 pi 2000 / 48000 = pi / 12, G = (3 + 4 cos(pi/12) + 2 cos(pi/6)) / 9 = 0.955.
predicted = G_db(2_000)
assert abs(predicted + 0.40) < 0.005
x2 = aus.sine_wave(2_000.0, 0.25, sample_rate=16_000, amplitude=0.5, dtype=F64)
y2 = x2.resample(48_000, Q.fast).to_numpy()[3_600:8_400]
answer = level_db(y2, 2_000, 48_000, 0.5)
assert abs(answer - predicted) < 0.01

3. Alignment at a non-integer ratio. Convert a 1 kHz tone (amplitude 0.5) from 44.1 kHz to 16 kHz (\(r = 160/441\)) with high. Is the output still time-aligned? Measure the largest deviation from the ideal 16 kHz sine in the middle 100 ms and put it in answer.

answer = None  # TODO
# Solution
# Output sample m is evaluated at the exact input position 441 m / 160: no delay to remove and
# nothing rounded to whole frames.
x441 = aus.sine_wave(1_000.0, 0.25, sample_rate=44_100, amplitude=0.5, dtype=F64)
y441 = x441.resample(16_000, Q.high).to_numpy()
assert len(y441) == 4_000  # ceil(11025 * 160 / 441)
kk = np.arange(800, 2_400)
answer = np.max(np.abs(y441[kk] - 0.5 * np.sin(2 * np.pi * 1_000 * kk / 16_000)))
# A shift of tau output frames causes an error of up to 0.5 * (2 pi / 16) * tau = 0.196 tau, so
# an error below 1e-7 means |tau| < 5.1e-7 frames.
assert answer < 1e-7 and 1e-7 / (0.5 * 2 * np.pi / 16) < 5.1e-7

Common pitfalls

  • Naive decimation (x[::q]) is not resampling: it folds everything above the output’s Nyquist frequency back at full level. Every ResamplingQuality filters first.

  • fast is the default of AudioSamples.resample and resample_by_ratio, and it trades bandwidth and rejection for speed: its downsampling filter starts rolling off at \(0.80 f_N\) and gives 70 dB by design; when upsampling it is linear interpolation. Pass aus.ResamplingQuality.medium or .high for analysis or listening.

  • Measure rejection away from the ends. The input is treated as zero outside the buffer, so a signal that starts or stops abruptly produces broadband clicks that no anti-aliasing filter removes.

  • Other resamplers use other designs. scipy.signal.resample uses the FFT (assuming a periodic signal); resample_poly uses a short Kaiser-windowed FIR (about 57 dB of alias rejection above). Expect small differences in edge behaviour and alignment, not in the pass band.

  • Output length is \(\lceil N r \rceil\) frames.

See also

References

  • Crochiere, R. E. and Rabiner, L. R. (1983). Multirate Digital Signal Processing. Prentice-Hall.

  • Oppenheim, A. V. and Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson. Section 4.6 (changing the sampling rate by an integer or rational factor).