{ "cells": [ { "cell_type": "markdown", "id": "c000", "metadata": {}, "source": [ "# 02. Quantisation and dither\n", "\n", "Sampling (notebook 01) makes time discrete; quantisation makes amplitude discrete. A 16-bit file\n", "can store only 65 536 different values, so every sample is rounded, and the rounding error\n", "behaves like added noise. The level of that noise, and whether it is heard as noise or as\n", "distortion, determine how many bits a recording needs and how to reduce bit depth without\n", "degrading quiet passages such as a fading voice or a reverb tail.\n", "\n", "**Learning outcomes.** After working through this notebook you can\n", "\n", "* describe the library's (asymmetric) integer/float scaling and requantise a signal by hand,\n", " bit for bit;\n", "* derive the $6.02\\,b + 1.76$ dB SQNR rule and confirm it by measurement;\n", "* explain why quantising a quiet signal produces distortion, and remove it with TPDF dither;\n", "* predict the noise cost of dither (4.77 dB)." ] }, { "cell_type": "code", "execution_count": null, "id": "c001", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import audio_samples as aus\n", "from audio_samples.utils import snr\n", "\n", "rng = np.random.default_rng(seed=2026)\n", "F64 = np.dtype(\"float64\")\n", "I16, U8, AS_F64 = aus.SampleType.I16, aus.SampleType.U8, aus.SampleType.F64\n", "\n", "def through(x, fmt, fs=16_000):\n", " # Convert a float array to the sample format `fmt` and back to float64 with the library.\n", " return aus.AudioSamples.new_mono(np.asarray(x, dtype=float), sample_rate=fs).to_format(fmt).to_format(AS_F64).to_numpy()\n", "\n", "def power(v):\n", " return float(np.mean(np.square(v)))" ] }, { "cell_type": "markdown", "id": "c002", "metadata": {}, "source": [ "## Concept\n", "\n", "**Uniform quantisation** maps a sample $x$ on the normalised scale $[-1, 1]$ to an integer code\n", "$q$ and back. This library uses an *asymmetric* mapping so that both $-1$ and $+1$ are reachable\n", "and the integer round trip is exact:\n", "\n", "$$q = \\mathrm{round}(x \\cdot 2^{b-1}) \\;\\; (x < 0), \\qquad q = \\mathrm{round}\\big(x \\cdot (2^{b-1} - 1)\\big) \\;\\; (x \\ge 0)$$\n", "\n", "where $b$ is the word length in bits, $x$ is clamped to $[-1, 1]$ and $\\mathrm{round}$ rounds\n", "half away from zero. Converting back divides by the same factors. The **step size** (one\n", "least-significant bit, LSB, in units of full scale) is therefore\n", "\n", "$$\\Delta = 2^{1-b} \\;\\; \\text{(below zero)}, \\qquad \\Delta_+ = \\frac{1}{2^{b-1} - 1} \\;\\; \\text{(above zero)}$$\n", "\n", "For $b = 16$: $\\Delta = 1/32768$ and $\\Delta_+ = 1/32767$, a difference of 0.003 %. (A symmetric\n", "mapping divides by $2^{b-1}$ on both sides.)\n", "\n", "**Quantisation noise.** If the signal is busy enough, the rounding error $e = \\hat{x} - x$ is\n", "spread uniformly over one step, $[-\\Delta/2, \\Delta/2]$, so its power is\n", "\n", "$$\\sigma_e^2 = \\frac{\\Delta^2}{12}$$\n", "\n", "in units of full scale squared, where $\\hat{x}$ is the quantised value.\n", "\n", "**SQNR of a full-scale sine.** A sine of amplitude 1 has power $1/2$. With $\\Delta = 2/2^b$:\n", "\n", "$$\\mathrm{SQNR} = 10 \\log_{10} \\frac{1/2}{\\Delta^2/12} = 10\\log_{10}\\!\\left(\\tfrac{3}{2} \\, 4^{b}\\right) \\approx 6.02\\,b + 1.76 \\ \\mathrm{dB}$$\n", "\n", "Each extra bit adds about 6 dB. A signal peaking $L$ dB below full scale loses $L$ dB of SQNR.\n", "\n", "**Dither.** For a quiet signal only a few steps tall, the error is *not* uniform noise: it is a\n", "deterministic function of the signal, so it repeats with the signal and shows up as harmonics\n", "(distortion). **TPDF dither** adds, before rounding, a random value $d = u_1 + u_2$ where $u_1,\n", "u_2$ are independent and uniform on $[-\\Delta/2, \\Delta/2)$; $d$ has a triangular density on\n", "$[-\\Delta, \\Delta]$ and power $\\Delta^2/6$. The total error power becomes\n", "\n", "$$\\sigma^2_{e,\\mathrm{TPDF}} = \\frac{\\Delta^2}{12} + \\frac{\\Delta^2}{6} = \\frac{\\Delta^2}{4}$$\n", "\n", "i.e. $10\\log_{10} 3 \\approx 4.77$ dB more noise, but the error's mean and variance no longer\n", "depend on the signal: the distortion is replaced by steady noise. The library applies **no** dither in any\n", "conversion, so this notebook implements it with NumPy." ] }, { "cell_type": "markdown", "id": "c003", "metadata": {}, "source": [ "## With the library\n", "\n", "The library's convention, step sizes and the SQNR at 16 bits through the `int16` conversion\n", "(`AudioSamples.to_format(SampleType.I16)`), measured with `audio_samples.utils.snr`:" ] }, { "cell_type": "code", "execution_count": null, "id": "c004", "metadata": {}, "outputs": [], "source": [ "# The asymmetric mapping: -1 -> -32768, +1 -> 32767.\n", "edge = aus.AudioSamples.new_mono(np.array([-1.0, -0.5, 0.0, 0.5, 1.0]), sample_rate=16_000)\n", "codes = edge.to_format(I16).to_numpy()\n", "print(codes)\n", "assert codes.tolist() == [-32768, -16384, 0, 16384, 32767]\n", "# ... and back: 16384 / 32767 is not exactly 0.5.\n", "print(edge.to_format(I16).to_format(AS_F64).to_numpy())\n", "assert abs(through([0.5], I16)[0] - 16384 / 32767) < 1e-15\n", "\n", "# Full-scale 997 Hz sine at 48 kHz, 1 s, rounded to int16 and back.\n", "x = aus.sine_wave(997.0, 1.0, sample_rate=48_000, dtype=F64)\n", "back = x.to_format(I16).to_format(AS_F64)\n", "err = aus.AudioSamples.new_mono(back.to_numpy() - x.to_numpy(), sample_rate=48_000)\n", "measured = snr(x, err)\n", "predicted = 10 * np.log10(1.5 * 4.0 ** 16)\n", "print(f\"SQNR at 16 bits: predicted {predicted:.2f} dB, measured {measured:.2f} dB\")\n", "assert abs(predicted - 98.09) < 0.01\n", "assert abs(measured - predicted) < 0.05 # measured: 98.10 dB\n", "assert abs(measured - 98.10) < 0.005" ] }, { "cell_type": "markdown", "id": "c005", "metadata": {}, "source": [ "Now the quiet case: a 997 Hz sine of amplitude 2.5 LSB (5 LSB peak to peak) at 16 kHz, rounded to `int16` with and\n", "without TPDF dither. The dither is two independent uniform variables on $[-\\Delta/2, \\Delta/2)$\n", "from NumPy's generator. (The library's `aus.white_noise(..., amplitude=A, seed=...)` is also\n", "uniform on $[-A, A)$ and gives the same result with $A = \\Delta/2$; exercise 3 uses NumPy too.)" ] }, { "cell_type": "code", "execution_count": null, "id": "c006", "metadata": {}, "outputs": [], "source": [ "fs = 16_000\n", "lsb = 1.0 / 32768.0\n", "xq = aus.sine_wave(997.0, 1.0, sample_rate=fs, amplitude=2.5 * lsb, dtype=F64).to_numpy()\n", "\n", "dither = rng.uniform(-lsb / 2, lsb / 2, xq.size) + rng.uniform(-lsb / 2, lsb / 2, xq.size)\n", "e_plain = through(xq, I16) - xq\n", "e_dith = through(xq + dither, I16) - xq\n", "\n", "ratio_plain = power(e_plain) / (lsb ** 2 / 12)\n", "ratio_dith = power(e_dith) / (lsb ** 2 / 12)\n", "print(f\"error power / (LSB^2/12): undithered {ratio_plain:.2f}, dithered {ratio_dith:.2f}\")\n", "# Dithered error power is LSB^2/4 = 3 x (LSB^2/12); a 16 000-sample estimate is good to ~2 %.\n", "assert abs(ratio_dith - 3.0) < 0.1\n", "assert abs(ratio_plain - 1.23) < 0.005 # deterministic: no randomness involved\n", "\n", "def spur_db(e):\n", " # Error power in the 3rd-harmonic bin (2991 Hz) relative to the mean bin power, in dB.\n", " m = aus.AudioSamples.new_mono(e, sample_rate=fs).rfft(16_000)[0] # 1 Hz bins (magnitudes)\n", " return 10 * np.log10(m[2991] ** 2 / np.mean(m ** 2))\n", "\n", "def corr(e):\n", " return np.sum(e * xq) / (np.sqrt(power(e) * power(xq)) * xq.size)\n", "\n", "print(f\"3rd-harmonic spur: {spur_db(e_plain):+.1f} dB undithered, {spur_db(e_dith):+.1f} dB dithered\")\n", "print(f\"error/signal correlation: {corr(e_plain):+.3f} undithered, {corr(e_dith):+.3f} dithered\")\n", "assert abs(spur_db(e_plain) - 31.9) < 0.05 # a clear harmonic\n", "assert spur_db(e_dith) < 3.0 # noise only\n", "assert abs(corr(e_plain) - (-0.516)) < 0.001 # half correlated with the signal\n", "assert abs(corr(e_dith)) < 0.03 # uncorrelated" ] }, { "cell_type": "code", "execution_count": null, "id": "c007", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 2, figsize=(8, 3))\n", "n = np.arange(64)\n", "axes[0].plot(n / fs * 1000, xq[:64] / lsb, label=\"input\")\n", "axes[0].step(n / fs * 1000, (xq + e_plain)[:64] / lsb, where=\"mid\", label=\"int16, no dither\")\n", "axes[0].set(xlabel=\"Time (ms)\", ylabel=\"Amplitude (LSB)\", title=\"A 2.5 LSB sine\")\n", "axes[0].legend(fontsize=7)\n", "f = np.arange(8001)\n", "for e, lab in [(e_plain, \"no dither\"), (e_dith, \"TPDF dither\")]:\n", " m = aus.AudioSamples.new_mono(e, sample_rate=fs).rfft(16_000)[0]\n", " axes[1].plot(f, 20 * np.log10(m / 16_000 + 1e-20), lw=0.6, label=lab)\n", "axes[1].set(xlabel=\"Frequency (Hz)\", ylabel=\"Error level (dB re full scale)\", title=\"Error spectrum\",\n", " ylim=(-180, -100))\n", "axes[1].legend(fontsize=7)\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c008", "metadata": {}, "source": [ "Dither tripled the error power, but the result is better: the undithered error is half\n", "correlated with the signal and is concentrated at harmonics of 997 Hz, which are heard as\n", "distortion, while the dithered error has a flat spectrum." ] }, { "cell_type": "markdown", "id": "c009", "metadata": {}, "source": [ "## How it works\n", "\n", "Write the requantiser in NumPy with the same convention, check that it is *bit-identical* to the\n", "library's 16-bit and 8-bit (`u8`, offset binary) round trips, then measure SQNR at several word\n", "lengths against $6.02\\,b + 1.76$.\n", "\n", "Note that `np.round` rounds half to **even** (`np.round(2.5) == 2.0`), while the library rounds\n", "half away from zero, so we write that rounding explicitly." ] }, { "cell_type": "code", "execution_count": null, "id": "c010", "metadata": {}, "outputs": [], "source": [ "def round_half_away(v):\n", " return np.sign(v) * np.floor(np.abs(v) + 0.5)\n", "\n", "def requantise(x, b):\n", " half = 2.0 ** (b - 1)\n", " x = np.clip(x, -1.0, 1.0)\n", " return np.where(x < 0, round_half_away(x * half) / half, round_half_away(x * (half - 1)) / (half - 1))\n", "\n", "assert np.round(2.5) == 2.0 and round_half_away(2.5) == 3.0\n", "# A tie: 2.5 steps on the positive side rounds away from zero to 3 in the library.\n", "assert through([2.5 / 32767], I16)[0] * 32767 == 3.0\n", "\n", "xs = x.to_numpy() # full-scale 997 Hz at 48 kHz\n", "assert np.allclose(through(xs, I16, fs=48_000), requantise(xs, 16), rtol=0, atol=1e-15)\n", "assert np.allclose(through(xs, U8, fs=48_000), requantise(xs, 8), rtol=0, atol=1e-15)\n", "\n", "p_signal = power(xs)\n", "measured_sqnr = {}\n", "for b, expected in [(4, 25.62), (8, 49.98), (12, 74.03), (16, 98.10)]:\n", " sqnr = 10 * np.log10(p_signal / power(requantise(xs, b) - xs))\n", " measured_sqnr[b] = sqnr\n", " rule = 6.02 * b + 1.76\n", " print(f\"{b:2d} bits: measured {sqnr:6.2f} dB, rule {rule:6.2f} dB\")\n", " assert abs(sqnr - expected) < 0.01\n", " # The rule of thumb: within 0.25 dB at 4 and 8 bits (the error is less uniform when the steps\n", " # are coarse), within 0.05 dB from 12 bits up.\n", " assert abs(sqnr - rule) < (0.05 if b >= 12 else 0.25)" ] }, { "cell_type": "markdown", "id": "c011", "metadata": {}, "source": [ "At 16 bits the effect of the asymmetry is small. The positive-half step is larger by a factor\n", "$32768/32767$, i.e. by $3.05\\times10^{-5}$ (0.003 %); averaging the two halves' noise powers\n", "changes the noise by about $3\\times10^{-5}$, about 0.0001 dB:" ] }, { "cell_type": "code", "execution_count": null, "id": "c012", "metadata": {}, "outputs": [], "source": [ "eps = 32768 / 32767 - 1\n", "assert abs(eps - 3.05e-5) < 1e-7\n", "assert abs(100 * eps - 0.003) < 0.0001 # 0.003 %\n", "noise_ratio = (1 + (1 + eps) ** 2) / 2\n", "assert abs(noise_ratio - 1 - 3.05e-5) < 1e-7\n", "assert 10 * np.log10(noise_ratio) < 1.4e-4 # about 0.0001 dB\n", "# The numbers quoted in the Concept section:\n", "assert 2 ** 16 == 65_536\n", "assert abs(10 * np.log10(3) - 4.77) < 0.005" ] }, { "cell_type": "markdown", "id": "c013", "metadata": {}, "source": [ "Integer-to-integer conversions are a separate path. Narrowing `int32` to `int16` *shifts bits*\n", "(truncating towards $-\\infty$, a $-\\tfrac12$ LSB bias), while conversions **to `u8`** rescale with\n", "the asymmetric factors and round to nearest. Go through `float64` if you want rounding\n", "everywhere." ] }, { "cell_type": "code", "execution_count": null, "id": "c014", "metadata": {}, "outputs": [], "source": [ "v = np.array([-65537, -65536, -1, 0, 65535, 65536], dtype=np.int32)\n", "i32 = aus.AudioSamples.new_mono(v, sample_rate=8_000)\n", "narrowed = i32.to_format(I16).to_numpy()\n", "print(narrowed)\n", "assert narrowed.tolist() == (v >> 16).tolist() == [-2, -1, -1, 0, 0, 1]\n", "\n", "# int16 -> u8 rounds: 255/32767 * 127 = 0.99 -> 1, whereas a bit shift (255 >> 8) would give 0.\n", "i16 = aus.AudioSamples.new_mono(np.array([-1, 128, 255], dtype=np.int16), sample_rate=8_000)\n", "centred = i16.to_format(U8).to_numpy().astype(int) - 128\n", "assert centred.tolist() == [0, 0, 1]" ] }, { "cell_type": "markdown", "id": "c015", "metadata": {}, "source": [ "## Ask the library to explain\n", "\n", "`aus.explain.quantisation(bits)` states the convention, the step sizes, the noise level, the SQNR\n", "and the SQNR you would get with TPDF dither.\n", "\n", "**Which dBFS?** dBFS means decibels relative to digital full scale, an amplitude of 1. A *peak*\n", "level is $20\\log_{10}$ of the peak amplitude (dBFS peak); an *RMS* level is $20\\log_{10}$ of the\n", "RMS, i.e. $10\\log_{10}$ of the mean square (dBFS RMS). A full-scale sine is therefore 0 dBFS peak\n", "but $-3.01$ dBFS RMS. The explainer's \"Noise level\", $10\\log_{10}(\\Delta^2/12) = -101.10$ dB at\n", "16 bits, is in dB re 1, the power of a full-scale DC level: an RMS level in this convention. AES17 instead calibrates RMS levels so that a\n", "full-scale sine reads 0 dBFS, which adds 3.01 dB: the same noise is $-98.09$ dBFS (AES17)." ] }, { "cell_type": "code", "execution_count": null, "id": "c016", "metadata": {}, "outputs": [], "source": [ "doc = aus.explain.quantisation(16)\n", "assert doc.quantity(\"Quantisation levels\") == 65_536\n", "assert doc.quantity(\"Step size (negative half)\") == 1 / 32768\n", "assert abs(doc.quantity(\"Step size (positive half)\") - 1 / 32767) < 1e-18\n", "sqnr16 = doc.quantity(\"SQNR (full-scale sine)\")\n", "assert abs(sqnr16 - 98.09) < 0.01 and abs(doc.quantity(\"Rule of thumb\") - 98.09) < 0.01\n", "assert abs(sqnr16 - doc.quantity(\"SQNR with TPDF dither\") - 4.77) < 0.01 # 10 log10 3\n", "assert abs(doc.quantity(\"Noise level\") - (-101.10)) < 0.01 # dB re 1 (full-scale DC)\n", "assert abs(10 * np.log10((1 / 32768) ** 2 / 12) - doc.quantity(\"Noise level\")) < 1e-9\n", "assert abs(10 * np.log10(0.5) + 3.01) < 0.01 # full-scale sine, RMS\n", "assert abs(doc.quantity(\"Noise level\") - 10 * np.log10(0.5) - (-98.09)) < 0.01 # AES17\n", "assert doc.has_warning_containing(\"i16\")\n", "doc" ] }, { "cell_type": "markdown", "id": "c017", "metadata": {}, "source": [ "## Exercises\n", "\n", "1. How many bits do you need for an SQNR of at least 90 dB on a full-scale sine? Predict from the\n", " rule, then confirm by measurement (with `requantise`) at that word length and one bit fewer." ] }, { "cell_type": "code", "execution_count": null, "id": "c018", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c019", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = int(np.ceil((90 - 1.76) / 6.02)) # 14.66 -> 15 bits\n", "assert answer == 15\n", "sqnr_at = lambda b: 10 * np.log10(power(xs) / power(requantise(xs, b) - xs))\n", "assert sqnr_at(15) >= 90.0 and sqnr_at(14) < 90.0" ] }, { "cell_type": "markdown", "id": "c020", "metadata": {}, "source": [ "2. A sine peaks at $-20$ dBFS peak (amplitude 0.1) and is stored as `int16`. Predict its SQNR in dB,\n", " then measure it with the library conversion and `snr`." ] }, { "cell_type": "code", "execution_count": null, "id": "c021", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c022", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = 98.09 - 20.0 # 78.09 dB\n", "quiet = aus.sine_wave(997.0, 1.0, sample_rate=48_000, amplitude=0.1, dtype=F64)\n", "e = aus.AudioSamples.new_mono(quiet.to_format(I16).to_format(AS_F64).to_numpy() - quiet.to_numpy(),\n", " sample_rate=48_000)\n", "assert abs(snr(quiet, e) - answer) < 0.1" ] }, { "cell_type": "markdown", "id": "c023", "metadata": {}, "source": [ "3. Predict how much TPDF dither lowers the SQNR (in dB) of a loud sine (amplitude 0.9) quantised\n", " to 8 bits, and measure it." ] }, { "cell_type": "code", "execution_count": null, "id": "c024", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c025", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = 10 * np.log10(3) # 4.77 dB\n", "lsb8 = 1.0 / 128.0 # one step at 8 bits\n", "loud = aus.sine_wave(997.0, 1.0, sample_rate=48_000, amplitude=0.9, dtype=F64).to_numpy()\n", "d = rng.uniform(-lsb8 / 2, lsb8 / 2, loud.size) + rng.uniform(-lsb8 / 2, lsb8 / 2, loud.size)\n", "sq = lambda y: 10 * np.log10(power(loud) / power(y - loud))\n", "penalty = sq(requantise(loud, 8)) - sq(requantise(loud + d, 8))\n", "# Random dither over 48 000 samples: the noise power estimate is good to ~1 %.\n", "assert abs(penalty - answer) < 0.2" ] }, { "cell_type": "markdown", "id": "c026", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "* The library maps integers to floats **asymmetrically** (divide by $2^{b-1}$ below zero, by\n", " $2^{b-1}-1$ above). Compared with a symmetric mapping that divides by $2^{b-1}$ on both sides,\n", " positive samples differ by up to about $3\\times10^{-5}$.\n", "* `np.round` rounds half to even; the library rounds half away from zero.\n", "* Integer-to-integer narrowing between signed types shifts bits (truncates towards $-\\infty$);\n", " conversions to `u8` round. Go through `float64` if you want rounding everywhere.\n", "* No dither is applied by any conversion; add it yourself before reducing the bit depth of quiet\n", " material.\n", "* $6.02\\,b + 1.76$ dB is for a **full-scale sine**. Speech peaks well below full scale and has a\n", " high crest factor; its SQNR is much lower.\n", "* `aus.white_noise` is *uniform*, not Gaussian: amplitude $A$ gives RMS $A/\\sqrt{3}$.\n", "\n", "## See also\n", "\n", "* Rust guide chapter: [02. Quantisation and dither](https://docs.rs/audio_samples/latest/audio_samples/guide/c02_quantisation_dither/index.html) (available from the next release; until then build the docs locally with `cargo doc --features educational,full_no_plotting --open`)\n", " and the lab `examples/tutorial_02_quantisation_dither.rs`.\n", "* Python API: `AudioSamples.to_format`, `SampleType`, `audio_samples.utils.snr`,\n", " `aus.white_noise`, `aus.explain.quantisation` ([API reference](../api/audio_samples.rst)).\n", "* Previous: [01. Sampling and aliasing](01_sampling_aliasing.ipynb).\n", " Next: [03. The DFT, windows and leakage](03_dft_windows.ipynb)." ] }, { "cell_type": "markdown", "id": "references", "metadata": {}, "source": [ "## References\n", "\n", "* Lipshitz, S. P., Wannamaker, R. A. and Vanderkooy, J. (1992). Quantization and dither: a theoretical survey. *Journal of the Audio Engineering Society*, 40(5), 355-375.\n", "* Oppenheim, A. V. and Schafer, R. W. (2010). *Discrete-Time Signal Processing*, 3rd ed. Pearson. Section 4.8 (quantisation error in A/D conversion)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }