Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Resampling: polyphase, half-band and CIC filters

ProblemChange a signal’s sampling rate by a rational or arbitrary factor without aliasing or imaging, at the lowest cost per sample
Devised byRonald Schafer and Lawrence Rabiner (1973), digital interpolation; Maurice Bellanger, Georges Bonnerot and M. Coudreuse (1976), polyphase decomposition; Ronald Crochiere and Lawrence Rabiner (1983), the standard text; Eugene Hogenauer (1981), the cascaded integrator-comb (CIC) filter
AccuracyThe polyphase resampler equals SciPy’s upfirdn exactly, including its length; the CIC impulse response matches its closed form to
CostPolyphase: multiplies per output for a filter of taps and upsampling . Half-band: about per output. CIC: no multiplies
Read firstBackground: sampling and aliasing, FIR design: windows, frequency sampling and Parks-McClellan
APIPolyphaseIntegerResampler, PolyphaseArbitraryResampler, halfband_lowpass, HalfBandDecimator, HalfBandInterpolator, CicDecimator, CicInterpolator, cic_magnitude_response

Overview

Audio moves between 44.1 and 48 kHz, radios decimate from megasamples to kilosamples per second, and images are scaled. Changing a sampling rate by means conceptually (the reasons for each step are in sampling and aliasing): insert zeros between samples (upsampling, which creates spectral images), low-pass filter, and keep every -th sample (downsampling, which aliases anything above the new Nyquist). Done literally, most of the multiplications are by the inserted zeros or produce samples that are thrown away. Polyphase filtering computes only the outputs that are kept, from only the nonzero inputs. Two special filters push the cost down further: half-band filters, with almost half their taps zero, for factors of two, and CIC filters, which need no multiplications at all, for large factors.

Where it is used

Changing the sampling rate is needed whenever two systems disagree on it.

  • Audio. Converting between 44.1 kHz and 48 kHz, and the sample-rate converters inside sound cards and codecs.
  • Software-defined radio. Decimating a wideband capture to the bandwidth of one signal using CIC and half-band filters, cheaply enough for FPGAs.
  • Data acquisition. Matching the sampling rates of sensors with different rates.
  • Anti-aliasing. Why a low-pass filter must come before downsampling.

History

Ronald Schafer and Lawrence Rabiner (1973) set out the theory of digital interpolation by an integer factor. Maurice Bellanger, Georges Bonnerot and M. Coudreuse (1976) introduced the polyphase decomposition, splitting a filter into subfilters that run at the low rate. Eugene Hogenauer (1981) designed the cascaded integrator-comb filter for hardware decimators. It is now in nearly every digital radio receiver. Ronald Crochiere and Lawrence Rabiner’s Multirate Digital Signal Processing (1983) and P. P. Vaidyanathan’s Multirate Systems and Filter Banks (1993) are the standard texts.

The idea

Polyphase resampling

The textbook procedure. To change the sampling rate of a signal by the rational factor , three steps are needed in principle.

  1. Upsample by : insert zeros between consecutive samples. The rate is now times higher, but the spectrum of the zero-stuffed signal contains unwanted copies (images) of the original spectrum at higher frequencies.
  2. Low-pass filter at the high rate. One filter does two jobs: it removes the images, which turns the zeros into interpolated values, and it removes everything above the new Nyquist frequency, which would otherwise fold back (alias) into the band in the next step.
  3. Downsample by : keep every -th sample.

Done literally this is very wasteful. The filter runs at the high rate, yet most of its inputs are zeros that contribute nothing, and most of its outputs are thrown away.

The polyphase shortcut. Both kinds of waste can be removed by algebra. Write the upsampled signal as when divides , and 0 otherwise. Filtering with and keeping every -th sample gives

where the second form drops the zero terms: the sum runs only over actual inputs , those whose tap index lies in for a filter of length . Two things have happened. Only the outputs that are kept are ever computed. And each one uses only every -th tap of the filter, about of them: the subset with . Such a subset is called a phase of the filter, and the filter is in effect split into short filters used in rotation, which gives the method its name. This is SciPy’s upfirdn, and PolyphaseIntegerResampler computes it as a stream, multiplying the taps by so that interpolation keeps unit gain (as resample_poly does). Without taps, it designs a Kaiser-window low-pass with cutoff of the high-rate Nyquist and 60 dB attenuation.

Figure 15.15. Interpolation by 4.

A polyphase resampler must push each stuffed zero into the history before computing the output due after it. Computing all outputs from the same history makes them equal: upsampling by 3 would turn into . Asymmetric filters must also be applied unreversed. A test with a single unit tap shows neither error.

Arbitrary ratios

PolyphaseArbitraryResampler allows a real . Output takes the filtered upsampled signal at position , so output times are rounded to the nearest point below on a grid times finer than the input. The error in time is less than input samples:

Table 15.13. Accuracy of arbitrary-ratio resampling.

up_ratedown_rate (ratio 1/1.37)error against the rounded output timeserror against the exact output times
45.482.0e-51.7e-2
1621.921.8e-54.2e-3
6487.681.8e-51.1e-3
256350.721.8e-52.7e-4

Against the rounded times the output is accurate to the filter’s stopband; against the exact times the rounding error falls in proportion to . A large costs only memory for the filter, not computation, because each output uses one phase.

Half-band filters

Halving the sampling rate is the most common rate change, and there is a filter made for it. A half-band filter has its cutoff at a quarter of the sampling rate and a response symmetric about it, . Its impulse response, windowed, is zero at every even offset from the centre except the centre itself, where it is :

Figure 15.16. Half-band filter.

The 31-tap half-band filter has 14 zero taps; decimating 400 samples gives 200 outputs.

Decimating by two needs only every other output, and of those only the nonzero taps: about multiplies per output. Cascades of half-band stages are the usual way to decimate by powers of two.

CIC filters

At very high sampling rates, as at the output of a radio’s analogue-to-digital converter, even one multiplication per sample is expensive. The cascaded integrator-comb (CIC) filter changes the rate by a large factor using only additions and subtractions.

Its starting point is the simplest low-pass filter, a moving sum. A moving sum of length , , can be built from an integrator at the high rate and a comb at the low rate, with the rate change in between. cascaded integrators and combs give

with nulls at every multiple of the output rate, where aliases would land, and no multiplications at all:

Figure 15.17. CIC response.

More stages deepen the nulls and widen the attenuation around them, but also increase the droop, the falling gain across the passband, which a short compensating FIR filter at the low rate corrects. The integrators’ registers overflow by design. In two’s complement arithmetic the wrap-around cancels exactly in the combs, as long as the output fits, which is why the library’s CIC filters work on i64. The impulse response of a 3-stage CIC with RM = 4 matches |sin(4πf)/sin(πf)|³ to 4.4e-16. A 5-stage decimator by 64 turns a constant input of 1000 into 1073741824000 (gain 64⁵ = 1073741824), with integrator registers that wrap around without corrupting the output.

Algorithm

Polyphase resampler (a stream), with upsampling factor , downsampling factor and a filter of length . Positions on the upsampled time axis are numbered so that input sample sits at position . Output is taken at position (or for a real ).

  1. Keep the recent input samples in a buffer.
  2. The next output, at position , needs the inputs up to . Wait until that sample has arrived.
  3. Compute the output as over the inputs for which the tap index lies in . These are the taps of one phase, .
  4. Advance to the next output position, and discard the buffered inputs that no later output can reach.

At the end of the stream, flush feeds zeros until the position has been passed, so that the filter’s tail is emitted. Each output costs about multiplications.

Half-band decimator by 2: for each pair of input samples, the output is the centre tap times the suitably delayed sample, plus the sum of the taps at odd offsets times their samples. The taps at even offsets are zero and are skipped.

CIC decimator by , with stages and differential delay , on integers.

  1. For each input sample, pass it through the integrators in turn: each adds its input to its running total, with wrapping arithmetic, and passes the total on.
  2. For every -th input sample, pass the last integrator’s output through the combs in turn: each subtracts the value it received output samples earlier.
  3. The result of the last comb is the output sample.

Implementation

    fn drain(&mut self, end: usize, out: &mut Vec<T>) {
        let len = self.taps.len();
        loop {
            let p = self.position(self.next);
            if p >= end || self.received == 0 || p / self.up > self.received - 1 {
                break;
            }
            // Inputs j with 0 <= p − j·up < len.
            let hi = p / self.up;
            let lo = if p + 1 > len { (p + 1 - len).div_ceil(self.up) } else { 0 };
            let mut acc = T::zero();
            for j in lo..=hi {
                acc += self.history[j - self.first].f_scale(self.taps[p - j * self.up]);
            }
            out.push(acc);
            self.next += 1;
        }
    pub fn process(&mut self, x: &[i64]) -> Vec<i64> {
        let mut out = Vec::with_capacity(x.len() / self.rate + 1);
        for &v in x {
            let mut acc = v;
            for integrator in self.integrators.iter_mut() {
                *integrator = integrator.wrapping_add(acc);
                acc = *integrator;
            }
            self.phase += 1;
            if self.phase == self.rate {
                self.phase = 0;
                out.push(self.combs.iter_mut().fold(acc, |a, comb| comb.step(a)));
            }
        }
        out
    }
  • Both polyphase resamplers share one engine and implement StreamOperator. The integer resampler reduces to lowest terms.
  • The output is delayed by the filter’s group delay, high-rate samples for a linear-phase filter, as with upfirdn. Unlike resample_poly, no samples are trimmed.

In practice

//! Changing the sampling rate: polyphase resamplers, a half-band decimator and a CIC filter.

use lib_jsl_dsp::discrete::resampling::cic::CicDecimator;
use lib_jsl_dsp::discrete::resampling::half_band::{HalfBandDecimator, halfband_lowpass};
use lib_jsl_dsp::discrete::resampling::polyphase_arbitrary_resampling::PolyphaseArbitraryResampler;
use lib_jsl_dsp::discrete::resampling::polyphase_integer_resampling::PolyphaseIntegerResampler;
use lib_jsl_dsp::discrete::stream_operator::StreamOperator;

fn main() {
    // 44.1 kHz to 48 kHz is 160/147.
    let x: Vec<f64> = (0..4410).map(|n| (2.0 * std::f64::consts::PI * 1000.0 * n as f64 / 44100.0).sin()).collect();
    let mut r = PolyphaseIntegerResampler::new(160, 147, None).unwrap();
    let mut y = r.process(&x).unwrap().unwrap_or_default();
    y.extend(r.flush().unwrap().unwrap_or_default());
    let rms = |v: &[f64]| (v.iter().map(|s| s * s).sum::<f64>() / v.len() as f64).sqrt();
    println!("44.1 → 48 kHz: {} samples in, {} out; RMS {:.4} (sine: 0.7071)", x.len(), y.len(), rms(&y[1000..4000]));
    let mut a = PolyphaseArbitraryResampler::new(64, 64.0 * 1.25, None).unwrap();
    println!("arbitrary 1/1.25: {} outputs from {}", a.process(&x).unwrap().unwrap().len(), x.len());
    let taps = halfband_lowpass(23, 7.0).unwrap();
    let mut hb = HalfBandDecimator::new(&taps).unwrap();
    println!("half-band: {} taps, {} zero; {} outputs", taps.len(), taps.iter().filter(|t| **t == 0.0).count(), hb.process(&x).len());
    let mut cic = CicDecimator::new(16, 4, 1).unwrap();
    let out = cic.process(&vec![100; 640]);
    println!("CIC R = 16, N = 4: steady output {} = 100 × gain {}", out.last().unwrap(), cic.gain());
}
44.1 → 48 kHz: 4410 samples in, 4816 out; RMS 0.7070 (sine: 0.7071)
arbitrary 1/1.25: 3528 outputs from 4410
half-band: 23 taps, 10 zero; 2205 outputs
CIC R = 16, N = 4: steady output 6553600 = 100 × gain 65536

Strengths

  • Exact rational resampling at the low rate’s cost; any ratio with bounded timing error.
  • Half-band and CIC filters make large power-of-two and integer factors cheap.

Weaknesses

  • The arbitrary resampler rounds output times; a fractional-delay interpolator (such as a Farrow filter) is needed for exact timing with a small .
  • CIC filters droop and alias near the band edges, and need integer arithmetic and compensation.

Exercises

  1. Show that upsampling by compresses the spectrum by and creates images, and that downsampling by aliases the spectrum times.
  2. Show that the polyphase sum uses only taps per output.
  3. Prove that the half-band impulse response vanishes at even nonzero offsets, and that .
  4. Show that integrators followed by combs compute the -fold moving sum even when the integrators overflow in two’s complement arithmetic.
  5. Find how many bits a CIC decimator with , , and 16-bit input needs in its registers (Hogenauer’s rule).
Hints and answers
  1. Inserting zeros between samples replaces by : the spectrum is compressed by and repeated times over , i.e. images. Keeping every -th sample sums shifted, stretched copies of the spectrum, of which fold onto the original.
  2. The upsampled sequence is zero at out of positions, so only every -th tap meets a non-zero sample: taps per output.
  3. Half-band: is the sum of the response and its mirror about ; the inverse transform of a constant is a single impulse, so every other sample of (except the centre) is zero.
  4. Two’s complement arithmetic is a ring modulo , so the combs’ differences are computed correctly modulo even if the integrators overflow, as long as the true result fits in the register.
  5. Hogenauer: register width bits.

Further reading

  • R. E. Crochiere and L. R. Rabiner, Multirate Digital Signal Processing, Prentice Hall, 1983.
  • E. B. Hogenauer, “An economical class of digital filters for decimation and interpolation”, IEEE Transactions on Acoustics, Speech, and Signal Processing 29 (1981) 155–162.
  • P. P. Vaidyanathan, Multirate Systems and Filter Banks, Prentice Hall, 1993.
  • R. W. Schafer and L. R. Rabiner, “A digital signal processing approach to interpolation”, Proceedings of the IEEE 61 (1973) 692–702.