Real-Time DSP: Blocks, Buffers, Latency and Hardware
Every filter so far ran on a whole recorded signal with one call to sosfilt. A guitar effect, a hearing aid, an active noise canceller or a motor-current loop cannot wait for the recording to end: samples arrive one by one from an ADC at a fixed rate, and each output must leave through a DAC (or into a control law) before a deadline. Real-time DSP is the same mathematics under two constraints: the processing must keep up on average (throughput), and the delay from input to output must stay below a limit (latency). This lesson shows how processors handle samples in blocks with double buffering, how to carry filter state across blocks, how to budget latency and processor cycles, and what hardware features DSP code relies on.
Sample by sample or in blocks
The simplest real-time loop runs the filter once per sample in the ADC interrupt. It has the lowest latency (one sample plus the converters) but pays the interrupt entry and exit cost times per second, and gives the processor no chance to use its pipelines and caches efficiently. Most systems therefore use block processing: a DMA controller moves samples from the ADC into memory without the CPU, and the CPU processes a block of samples at a time.
Ping-pong (double) buffering: the input buffer has two halves. While the DMA fills half A, the CPU processes half B (the block that just finished), writing results into an output buffer that a second DMA channel sends to the DAC. The DMA's "half complete" and "complete" interrupts tell the CPU which half is ready. The CPU must finish each block within one block period , otherwise the DMA overwrites data still being processed (an overrun, audible as a click). The minimum latency of this scheme is two block periods () plus the converters' own delays.
Carrying the state
A filter's memory (the delays of every biquad, or the last inputs of an FIR) must survive from one block to the next. In SciPy that memory is zi; on a processor it is the state array of each filter instance. Forgetting it is the classic block-processing bug:
import numpy as np
from scipy import signal
fs, B = 48000, 64 # sample rate and block size
sos = signal.butter(6, 2000, output="sos", fs=fs) # 3 biquads
rng = np.random.default_rng(7)
x = rng.standard_normal(B * 50) # 50 blocks of test signal
y_ref = signal.sosfilt(sos, x) # the whole record at once
zi = np.zeros((sos.shape[0], 2)) # filter state: 2 values per biquad, kept between blocks
y_blk = np.empty_like(x)
y_bad = np.empty_like(x)
for k in range(0, len(x), B):
y_blk[k:k + B], zi = signal.sosfilt(sos, x[k:k + B], zi=zi) # state carried over
y_bad[k:k + B] = signal.sosfilt(sos, x[k:k + B]) # state reset every block (a bug)
print("state carried : equals the whole-record result to 1e-12:", bool(np.abs(y_blk - y_ref).max() < 1e-12))
print(f"state reset : max error {np.abs(y_bad - y_ref).max():.3f} (signal rms {np.std(y_ref):.3f})")
print(f"state size: {zi.size} numbers for {sos.shape[0]} biquads")state carried : equals the whole-record result to 1e-12: True
state reset : max error 0.782 (signal rms 0.307)
state size: 6 numbers for 3 biquads
With the state carried, block processing is exactly the same computation as processing the whole record. With the state reset, each block starts with a transient, and the error reaches for a signal of rms : a periodic click at . A 6th-order IIR filter in SOS form needs only 6 state values; an FIR filter of taps keeps past inputs, usually in a circular buffer so that no data are copied when a new sample arrives.
Worked example: latency and cycle budget of a stereo audio filter
Given: , stereo, block size ; a 129-tap linear-phase FIR and 8 biquads per channel; a 200 MHz processor with a single-cycle multiply-accumulate (MAC); an assumed overhead factor of 1.5 for loads, stores and loop control; ADC and DAC digital filters with an assumed group delay of 16 samples each.
Find: the end-to-end latency, the processor load, and how the latency depends on the block size.
Solve: latency samples . Work per sample and channel: MACs (each biquad has five coefficients). Cycles per second: , i.e. 12 % of the core.
# Latency and processing budget of a block-based audio filter (all assumptions are explicit inputs)
fs = 48000 # sample rate, Hz
B = 64 # block size (samples per DMA half-buffer)
codec_adc = 16 # ADC digital filter group delay, samples (assumed; take it from the codec datasheet)
codec_dac = 16 # DAC interpolation filter group delay, samples (assumed)
fir_taps = 129 # linear-phase FIR in the chain
biquads = 8 # IIR sections in the chain
f_cpu = 200e6 # processor clock, Hz
cyc_per_mac = 1.0 # single-cycle MAC
overhead = 1.5 # loads, stores, loop control, interrupt entry: a factor on the MAC count (assumed)
blk_time = B / fs
lat_samples = B + B + codec_adc + codec_dac + (fir_taps - 1) / 2 # input block + output block + converters + FIR delay
print(f"block period {1e3 * blk_time:.3f} ms; latency {lat_samples:.0f} samples = {1e3 * lat_samples / fs:.2f} ms")
macs = fir_taps + 5 * biquads # per sample, per channel
cycles = macs * cyc_per_mac * overhead * fs * 2 # 2 channels (stereo)
print(f"{macs} MAC/sample/channel -> {cycles / 1e6:.1f} Mcycles/s = {100 * cycles / f_cpu:.0f} % of a {f_cpu / 1e6:.0f} MHz core")
for B2 in (16, 32, 64, 256):
l2 = 2 * B2 + codec_adc + codec_dac + (fir_taps - 1) / 2
print(f" block {B2:3d}: latency {1e3 * l2 / fs:5.2f} ms, interrupts per second {fs / B2:6.0f}")block period 1.333 ms; latency 224 samples = 4.67 ms
169 MAC/sample/channel -> 24.3 Mcycles/s = 12 % of a 200 MHz core
block 16: latency 2.67 ms, interrupts per second 3000
block 32: latency 3.33 ms, interrupts per second 1500
block 64: latency 4.67 ms, interrupts per second 750
block 256: latency 12.67 ms, interrupts per second 188
Check: the block period () is the deadline for processing one block; at 12 % load the CPU finishes in about . Smaller blocks lower the latency but multiply the interrupts: gives and 3000 interrupts per second. Note that the FIR's own delay (64 samples, ) is as large as a whole block: for low latency, use a minimum-phase or IIR filter instead of a long linear-phase FIR. For comparison, a few milliseconds is fine for most audio effects, while in-ear monitoring and hearing aids aim for well under in total, and an active noise canceller needs tens of microseconds, which forces sample-by-sample processing at high rates.
What DSP hardware provides
DSP code is dominated by sums of products, so processors built or extended for it share a set of features (described here generically; the planned Embedded Systems track covers specific microcontrollers and their tools):
- Single-cycle MAC with a wide accumulator (for example 16 × 16-bit products into 40 or 64 bits) and saturating arithmetic, so fixed-point sums neither overflow silently nor need a branch.
- SIMD instructions that do two 16-bit MACs (or four 8-bit operations) at once, and floating-point units (single precision on many microcontrollers).
- Harvard memory buses and multiple address generators that fetch a coefficient and a sample in the same cycle, with circular (modulo) addressing for delay lines and zero-overhead loops.
- DMA controllers that move ADC, DAC and serial-audio data without the CPU, with half- and full-transfer interrupts for ping-pong buffers.
- Vendor and open DSP libraries (CMSIS-DSP-style collections of FIR, biquad cascade, FFT and matrix routines) in float32, Q15 and Q31 versions, already structured as block functions with state arrays, exactly like
sosfiltwithzi.
Floating or fixed point? A processor with a single-precision FPU runs biquads in DF II transposed form in float32 with little risk (but see the high-Q sections in Biquads and SOS). Without an FPU, or for the lowest power, use Q15/Q31 with DF I and a wide accumulator (Filter Structures). Either way, simulate the exact arithmetic in Python first and compare it with a double-precision reference.
Guided lab: measuring latency
Hand calculation. With at and the assumed converter delays, the delay from input to output should be about with the FIR, or with the FIR removed (only the two blocks and the converters).
Simulation. Change B, fir_taps and codec_adc in the budget program; find the largest block size that keeps the latency under .
What you would measure. Feed a short pulse or a square-wave edge from a function generator into the board's audio input and trigger a two-channel scope on it; measure the time to the same edge at the output. Expect the calculated latency within about sample period plus the codec's actual filter delay (the datasheet value replaces the 16-sample assumption). To measure the processor load, toggle a GPIO pin at the start and end of the block routine and read the duty cycle on the scope: expect roughly 12 % if the overhead assumption holds.
Hazards and safe setup. A USB-powered board and audio-level signals (below peak) from a function generator; no mains-powered amplifier is opened. Keep headphones at low volume, since a bug (overrun, unstable filter) can produce full-scale noise.
Pitfalls
- Resetting the filter state every block (periodic clicks at ).
- Doing slow work (printing, memory allocation, waiting) inside the audio interrupt or block routine.
- Measuring only the average load: the worst case (cache misses, other interrupts) must still finish in the block period.
- Ignoring the converter and FIR delays in the latency budget.
- Choosing a huge block "for efficiency" in a system where latency matters.
Practice
- At with and ping-pong buffers, what is the minimum buffering latency?
- A 255-tap FIR runs on a 100 MHz core at , one channel, with 1 MAC per cycle and an overhead factor of 2. What is the load?
- Why does an FIR filter in a real-time system usually use a circular buffer?
Answer
- (plus the converters).
- cycles/s: 24.5 % of the core.
- So that a new sample overwrites the oldest one in place; only a pointer moves, instead of shifting values every sample.
Test yourself
With ping-pong buffers of samples, the minimum buffering latency is
- one sample
What goes wrong if zi is not carried from one block to the next?
- nothing
- each block starts with a transient, causing periodic clicks
- the filter becomes unstable
- the latency doubles
Which hardware feature lets an FIR delay line advance without copying data?
- a single-cycle MAC
- circular (modulo) addressing
- an FPU
- saturation
In the worked example, a 129-tap linear-phase FIR adds a delay of
- 129 samples
- 64 samples (1.33 ms)
- 2 samples
- none