Sign in

Resampling

Sample rate conversion (resampling)

Changes a signal's sample rate by a ratio of whole numbers: insert zeros, low-pass filter, then keep every few samples, without creating aliases.

Overview

A sampled signal can only hold frequencies up to half its sample rate, a limit called the Nyquist frequency. To lower the rate you keep fewer samples, but anything above the new limit must be filtered out first. Otherwise it folds down and appears as a false low frequency, an alias. To raise the rate you need new samples between the old ones. Placing zeros there creates the right number of samples but also mirror copies of the spectrum, which a low-pass filter removes, and the filter fills the zeros with smoothly interpolated values. A general ratio such as 3 to 2 does both in sequence, with one filter doing both jobs.

A short history

The practice rests on the sampling theorem, stated by Harry Nyquist in 1928 and proved in its familiar form by Claude Shannon in 1949: a signal is captured fully only if sampled above twice its highest frequency. Multirate digital signal processing grew up in the 1970s, and Ronald Crochiere and Lawrence Rabiner set out the upsample, filter, downsample method in their 1983 book. Polyphase filters made it cheap enough for real-time use.

How it works

  1. Write the rate change as a fraction L/ML / M in lowest terms: LL is the upsampling factor and MM the downsampling factor.
  2. Insert L−1L - 1 zeros after every input sample. The signal now runs at LL times the input rate.
  3. Design a low-pass filter at that intermediate rate, with its cutoff at the lower of the input and output Nyquist frequencies.
  4. Apply the filter. It removes the spectral copies created by the zeros and any content that the output rate cannot hold.
  5. Keep every MM-th sample of the filtered signal. The result has the output rate.
  6. For a pure decrease set L=1L = 1 (decimation), and for a pure increase set M=1M = 1 (interpolation).

Watch out for

  • Dropping samples without filtering first lets everything above the new Nyquist frequency fold back into the signal. Once mixed in, an alias cannot be removed.
  • The filter is not ideal. A band just below the new Nyquist frequency is attenuated, and a little content just above it leaks through. A larger half_width narrows that band and costs more computation.
  • About half_width samples at each end of the output are less accurate, because the filter sees zeros beyond the edges of the signal.
  • resample_fft treats the signal as one period of a repeating pattern. A signal whose two ends do not match will ring near the edges.
  • Linear interpolation is a weak low-pass filter. It dulls high frequencies and does not prevent aliasing when the rate goes down.

Use cases

When to use it

Bringing recordings made at different rates to one common rate before training, and reducing the rate to save computation when the content of interest is at low frequencies.

In industry

Audio production
Studio audio at 48 kHz is converted to 44.1 kHz for CD, a ratio of 147 to 160, with a low-pass filter to prevent aliasing.
Speech and machine learning
Recordings from many sources are resampled to 16 kHz before training or running a speech recogniser, so the model sees one rate.
Software radio
Receivers decimate a wideband sampled signal in stages to reach the narrow channel of interest at a low rate.

Choosing it: what must hold

  • A uniformly sampled signal with a known original rate.
  • A target rate that is a ratio of whole numbers to the original rate.
  • When reducing the rate, acceptance that content above half the new rate is removed by the filter.
  • A low-pass filter long enough to give the stopband rejection you need.

When to choose something else

IfUse instead
Samples are irregularly spaced in timeInterpolation onto a regular grid first
You only want to remove a frequency band and keep the rateFiltering
The ratio is not a simple fraction or changes over timeAn arbitrary-ratio resampler based on interpolation, for example a windowed-sinc interpolator

Math foundations

  1. The rate change

    fout=fin⋅LMf_{\text{out}} = f_{\text{in}} \cdot \frac{L}{M}

    The output rate for upsampling by LL and downsampling by MM. The template divides both by their greatest common divisor first. Going from 44100 Hz to 48000 Hz needs L=160L = 160 and M=147M = 147.

  2. Zero stuffing

    v[n]={x[n/L]if L divides n0otherwisev[n] = \begin{cases} x[n / L] & \text{if } L \text{ divides } n \\ 0 & \text{otherwise} \end{cases}

    The signal at the intermediate rate LfinL f_{\text{in}}. Its spectrum holds the original plus L−1L - 1 shifted copies, called images, that the filter must remove.

  3. The filter's cutoff

    fcut=12min⁡ ⁣(fin, fout)f_{\text{cut}} = \tfrac{1}{2}\min\!\big(f_{\text{in}},\ f_{\text{out}}\big)

    The filter must block the images, which start at the input Nyquist frequency, and everything the output cannot hold, which starts at the output Nyquist frequency. The lower of the two limits covers both.

  4. The filter's taps

    h[k]=c sinc⁡ ⁣(kmax⁡(L,M))w[k],∑kh[k]=Lh[k] = c\,\operatorname{sinc}\!\left(\frac{k}{\max(L, M)}\right) w[k], \qquad \sum_{k} h[k] = L

    A sinc tapered by a Hamming window, for kk from −K-K to KK with KK equal to half_width times max⁡(L,M)\max(L, M). The constant cc is chosen so the taps sum to LL, which restores the level lost when L−1L - 1 of every LL samples were set to zero.

  5. The whole conversion

    y[m]=∑kh[mM−kL] x[k]y[m] = \sum_{k} h[mM - kL]\,x[k]

    Stuffing, filtering and keeping every MM-th sample collapse into one formula. Output sample mm sits at input position mM/LmM / L and is a weighted sum of the input samples around that position.

  6. Where an alias lands

    falias=∣ f−r fs ∣,r=round⁡ ⁣(ffs)f_{\text{alias}} = \big|\,f - r\,f_s\,\big|, \qquad r = \operatorname{round}\!\left(\frac{f}{f_s}\right)

    A tone at ff sampled at rate fsf_s is indistinguishable from one at this frequency, which always lies between 0 and fs/2f_s / 2. If ff is already below fs/2f_s / 2 then r=0r = 0 and nothing changes.

Symbols

fin, foutf_{\text{in}},\ f_{\text{out}}
the input and output sample rates
L, ML,\ M
the upsampling and downsampling factors (up and down in the config)
x[k]x[k]
the input signal
v[n]v[n]
the zero-stuffed signal at the intermediate rate
h[k]h[k]
the taps of the low-pass filter
w[k]w[k]
the Hamming window
cc
the scaling constant that makes the taps sum to LL
KK
half the filter length: half_width times max⁡(L,M)\max(L, M)
y[m]y[m]
the output signal
f, fsf,\ f_s
a tone's frequency and the rate it is sampled at
faliasf_{\text{alias}}
the frequency at which the tone appears after sampling

Worked by hand

Convert a recording from 48 kHz to 16 kHz with the default half_width of 10. The fraction is 16/48=1/316/48 = 1/3, so L=1L = 1 and M=3M = 3. Suppose the recording contains a 10 kHz tone.

new Nyquist frequency=162=8 kHz\text{new Nyquist frequency} = \frac{16}{2} = 8 \ \text{kHz}
falias=∣10−1×16∣=6 kHzf_{\text{alias}} = |10 - 1 \times 16| = 6 \ \text{kHz}
number of taps=2×10×max⁡(1,3)+1=61\text{number of taps} = 2 \times 10 \times \max(1, 3) + 1 = 61
output length for 1000 samples=⌈1000×13⌉=334\text{output length for } 1000 \text{ samples} = \left\lceil \frac{1000 \times 1}{3} \right\rceil = 334

The 10 kHz tone is above the new 8 kHz limit. Kept unfiltered it would appear as a false 6 kHz tone, so the 61-tap filter removes it before every third sample is kept.

Visual example

Loading the example.

Try this

  • Leave the tone at 10 kHz with M = 3 and bypass the filter: the output shows a 6 kHz wave that is not in the input.
  • Turn the filter back on and lower the tone below 8 kHz. Now it passes at full amplitude.
  • Set L = 2 and M = 1 and click Zero stuffing, then Low-pass filter, to watch the zeros get filled in.

Code sample

import numpy as np
from impl import Resampler, downsample
from config import ResamplerConfig

sr = 48000
x = np.sin(2 * np.pi * 440 * np.arange(4800) / sr)

r = Resampler(ResamplerConfig(up=1, down=3))      # 48 kHz -> 16 kHz
y = r.resample(x)                                 # (1600,), filtered then thinned
r.output_rate(sr)                                 # 16000.0
z = Resampler(ResamplerConfig(up=147, down=160)).resample(x)   # 48 kHz -> 44.1 kHz
Read the implementation (129 lines)
"""Changing the sample rate of a signal.

`Resampler` converts by a rational factor up / down: insert zeros, low-pass filter with a windowed sinc, keep
every down-th sample. With up = 1 this is decimation, with down = 1 interpolation. `resample_fft` resamples a
periodic signal exactly in the frequency domain, `resample_linear` joins the dots, and `upsample_zero_stuff`
and `downsample` are the raw building blocks without any filtering.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import ResamplerConfig
except ImportError:  # run from the template's own folder
    from config import ResamplerConfig

def upsample_zero_stuff(x, factor: int) -> np.ndarray:
    """Insert factor - 1 zeros after every sample. Returns array (len(x) * factor,).

    This raises the rate but leaves copies (images) of the spectrum that a low-pass filter must remove.
    """
    x = np.asarray(x, dtype=float).ravel()
    if factor < 1:
        raise ValueError("factor must be at least 1")
    out = np.zeros(x.size * factor)
    out[::factor] = x
    return out


def downsample(x, factor: int) -> np.ndarray:
    """Keep every factor-th sample, with no filtering. Returns array (ceil(len(x) / factor),).

    Anything above the new Nyquist frequency folds back (aliases) into the result. Use `Resampler.decimate`
    unless the signal is already band-limited.
    """
    if factor < 1:
        raise ValueError("factor must be at least 1")
    return np.asarray(x, dtype=float).ravel()[::factor].copy()


def resample_fft(x, num: int) -> np.ndarray:
    """Resample x to `num` samples by truncating or zero-padding its spectrum. Returns array (num,).

    Exact for a periodic, band-limited signal sampled over a whole number of periods. Other signals ring at
    the ends, because the method treats x as one period of an endless repetition.
    """
    x = np.asarray(x, dtype=float).ravel()
    n = x.size
    if n == 0 or num < 1:
        raise ValueError("x must be non-empty and num at least 1")
    spectrum = np.fft.rfft(x)
    out = np.zeros(num // 2 + 1, dtype=complex)
    keep = min(spectrum.size, out.size)
    out[:keep] = spectrum[:keep]
    if num > n and n % 2 == 0:
        out[n // 2] *= 0.5            # the old Nyquist bin is shared between +f and -f in the longer spectrum
    elif num < n and num % 2 == 0:
        out[num // 2] = 2.0 * spectrum[num // 2].real   # the new Nyquist bin collects +f and -f
    return np.fft.irfft(out, num) * (num / n)


def resample_linear(x, num: int) -> np.ndarray:
    """Resample x to `num` samples covering the same span by linear interpolation. Returns array (num,)."""
    x = np.asarray(x, dtype=float).ravel()
    if x.size == 0 or num < 1:
        raise ValueError("x must be non-empty and num at least 1")
    return np.interp(np.linspace(0.0, x.size - 1.0, num), np.arange(x.size), x)


class Resampler:
    """Rational-rate resampling by up / down with a windowed-sinc anti-aliasing filter."""

    def __init__(self, config: ResamplerConfig | None = None) -> None:
        self.config = config or ResamplerConfig()
        g = math.gcd(self.config.up, self.config.down)
        self.up, self.down = self.config.up // g, self.config.down // g

    def design_filter(self, up: int, down: int) -> np.ndarray:
        """Low-pass FIR used at the intermediate rate (input rate times up). Returns array (taps,), odd length.

        The cutoff is the lower of the input and output Nyquist frequencies. The taps sum to `up`, which
        restores the amplitude lost by zero stuffing.
        """
        widest = max(up, down)
        half = self.config.half_width * widest
        k = np.arange(-half, half + 1)
        window = 0.54 + 0.46 * np.cos(np.pi * k / half)  # Hamming, centred on k = 0
        taps = np.sinc(k / widest) * window
        return taps * (up / taps.sum())

    def _convert(self, x, up: int, down: int) -> np.ndarray:
        x = np.asarray(x, dtype=float).ravel()
        if up == 1 and down == 1:
            return x.copy()
        taps = self.design_filter(up, down)
        stuffed = upsample_zero_stuff(x, up)
        half = taps.size // 2
        filtered = np.convolve(stuffed, taps, mode="full")[half: half + stuffed.size]
        return filtered[::down]

    def resample(self, x) -> np.ndarray:
        """Change the rate of x, array (n,), by up / down. Returns array (ceil(n * up / down),).

        Sample i of the output sits at input position i * down / up, so the first samples line up. Outside the
        signal the filter sees zeros, so about half_width samples at each end are less accurate.
        """
        return self._convert(x, self.up, self.down)

    def decimate(self, x, factor: int | None = None) -> np.ndarray:
        """Low-pass filter, then keep every factor-th sample. factor defaults to the configured `down`."""
        return self._convert(x, 1, self.config.down if factor is None else factor)

    def interpolate(self, x, factor: int | None = None) -> np.ndarray:
        """Insert zeros, then low-pass filter: factor times as many samples. factor defaults to the configured `up`.

        The filter is zero at every factor-th tap but the centre, so the original samples come through
        unchanged apart from the overall gain normalization (a fraction of a percent).
        """
        return self._convert(x, self.config.up if factor is None else factor, 1)

    def output_length(self, n: int) -> int:
        """Number of samples `resample` returns for an input of n samples."""
        return -(-n * self.up // self.down)

    def output_rate(self, sample_rate: float) -> float:
        """Sample rate of the output, given the rate of the input."""
        return sample_rate * self.up / self.down
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Make one second of a 10 kHz sine sampled at 48 kHz. Compare downsample(x, 3) with Resampler(ResamplerConfig(up=1, down=3)).resample(x), using an FFT of each to see where the energy lands. Then resample a 440 Hz sine from 44100 Hz to 48000 Hz with up=160 and down=147 and check output_length and output_rate.

Check on learning

  1. Why must the low-pass filter come before the samples are dropped when decimating, and not after?
    A way to think about it

    Once high and low frequencies give the same sample values they are the same data. Ask what a filter could look at to tell them apart afterwards.

  2. When upsampling, zero stuffing makes the signal quieter by a factor of LL. Where did the energy per sample go, and how does the filter put the level back?
    A way to think about it

    Only one sample in LL is non-zero, so the average is LL times smaller. Look at what the taps are scaled to sum to.

  3. For a 3 to 2 conversion the filter cutoff is set by the smaller of two Nyquist frequencies. Which one is smaller here, and which would it be for 2 to 3?
    A way to think about it

    Compute foutf_{\text{out}} in each case and compare it with finf_{\text{in}}. The filter has to satisfy whichever limit is tighter.

  4. resample_fft is exact for a sine that completes a whole number of cycles in the record. Why does it ring for a signal that jumps between its last and first sample?
    A way to think about it

    The method assumes the record repeats for ever. A mismatch at the seam is a sharp step, and a step needs high frequencies that are being cut off.

  5. Upsampling by 160 and downsampling by 147 uses a filter thousands of taps long. Why so many, and is every multiplication needed?
    A way to think about it

    The filter runs at 160 times the input rate, so its cutoff is a tiny fraction of that rate. Then note that most of the stuffed samples it multiplies are zeros.