{ "cells": [ { "cell_type": "markdown", "id": "nb07-000", "metadata": {}, "source": [ "# 07. Resampling\n", "\n", "Speech models are trained at 16 kHz, CDs are 44.1 kHz, video is 48 kHz: almost every audio\n", "pipeline converts sample rates somewhere. Without filtering, downsampling folds high frequencies\n", "back into the band as *aliases* and upsampling leaves spectral *images*. This notebook\n", "measures both effects on the library's three quality tiers, compares them with\n", "`scipy.signal.resample_poly`, and rebuilds a windowed-sinc decimator by hand.\n", "\n", "**Learning outcomes.** After this notebook you can\n", "\n", "- predict where an out-of-band component lands after downsampling ($f_a = |f - k f_{out}|$);\n", "- measure alias and image rejection in dB with a single DFT bin;\n", "- explain why naive decimation aliases, and how the `fast`, `medium` and `high` tiers trade\n", " bandwidth and rejection for speed;\n", "- build a windowed-sinc decimator in NumPy and check it against the library and SciPy." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-001", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import scipy.signal as ss\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\n", "Q = aus.ResamplingQuality\n", "\n", "\n", "def amplitude(x, f, fs):\n", " # Amplitude of the component at f Hz from one DFT bin (exact for whole periods).\n", " n = np.arange(len(x))\n", " return 2 * np.abs(np.sum(x * np.exp(-2j * np.pi * f * n / fs))) / len(x)\n", "\n", "\n", "def level_db(x, f, fs, ref):\n", " return 20 * np.log10(amplitude(x, f, fs) / ref)" ] }, { "cell_type": "markdown", "id": "nb07-002", "metadata": {}, "source": [ "## Concept\n", "\n", "**Ratio.** Converting from $f_{in}$ to $f_{out}$ (both in Hz) has the dimensionless ratio\n", "\n", "$$r = f_{out} / f_{in}$$\n", "\n", "The output can only represent frequencies below its Nyquist frequency $f_{out}/2$.\n", "\n", "**Downsampling and aliasing.** Keeping every $q$-th sample ($r = 1/q$) samples the signal\n", "again at $f_{out}$. A component at $f$ Hz above $f_{out}/2$ reappears at\n", "\n", "$$f_a = |f - k f_{out}|$$\n", "\n", "where $k$ is the integer that brings $f_a$ into $[0, f_{out}/2]$ (notebook 01). Once folded it\n", "is indistinguishable from real content, so a resampler must **low-pass filter before\n", "decimating**, with a cutoff at or below $\\min(f_{in}, f_{out})/2$.\n", "\n", "**Upsampling and imaging.** Raising the rate by $L$ can be modelled as inserting $L - 1$ zeros\n", "between samples, which leaves copies (*images*) of the spectrum at $k f_{in} \\pm f$, followed by\n", "a low-pass *interpolation* filter that removes them.\n", "\n", "**Ideal band-limited interpolation.** A band-limited signal is fully described by its samples;\n", "its value at time $t$ (seconds) is\n", "\n", "$$x(t) = \\sum_n x[n]\\, \\mathrm{sinc}(f_{in} t - n), \\qquad \\mathrm{sinc}(u) = \\frac{\\sin(\\pi u)}{\\pi u}$$\n", "\n", "A practical resampler truncates and windows the sinc and scales it so that its cutoff is\n", "$f_c = \\min(f_{in}, f_{out})/2$ (slightly less, to leave room for the transition band). One\n", "formula then does both jobs: interpolation and anti-aliasing.\n", "\n", "**Linear interpolation** uses a triangular kernel instead. For integer upsampling by $L = 3$\n", "it equals zero-stuffing followed by the FIR $[1, 2, 3, 2, 1]/3$, whose gain at $f$ (Hz) is\n", "\n", "$$G(f) = \\frac{3 + 4\\cos\\omega + 2\\cos 2\\omega}{9}, \\qquad \\omega = 2\\pi f / f_{out}$$\n", "\n", "(the extra $1/3$ undoes the kernel's gain of 3 at DC). $G$ is neither flat in the pass band nor\n", "zero at the images.\n", "\n", "**Alias (or image) rejection** is the level of the unwanted component relative to the input\n", "component that produced it:\n", "\n", "$$R = 20 \\log_{10}(A_{alias} / A_{in})\\ \\text{dB}$$\n", "\n", "where $A$ is a sinusoid's amplitude. 0 dB means no rejection.\n", "\n", "**The library's tiers** (`aus.ResamplingQuality`). Every tier except `fast` upsampling is a\n", "Kaiser-windowed sinc low-pass whose cut-off is set relative to the lower Nyquist frequency\n", "$f_N = \\min(f_{in}, f_{out})/2$; the stop band starts at $f_N$:\n", "\n", "- `fast` (*the default of `AudioSamples.resample`*): when downsampling, a short filter with its\n", " pass band to $0.80 f_N$ and 70 dB of stop-band attenuation; when upsampling, linear\n", " interpolation (no anti-imaging filter).\n", "- `medium`: pass band to $0.90 f_N$, 100 dB.\n", "- `high`: pass band to $0.913 f_N$, 125 dB.\n", "\n", "The filter is computed in the buffer's float type: float32 for float32, int16 and uint8\n", "buffers, float64 for float64 and int32 ones.\n", "\n", "**Time alignment.** Output sample $m$ is the band-limited reconstruction of the input at the\n", "exact input position $m/r = m f_{in}/f_{out}$: the sinc is centred on that position, so the\n", "filter is symmetric (linear phase) and adds **no delay**. Input before the start and after the\n", "end counts as zeros, and the output has exactly $\\lceil N r \\rceil$ samples for $N$ input samples." ] }, { "cell_type": "markdown", "id": "nb07-003", "metadata": {}, "source": [ "## With the library\n", "\n", "Mix a 1 kHz tone (to keep) with a 10 kHz tone (to remove), both at amplitude 0.5, and convert\n", "48 kHz to 16 kHz by naive decimation (keep every third sample, written by hand) and with each\n", "tier. The 10 kHz tone should fold to\n", "$|10\\,000 - 16\\,000| = 6\\,000$ Hz. We measure each component with one DFT bin over the middle\n", "1600 output samples (whole periods of both 1 kHz and 6 kHz, so there is no leakage)." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-004", "metadata": {}, "outputs": [], "source": [ "fs_in, fs_out = 48_000, 16_000\n", "n = np.arange(12_000) # 250 ms\n", "x = 0.5 * np.sin(2 * np.pi * 1_000 * n / fs_in) + 0.5 * np.sin(2 * np.pi * 10_000 * n / fs_in)\n", "signal = aus.AudioSamples.new_mono(x, fs_in)\n", "\n", "mid = slice(1_200, 2_800) # middle 100 ms of the 16 kHz output\n", "results = {}\n", "outputs = {\"naive\": x[::3]} # naive decimation, by hand: keep every third sample\n", "results[\"naive\"] = (level_db(x[::3][mid], 1_000, fs_out, 0.5), level_db(x[::3][mid], 6_000, fs_out, 0.5))\n", "for name in (\"fast\", \"medium\", \"high\"):\n", " y = signal.resample(fs_out, getattr(Q, name)).to_numpy()\n", " assert len(y) == 4_000 # ceil(12000 / 3)\n", " outputs[name] = y\n", " results[name] = (level_db(y[mid], 1_000, fs_out, 0.5), level_db(y[mid], 6_000, fs_out, 0.5))\n", "for name, (p, a) in results.items():\n", " print(f\"{name:6s}: 1 kHz {p:+.4f} dB, alias at 6 kHz {a:+.1f} dB\")\n", "\n", "# Every tier passes 1 kHz unchanged (better than 0.001 dB).\n", "assert all(abs(p) < 1e-3 for p, _ in results.values())\n", "# Naive decimation: the alias arrives at full level, 0 dB.\n", "assert abs(results[\"naive\"][1]) < 1e-9\n", "# Every tier removes it: for this 1 : 3 ratio the resampler drops everything above the output's\n", "# Nyquist frequency in the frequency domain, so what is left is float64 round-off.\n", "assert all(results[name][1] < -180 for name in (\"fast\", \"medium\", \"high\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-005", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(8, 3))\n", "win = np.hanning(1_600)\n", "freqs = np.fft.rfftfreq(1_600, 1 / fs_out)\n", "for name, y in outputs.items():\n", " spec = np.abs(np.fft.rfft(y[mid] * win)) / win.sum() * 2\n", " ax.plot(freqs, 20 * np.log10(spec / 0.5 + 1e-12), label=name, lw=1)\n", "ax.set(xlabel=\"Frequency (Hz)\", ylabel=\"Level re input (dB)\", ylim=(-170, 10),\n", " title=\"48 kHz -> 16 kHz: 1 kHz kept, 10 kHz aliases to 6 kHz unless filtered\")\n", "ax.legend(fontsize=8)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "nb07-006", "metadata": {}, "source": [ "**Compare with SciPy.** `scipy.signal.resample_poly(x, 1, 3)` uses a polyphase FIR designed by\n", "`firwin` with a Kaiser window ($\\beta = 5$) and $2 \\cdot 10 \\cdot \\max(\\text{up}, \\text{down}) + 1 = 61$\n", "taps. It is exactly time-aligned (zero phase), like the library, but with its default filter it\n", "rejects the alias by about 57 dB. This is a different design choice, not an error." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-007", "metadata": {}, "outputs": [], "source": [ "y_poly = ss.resample_poly(x, 1, 3)\n", "assert len(y_poly) == 4_000\n", "pass_poly, alias_poly = level_db(y_poly[mid], 1_000, fs_out, 0.5), level_db(y_poly[mid], 6_000, fs_out, 0.5)\n", "print(f\"resample_poly: 1 kHz {pass_poly:+.4f} dB, alias {alias_poly:+.1f} dB\")\n", "assert abs(pass_poly) < 0.01 # pass band intact (0.01 dB)\n", "assert abs(alias_poly + 57.3) < 0.5 # about 57 dB of rejection\n", "# Every tier rejects the alias more than SciPy's default filter here: fast by more than 30 dB, medium and high by\n", "# more than 40 dB.\n", "assert results[\"fast\"][1] < alias_poly - 30\n", "assert results[\"medium\"][1] < alias_poly - 40 and results[\"high\"][1] < alias_poly - 40" ] }, { "cell_type": "markdown", "id": "nb07-008", "metadata": {}, "source": [ "**Time alignment.** An impulse at input sample 3000 (48 kHz) peaks at output sample\n", "$3000/3 = 1000$ (16 kHz) for every tier, and its response is symmetric about the peak. The phase\n", "of a 1 kHz tone measures any sub-sample shift: it is zero to rounding error for every tier." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-009", "metadata": {}, "outputs": [], "source": [ "imp = np.zeros(12_000)\n", "imp[3_000] = 1.0\n", "for name in (\"fast\", \"medium\", \"high\"):\n", " y = aus.AudioSamples.new_mono(imp, fs_in).resample(fs_out, getattr(Q, name)).to_numpy()\n", " assert np.argmax(np.abs(y)) == 1_000\n", " assert abs(y[999] - y[1_001]) < 1e-12 # symmetric (linear-phase) filter\n", "\n", "tone = aus.sine_wave(1_000.0, 0.25, sample_rate=fs_in, amplitude=0.5, dtype=F64)\n", "k = np.arange(1_200, 2_800)\n", "shift = {}\n", "for name in (\"fast\", \"medium\", \"high\"):\n", " y = tone.resample(fs_out, getattr(Q, name)).to_numpy()[k]\n", " phase = np.angle(np.sum(y * np.exp(-2j * np.pi * 1_000 * k / fs_out))) + np.pi / 2\n", " shift[name] = phase / (2 * np.pi * 1_000 / fs_out) # in output frames; > 0 means early\n", "print({k_: float(f\"{v:.1e}\") for k_, v in shift.items()})\n", "# No delay: zero shift to rounding error, for every tier.\n", "assert all(abs(v) < 1e-9 for v in shift.values())" ] }, { "cell_type": "markdown", "id": "nb07-010", "metadata": {}, "source": [ "## How it works\n", "\n", "**Naive decimation is plain sampling.** With $r = 1/3$, keeping every third sample returns\n", "$x[3m]$, and $\\sin(2\\pi\\, 10\\,000\\, m / 16\\,000) = -\\sin(2\\pi\\, 6\\,000\\, m / 16\\,000)$ for every\n", "integer $m$: the 10 kHz tone *is* a 6 kHz tone on the 16 kHz grid. No filter afterwards can tell\n", "the two apart, which is why every tier filters first." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-011", "metadata": {}, "outputs": [], "source": [ "x10 = aus.sine_wave(10_000.0, 0.1, sample_rate=fs_in, amplitude=0.5, dtype=F64)\n", "y10 = x10.to_numpy()[::3] # naive decimation: 1600 samples at 16 kHz\n", "m = np.arange(len(y10))\n", "# Tolerance: sin of arguments up to ~6e3 rad carries ~1e-12 of rounding.\n", "assert np.allclose(y10, -0.5 * np.sin(2 * np.pi * 6_000 * m / fs_out), rtol=0, atol=1e-9)" ] }, { "cell_type": "markdown", "id": "nb07-012", "metadata": {}, "source": [ "**A windowed-sinc decimator, written out.** Low-pass with a 193-tap Blackman-windowed sinc whose\n", "cutoff is $0.95 \\times 8$ kHz $= 7.6$ kHz, then keep every third sample. The filter is centred\n", "(no delay), so the 1 kHz output matches the ideal 16 kHz sine, and the 6 kHz alias is 107.5 dB\n", "down: this filter's stopband, folded back (the library drops that part of the spectrum for this\n", "ratio). Since the library adds no delay\n", "either, its `high` output and ours agree sample by sample." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-013", "metadata": {}, "outputs": [], "source": [ "half = 96\n", "fc = 0.95 * (fs_out / 2) / fs_in # cutoff as a fraction of fs_in\n", "t = np.arange(-half, half + 1)\n", "h = 2 * fc * np.sinc(2 * fc * t) * np.blackman(2 * half + 1) # np.sinc(u) = sin(pi u)/(pi u)\n", "\n", "# y[m] = sum_k h[k] x[3m + half - k]: full convolution, then keep the centred samples.\n", "y_mine = np.convolve(x, h)[half::3][:4_000]\n", "\n", "assert abs(level_db(y_mine[mid], 1_000, fs_out, 0.5)) < 1e-3 # pass band intact\n", "assert abs(level_db(y_mine[mid], 6_000, fs_out, 0.5) + 107.5) < 0.1 # alias 107.5 dB down\n", "ideal = 0.5 * np.sin(2 * np.pi * 1_000 * np.arange(4_000) / fs_out)\n", "# Matches the ideal 16 kHz sine to 1e-5 (window ripple in the pass band) ...\n", "assert np.max(np.abs(y_mine[mid] - ideal[mid])) < 1e-5\n", "# ... and the library's high tier, also centred, to 1e-5.\n", "assert np.max(np.abs(y_mine[mid] - outputs[\"high\"][mid])) < 1e-5\n", "\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "H = np.fft.rfft(h, 8192)\n", "ax.plot(np.fft.rfftfreq(8192, 1 / fs_in), 20 * np.log10(np.abs(H) + 1e-12))\n", "ax.axvline(8_000, color=\"grey\", ls=\":\", lw=0.8)\n", "ax.set(xlim=(0, 24_000), ylim=(-160, 5), xlabel=\"Frequency (Hz)\", ylabel=\"Gain (dB)\",\n", " title=\"193-tap Blackman-windowed sinc, cutoff 7.6 kHz (output Nyquist dotted)\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "nb07-014", "metadata": {}, "source": [ "**Linear interpolation is a poor interpolation filter.** Upsampling a 6 kHz tone from 16 kHz\n", "to 48 kHz with `fast` should, by $G(f)$, droop the tone to $G(6\\,000) = -3.77$ dB and leave an\n", "image at $16\\,000 - 6\\,000 = 10\\,000$ Hz at $G(10\\,000) = -11.8$ dB. The sinc tiers pass the\n", "tone flat (to 0.0001 dB) and remove the image: for 1 : 3 every bin above 8 kHz is zero before\n", "the inverse transform, so what is left is float64 round-off." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-015", "metadata": {}, "outputs": [], "source": [ "def G_db(f, fs=48_000):\n", " w = 2 * np.pi * f / fs\n", " return 20 * np.log10(abs((3 + 4 * np.cos(w) + 2 * np.cos(2 * w)) / 9))\n", "\n", "assert abs(G_db(6_000) + 3.77) < 0.01 and abs(G_db(10_000) + 11.8) < 0.05\n", "\n", "x6 = aus.sine_wave(6_000.0, 0.25, sample_rate=16_000, amplitude=0.5, dtype=F64)\n", "seg = slice(3_600, 8_400) # 100 ms: whole periods of 6 and 10 kHz\n", "up = {name: x6.resample(48_000, getattr(Q, name)).to_numpy()[seg] for name in (\"fast\", \"medium\", \"high\")}\n", "lv = {name: (level_db(y, 6_000, 48_000, 0.5), level_db(y, 10_000, 48_000, 0.5)) for name, y in up.items()}\n", "print({name: tuple(round(float(v), 2) for v in vals) for name, vals in lv.items()})\n", "# Measured equals predicted to 1e-6 dB (this buffer is float64, so the resampler computes in float64).\n", "assert abs(lv[\"fast\"][0] - G_db(6_000)) < 1e-6 and abs(lv[\"fast\"][1] - G_db(10_000)) < 1e-6\n", "# The sinc tiers: tone flat to 0.0001 dB, image strongly attenuated.\n", "assert abs(lv[\"medium\"][0]) < 1e-4 and abs(lv[\"high\"][0]) < 1e-4\n", "assert lv[\"medium\"][1] < -180 and lv[\"high\"][1] < -180" ] }, { "cell_type": "markdown", "id": "nb07-016", "metadata": {}, "source": [ "## Ask the library to explain\n", "\n", "`aus.explain.resampling(from_rate, to_rate)` summarises a conversion: ratio, both Nyquist\n", "frequencies, the pass-band edge of the sinc tiers, a table of the three tiers, and a warning when\n", "you downsample." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-017", "metadata": {}, "outputs": [], "source": [ "doc = aus.explain.resampling(48_000.0, 16_000.0)\n", "doc" ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-018", "metadata": {}, "outputs": [], "source": [ "assert abs(doc.quantity(\"Ratio\") - 1 / 3) < 1e-12\n", "assert doc.quantity(\"Output Nyquist\") == 8_000.0\n", "# medium's pass band ends at 0.90 x 8 kHz.\n", "assert abs(doc.quantity(\"Sinc pass-band edge\") - 7_200.0) < 1e-9\n", "assert doc.has_warning_containing(\"Downsampling\")\n", "# Upsampling discards nothing, so there is no such warning.\n", "assert not aus.explain.resampling(16_000.0, 48_000.0).has_warning_containing(\"Downsampling\")" ] }, { "cell_type": "markdown", "id": "nb07-019", "metadata": {}, "source": [ "## Exercises\n", "\n", "**1. Where does 13 kHz go?** A 13 kHz tone (amplitude 0.5) is converted from 48 kHz to 16 kHz\n", "by keeping every third sample. Predict the output frequency, confirm it with\n", "`aus.explain.aliasing`, and measure the output amplitude at that frequency. How much of it does\n", "each tier of `resample` leave in the middle 50 ms? Put the alias frequency in Hz in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-020", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-021", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = abs(13_000 - 16_000)\n", "assert aus.explain.aliasing(13_000.0, 16_000.0).quantity(\"Alias frequency\") == answer == 3_000\n", "x13 = aus.sine_wave(13_000.0, 0.1, sample_rate=48_000, amplitude=0.5, dtype=F64)\n", "naive13 = x13.to_numpy()[::3] # 1600 samples = 300 periods of 3 kHz\n", "assert abs(amplitude(naive13, 3_000, 16_000) - 0.5) < 1e-9 # full level\n", "# Every tier removes it: below -150 dB (fast) and -220 dB (medium, high) in the middle 50 ms\n", "# (150 periods); over the whole 100 ms all read about -74 dB, set by the edge clicks.\n", "for name, below in ((\"fast\", -150), (\"medium\", -220), (\"high\", -220)):\n", " y13 = x13.resample(16_000, getattr(Q, name)).to_numpy()\n", " assert level_db(y13[400:1_200], 3_000, 16_000, 0.5) < below\n", " assert abs(level_db(y13, 3_000, 16_000, 0.5) + 74.0) < 0.5" ] }, { "cell_type": "markdown", "id": "nb07-022", "metadata": {}, "source": [ "**2. Droop at 2 kHz.** Predict the gain (dB) of `fast` upsampling 16 kHz to 48 kHz at 2 kHz\n", "from $G(f)$, then measure it. Put the measured gain in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-023", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-024", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "# w = 2 pi 2000 / 48000 = pi / 12, G = (3 + 4 cos(pi/12) + 2 cos(pi/6)) / 9 = 0.955.\n", "predicted = G_db(2_000)\n", "assert abs(predicted + 0.40) < 0.005\n", "x2 = aus.sine_wave(2_000.0, 0.25, sample_rate=16_000, amplitude=0.5, dtype=F64)\n", "y2 = x2.resample(48_000, Q.fast).to_numpy()[3_600:8_400]\n", "answer = level_db(y2, 2_000, 48_000, 0.5)\n", "assert abs(answer - predicted) < 0.01" ] }, { "cell_type": "markdown", "id": "nb07-025", "metadata": {}, "source": [ "**3. Alignment at a non-integer ratio.** Convert a 1 kHz tone (amplitude 0.5) from 44.1 kHz to\n", "16 kHz ($r = 160/441$) with `high`. Is the output still time-aligned? Measure the largest deviation\n", "from the ideal 16 kHz sine in the middle 100 ms and put it in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-026", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "nb07-027", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "# Output sample m is evaluated at the exact input position 441 m / 160: no delay to remove and\n", "# nothing rounded to whole frames.\n", "x441 = aus.sine_wave(1_000.0, 0.25, sample_rate=44_100, amplitude=0.5, dtype=F64)\n", "y441 = x441.resample(16_000, Q.high).to_numpy()\n", "assert len(y441) == 4_000 # ceil(11025 * 160 / 441)\n", "kk = np.arange(800, 2_400)\n", "answer = np.max(np.abs(y441[kk] - 0.5 * np.sin(2 * np.pi * 1_000 * kk / 16_000)))\n", "# A shift of tau output frames causes an error of up to 0.5 * (2 pi / 16) * tau = 0.196 tau, so\n", "# an error below 1e-7 means |tau| < 5.1e-7 frames.\n", "assert answer < 1e-7 and 1e-7 / (0.5 * 2 * np.pi / 16) < 5.1e-7" ] }, { "cell_type": "markdown", "id": "nb07-028", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "- **Naive decimation (`x[::q]`) is not resampling**: it folds everything above the output's Nyquist\n", " frequency back at full level. Every `ResamplingQuality` filters first.\n", "- **`fast` is the default** of `AudioSamples.resample` and `resample_by_ratio`, and it trades\n", " bandwidth and rejection for speed: its downsampling filter starts rolling off at $0.80 f_N$ and\n", " gives 70 dB by design; when upsampling it is linear interpolation. Pass\n", " `aus.ResamplingQuality.medium` or `.high` for analysis or listening.\n", "- **Measure rejection away from the ends.** The input is treated as zero outside the buffer, so\n", " a signal that starts or stops abruptly produces broadband clicks that no anti-aliasing filter\n", " removes.\n", "- **Other resamplers use other designs.** `scipy.signal.resample` uses the FFT (assuming a\n", " periodic signal); `resample_poly` uses a short Kaiser-windowed FIR (about 57 dB of alias\n", " rejection above). Expect small differences in edge behaviour and alignment, not in the pass\n", " band.\n", "- **Output length** is $\\lceil N r \\rceil$ frames.\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", " and the lab `examples/tutorial_07_resampling.rs`.\n", "- Python API: `AudioSamples.resample`, `AudioSamples.resample_by_ratio`,\n", " `audio_samples.ResamplingQuality`, `aus.explain.resampling`, `aus.explain.aliasing`.\n", "- Previous: [06. IIR filters](06_iir_filters.ipynb); next:\n", " [08. LPC, the source-filter model and formants](08_lpc_formants.ipynb); aliasing basics:\n", " [01. Sampling and aliasing](01_sampling_aliasing.ipynb)." ] }, { "cell_type": "markdown", "id": "references", "metadata": {}, "source": [ "## References\n", "\n", "* Crochiere, R. E. and Rabiner, L. R. (1983). *Multirate Digital Signal Processing*. Prentice-Hall.\n", "* Oppenheim, A. V. and Schafer, R. W. (2010). *Discrete-Time Signal Processing*, 3rd ed. Pearson. Section 4.6 (changing the sampling rate by an integer or rational factor)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }