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