---
title: "Project: a sample-rate converter"
heading: Converting 32 kHz audio to 48 kHz with a polyphase 3/2 resampler, from the prototype filter to an efficient implementation verified against the direct method
eyebrow: S7 · Lesson 51 · Project
xp: 80
---

::: hook
Every time audio moves between a 44.1 kHz file, a 48 kHz interface and a 16 kHz voice link, a sample-rate converter runs. This project builds one for a rational ratio, 3/2, which takes 32 kHz audio to 48 kHz. You'll design the single lowpass filter that does both the interpolation and the anti-aliasing, write the obvious implementation, which stuffs zeros, filters at three times the rate and throws most of the results away, and then the polyphase version, which computes only the outputs that are kept and never touches a stuffed zero. The tests require the two to agree to rounding error and the converted tone to keep its pitch and level.
:::

::: predict
## The direct 3/2 converter filters at 96 kHz and keeps every second output. What fraction of its multiplications are wasted?

- [ ] None
- [ ] Half
- [x] Five sixths: two thirds multiply stuffed zeros, and half of the remaining outputs are discarded
- [ ] Two thirds

::: reveal
Five sixths. Of every three samples the filter sees at 96 kHz, two are zeros, so two thirds of its products are zero by construction; and of the outputs it computes, the downsampler keeps only every second one. The useful work is 1/3 × 1/2 = 1/6 of the total. The polyphase form does only that sixth: each kept output uses only the taps that line up with real input samples.
:::
:::

::: nameit
## The prototype

One lowpass serves both purposes: removing the images that upsampling by L creates (cutoff π/L) and preventing the aliasing that downsampling by M would cause (cutoff π/M). So its cutoff is $\pi/\max(L, M)$, measured at the upsampled rate, and its gain is L, to restore the amplitude that zero stuffing divides by L. A Kaiser window with β = 8 gives about 80 dB of stopband.

## The direct method

Insert L − 1 zeros after each input sample, convolve with h, keep every Mth output. Simple, and the reference against which the fast version is checked.

## The polyphase method

The output sample m is $y[m] = \sum_kh[k]v[mM - k]$, where v is the zero-stuffed input, nonzero only when $mM - k$ is a multiple of L. With $p = (mM) \bmod L$ and $b = \lfloor mM/L\rfloor$, only the taps $h[p + jL]$ meet real samples:

$$y[m] = \sum_jh[p + jL]\,x[b - j]$$

Each output uses one polyphase branch, N/L taps, chosen by the phase p, which cycles through L values. The cost is N/L multiplications per output, against N per upsampled sample for the direct method.
:::

::: example
## A 96-tap prototype converts 32 kHz to 48 kHz. Compare the multiplications per output sample.

::: solution
1. **Direct.** The filter runs at 96 kHz, 96 multiplications per upsampled sample, and two upsampled samples are computed per kept output:
   $$2 \times 96 = 192\ \text{per output}$$
2. **Polyphase.** Each output uses one branch of 96/3 = 32 taps: 32 per output, a sixth of the direct count.
3. **Per second.** At 48,000 outputs per second:
   $$32 \times 48\,000 \approx 1.5 \times 10^6$$
   multiplications per second for each audio channel.

**Answer:** 192 multiplications per output directly, against 32 in polyphase form.
:::
:::

::: example
## Which taps does output m = 5 use in the 3/2 converter, and which input samples?

::: solution
1. **Output 5.**
   $$\begin{aligned} mM &= 10 \\ p &= 10 \bmod 3 \\ &= 1 \\ b &= \lfloor 10/3 \rfloor \\ &= 3 \end{aligned}$$
   so taps h[1], h[4], h[7], … meet x[3], x[2], x[1], ….
2. **Output 6.** Here mM = 12, p = 0 and b = 4: taps h[0], h[3], h[6], … with x[4], x[3], ….
3. **The phase cycle.** The phase p runs 0, 2, 1, 0, 2, 1, …, cycling through all three branches.

**Answer:** output 5 uses taps h[1], h[4], h[7], … on inputs x[3], x[2], x[1], ….
:::
:::

::: check
kind: python

## Step 1. Write `prototype(L, M, N, beta)`: the converter's lowpass, with cutoff π/max(L, M) and gain L.

```python starter
import numpy as np

def prototype(L, M, N, beta):
    # Lowpass for an L/M rate converter: N taps, cutoff pi/max(L, M), passband gain L,
    # Kaiser window with parameter beta, linear phase.
    return np.zeros(N)

h = prototype(3, 2, 96, 8.0)
print(np.sum(h))
```

```python solution
import numpy as np

def prototype(L, M, N, beta):
    wc = np.pi/max(L, M)
    n = np.arange(N) - (N - 1)/2
    return L*wc/np.pi*np.sinc(wc*n/np.pi)*np.kaiser(N, beta)

h = prototype(3, 2, 96, 8.0)
print(np.sum(h))
```

```python tests
import numpy as np
def resp(h, w):
    return np.abs(np.exp(-1j*np.outer(w, np.arange(len(h)))) @ h)
h = prototype(3, 2, 96, 8.0)
assert len(h) == 96 and np.allclose(h, h[::-1]), "Return N symmetric taps."
assert abs(np.sum(h) - 3) < 0.01, f"The DC gain must be L = 3, to restore the amplitude lost to zero stuffing; got {np.sum(h):.4f}."
pb = resp(h, np.linspace(0, 0.75*np.pi/3, 400))
assert np.max(np.abs(pb/3 - 1)) < 0.001, f"The passband (to 75% of the cutoff) should be flat to 0.1%; the error is {np.max(np.abs(pb/3 - 1)):.5f}."
sb = resp(h, np.linspace(np.pi/3 + 0.2, np.pi, 800))
att = -20*np.log10(np.max(sb)/3)
assert att > 75, f"With β = 8 the stopband should be at least 75 dB down; got {att:.1f} dB."
h2 = prototype(2, 5, 120, 6.0)
assert abs(np.sum(h2) - 2) < 0.01, "For L = 2, M = 5 the gain is 2 and the cutoff π/5."
assert resp(h2, [np.pi/5 + 0.3])[0]/2 < 0.01, "The cutoff must be π/max(L, M): content at π/5 + 0.3 must be rejected."
```

::: right
Right. A flat passband with gain 3 and more than 75 dB of rejection beyond the cutoff.
:::
:::

::: check
kind: python

## Step 2. Write `resample_direct(x, L, M, h)`: zero-stuff, filter, keep every Mth sample.

```python starter
import numpy as np

def resample_direct(x, L, M, h):
    # Reference converter: insert L - 1 zeros after each sample, filter with h (full convolution),
    # then keep every Mth sample, starting with the first.
    return np.zeros(1)

print(resample_direct(np.ones(4), 3, 2, np.ones(3)))
```

```python solution
import numpy as np

def resample_direct(x, L, M, h):
    v = np.zeros(len(x)*L)
    v[::L] = x
    return np.convolve(v, h)[::M]

print(resample_direct(np.ones(4), 3, 2, np.ones(3)))
```

```python tests
import numpy as np
y = resample_direct(np.array([1.0, 2.0, 3.0]), 2, 1, np.array([1.0, 1.0]))
assert np.allclose(y, [1, 1, 2, 2, 3, 3, 0]), f"Upsampling [1, 2, 3] by 2 and filtering with [1, 1] should hold each sample: got {y}."
y = resample_direct(np.arange(6.0), 1, 2, np.array([1.0]))
assert np.allclose(y, [0, 2, 4]), f"Downsampling by 2 keeps every second sample, starting with the first: got {y}."
y = resample_direct(np.ones(4), 3, 2, np.ones(3))
assert len(y) == 7 and np.allclose(y, [1, 1, 1, 1, 1, 1, 0]), f"Ones through L = 3, h = [1, 1, 1], M = 2 give seven outputs, [1, 1, 1, 1, 1, 1, 0]: got {y}."
```

::: right
Right. The reference converter, simple and slow.
:::
:::

::: check
kind: python

## Step 3. Write `resample_poly(x, L, M, h)`: the same result from only the taps that meet real samples.

```python starter
import numpy as np

def resample_poly(x, L, M, h):
    # The same result as resample_direct, without ever forming the zero-stuffed signal:
    # output m uses taps h[p + jL] with p = (m*M) % L, against x[(m*M)//L - j].
    return np.zeros(1)

print(resample_poly(np.ones(4), 3, 2, np.ones(3)))
```

```python solution
import numpy as np

def resample_poly(x, L, M, h):
    n_out = (len(x)*L + len(h) - 1 + M - 1)//M
    y = np.zeros(n_out)
    for m in range(n_out):
        p, base = (m*M) % L, (m*M)//L
        taps = h[p::L]
        for j, t in enumerate(taps):
            i = base - j
            if 0 <= i < len(x):
                y[m] += t*x[i]
    return y

print(resample_poly(np.ones(4), 3, 2, np.ones(3)))
```

```python tests
import numpy as np
def direct(x, L, M, h):
    v = np.zeros(len(x)*L); v[::L] = x
    return np.convolve(v, h)[::M]
def proto(L, M, N, beta):
    wc = np.pi/max(L, M); n = np.arange(N) - (N - 1)/2
    return L*wc/np.pi*np.sinc(wc*n/np.pi)*np.kaiser(N, beta)
rng = np.random.default_rng(2)
for L, M in ((3, 2), (2, 3), (5, 4), (1, 3), (4, 1)):
    x = rng.normal(size=50); h = proto(L, M, 48, 7.0)
    a, b = resample_poly(x, L, M, h), direct(x, L, M, h)
    assert len(a) == len(b), f"For L = {L}, M = {M} produce {len(b)} outputs, as the direct method does; got {len(a)}."
    assert np.max(np.abs(a - b)) < 1e-10, f"For L = {L}, M = {M} the polyphase result must equal the direct one; the largest difference is {np.max(np.abs(a - b)):.2e}."
n = np.arange(3200)
x = np.cos(2*np.pi*1000*n/32000)
h = proto(3, 2, 96, 8.0)
y = resample_poly(x, 3, 2, h)
seg = y[300:4300]
spec = np.abs(np.fft.rfft(seg*np.hanning(len(seg))))
k = np.argmax(spec)
assert abs(k*48000/len(seg) - 1000) < 15, f"A 1 kHz tone resampled from 32 to 48 kHz must stay at 1 kHz; it peaks at {k*48000/len(seg):.0f} Hz."
amp = np.max(np.abs(seg))
assert abs(amp - 1) < 0.01, f"The tone's amplitude should stay 1; got {amp:.4f}."
```

::: right
Right. Your polyphase converter matches the direct one to rounding error for five different ratios, and turns a 32 kHz tone into a 48 kHz tone of the same pitch and level.
:::
:::

::: explain
## Why does the polyphase converter give exactly the same output as the direct one, not an approximation?

::: model
The direct method computes every output of a convolution between the filter and a signal that is zero at all but every Lth position. Each of those outputs is a sum of products, and every product that involves a stuffed zero contributes exactly nothing. The polyphase method computes the same sums but skips those zero products, using only the taps that line up with real samples, and it only computes the outputs that the downsampler would keep. Nothing that could change the result is left out; only arithmetic whose answer is known in advance to be zero, or that would be thrown away. The two methods are algebraically identical, which is why the test can demand agreement to rounding error.
:::
:::

::: practice

::: check
given: N = 64 | 96 | 240; L = 2 | 3 | 5
answer: N/L
tolerance: 0.5%

## Polyphase taps per output: {N}-tap prototype, L = {L}?

::: misses
- [any] N/L.
:::
:::

::: check
given: m = 4 | 7 | 11; M = 2 | 3; L = 3 | 5
answer: (m*M) - L*floor(m*M/L + 0.0001)
tolerance: 0

## Polyphase phase p for output m = {m}, M = {M}, L = {L}?

::: misses
- [any] $p = mM \bmod L$.
:::
:::

::: check
given: L = 3 | 160; M = 2 | 147
answer: 1/((L + M + abs(L - M))/2)
tolerance: 0.5%

## Prototype cutoff (units of π) for L = {L}, M = {M}?

::: misses
- [any] $1/\max(L, M)$.
:::
:::
:::
