14. Psychoacoustics and codecs
Telephone speech, MP3, AAC and Opus all discard information, in two different ways. Waveform codecs such as G.711 band-limit the speech and compand it: 8 bits per sample, with steps that grow with the amplitude. Perceptual codecs such as MP3, AAC and Opus discard far more, because the ear cannot hear everything that is in the signal: quiet sounds near loud ones are masked, very quiet sounds fall below the threshold of hearing, and perceived loudness grows much more slowly than intensity. This notebook puts numbers on those effects and implements G.711 μ-law companding from the standard.
Learning outcomes. After this notebook you can
distinguish dB SPL from dBFS and explain why a calibration is always an assumption;
convert between Hz and the mel (HTK and Slaney), Bark and ERB scales, and say which mel the library uses where;
evaluate Terhardt’s threshold in quiet and a spreading function for simultaneous masking;
implement μ-law companding and show why it keeps the SNR roughly constant over 40 dB.
Note. The perceptual-codec, Bark, ERB and threshold-of-hearing functions of the Rust crate
(audio_samples::codecs) are not exposed in the Python bindings, so this notebook computes
them with NumPy from the same published formulas (the Rust chapter checks the Rust functions
against the same numbers).
import numpy as np
import matplotlib.pyplot as plt
import librosa
import audio_samples as aus
rng = np.random.default_rng(0)
F64 = np.dtype("float64") # the generators take a numpy dtype instance
Concept
dBFS is not dB SPL. Sound pressure level is an absolute physical quantity,
where \(p\) is the RMS sound pressure in pascals; 1 Pa is 93.98 dB SPL. Digital audio has only dBFS, decibels relative to digital full scale (an amplitude of 1): a peak level is \(20\log_{10}\) of the peak amplitude (dBFS peak) and an RMS level \(20\log_{10}\) of the RMS (dBFS RMS), so a full-scale sine is 0 dBFS peak and \(-3.01\) dBFS RMS. (AES17 instead calibrates RMS levels so that a full-scale sine reads 0 dBFS.) The link between the two is the whole playback chain (converter, amplifier, volume knob, transducer, distance), so a file has no absolute level; a psychoacoustic model that compares a signal with the threshold of hearing must assume a calibration.
Perceptual frequency scales. The ear’s frequency resolution is roughly constant in Hz below about 500 Hz and roughly proportional to frequency above. With \(f\) in Hz:
Mel, HTK form: \(m = 2595 \log_{10}(1 + f/700)\) mel (1000 Hz ≈ 1000 mel). This is what
aus.utils.hz_to_melcomputes. Slaney form (what the library’s mel spectrogram uses): linear, \(m = 3f/200\), below 1 kHz and logarithmic above.Bark (Traunmüller 1990): \(z = 26.81 f / (1960 + f) - 0.53\) Bark (without the paper’s corrections below 2 Bark and above 20.1 Bark). One Bark is about one critical band.
ERB (Glasberg and Moore 1990): the equivalent rectangular bandwidth of the auditory filter at \(f\) is \(\mathrm{ERB}(f) = 24.7 (4.37 f / 1000 + 1)\) Hz; the perceptual coordinate is the ERB-number \(E(f) = 21.4 \log_{10}(1 + 0.00437 f)\) Cam.
Absolute threshold of hearing (Terhardt 1979), in dB SPL with \(k = f/1000\):
High at low frequencies, a minimum of about \(-5\) dB SPL near 3.3 kHz (the ear-canal resonance), and rising again above it: back above 0 dB SPL by 6 kHz and above 20 dB SPL by 12 kHz.
Simultaneous masking. A loud component raises the threshold for components nearby in frequency. On the Bark scale the masked threshold falls off steeply below the masker and more gently above it: masking spreads upwards. The spreading function of Schroeder, Atal and Hall (1979) is
where \(\Delta z\) is the maskee’s Bark position minus the masker’s. Far from the masker its slopes approach \(-10\) dB/Bark above and \(+25\) dB/Bark below. A perceptual coder may add quantisation noise up to the masked threshold without it being audible.
From spreading to a masked threshold. The threshold lies some distance below the spread masker energy. Johnston (1988) puts it \(14.5 + z\) dB below a tonal masker at \(z\) Bark and 5.5 dB below a noise-like one (blending the two with a tonality index). The Rust crate’s masking model uses constant offsets of 14.5 dB and 5.5 dB, a simplification that drops the \(+z\) term: for a tonal masker at \(z = 10\) Bark it places the threshold 10 dB higher than Johnston’s 24.5 dB offset would, so it allows more noise.
Perceptual transform codecs. MP3 (MPEG-1 Layer III) analyses the signal with a hybrid filterbank: a polyphase filterbank followed by a modified discrete cosine transform (MDCT) in each subband. AAC uses an MDCT whose blocks overlap by half, and a psychoacoustic model decides how much quantisation noise each band may carry. Opus’s CELT layer uses a low-overlap MDCT (short window overlaps, for low delay); it codes each band’s energy explicitly and the normalised shape of the band with pyramid vector quantisation, and it has no explicit masking-threshold model. The Rust crate’s teaching codec follows the MDCT-plus-masking outline.
μ-law companding (ITU-T G.711). Uniform quantisation gives quiet talkers a poor SNR (6.02 dB per bit, minus the number of dB by which the signal is below full scale; notebook 02). Companding quantises the logarithm of the amplitude instead. The continuous μ-law curve is
for \(x \in [-1, 1]\). G.711 implements a segmented approximation: a 14-bit linear sample becomes an 8-bit code (sign bit, 3-bit segment, 4-bit mantissa). The magnitude plus a bias of 33 falls in one of 8 segments, each twice as wide as the last, with 16 equal steps per segment: step sizes 2, 4, …, 256 (14-bit units). The one exception is the first step of segment 0, which holds magnitude 0 alone (width 1).
The library’s mu_compress implements this continuous curve (without quantising; it maps 0 to
0), and mu_expand inverts it. This notebook
also writes the curve out with NumPy and checks both against it.
With the library
Mel, two ways. aus.utils.hz_to_mel is the HTK formula and agrees with
librosa.hz_to_mel(..., htk=True); mel_to_hz inverts it.
u = aus.utils
assert abs(u.hz_to_mel(1_000.0) - 1_000.0) < 0.02 # 999.99 mel
for f in (100.0, 1_000.0, 4_000.0):
assert abs(u.hz_to_mel(f) - librosa.hz_to_mel(f, htk=True)) < 1e-9
assert abs(u.mel_to_hz(u.hz_to_mel(f)) - f) < 1e-9
# mel_frequencies is HTK-spaced too.
assert np.allclose(u.mel_frequencies(5, 0.0, 8_000.0),
librosa.mel_frequencies(5, fmin=0.0, fmax=8_000.0, htk=True), atol=1e-9)
# Slaney is a different scale: 1000 Hz is 15 "Slaney mel".
assert abs(librosa.hz_to_mel(1_000.0) - 15.0) < 1e-9
The mel spectrogram, however, uses Slaney filters. Put a pure tone on FFT bin \(k\), find the mel band with the most energy, and compare with the band whose Slaney (and whose HTK) triangle peaks highest at that bin. Below 1 kHz the two scales disagree on dozens of bins; the library always follows Slaney.
sr, n_fft, n_mels = 16_000, 512, 40
spec_params = aus.SpectrogramParams(
aus.StftParams(n_fft=n_fft, hop_size=256, window=aus.WindowType.hanning, centre=True), float(sr))
mel_params = aus.MelParams(n_mels=n_mels, f_min=0.0, f_max=8_000.0)
fb_slaney = librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=0, fmax=8_000, htk=False, norm=None)
fb_htk = librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=0, fmax=8_000, htk=True, norm=None)
agree_slaney = agree_htk = disputed = 0
for k in range(2, 256, 2): # tones exactly on FFT bins
tone = aus.sine_wave(k * sr / n_fft, 0.25, sample_rate=sr, dtype=F64)
mel = np.asarray(tone.mel_spectrogram(spec_params, mel_params, None))
band = np.argmax(mel[:, mel.shape[1] // 2])
s, h = np.argmax(fb_slaney[:, k]), np.argmax(fb_htk[:, k])
if s != h:
disputed += 1
agree_slaney += band == s
agree_htk += band == h
print(f"{disputed} bins where the scales disagree: Slaney matches {agree_slaney}, HTK matches {agree_htk}")
assert disputed > 50 and agree_slaney == disputed and agree_htk == 0
78 bins where the scales disagree: Slaney matches 78, HTK matches 0
μ-law compression and expansion. The library’s mu_compress equals the standard curve
computed with NumPy (\(F(0) = 0\), \(F(\pm 1) = \pm 1\)), and mu_expand inverts it: the composition
is the identity.
mu = 255.0
def mu_law(x, mu=255.0):
return np.sign(x) * np.log1p(mu * np.abs(x)) / np.log1p(mu)
xs = np.array([-0.9, -0.3, -0.01, 0.0, 0.02, 0.5, 1.0])
lib_mu = aus.AudioSamples.new_mono(xs, 8_000).mu_compress(mu)
assert np.allclose(lib_mu.to_numpy(), mu_law(xs), rtol=0, atol=1e-12) # the standard curve
assert lib_mu.to_numpy()[3] == 0.0 and abs(lib_mu.to_numpy()[6] - 1.0) < 1e-12 # F(0) = 0, F(1) = 1
back = lib_mu.mu_expand(mu).to_numpy()
assert np.allclose(back, xs, rtol=0, atol=1e-12) # identity to rounding
How it works
The scales. 1 kHz is 8.53 Bark and 4 kHz is 17.46 Bark; the ERB bandwidth is 132.6 Hz at 1 kHz and 456.5 Hz at 4 kHz; the ERB-number at 1 kHz is 15.62 Cam.
def hz_to_bark(f):
return 26.81 * f / (1960 + f) - 0.53
def bark_to_hz(z):
return 1960 * (z + 0.53) / (26.28 - z)
erb_bandwidth = lambda f: 24.7 * (4.37 * f / 1000 + 1)
erb_number = lambda f: 21.4 * np.log10(1 + 0.00437 * f)
assert abs(hz_to_bark(1_000) - 8.527) < 1e-3 and abs(hz_to_bark(4_000) - 17.46) < 0.01
assert abs(bark_to_hz(hz_to_bark(1_000.0)) - 1_000) < 1e-9
assert abs(erb_bandwidth(1_000) - 132.639) < 1e-3 and abs(erb_bandwidth(4_000) - 456.456) < 1e-3
assert abs(erb_number(1_000) - 15.62) < 0.01
f = np.linspace(20, 8_000, 800)
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(f, librosa.hz_to_mel(f, htk=True) / librosa.hz_to_mel(8_000, htk=True), label="mel (HTK)")
ax.plot(f, librosa.hz_to_mel(f) / librosa.hz_to_mel(8_000), label="mel (Slaney)")
ax.plot(f, hz_to_bark(f) / hz_to_bark(8_000), label="Bark")
ax.plot(f, erb_number(f) / erb_number(8_000), label="ERB-number")
ax.set(xlabel="Frequency (Hz)", ylabel="Scale value / value at 8 kHz",
title="Perceptual scales, normalised at 8 kHz")
ax.legend(fontsize=8)
plt.show()
Threshold of hearing and spreading. Terhardt’s curve is 22.95 dB SPL at 100 Hz, 3.37 dB SPL at 1 kHz, and has its minimum of \(-4.98\) dB SPL near 3.32 kHz. The Schroeder spreading function’s slopes far from the masker are \(-10\) dB/Bark above and \(+25\) dB/Bark below.
def ath(f):
k = np.asarray(f, dtype=float) / 1000
return 3.64 * k**-0.8 - 6.5 * np.exp(-0.6 * (k - 3.3) ** 2) + 1e-3 * k**4
assert abs(ath(100) - 22.95) < 0.01 and abs(ath(1_000) - 3.37) < 0.01 and abs(ath(3_300) + 4.98) < 0.01
assert ath(4_000) < 0 < ath(6_000) and ath(12_000) > 20 # rising again above 3.3 kHz
grid = np.arange(20, 16_001, 10)
i = np.argmin(ath(grid))
assert abs(grid[i] - 3_320) <= 20 and abs(ath(grid)[i] + 4.98) < 0.01
def spread(dz):
return 15.81 + 7.5 * (dz + 0.474) - 17.5 * np.sqrt(1 + (dz + 0.474) ** 2)
upper = (spread(10.0) - spread(8.0)) / 2 # dB per Bark, far above the masker
lower = (spread(-8.0) - spread(-10.0)) / 2 # dB per Bark, far below (rising towards it)
assert abs(upper + 10) < 0.3 and abs(lower - 25) < 0.3
# Johnston's (1988) offsets below a masker at z Bark: 14.5 + z dB (tonal), 5.5 dB (noise).
johnston_tonal = lambda z: 14.5 + z
assert johnston_tonal(10.0) == 24.5 and johnston_tonal(10.0) - 14.5 == 10.0
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
fq = np.geomspace(20, 16_000, 400)
axes[0].semilogx(fq, ath(fq))
axes[0].set(xlabel="Frequency (Hz)", ylabel="Threshold (dB SPL)", ylim=(-10, 80),
title="Threshold in quiet (Terhardt)")
dz = np.linspace(-4, 8, 400)
axes[1].plot(dz, spread(dz))
axes[1].set(xlabel="Maskee - masker (Bark)", ylabel="S (dB)", title="Spreading (Schroeder)")
fig.tight_layout()
plt.show()
G.711 μ-law, from the standard. Encode a 14-bit sample to an 8-bit code and back. The error never exceeds half a step, the code tracks \(127\,F(x)\) to within 2 codes, and the SNR of a sine stays between 34 and 40.5 dB over 40 dB of level, while 8-bit linear PCM starts at \(6.02 \cdot 8 + 1.76 = 49.9\) dB and loses about 40 dB.
def ulaw_encode(x):
mag, sign = (-x, 0x80) if x < 0 else (x, 0x00)
biased = min(min(mag, 8_159) + 33, 8_191) # clip, bias, saturate
seg = next(s for s in range(8) if biased < (64 << s)) # segment 0..7
mant = (biased >> (seg + 1)) & 0x0F # 4-bit mantissa
return ~(sign | (seg << 4) | mant) & 0xFF # G.711 transmits the code inverted
def ulaw_decode(code):
c = ~code & 0xFF
seg, mant = (c >> 4) & 7, c & 0x0F
mag = (((mant << 1) + 33) << seg) - 33 # middle of the step
return -mag if c & 0x80 else mag
assert ulaw_encode(0) == 0xFF # positive zero
assert ulaw_decode(ulaw_encode(8_159)) == 8_031 # largest magnitude
xs14 = np.arange(-8_159, 8_160)
dec = np.array([ulaw_decode(ulaw_encode(int(v))) for v in xs14])
seg = np.array([next(s for s in range(8) if min(abs(int(v)) + 33, 8_191) < (64 << s)) for v in xs14])
assert np.all(np.abs(xs14 - dec) <= 2.0**seg) # at most half a step, 2^seg
# Segment 0: magnitude 0 has a code of its own; then each code covers 2 magnitudes.
codes0 = [ulaw_encode(v) for v in range(31)]
runs = [len(list(g)) for _, g in __import__("itertools").groupby(codes0)]
assert runs == [1] + [2] * 15
pos = np.arange(1, 8_160)
idx = np.array([~ulaw_encode(int(v)) & 0x7F for v in pos]) # segment/mantissa index 0..127
assert np.max(np.abs(idx - 127 * mu_law(pos / 8_159))) < 2.0
def snr_db(level_db, q):
x = 10 ** (level_db / 20) * np.sin(2 * np.pi * 0.1234567 * np.arange(8_000))
return 10 * np.log10(np.sum(x**2) / np.sum((x - q(x)) ** 2))
ulaw_q = lambda x: np.array([ulaw_decode(ulaw_encode(int(round(v * 8_159)))) for v in x]) / 8_159
lin8_q = lambda x: np.round(x * 127) / 127
levels = [0.0, -10.0, -20.0, -30.0, -40.0]
su = np.array([snr_db(l, ulaw_q) for l in levels])
sl = np.array([snr_db(l, lin8_q) for l in levels])
print("mu-law SNR (dB):", np.round(su, 1))
print("8-bit SNR (dB):", np.round(sl, 1))
assert np.all((su >= 34.0) & (su < 40.5))
assert abs(sl[0] - 49.9) < 0.5 and abs(sl[0] - sl[4] - 40.0) < 1.5
assert su[4] > sl[4] + 20
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(levels, su, "o-", label="G.711 mu-law (8 bits)")
ax.plot(levels, sl, "s-", label="linear PCM (8 bits)")
ax.set(xlabel="Sine peak level (dBFS)", ylabel="SNR (dB)", title="Companding keeps the SNR flat")
ax.legend(fontsize=8)
plt.show()
mu-law SNR (dB): [39.7 37.1 38.3 34.5 34.2]
8-bit SNR (dB): [50. 40.5 29.3 20.5 11.1]
Ask the library to explain
There is no explainer for psychoacoustics or codecs. The closest is the quantisation topic, which gives the uniform-quantiser SNR that μ-law improves on for quiet signals: \(6.02 \cdot 8 + 1.76 = 49.9\) dB for a full-scale sine at 8 bits.
doc = aus.explain.quantisation(8)
doc
Quantisation
8-bit quantisation maps each sample to one of 256 levels, 0.0078125 apart on the [-1, 1] scale. For a full-scale sine the rounding noise is 49.9257 dB below the signal.
Formulas
Float to integer as implemented (x clamped to [-1, 1], round half away from zero):
$$ q = \begin{cases} \mathrm{round}(x \cdot 2^{b-1}) & x < 0 \ \mathrm{round}(x \cdot (2^{b-1} - 1)) & x \geq 0 \end{cases} $$
Step size over the full scale [-1, 1):
$$ \Delta = \frac{2}{2^{b}} = 2^{1-b} $$
Noise power of rounding error uniformly distributed in one step:
$$ \sigma_e^2 = \frac{\Delta^2}{12} $$
Signal-to-quantisation-noise ratio of a full-scale sine: signal power 1/2 over noise power Δ²/12:
$$ \mathrm{SQNR} = 10 \log_{10} \frac{6}{\Delta^2} \approx 6.02,b + 1.76 \ \mathrm{dB} $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $b$ | word length | 8 bits | | $\Delta$ | quantisation step | 0.0078125 | | $x$ | sample value on the normalised [-1, 1] scale | | | $q$ | integer code | |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | Quantisation levels | $L$ = 256 | $2^{b}$ | | Step size (negative half) | $\Delta$ = 0.0078125 | $2^{1-b}$ | | Step size (positive half) | $\Delta_+$ = 0.00787402 | $1 / (2^{b-1} - 1)$ | | Noise power | $\sigma_e^2$ = 5.0863e-6 | $\Delta^2 / 12$ | | Noise level | $10 \log_{10} \sigma_e^2$ = -52.936 dB re 1 (power of a full-scale DC level) | $10 \log_{10}(\Delta^2/12)$ | | Noise level (AES17 dBFS) | $10 \log_{10} (2 \sigma_e^2)$ = -49.9257 dBFS (AES17: full-scale sine = 0 dBFS) | $10 \log_{10}(\Delta^2/12) + 10 \log_{10} 2$ | | SQNR (full-scale sine) | $SQNR$ = 49.9257 dB | $10 \log_{10}((1/2)/(\Delta^2/12))$ | | Rule of thumb | $20 \log_{10}(2) , b + 10 \log_{10}(1.5)$ = 49.9257 dB | $\text{exact form of } 6.02,b + 1.76 \text{ (the rounded constants give 0.01 dB less at 16 bits)}$ | | SQNR with TPDF dither | $\mathrm{SQNR}d$ = 45.1545 dB | $\mathrm{SQNR} - 10 \log{10} 3$ |
Trade-offs
Each extra bit halves the step size and raises the SQNR by about 6.02 dB.
Triangular (TPDF) dither of ±1 step adds noise of power Δ²/6, raising total noise to Δ²/4 (about 4.77 dB worse) but making the error independent of the signal, which removes distortion on quiet signals.
This crate’s float-to-integer conversion rounds without dither; add dither yourself before requantising quiet material.
The SQNR formula assumes a full-scale signal; a signal peaking 20 dB below full scale loses 20 dB of SQNR.
Warnings
Info: 8 bits is the word length of this crate’s u8 (offset binary, centred on 128) sample type.
See also
Type conversion:
audio_samples::AudioTypeConversion::to_formatType conversion (Python):
audio_samples.AudioSamples.to_formatPython:
audio_samples.explain.quantisation
assert abs(doc.quantity("Rule of thumb") - 49.92) < 0.01
assert abs(doc.quantity("SQNR (full-scale sine)") - 49.92) < 0.1
assert abs(doc.quantity("SQNR (full-scale sine)") - sl[0]) < 0.5 # our 8-bit measurement
Exercises
1. Bark distance. Predict roughly how many Bark lie between 1 kHz and 4 kHz, then compute
it. Put the difference in answer.
answer = None # TODO
# Solution
answer = hz_to_bark(4_000) - hz_to_bark(1_000)
# About 9 critical bands for two octaves, while 0 to 1 kHz is 8.5 Bark.
assert abs(answer - 8.93) < 0.01
2. Threshold at 50 Hz. Is a 50 Hz tone at 30 dB SPL audible in quiet according to
Terhardt’s formula? Put the threshold (dB SPL) in answer.
answer = None # TODO
# Solution
answer = float(ath(50))
assert abs(answer - 40.0) < 0.1
assert 30 < answer # about 10 dB below threshold: inaudible
3. Smallest and largest μ-law steps. What is the ratio between the largest and the smallest
G.711 step, in dB? Why does this keep the SNR roughly constant? Put the ratio in dB in
answer.
answer = None # TODO
# Solution
steps = [2 << s for s in range(8)]
assert (steps[0], steps[-1]) == (2, 256)
# Check against the codec: adjacent decoded levels differ by the step size.
levels_pos = sorted({ulaw_decode(c) for c in range(256) if ulaw_decode(c) >= 0})
gaps = np.diff(levels_pos)
assert gaps.max() == 256 and gaps[1:].min() == 2 # (the first gap straddles zero)
answer = 20 * np.log10(256 / 2)
# The step grows in proportion to the amplitude, so the noise grows with the signal and the
# SNR stays roughly constant (until the signal falls into segment 0).
assert abs(answer - 42.14) < 0.01
4. Calibration. A recording’s speech peaks at \(-12\) dBFS peak. The playback chain is
calibrated so that a full-scale sine (0 dBFS peak, \(-3.01\) dBFS RMS) plays at 94 dB SPL. What SPL do the speech peaks
correspond to (as a sine of that peak)? Put it in answer.
answer = None # TODO
# Solution
calibration_spl = 94.0 # full-scale sine
sine12 = aus.sine_wave(1_000.0, 1.0, sample_rate=16_000, amplitude=10 ** (-12 / 20), dtype=F64)
full = aus.sine_wave(1_000.0, 1.0, sample_rate=16_000, amplitude=1.0, dtype=F64)
rms_offset = 20 * np.log10(sine12.rms() / full.rms()) # same shape: RMS offset = peak offset
answer = calibration_spl + rms_offset
assert abs(20 * np.log10(sine12.rms()) + 15.01) < 0.01 # its RMS is -15.01 dBFS
assert abs(20 * np.log10(full.rms()) + 3.01) < 0.01 # full-scale sine: -3.01 dBFS RMS
assert abs(answer - 82.0) < 1e-9
# And 1 Pa is 93.98 dB SPL.
assert abs(20 * np.log10(1 / 20e-6) - 93.98) < 0.01
Common pitfalls
dBFS conventions. Some tools quote the RMS of a full-scale sine as 0 dBFS (AES17); this library uses \(20\log_{10}(\text{RMS})\), giving \(-3.01\) dBFS.
“Mel” is ambiguous.
aus.utils.hz_to_mel/mel_to_hz/mel_frequenciesare HTK; the mel spectrogram uses Slaney filters. Ask for the HTK scale (for examplelibrosa.hz_to_mel(f, htk=True)) when comparing withaus.utils.ERB bandwidth vs ERB-number. A bandwidth in Hz is not a perceptual coordinate. Space filters uniformly in ERB-number \(E(f)\), not in Hz: equal steps in \(E\) give bandwidths that grow with \(f\).
Masking spreads upwards in frequency. Check the slopes of any masking model you use.
mu_compressis the continuous curve, not G.711. It applies \(F(x)\) without quantising (mu_law_encodegives quantised codes); the 8-bit segmented codes of G.711 above are a different, piecewise-linear approximation.The library’s perceptual and “Opus” codecs (Rust only) are teaching codecs, not bitstream compatible with MP3 or Opus.
See also
Rust guide chapter: https://docs.rs/audio_samples/latest/audio_samples/guide/c14_psychoacoustics_codecs/index.html (available from the next release; until then build the docs locally with
cargo doc --features educational,full_no_plotting --open) (Bark, ERB, threshold of hearing, masking and the perceptual codec in Rust), and the labexamples/tutorial_14_psychoacoustics_codecs.rs.Python API:
aus.utils.hz_to_mel,aus.utils.mel_to_hz,aus.utils.mel_frequencies,AudioSamples.mel_spectrogram,AudioSamples.mu_compress,AudioSamples.mu_expand,aus.explain.quantisation.Previous: 13. Onsets and tempo; quantisation basics: 02. Quantisation and dither; the mel scale in practice: 10. Cepstrum, mel and MFCC.
References
Terhardt, E. (1979). Calculating virtual pitch. Hearing Research, 1(2), 155-182. (The threshold-in-quiet formula.)
Traunmüller, H. (1990). Analytical expressions for the tonotopic sensory scale. Journal of the Acoustical Society of America, 88(1), 97-100.
Glasberg, B. R. and Moore, B. C. J. (1990). Derivation of auditory filter shapes from notched-noise data. Hearing Research, 47(1-2), 103-138.
Schroeder, M. R., Atal, B. S. and Hall, J. L. (1979). Optimizing digital speech coders by exploiting masking properties of the human ear. Journal of the Acoustical Society of America, 66(6), 1647-1652.
Johnston, J. D. (1988). Transform coding of audio signals using perceptual noise criteria. IEEE Journal on Selected Areas in Communications, 6(2), 314-323.
Slaney, M. (1998). Auditory Toolbox, version 2. Technical Report 1998-010, Interval Research Corporation. (The Slaney mel scale.)
ITU-T Recommendation G.711 (1988). Pulse code modulation (PCM) of voice frequencies.
Valin, J.-M., Vos, K. and Terriberry, T. (2012). Definition of the Opus Audio Codec. RFC 6716, IETF. (CELT and SILK.)