12. Dynamics: compressors and limiters
Speech varies by 30 dB or more between a whispered consonant and a shouted vowel, and broadcast, telephony and hearing aids all reduce that range so the quiet parts stay audible and the loud parts do not clip. A compressor has three parts: a level detector with attack and release ballistics, a static gain computer in decibels, and a multiplier. This notebook measures each part on the library’s implementation and rebuilds the whole processor in a few lines of NumPy.
Learning outcomes. After this notebook you can
write down the hard-knee and quadratic soft-knee static curves and read
get_compression_curve;relate attack and release time constants to measurable step responses (63.2 %, and a 10-90 % rise of \(\tau \ln 9 \approx 2.2\tau\));
reproduce
apply_compressorandapply_limitersample for sample in NumPy;explain why a limiter on a smoothed envelope is not a brick wall, and how much lookahead reduces the overshoot.
import numpy as np
import matplotlib.pyplot as plt
import audio_samples as aus
rng = np.random.default_rng(0)
fs = 48_000
PEAK, HARD, SOFT = aus.DynamicRangeMethod.peak, aus.KneeType.hard, aus.KneeType.soft
SIDE = aus.SideChainConfig.default() # side-chain off
def compressor(threshold_db=-20.0, ratio=4.0, attack_ms=5.0, release_ms=50.0, makeup_gain_db=0.0,
knee_type=HARD, knee_width_db=0.0, detection_method=PEAK, lookahead_ms=0.0):
return aus.CompressorConfig(
threshold_db=threshold_db, ratio=ratio, attack_ms=attack_ms, release_ms=release_ms,
makeup_gain_db=makeup_gain_db, knee_type=knee_type, knee_width_db=knee_width_db,
detection_method=detection_method, side_chain=SIDE, lookahead_ms=lookahead_ms)
def limiter(ceiling_db=-6.0, attack_ms=1.0, release_ms=100.0, knee_type=HARD, knee_width_db=0.0,
detection_method=PEAK, lookahead_ms=0.0):
return aus.LimiterConfig(
ceiling_db=ceiling_db, attack_ms=attack_ms, release_ms=release_ms, knee_type=knee_type,
knee_width_db=knee_width_db, detection_method=detection_method, side_chain=SIDE,
lookahead_ms=lookahead_ms, isp_limiting=False)
def mono(x, sr=fs):
# new_mono may share memory with the array (in-place methods would then modify it): copy.
return aus.AudioSamples.new_mono(np.array(x, dtype=float), sr)
Concept
Detector and ballistics. The detector turns the input \(x[n]\) into a non-negative value \(d[n]\): \(|x[n]|\) for a peak detector, or the RMS over the last 10 ms. A one-pole smoother then produces the envelope
where \(f_s\) is the sample rate in Hz and \(\tau\) the time constant in seconds: the attack constant \(\tau_A\) while \(d[n] > e[n-1]\) (the level is rising) and the release constant \(\tau_R\) otherwise. After a step from \(d_0\) to \(d_1\) the envelope follows
so it covers \(1 - e^{-1} = 63.2\%\) of the step after one time constant, and its 10-90 % rise time is \(\tau \ln 9 \approx 2.2\,\tau\). (Manufacturers quote attack times in either convention, so numbers are not comparable across products.)
Static gain computer (dB domain). With envelope level \(L = 20\log_{10} e\) (dBFS), threshold \(T\) (dBFS), ratio \(R \ge 1\) (dimensionless) and knee width \(W\) (dB), the hard-knee compressor’s output level is
so the gain reduction is \(r = L - Y = (1 - 1/R)\max(L - T, 0)\) dB. The quadratic soft knee (Giannoulis, Massberg and Reiss, JAES 2012) joins the two lines with a parabola over \([T - W/2, T + W/2]\):
It has slope 1 at the lower edge and \(1/R\) at the upper edge, so the curve has no corner, and at \(L = T\) it already reduces by \((1 - 1/R)W/8\) dB.
Gain. The output is \(y[n] = x[n]\, 10^{-r[n]/20}\, 10^{M/20}\), where \(M\) is the make-up gain in dB. Working in dB makes the ratio a slope and the threshold an offset.
Limiter. The compressor with \(R \to \infty\) and the ceiling \(C\) (dBFS) in place of \(T\): \(r = \max(L - C, 0)\). Because the gain follows a smoothed envelope, the output can still exceed \(C\) at the start of a transient.
Lookahead. Delay the audio by \(N_L\) samples and apply to sample \(n\) the largest reduction computed for samples \(n, \dots, n + N_L\). If the envelope starts from zero and the step is to \(d_1\), the reduction applied to the first sample of the step comes from an envelope of \(d_1(1 - a^{N_L + 1})\), so the overshoot is
(The library processes whole buffers, so it compensates the delay: output index \(n\) stays aligned with input index \(n\).)
With the library
AudioSamples.get_compression_curve(config, levels_db) returns the static output level for
each input level (make-up gain included); it does not read the samples.
probe = mono(np.zeros(16)) # any signal: the curve is analytic
hard = compressor(threshold_db=-20.0, ratio=4.0)
# -8 dBFS is 12 dB over the threshold: the output is -20 + 12/4 = -17.
assert np.allclose(probe.get_compression_curve(hard, np.array([-30.0, -20.0, -8.0])),
[-30.0, -20.0, -17.0], atol=1e-12)
soft = compressor(threshold_db=-20.0, ratio=4.0, knee_type=SOFT, knee_width_db=10.0)
L = np.array([-25.0, -20.0, -15.0])
r = L - probe.get_compression_curve(soft, L)
# No reduction at T - W/2, (1 - 1/R) W / 8 = 0.9375 dB at T, back on the hard line at T + W/2.
assert np.allclose(r, [0.0, 0.9375, 3.75], atol=1e-12)
# Slopes of the output curve: 1 at the lower knee edge, 1/R at the upper one.
d = 1e-6
y = lambda l: probe.get_compression_curve(soft, np.array([l - d, l + d]))
assert abs(np.diff(y(-25.0))[0] / (2 * d) - 1.0) < 1e-5
assert abs(np.diff(y(-15.0))[0] / (2 * d) - 0.25) < 1e-5
Lg = np.linspace(-40, 0, 401)
fig, ax = plt.subplots(figsize=(5, 4))
ax.plot(Lg, Lg, color="grey", lw=0.8, ls=":", label="no compression")
ax.plot(Lg, probe.get_compression_curve(hard, Lg), label="hard knee")
ax.plot(Lg, probe.get_compression_curve(soft, Lg), label="soft knee, W = 10 dB")
ax.set(xlabel="Input level L (dBFS)", ylabel="Output level Y (dBFS)",
title="Static curve, T = -20 dBFS, R = 4", aspect="equal")
ax.legend(fontsize=8)
plt.show()
Ballistics. Feed a DC level of \(-40\) dBFS for 100 ms, then 0 dBFS for 200 ms (peak detector,
attack 5 ms, release 50 ms, hard knee at \(-20\) dBFS, 4:1), and read the per-sample reduction
with get_gain_reduction. Above the threshold the hard-knee curve can be inverted,
\(L = T + r/(1 - 1/R)\), which recovers the envelope; it reaches 63.2 % of the step after
\(\tau_A = 5\) ms and rises from 10 % to 90 % in \(5 \ln 9 = 10.99\) ms.
x_step = np.concatenate([np.full(4_800, 0.01), np.full(9_600, 1.0)])
cfg = compressor(threshold_db=-20.0, ratio=4.0, attack_ms=5.0, release_ms=50.0)
gr = np.asarray(mono(x_step).get_gain_reduction(cfg))
env = 10 ** ((-20.0 + gr / 0.75) / 20) # valid where gr > 0
lo, hi = 0.01, 1.0
def reach(level):
idx = np.flatnonzero((np.arange(len(gr)) >= 4_800) & (gr > 0) & (env >= level))
return idx[0]
# Sample 4800 is the first at the higher level and already one update of the recursion.
t63_ms = (reach(lo + (1 - np.exp(-1)) * (hi - lo)) - 4_800 + 1) / fs * 1e3
rise_ms = (reach(lo + 0.9 * (hi - lo)) - reach(lo + 0.1 * (hi - lo))) / fs * 1e3
print(f"63 % after {t63_ms:.3f} ms, 10-90 % rise {rise_ms:.3f} ms")
# One sample is 0.021 ms, so both are within 0.03 ms of theory.
assert abs(t63_ms - 5.0) < 0.03
assert abs(rise_ms - 5.0 * np.log(9)) < 0.03 and abs(5.0 * np.log(9) - 10.99) < 0.005
# Settled: the envelope is 0 dBFS, 20 dB over the threshold, so 15 dB of reduction.
assert abs(gr[14_000] - 15.0) < 1e-6
fig, ax = plt.subplots(figsize=(8, 3))
t_ms = (np.arange(len(gr)) - 4_800) / fs * 1e3
ax.plot(t_ms, gr)
ax.set(xlim=(-5, 60), xlabel="Time after the step (ms)", ylabel="Gain reduction (dB)",
title="Attack: -40 -> 0 dBFS step, tau_A = 5 ms, T = -20 dBFS, 4:1")
plt.show()
63 % after 5.021 ms, 10-90 % rise 10.979 ms
The same step through apply_compressor settles at \(-20 + 20/4 = -15\) dBFS. The
attack_decay_envelope method exposes the envelope follower directly; its attack output is
the envelope while it rises, so on a step from 0 to 1 it reads exactly \(1 - a^k\) after \(k\)
samples.
out = mono(x_step)
out.apply_compressor(cfg) # in place
assert abs(20 * np.log10(out.to_numpy()[-1]) + 15.0) < 1e-3
follower = aus.EnvelopeFollower(5.0, 50.0, float(fs), PEAK)
unit = mono(np.concatenate([np.zeros(10), np.ones(2_000)]))
rising, _ = unit.attack_decay_envelope(follower, PEAK)
a = np.exp(-1 / (0.005 * fs))
k = np.arange(1, 2_001)
assert np.allclose(rising[10:], 1 - a**k, atol=1e-12)
assert abs(rising[10 + 240 - 1] - (1 - np.exp(-1))) < 1e-12 # 63.2 % after 240 samples = 5 ms
How it works
The whole compressor is an envelope follower, the gain computer and a multiplication. Written
out in NumPy it matches apply_compressor sample for sample, here with a 6 dB soft knee on a
step up and back down (which also exercises the release).
def compress_numpy(x, T, R, W, attack_ms, release_ms, sr=fs):
a_att, a_rel = np.exp(-1 / (attack_ms * 1e-3 * sr)), np.exp(-1 / (release_ms * 1e-3 * sr))
slope = 1 - 1 / R
y = np.empty_like(x)
e = 0.0
for n, v in enumerate(x):
dv = abs(v) # peak detector
a = a_att if dv > e else a_rel
e = a * e + (1 - a) * dv
level = 20 * np.log10(e) if e > 0 else -80.0
o = level - T
r = slope * (o + W / 2) ** 2 / (2 * W) if 2 * abs(o) <= W else slope * max(o, 0.0)
y[n] = v * 10 ** (-r / 20)
return y
x3 = np.concatenate([np.full(4_800, 0.01), np.full(9_600, 1.0), np.full(14_400, 0.01)])
soft6 = compressor(threshold_db=-20.0, ratio=4.0, knee_type=SOFT, knee_width_db=6.0)
lib = mono(x3)
lib.apply_compressor(soft6)
mine = compress_numpy(x3, -20.0, 4.0, 6.0, 5.0, 50.0)
# Same operations in the same order: only last-bit differences remain.
assert np.max(np.abs(mine - lib.to_numpy())) < 1e-12
A sine is not a DC level. Through the hard-knee compressor (attack 10 ms, release 100 ms) a 0 dBFS, 1 kHz sine does not come out at \(-15\) dBFS: the peak detector rises only near each crest and releases in between, so the envelope settles below the peak and the output peaks near \(-14.1\) dBFS. The NumPy model predicts the same number.
sine = np.sin(2 * np.pi * 1_000 * np.arange(fs) / fs)
c10 = compressor(threshold_db=-20.0, ratio=4.0, attack_ms=10.0, release_ms=100.0)
s = mono(sine)
s.apply_compressor(c10)
peak_out = 20 * np.log10(np.max(np.abs(s.to_numpy()[fs // 2:])))
model = compress_numpy(sine, -20.0, 4.0, 0.0, 10.0, 100.0)
print(f"output peak {peak_out:.2f} dBFS")
assert np.max(np.abs(model - s.to_numpy())) < 1e-12
assert abs(peak_out + 14.13) < 0.01 # 0.87 dB above the DC prediction of -15 dBFS
output peak -14.13 dBFS
The limiter and lookahead. A limiter with a \(-6\) dBFS ceiling and a 1 ms attack, on a step from silence to 0 dBFS. Without lookahead the first sample of the step passes untouched (the envelope is still at \(1 - a = 0.02\)), a 6 dB overshoot. With 5 ms of lookahead (\(N_L = 240\) samples) the overshoot is \(-20\log_{10}(1 - a^{241}) = 0.0575\) dB. A NumPy model with a max-hold over the next \(N_L\) reductions reproduces the library exactly.
x_lim = np.concatenate([np.zeros(960), np.ones(2_400)])
def limit_numpy(x, C, attack_ms, release_ms, lookahead_ms, sr=fs):
a_att, a_rel = np.exp(-1 / (attack_ms * 1e-3 * sr)), np.exp(-1 / (release_ms * 1e-3 * sr))
D = round(lookahead_ms * 1e-3 * sr)
e, r = 0.0, []
for v in np.concatenate([x, np.zeros(D)]): # the detector sees zeros past the end
a = a_att if abs(v) > e else a_rel
e = a * e + (1 - a) * abs(v)
level = 20 * np.log10(e) if e > 0 else -80.0
r.append(max(level - C, 0.0))
r = np.array(r)
held = np.array([r[n:n + D + 1].max() for n in range(len(x))])
return x * 10 ** (-held / 20)
peaks = {}
for la in (0.0, 5.0):
y = mono(x_lim)
y.apply_limiter(limiter(ceiling_db=-6.0, attack_ms=1.0, release_ms=100.0, lookahead_ms=la))
assert np.max(np.abs(y.to_numpy() - limit_numpy(x_lim, -6.0, 1.0, 100.0, la))) < 1e-12
peaks[la] = 20 * np.log10(np.max(np.abs(y.to_numpy())))
a1 = np.exp(-1 / (0.001 * fs))
predicted = -20 * np.log10(1 - a1**241)
assert abs(peaks[0.0]) < 1e-9 # 0 dBFS: 6 dB over the ceiling
assert abs(predicted - 0.0575) < 1e-3
assert abs(peaks[5.0] - (-6.0 + predicted)) < 1e-9
print({k: round(float(v), 4) for k, v in peaks.items()})
{0.0: 0.0, 5.0: -5.9425}
Ask the library to explain
CompressorConfig.explain(sample_rate) and LimiterConfig.explain(sample_rate) give the
smoothing coefficients, the 10-90 % times, a table of the static curve, and a note when there
is no lookahead.
doc = cfg.explain(48_000.0)
doc
Compressor
Above -20 dBFS the compressor lets the level rise only 1 dB per 4 dB of input; the gain follows the signal with a 5 ms attack and 50 ms release, then 0 dB of make-up gain is added.
Formulas
Overshoot above the threshold (dB):
$$ o = L - T $$
Hard-knee gain reduction (dB): above T the output rises only 1/R dB per input dB:
$$ GR = \begin{cases} 0 & o \le 0 \ o \left(1 - \frac{1}{R}\right) & o > 0 \end{cases} $$
Output: the held gain reduction (see Lookahead below) and the make-up gain applied to the sample:
$$ y[n] = x[n] \cdot 10^{\frac{M - \overline{GR}[n]}{20}} $$
Peak detector:
$$ x_d[n] = |x[n]| $$
Envelope follower: attack coefficient while the detector is above the envelope, release otherwise:
$$ e[n] = \alpha , e[n-1] + (1 - \alpha) , x_d[n], \quad \alpha = \begin{cases} \alpha_A & x_d[n] > e[n-1] \ \alpha_R & x_d[n] \le e[n-1] \end{cases} $$
One-pole coefficient for a time constant τ (seconds); after τ the envelope has covered 63.2% of a step:
$$ \alpha = e^{-\frac{1}{\tau f_s}} $$
Envelope level in dBFS (-80 dBFS when e = 0):
$$ L[n] = 20 \log_{10} e[n] $$
Lookahead: each sample receives the largest reduction computed over the next D samples, so the gain starts falling before a peak arrives (the output is re-aligned with the input):
$$ \overline{GR}[n] = \max_{0 \le k \le D} GR[n + k], \quad D = \mathrm{round}(t_{la} f_s) $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $T$ | threshold | -20 dBFS | | $R$ | ratio | 4 : 1 | | $M$ | make-up gain | 0 dB | | $W$ | knee width | 0 (hard knee) dB | | $\tau_A$ | attack time | 5 ms | | $\tau_R$ | release time | 50 ms | | $t_{la}$ | lookahead time | 0 ms |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | Attack coefficient | $\alpha_A$ = 0.995842 | $e^{-1/(\tau_A f_s)}$ | | Release coefficient | $\alpha_R$ = 0.999583 | $e^{-1/(\tau_R f_s)}$ | | Attack 10-90% rise time | $\tau_A \ln 9$ = 10.9861 ms | $\tau_A \ln 9$ | | Release 90-10% fall time | $\tau_R \ln 9$ = 109.861 ms | $\tau_R \ln 9$ | | Lookahead | $D$ = 0 samples | $\mathrm{round}(t_{la} f_s / 1000)$ | | Gain reduction at 0 dBFS | $GR(0)$ = 15 dB | $\text{static curve at } L = 0$ | | Output for a 0 dBFS input | $M - GR(0)$ = -15 dBFS | $M - GR(0)$ | | Slope above the knee | $1/R$ = 0.25 dB/dB | $1/R$ |
Static curve (calculate_compression_gain)
| Input level (dBFS) | Gain reduction (dB) | Output level (dBFS) | |—|—|—| | -32 | 0 | -32 | | -26 | 0 | -26 | | -20 | 0 | -20 | | -14 | 4.5 | -18.5 | | -8 | 9 | -17 | | 0 | 15 | -15 |
Trade-offs
A fast attack reduces transients and softens them; a slow attack lets them pass at close to their original level.
A fast release restores the level quickly but can cause audible pumping; a slow release is smoother but keeps reducing the gain of the material that follows.
RMS detection follows loudness; peak detection follows the waveform and reacts to short spikes.
Warnings
Info: No lookahead: the gain reacts only after the envelope has risen, so the start of each transient passes partly unreduced (for roughly the attack time). Hint: A lookahead of about the attack time starts the gain reduction before each peak.
See also
Apply:
audio_samples::AudioDynamicRange::apply_compressorApply (Python):
audio_samples.AudioSamples.apply_compressorGain computer:
audio_samples::operations::dynamic_range::calculate_compression_gainPython:
audio_samples.CompressorConfig.explain
assert abs(doc.quantity("Attack 10-90% rise time") - 10.986) < 1e-3
assert abs(doc.quantity("Attack coefficient") - np.exp(-1 / 240)) < 1e-12
assert abs(doc.quantity("Gain reduction at 0 dBFS") - 15.0) < 1e-9
assert doc.has_warning_containing("No lookahead")
lim_doc = mono(np.zeros(480)).explain(aus.LimiterConfig.transparent())
assert lim_doc.quantity("Gain reduction for a 0 dBFS envelope") is not None
# transparent() sets isp_limiting (true-peak detection), and the explainer notes it.
for w in lim_doc.warnings:
print(f"[{w['level']}] {w['message']}")
[info] isp_limiting detects true (inter-sample) peaks from a 4x oversampled detector signal, which can read a peak up to 0.7 dB low near the Nyquist frequency.
Exercises
1. Read the curve. With \(T = -18\) dBFS and \(R = 3\) (hard knee), predict the output level for
a \(-2\) dBFS input, then check with get_compression_curve. Put it in answer.
answer = None # TODO
# Solution
c = compressor(threshold_db=-18.0, ratio=3.0)
answer = probe.get_compression_curve(c, np.array([-2.0]))[0]
# 16 dB over the threshold becomes 16/3 = 5.33 dB over it.
assert abs(answer - (-18 + 16 / 3)) < 1e-12 and abs(answer + 12.67) < 0.005
2. Knee at the threshold. For a 6 dB soft knee and \(R = 3\), predict the reduction exactly at
\(L = T\). Put it in answer (dB).
answer = None # TODO
# Solution
c = compressor(threshold_db=-18.0, ratio=3.0, knee_type=SOFT, knee_width_db=6.0)
answer = -18.0 - probe.get_compression_curve(c, np.array([-18.0]))[0]
assert abs(answer - (1 - 1 / 3) * 6 / 8) < 1e-12 # 0.5 dB
3. Attack in samples. At 16 kHz with \(\tau_A = 10\) ms, predict \(a\) and how many samples an
envelope follower needs to reach 63.2 % of a step from 0 to 1. Put the number of samples in
answer.
answer = None # TODO
# Solution
a16 = np.exp(-1 / 160)
assert abs(a16 - 0.99377) < 1e-5
f16 = aus.EnvelopeFollower(10.0, 100.0, 16_000.0, PEAK)
env16, _ = mono(np.ones(1_000), 16_000).attack_decay_envelope(f16, PEAK)
# After k updates the envelope is 1 - a^k; tiny tolerance for the comparison at k = 160.
answer = int(np.argmax(env16 >= 1 - np.exp(-1) - 1e-12)) + 1
assert answer == 160 # 10 ms
4. Required lookahead. For the limiter above (1 ms attack at 48 kHz), how much lookahead in
samples keeps the overshoot below 0.01 dB? Put the smallest \(N_L\) in answer.
answer = None # TODO
# Solution
overshoot = lambda n: -20 * np.log10(1 - a1 ** (n + 1))
answer = next(n for n in range(2_000) if overshoot(n) < 0.01)
# a^(N_L+1) < 1 - 10^(-0.0005) => N_L + 1 > 324.8.
assert answer == 324 and overshoot(323) >= 0.01
print(f"{answer} samples = {answer / fs * 1e3:.2f} ms")
324 samples = 6.75 ms
Common pitfalls
Attack and release are time constants, not “time to full reduction”: 63.2 % after \(\tau\), 10-90 % in \(2.2\,\tau\).
Detector choice shifts the threshold. An RMS detector reads a sine 3.01 dB below its peak, and a slow peak detector reads it lower still (the \(-14.1\) dBFS above). The default
CompressorConfiguses RMS.dB reference. Thresholds are in dBFS of the envelope, not of individual samples or of loudness (LUFS).
A limiter is not a brick wall. The start of every transient passes; lookahead shrinks the overshoot but does not remove it.
isp_limitingmakes the detector read true (inter-sample) peaks instead of sample peaks.Presets are inconsistent in Python:
CompressorConfig.vocal,.busand.drumare class attributes butCompressorConfig.default()and allLimiterConfigpresets are methods.get_gain_reductionignores lookahead;apply_compressorapplies the max-hold.The processing methods work in place and return
None.
See also
Rust guide chapter: https://docs.rs/audio_samples/latest/audio_samples/guide/c12_dynamics/index.html (available from the next release; until then build the docs locally with
cargo doc --features educational,full_no_plotting --open), theoperations::dynamic_rangemodule docs (full derivation), and the labexamples/tutorial_12_dynamics.rs.Python API:
AudioSamples.apply_compressor,AudioSamples.apply_limiter,AudioSamples.get_compression_curve,AudioSamples.get_gain_reduction,AudioSamples.attack_decay_envelope,audio_samples.CompressorConfig,audio_samples.LimiterConfig,audio_samples.EnvelopeFollower.Previous: 11. Short-time energy, zero crossings and VAD; next: 13. Onsets and tempo.
References
Giannoulis, D., Massberg, M. and Reiss, J. D. (2012). Digital dynamic range compressor design: a tutorial and analysis. Journal of the Audio Engineering Society, 60(6), 399-408.