{ "cells": [ { "cell_type": "markdown", "id": "c000", "metadata": {}, "source": [ "# 04. STFT and spectrograms\n", "\n", "The spectra of speech and music change over time: a vowel lasts 50 to 200 ms, a plosive burst a\n", "few milliseconds. One DFT of a whole utterance (notebook 03) combines them into one spectrum. The\n", "short-time Fourier transform (STFT) takes many short, overlapping DFTs instead, giving the\n", "time-frequency representation (the spectrogram) used as input by most speech systems. This\n", "notebook specifies exactly how `audio_samples` frames, windows, pads and inverts, and the\n", "time-frequency trade-off that applies to every choice of parameters.\n", "\n", "**Learning outcomes.** After working through this notebook you can\n", "\n", "* write the STFT as framing + windowing + DFT and predict the number of frames, bins and the\n", " time/frequency spacing of a spectrogram;\n", "* explain the time-frequency trade-off and choose a window length for a task;\n", "* invert an STFT exactly (weighted overlap-add) and state when that is possible (the NOLA and\n", " COLA conditions);\n", "* convert to decibels with an absolute floor, and contrast it with a floor set relative to the\n", " loudest value." ] }, { "cell_type": "code", "execution_count": null, "id": "c001", "metadata": {}, "outputs": [], "source": [ "import librosa\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import scipy.signal as ss\n", "\n", "import audio_samples as aus\n", "\n", "rng = np.random.default_rng(seed=2026)\n", "F64 = np.dtype(\"float64\")\n", "WT = aus.WindowType\n", "FS = 16_000" ] }, { "cell_type": "markdown", "id": "c002", "metadata": {}, "source": [ "## Concept\n", "\n", "**Frames.** Choose a window length $N$ (also the FFT size here) and a hop $H$, both in samples.\n", "Frame $m$ is the windowed block of $N$ samples starting at $mH - p$:\n", "\n", "$$X_m[k] = \\sum_{n=0}^{N-1} x[mH + n - p] \\, w[n] \\, e^{-j 2\\pi k n / N}, \\qquad k = 0, \\dots, \\lfloor N/2 \\rfloor$$\n", "\n", "where $x[n]$ is the signal (taken as 0 outside $0 \\le n < L$), $L$ its length in samples, $w[n]$\n", "the analysis window, $m$ the frame index and $p$ the padding in samples. With `centre=True` the\n", "library pads $p = \\lfloor N/2 \\rfloor$ **zeros** at both ends, so frame $m$ is centred on sample\n", "$mH$, i.e. time $t_m = mH/f_s$ seconds.\n", "\n", "**Sizes.** The number of frames and the spacings are\n", "\n", "$$M = \\left\\lfloor \\frac{L + 2p - N}{H} \\right\\rfloor + 1, \\qquad \\Delta f = \\frac{f_s}{N}, \\qquad \\Delta t = \\frac{H}{f_s}$$\n", "\n", "where $M$ is the number of frames, $\\Delta f$ the bin spacing in Hz, $\\Delta t$ the frame period in\n", "seconds and $f_s$ the sample rate in Hz. The result has $\\lfloor N/2\\rfloor + 1$ rows (bins) and $M$\n", "columns (frames).\n", "\n", "**Time-frequency trade-off.** A window of $N$ samples lasts $N/f_s$ seconds and has a main lobe a\n", "few bins wide (about $2\\Delta f = 2 f_s / N$ Hz at $-6$ dB for Hann), so a longer window separates\n", "closer frequencies but spreads events in time over a longer interval. The product of the two\n", "resolutions is fixed, so one cannot be improved without degrading the other. The hop $H$ only sets\n", "the frame rate; it does not improve resolution on either axis.\n", "\n", "**Inversion.** The library's `istft` uses weighted overlap-add (WOLA): each frame is inverse\n", "transformed, multiplied by the window again and added, and the sum is divided by the summed\n", "squared windows:\n", "\n", "$$\\hat{x}[n] = \\frac{\\sum_m w[n - mH + p] \\, y_m[n - mH + p]}{\\sum_m w^2[n - mH + p]}$$\n", "\n", "where $y_m$ is the inverse DFT of frame $m$. This is exact wherever the denominator is non-zero, for any window: the\n", "**NOLA** (nonzero overlap-add) condition, $\\sum_m w^2[n - mH] > 0$ for every $n$. Plain overlap-add\n", "(no window on synthesis, no division) needs the stronger **COLA** (constant overlap-add) condition\n", "$\\sum_m w[n - mH] = \\text{const}$.\n", "\n", "**Decibels.** A power spectrogram $P = |X_m[k]|^2$ is shown in dB as\n", "\n", "$$P_{\\mathrm{dB}} = \\max\\big(10 \\log_{10} P,\\; F\\big)$$\n", "\n", "where $F$ is an **absolute** floor in dB (`LogParams(floor_db=F)`). A floor set at a fixed\n", "distance below the loudest value (`top_db`) would instead move with the signal." ] }, { "cell_type": "markdown", "id": "c003", "metadata": {}, "source": [ "## With the library\n", "\n", "The test signal is two steady tones 40 Hz apart (1000 and 1040 Hz, like two close harmonics) plus a\n", "click at $t = 0.5$ s (like a plosive burst), 1 s at 16 kHz." ] }, { "cell_type": "code", "execution_count": null, "id": "c004", "metadata": {}, "outputs": [], "source": [ "t = np.arange(FS) / FS\n", "x = 0.5 * np.sin(2 * np.pi * 1000 * t) + 0.5 * np.sin(2 * np.pi * 1040 * t)\n", "x[8000] += 1.0\n", "audio = aus.AudioSamples.new_mono(x, sample_rate=FS)\n", "\n", "params = aus.StftParams(n_fft=512, hop_size=128, window=WT.hanning, centre=True)\n", "res = audio.stft(params)\n", "X = res.data # complex, shape (bins, frames)\n", "print(params, X.shape, X.dtype)\n", "assert X.shape == (257, 126) # 512/2 + 1 bins; 1 + floor(16000/128) frames\n", "assert res.n_bins == 257 and res.n_frames == 126\n", "assert res.frequency_resolution == 31.25 # Hz\n", "assert abs(res.time_resolution - 0.008) < 1e-15 # s\n", "assert np.allclose(res.frequencies, np.arange(257) * 31.25)" ] }, { "cell_type": "markdown", "id": "c005", "metadata": {}, "source": [ "The STFT bins are ordinary DFT bins, so a spectrogram is $|X|^2$. The bundled `spectrograms` module\n", "computes it directly (`compute_linear_power_spectrogram`, `..._magnitude_...`, `..._db_...`,\n", "taking a NumPy array and `SpectrogramParams`):" ] }, { "cell_type": "code", "execution_count": null, "id": "c006", "metadata": {}, "outputs": [], "source": [ "sp = aus.SpectrogramParams(params, sample_rate=float(FS))\n", "power = aus.spectrograms.compute_linear_power_spectrogram(x, sp)\n", "assert np.allclose(power.data, np.abs(X) ** 2, rtol=1e-12, atol=0)\n", "assert np.allclose(power.times, np.arange(126) * 0.008) # centred frames: t_m = m H / fs\n", "\n", "db = aus.spectrograms.compute_linear_db_spectrogram(x, sp, aus.LogParams(-100.0)).data\n", "assert db.min() == -100.0 # the absolute floor\n", "print(f\"dB range: {db.min():.1f} .. {db.max():.1f}\")\n", "\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "im = ax.pcolormesh(power.times, np.asarray(power.frequencies) / 1000, db, shading=\"nearest\", cmap=\"magma\")\n", "ax.set(xlabel=\"Time (s)\", ylabel=\"Frequency (kHz)\", title=\"N = 512, H = 128, Hann (power, dB)\")\n", "fig.colorbar(im, ax=ax, label=\"dB\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c007", "metadata": {}, "source": [ "Because the reference is 1 (not the loudest bin), dB values are absolute and can be well above\n", "0 dB. A full-scale 1 kHz sine is bin-centred for $N = 512$ at 16 kHz (bin 32), so its peak power\n", "is $(\\sum w / 2)^2$ and its level is $20\\log_{10}(255.5/2) = 42.13$ dB re 1. Silence is exactly\n", "at the floor, regardless of the rest of the file. Without centring the same 1 s signal gives 122 frames\n", "instead of 126." ] }, { "cell_type": "code", "execution_count": null, "id": "c008", "metadata": {}, "outputs": [], "source": [ "sine = aus.sine_wave(1000.0, 0.5, sample_rate=FS, amplitude=1.0, dtype=F64)\n", "floor = aus.LogParams(-80.0)\n", "lin = aus.spectrograms.compute_linear_db_spectrogram(sine.to_numpy(), sp, floor).data\n", "assert abs(WT.make_hanning(512).sum() - 255.5) < 1e-9 # (N - 1) / 2\n", "assert abs(lin.max() - 20 * np.log10(255.5 / 2)) < 0.01 and abs(lin.max() - 42.13) < 0.01\n", "quiet = aus.spectrograms.compute_linear_db_spectrogram(np.zeros(4000), sp, floor).data\n", "assert np.all(np.abs(quiet + 80.0) < 1e-9)\n", "\n", "no_centre = aus.StftParams(n_fft=512, hop_size=128, window=WT.hanning, centre=False)\n", "assert audio.stft(no_centre).n_frames == 122 == 1 + (16_000 - 512) // 128" ] }, { "cell_type": "markdown", "id": "c009", "metadata": {}, "source": [ "At $N = 512$ the two tones (40 Hz apart, a bit more than one bin) merge into one band, and the\n", "click is a short vertical line. Sweep $N$ (with $H = N/4$) and measure both: how many peaks appear\n", "between 900 and 1150 Hz in a frame far from the click, and how long the click's high-frequency\n", "energy (above 4 kHz, where the tones contribute nothing) stays within 6 dB of its peak." ] }, { "cell_type": "code", "execution_count": null, "id": "c010", "metadata": {}, "outputs": [], "source": [ "def tf_tradeoff(n):\n", " hop = n // 4\n", " r = audio.stft(aus.StftParams(n_fft=n, hop_size=hop, window=WT.hanning, centre=True))\n", " p = np.abs(r.data) ** 2\n", " f = np.arange(r.n_bins) * FS / n\n", " high = p[f >= 4000].sum(axis=0)\n", " click_ms = (high > high.max() * 10 ** (-6 / 10)).sum() * hop / FS * 1000\n", " m = np.sqrt(p[:, r.n_frames // 4]) # a frame around t = 0.25 s\n", " idx = np.where((f > 900) & (f < 1150))[0]\n", " top = m[idx].max()\n", " peaks = sum(1 for i in idx if m[i] > m[i - 1] and m[i] >= m[i + 1] and m[i] > 0.5 * top)\n", " return peaks, click_ms\n", "\n", "table = {n: tf_tradeoff(n) for n in [128, 256, 512, 1024, 2048]}\n", "for n, (peaks, click_ms) in table.items():\n", " print(f\"N = {n:4d} ({1000 * n / FS:5.1f} ms, bins {FS / n:6.2f} Hz): {peaks} peak(s), click {click_ms:4.0f} ms\")\n", "# The click stays within 6 dB for half a window, N / (2 fs): 4 ms at N = 128, 64 ms at N = 2048.\n", "assert all(click_ms == 1000 * n / (2 * FS) for n, (_, click_ms) in table.items())\n", "# Two tones 40 Hz apart need a Hann main lobe 2 fs / N <= 40 Hz, i.e. N >= 800: resolved from 1024.\n", "assert [table[n][0] for n in [128, 256, 512]] == [1, 1, 1]\n", "assert [table[n][0] for n in [1024, 2048]] == [2, 2]" ] }, { "cell_type": "code", "execution_count": null, "id": "c011", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)\n", "for ax, n in zip(axes, [128, 2048]):\n", " spn = aus.SpectrogramParams(aus.StftParams(n_fft=n, hop_size=n // 4, window=WT.hanning, centre=True), sample_rate=float(FS))\n", " s = aus.spectrograms.compute_linear_db_spectrogram(x, spn, aus.LogParams(-100.0))\n", " ax.pcolormesh(s.times, np.asarray(s.frequencies), s.data, shading=\"nearest\", cmap=\"magma\")\n", " ax.set(xlabel=\"Time (s)\", title=f\"N = {n} ({1000 * n / FS:.0f} ms)\", ylim=(500, 1500), xlim=(0.35, 0.65))\n", "axes[0].set_ylabel(\"Frequency (Hz)\")\n", "fig.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c012", "metadata": {}, "source": [ "With a short window the click is narrow in time and the two tones form one band. With a long\n", "window the two tones are separate and the click is spread in time.\n", "\n", "**Inversion.** `istft` reconstructs the signal to rounding error. Its output has\n", "$(M - 1)H$ samples, so with `centre=True` the last $L \\bmod H$ samples are not returned; pad the\n", "input to a multiple of $H$ if you need them all." ] }, { "cell_type": "code", "execution_count": null, "id": "c013", "metadata": {}, "outputs": [], "source": [ "y = audio.istft(res).to_numpy()\n", "L, H = audio.samples_per_channel(), params.hop_size\n", "print(len(y), (res.n_frames - 1) * H)\n", "assert len(y) == (res.n_frames - 1) * H == (L // H) * H # 16000 is a multiple of 128: nothing lost\n", "# WOLA divides by the summed squared windows: exact to rounding (values of size ~1).\n", "assert np.allclose(y, x[: len(y)], atol=1e-12)\n", "\n", "# A length that is not a multiple of the hop: 4000 samples, H = 256 -> 3840 returned.\n", "short = aus.AudioSamples.new_mono(rng.standard_normal(4000) * 0.1, sample_rate=FS)\n", "p256 = aus.StftParams(n_fft=512, hop_size=256, window=WT.hanning, centre=True)\n", "y_short = short.istft(short.stft(p256)).to_numpy()\n", "assert len(y_short) == 3840 and np.allclose(y_short, short.to_numpy()[:3840], atol=1e-12)" ] }, { "cell_type": "markdown", "id": "c014", "metadata": {}, "source": [ "## How it works\n", "\n", "Reimplement the STFT with NumPy: pad $\\lfloor N/2 \\rfloor$ zeros, cut frames every $H$ samples,\n", "multiply by SciPy's **symmetric** Hann (`hann(N, sym=True)`) and take `np.fft.rfft`. Then check\n", "against librosa as an independent reference, with its conventions switched to match (symmetric\n", "window passed explicitly, `pad_mode=\"constant\"`)." ] }, { "cell_type": "code", "execution_count": null, "id": "c015", "metadata": {}, "outputs": [], "source": [ "def my_stft(x, n, hop, window):\n", " p = n // 2\n", " xp = np.concatenate([np.zeros(p), x, np.zeros(p)])\n", " m = (len(xp) - n) // hop + 1\n", " frames = np.stack([xp[i * hop: i * hop + n] for i in range(m)], axis=1) # (n, M)\n", " return np.fft.rfft(frames * window[:, None], axis=0)\n", "\n", "w = ss.windows.hann(512, sym=True)\n", "mine = my_stft(x, 512, 128, w)\n", "# Each bin is a 512-term sum of values of size ~1: rounding of order 1e-13.\n", "assert mine.shape == X.shape and np.allclose(mine, X, atol=1e-10)\n", "\n", "ref = librosa.stft(x, n_fft=512, hop_length=128, window=w, center=True, pad_mode=\"constant\")\n", "assert np.allclose(ref, X, atol=1e-10)\n", "# With a periodic Hann window the numbers differ; the padding (zeros) is the same, so the whole\n", "# difference comes from the window:\n", "import inspect\n", "\n", "assert inspect.signature(librosa.stft).parameters[\"pad_mode\"].default == \"constant\"\n", "ref_default = librosa.stft(x, n_fft=512, hop_length=128)\n", "periodic_hann = ss.get_window(\"hann\", 512)\n", "assert np.allclose(ref_default, librosa.stft(x, n_fft=512, hop_length=128, window=periodic_hann,\n", " pad_mode=\"constant\"), atol=1e-12)\n", "assert np.allclose(my_stft(x, 512, 128, periodic_hann), ref_default, atol=1e-10)\n", "print(f\"max |library - librosa default| = {np.max(np.abs(ref_default - X)):.3f}\")\n", "assert not np.allclose(ref_default, X, atol=1e-3)\n", "\n", "# The frame-count formula, for a few lengths and both centring modes.\n", "for L_, n, hop, centre in [(16000, 512, 128, True), (16000, 400, 160, True), (4000, 512, 128, False), (1000, 256, 100, True)]:\n", " sig = aus.AudioSamples.new_mono(np.ones(L_), sample_rate=FS)\n", " r = sig.stft(aus.StftParams(n_fft=n, hop_size=hop, window=WT.hanning, centre=centre))\n", " p = n // 2 if centre else 0\n", " assert r.n_frames == (L_ + 2 * p - n) // hop + 1" ] }, { "cell_type": "markdown", "id": "c016", "metadata": {}, "source": [ "Inversion by weighted overlap-add, written out:" ] }, { "cell_type": "code", "execution_count": null, "id": "c017", "metadata": {}, "outputs": [], "source": [ "def my_istft(X, n, hop, window):\n", " m = X.shape[1]\n", " frames = np.fft.irfft(X, n=n, axis=0) * window[:, None]\n", " out = np.zeros(n + hop * (m - 1))\n", " norm = np.zeros_like(out)\n", " for i in range(m):\n", " out[i * hop: i * hop + n] += frames[:, i]\n", " norm[i * hop: i * hop + n] += window ** 2\n", " p = n // 2\n", " return (out / np.where(norm > 1e-10, norm, 1.0))[p: len(out) - p]\n", "\n", "y_mine = my_istft(X, 512, 128, w)\n", "assert len(y_mine) == len(y) and np.allclose(y_mine, y, atol=1e-12)" ] }, { "cell_type": "markdown", "id": "c018", "metadata": {}, "source": [ "Measuring COLA: the **periodic** Hann at 50 % overlap sums to exactly 1; the library's\n", "**symmetric** Hann deviates from 1 by a fraction of a percent. This does not affect `istft` (WOLA\n", "divides it out) but it does affect plain overlap-add." ] }, { "cell_type": "code", "execution_count": null, "id": "c019", "metadata": {}, "outputs": [], "source": [ "def ola_sum(window, hop, n_frames=16):\n", " n = len(window)\n", " s = np.zeros(n + hop * (n_frames - 1))\n", " for i in range(n_frames):\n", " s[i * hop: i * hop + n] += window\n", " return s[n: -n] # steady-state part only\n", "\n", "periodic = ss.get_window(\"hann\", 512) # denominator N\n", "sym = WT.make_hanning(512) # denominator N - 1\n", "s_per, s_sym = ola_sum(periodic, 256), ola_sum(sym, 256)\n", "ripple_sym = (s_sym.max() - s_sym.min()) / s_sym.mean()\n", "print(f\"periodic Hann, H = N/2: {s_per.min():.6f} .. {s_per.max():.6f}\")\n", "print(f\"symmetric Hann, H = N/2: {s_sym.min():.6f} .. {s_sym.max():.6f}, ripple {100 * ripple_sym:.3f} %\")\n", "assert np.allclose(s_per, 1.0, atol=1e-12)\n", "assert abs(100 * ripple_sym - 0.307) < 0.001" ] }, { "cell_type": "markdown", "id": "c020", "metadata": {}, "source": [ "Decibels with an absolute floor, against librosa. `librosa.power_to_db(P, ref=1.0, amin=1e-10,\n", "top_db=None)` is $10\\log_{10}\\max(P, 10^{-10})$, i.e. the same formula with a $-100$ dB floor;\n", "with `top_db=80` the floor is instead 80 dB below the loudest bin." ] }, { "cell_type": "code", "execution_count": null, "id": "c021", "metadata": {}, "outputs": [], "source": [ "P = np.abs(X) ** 2\n", "lib_db = aus.spectrograms.compute_linear_db_spectrogram(x, sp, aus.LogParams(-100.0)).data\n", "assert np.allclose(lib_db, np.maximum(10 * np.log10(np.maximum(P, 1e-300)), -100.0), atol=1e-9)\n", "assert np.allclose(lib_db, librosa.power_to_db(P, ref=1.0, amin=1e-10, top_db=None), atol=1e-9)\n", "\n", "top = librosa.power_to_db(P, ref=1.0) # top_db = 80 by default\n", "print(f\"library floor: {lib_db.min():.1f} dB (fixed); librosa top_db floor: {top.min():.1f} dB = max - 80\")\n", "assert abs(top.min() - (top.max() - 80.0)) < 1e-9" ] }, { "cell_type": "markdown", "id": "c022", "metadata": {}, "source": [ "## Ask the library to explain\n", "\n", "`aus.explain.explain(params, ...)` (or `audio.explain(params)`, which takes the sample rate and\n", "length from the signal) computes the sizes, spacings, overlap and the COLA/NOLA figures, and warns\n", "about problems such as a window too short for the lowest expected pitch." ] }, { "cell_type": "code", "execution_count": null, "id": "c023", "metadata": {}, "outputs": [], "source": [ "doc = audio.explain(params, f0_range=(80.0, 300.0))\n", "assert doc.quantity(\"Frequency bins\") == 257\n", "assert doc.quantity(\"Frequency resolution\") == res.frequency_resolution == 31.25 # Hz\n", "assert doc.quantity(\"Frame period\") == 8.0 # ms\n", "assert doc.quantity(\"Window duration\") == 32.0 # ms\n", "assert doc.quantity(\"Overlap\") == 75.0 # %\n", "assert doc.quantity(\"Frames\") == res.n_frames\n", "assert not doc.has_warning(\"caution\") # 32 ms >= two periods of 80 Hz (25 ms)\n", "assert doc.quantity(\"Overlap-add ripple\") > 0 and doc.has_warning_containing(\"constant-overlap-add\")\n", "doc" ] }, { "cell_type": "code", "execution_count": null, "id": "c024", "metadata": {}, "outputs": [], "source": [ "# A 16 ms window is too short for an 80 Hz voice: two periods take 25 ms.\n", "short_doc = aus.explain.explain(aus.StftParams(n_fft=256, hop_size=64, window=WT.hanning),\n", " sample_rate=16_000.0, f0_range=(80.0, 300.0))\n", "assert short_doc.has_warning(\"caution\")\n", "for w_ in short_doc.warnings:\n", " print(f\"[{w_['level']}] {w_['message']}\\n hint: {w_['hint']}\")" ] }, { "cell_type": "markdown", "id": "c025", "metadata": {}, "source": [ "## Exercises\n", "\n", "1. How many frames does `stft` produce for 2.5 s of audio at 22.05 kHz with $N = 2048$,\n", " $H = 512$ and `centre=True`? Predict, then check." ] }, { "cell_type": "code", "execution_count": null, "id": "c026", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c027", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "L_ = int(2.5 * 22_050) # 55 125 samples\n", "answer = 1 + (L_ + 2 * 1024 - 2048) // 512 # 1 + 107\n", "assert answer == 108\n", "clip = aus.sine_wave(440.0, 2.5, sample_rate=22_050, amplitude=0.5, dtype=F64)\n", "assert clip.samples_per_channel() == L_\n", "assert clip.stft(aus.StftParams(n_fft=2048, hop_size=512, window=WT.hanning, centre=True)).n_frames == answer" ] }, { "cell_type": "markdown", "id": "c028", "metadata": {}, "source": [ "2. You want one frame every 10 ms and a bin spacing $\\Delta f = f_s/N$ of at most 20 Hz at\n", " 16 kHz (the spacing of the bins, not the main-lobe resolution of about $2\\Delta f$). Choose $H$ and the\n", " smallest power-of-two $N$ (store `answer = (H, N)`), and confirm with the explainer." ] }, { "cell_type": "code", "execution_count": null, "id": "c029", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c030", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "h = round(0.010 * 16_000) # 160\n", "n = 1 << int(np.ceil(np.log2(16_000 / 20))) # N >= 800 -> 1024\n", "answer = (h, n)\n", "assert answer == (160, 1024)\n", "d = aus.explain.explain(aus.StftParams(n_fft=n, hop_size=h, window=WT.hanning), sample_rate=16_000.0)\n", "assert d.quantity(\"Frame period\") == 10.0 and d.quantity(\"Frequency resolution\") == 15.625" ] }, { "cell_type": "markdown", "id": "c031", "metadata": {}, "source": [ "3. A signal is 0.5 s of a full-scale 1 kHz sine followed by 0.5 s of silence. With\n", " `LogParams(-100.0)`, what value (dB) do the bins of the last frame take, and how far below the\n", " spectrogram's peak is that? (The second number is what a peak-referenced conversion such as\n", " `librosa.power_to_db(P, ref=np.max, top_db=None)` reports; with `top_db=80` it is clipped to\n", " $-80$ dB.)" ] }, { "cell_type": "code", "execution_count": null, "id": "c032", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c033", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "v = np.concatenate([sine.to_numpy(), np.zeros(8000)])\n", "s = aus.spectrograms.compute_linear_db_spectrogram(v, sp, aus.LogParams(-100.0)).data\n", "answer = (-100.0, 100.0 + 42.13) # -100 dB re 1, 142.13 dB below the peak\n", "assert np.all(np.abs(s[:, -1] - answer[0]) < 1e-9)\n", "assert abs((s.max() - s[0, -1]) - answer[1]) < 0.01\n", "# Peak-referenced: only with top_db=None (and amin = 1e-10, i.e. the same -100 dB floor) is it 142.13 dB.\n", "P_v = aus.spectrograms.compute_linear_power_spectrogram(v, sp).data\n", "assert np.allclose(librosa.power_to_db(P_v, ref=np.max, top_db=None, amin=1e-10)[:, -1], -answer[1], atol=0.01)\n", "assert np.allclose(librosa.power_to_db(P_v, ref=np.max)[:, -1], -80.0) # top_db = 80 clips" ] }, { "cell_type": "markdown", "id": "c034", "metadata": {}, "source": [ "4. A 4000-sample clip is analysed with $N = 512$, $H = 256$, `centre=True` and inverted with\n", " `istft`. How many samples come back? How many zeros must you append to the clip so that all\n", " 4000 original samples are returned?" ] }, { "cell_type": "code", "execution_count": null, "id": "c035", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c036", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "returned = (4000 // 256) * 256 # (M - 1) H with M = 1 + 4000 // 256\n", "answer = (returned, (-4000) % 256) # (3840 samples, 96 zeros -> 4096 = 16 H)\n", "assert answer == (3840, 96)\n", "clip = rng.standard_normal(4000) * 0.1\n", "padded = aus.AudioSamples.new_mono(np.concatenate([clip, np.zeros(answer[1])]), sample_rate=FS)\n", "back = padded.istft(padded.stft(p256)).to_numpy()\n", "assert len(back) == 4096 and np.allclose(back[:4000], clip, atol=1e-12)" ] }, { "cell_type": "markdown", "id": "c037", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "* `centre=True` pads with **zeros**. An STFT that pads by reflection gives different edge frames.\n", "* `WindowType.hanning` is the **symmetric** Hann. For the periodic one (as returned by\n", " `scipy.signal.get_window(\"hann\", N)`), pass `WindowType.custom(scipy.signal.get_window(\"hann\", N))`.\n", "* `StftResult.data` is a property (no parentheses), shaped `(bins, frames)`.\n", "* `istft` returns $(M-1)H$ samples: pad the input to a multiple of the hop to get every sample\n", " back.\n", "* dB conversion uses an **absolute** floor (`LogParams(floor_db)`), not one relative to the\n", " loudest value. Always pass a `LogParams` to the `*_db_*` functions.\n", "* The hop does not improve resolution in either axis; only $N$ (and the window shape) does.\n", "\n", "## See also\n", "\n", "* Rust guide chapter: [04. STFT and spectrograms](https://docs.rs/audio_samples/latest/audio_samples/guide/c04_stft_spectrograms/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_04_stft_spectrograms.rs`.\n", "* Python API: `AudioSamples.stft`, `AudioSamples.istft`, `StftParams`, `StftResult`,\n", " `SpectrogramParams`, `LogParams`, `audio_samples.spectrograms.compute_linear_db_spectrogram`,\n", " `aus.explain.explain` ([API reference](../api/audio_samples.rst)).\n", "* Previous: [03. The DFT, windows and leakage](03_dft_windows.ipynb).\n", " Next: [05. Convolution and FIR filters](05_convolution_fir.ipynb). Mel spectrograms and MFCCs:\n", " [10. Cepstrum, mel and MFCC](10_cepstrum_mel_mfcc.ipynb)." ] }, { "cell_type": "markdown", "id": "references", "metadata": {}, "source": [ "## References\n", "\n", "* Allen, J. B. and Rabiner, L. R. (1977). A unified approach to short-time Fourier analysis and synthesis. *Proceedings of the IEEE*, 65(11), 1558-1564.\n", "* Griffin, D. W. and Lim, J. S. (1984). Signal estimation from modified short-time Fourier transform. *IEEE Transactions on Acoustics, Speech, and Signal Processing*, 32(2), 236-243. (The weighted overlap-add inverse used by `istft`.)\n", "* Harris, F. J. (1978). On the use of windows for harmonic analysis with the discrete Fourier transform. *Proceedings of the IEEE*, 66(1), 51-83." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }