import matplotlib
if not hasattr(matplotlib.RcParams, "_get"):
matplotlib.RcParams._get = dict.get
10.6 Real-time processing#
Frame-based processing has one more essential use: real-time audio. Suppose we want to synthesize \(x[n] = f(n, c[n])\), where \(f\) is some function, and \(c[n]\) is a control set by a user at sample \(n\). For example, \(f\) could be a sinusoid, and \(c[n]\) its frequency. So far in this book, we have assumed that \(c[n]\) is known ahead of time for all \(n \in \{0, 1, \ldots, N - 1\}\), which we’ll refer to here as offline synthesis. But how might we synthesize audio in real time, while a user changes the controls live?
One idea is to synthesize each sample \(x[n]\) at time \(n \Delta t\) (recall that \(\Delta t = \frac{1}{f_s}\) is the sampling period), based on the current control \(c[n]\), and send it straight to the speaker. This approach has three issues:
The time budget is tiny. We need \(x[n]\) at time \(n \Delta t\), and \(x[n + 1]\) just \(\Delta t\) later, which is about \(0.023\) ms at \(f_s = 44{,}100\) Hz.
Function calls have overhead. As we saw with the unit generators of Chapter 4, paying function overhead once per sample adds up fast.
It is overkill. Human-provided controls change much more slowly than once every \(\Delta t\) seconds on average.
Instead, real-time systems use frame-based processing. In this context, frames are usually referred to as blocks, and \(B = N_H = N_F\) is the block size.
Each block lasts \(B \Delta t\) seconds. At the start of block \(k\), time \(k \cdot B \Delta t\), the system does three things: (1) it starts playing block \(x_k\) through the digital-to-analog converter (DAC), (2) it reads the latest control information \(c_k = c[k B]\), and (3) it synthesizes the next block, \({x_{k+1} = f_B\big([k + 1] \cdot B, c_k\big)}\), where \(f_B\) synthesizes \(B\) samples at a time:
Fig. 75 Block-based real-time synthesis. The playhead marks the sample currently leaving the speaker. At the start of each block, the system reads the control (top), and synthesizes the next block of output samples (middle), shown in the same color. The strip at the bottom shows when the computer is busy synthesizing, which must finish before the playhead reaches the next block.#
This addresses all three issues. The deadlines are now \(B \Delta t\) seconds apart rather than \(\Delta t\), and we pay the overhead of a function call once per block rather than once per sample. We also read the controls just once per block, which should be sufficient for human control inputs, assuming \(B\) is sufficiently small.
Latency#
Block-based processing comes at a cost: latency. The control \(c_k\) is read at time \(k \cdot B \Delta t\), but we do not hear its effect until block \(x_{k+1}\) starts playing at time \((k + 1) \cdot B \Delta t\), a delay of \(B \Delta t\) seconds.
We can reduce \(B\) to reduce the latency, but this increases the risk of glitches. The synthesis of each block must always finish within \(B \Delta t\) seconds, or else the DAC runs out of samples, and we hear a click or a dropout. Smaller blocks leave less time to absorb the overhead of each function call, as well as any hiccups, such as the operating system briefly pausing our program to run another one. So we must configure \(B\) to balance the two:
Block size |
Latency |
Glitch risk |
|---|---|---|
Small (\(B = 32\) to \(128\)) |
Very low (\(0.7\) to \(3\) ms) |
Higher |
Medium (\(B = 256\) to \(512\)) |
Low (\(6\) to \(12\) ms) |
Lower |
Large (\(B = 1024\) to \(2048\)) |
Noticeable (\(23\) to \(46\) ms) |
Much lower |
Stateful callback functions#
Finally, \(f_B\) often needs to remember some state \(h_k\) from one block to the next, so that \(x_{k+1}, h_{k+1} = f_B(c_k, h_k)\). For example, to stitch together the blocks of a sinusoid without clicks, we must carry its accumulated phase across block boundaries, as in the time-varying oscillator of Chapter 6. If the control \(c_k\) is the sinusoid’s frequency, each sample advances the phase by
So the samples of block \(x_{k+1}\) are \(x_{k+1}[n] = \sin(h_k + \Delta\phi_k \cdot n)\) for \(n \in \{0, 1, \ldots, B - 1\}\), and the state advances to \(h_{k+1} = h_k + \Delta\phi_k \cdot B\), the phase at which the next block should pick up.
A common abstraction for this is a class, which stores the state as members, and has a callback method that the audio system calls whenever it needs the next block. The code below compares offline synthesis of a melody to block-based synthesis with such a class, simulating both the audio system and a user who changes the pitch in real time:
# Offline synthesis: x[n] = f(n, c[n]), with the control c[n] (pitch) known ahead of time for all n
f_s = 44100
melody = [60, 64, 67, 72, 67, 64, 60]
c = np.repeat(melody, f_s // 4).astype(np.float64)
f = pq.helper.pitch_to_frequency(c)
x = np.sin(np.cumsum(2.0 * np.pi * f / f_s))
pq.play(pq.Audio(x, f_s))
# Real-time synthesis: the control c_k = c[kB] is read once per block, and the
# phase is state, carried from one block to the next
class Sinusoid:
def __init__(self, pitch: float = 0.0) -> None:
self.pitch, self.phase = (pitch, 0.0)
def callback(self, block: pq.Audio) -> None:
f = pq.helper.pitch_to_frequency(self.pitch) # read c_k
B = len(block)
dphase = 2.0 * np.pi * f / block.sample_rate
phases = self.phase + dphase * np.arange(B)
block[:] = np.sin(phases)[:, np.newaxis]
self.phase = (self.phase + dphase * B) % (2.0 * np.pi)
# Simulate the audio system, which asks for the next block every BΔt seconds,
# and a user who switches to the next note of the melody right on time.
# Try B = 1, and compare how much of the time budget it uses.
# Try B = 16384: the notes arrive late, and some are skipped entirely!
B = 512
synth = Sinusoid(melody[0])
blocks = [pq.Audio.zeros(B, 1, f_s)] # x_0: silence, queued before playback starts
start = time.perf_counter()
for k in range(len(c) // B):
synth.pitch = c[k * B] # the user's pitch at time kBΔt
block = pq.Audio.zeros(B, 1, f_s)
synth.callback(block) # synthesize x_{k+1}
blocks.append(block)
busy = time.perf_counter() - start # seconds spent synthesizing
print(f"B = {B}: {1000 * B / f_s:.2f} ms latency, {100 * busy / (len(c) / f_s):.1f}% of time budget")
pq.play(pq.Audio.concatenate(blocks))
B = 512: 11.61 ms latency, 0.1% of time budget