{ "cells": [ { "cell_type": "markdown", "id": "c000", "metadata": {}, "source": [ "# 13. Onsets and tempo\n", "\n", "Onset detection marks the instants at which each note or drum hit begins, that is, where new\n", "sound energy appears; tempo estimation looks for the period with which those\n", "instants repeat. Both are built on an *onset detection function* (ODF), one number per analysis\n", "frame, and both depend on its properties. This notebook states units explicitly (samples, frames,\n", "seconds, beats per minute) and identifies where the library's defaults give poor results.\n", "\n", "**Learning outcomes.** After working through this notebook you can\n", "\n", "* compute the half-wave-rectified spectral flux and reproduce the library's ODF exactly;\n", "* configure peak picking in **frames**, and explain what the default configuration's threshold\n", " floor does to weak onsets;\n", "* convert between lags, frames, seconds and BPM, and re-derive `estimate_tempo` from the ODF;\n", "* recognise tempo octave errors (and other metrical-level errors) and say why they happen.\n", "\n", "The click tracks here use 44.1 kHz audio and the same pseudo-random bursts as the Rust guide\n", "chapter, so every number below can be compared with it." ] }, { "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", "\n", "rng = np.random.default_rng(seed=2026)\n", "FS = 44_100 # sample rate in Hz\n", "HOP = 512 # ODF hop in samples (the default)\n", "MASK64 = (1 << 64) - 1\n", "\n", "\n", "def click_track(times, seconds, amps=None):\n", " # Decaying noise bursts (256 samples, 0.54 ms time constant) starting at `times` (s), with\n", " # peak amplitudes `amps` (0.9 each by default). The noise is the xorshift64 generator of the\n", " # Rust chapter, so the signals are identical.\n", " x = np.zeros(int(seconds * FS))\n", " seed = 0x2545_F491_4F6C_DD1D\n", " decay = np.exp(-np.arange(256) / 24)\n", " for t, amp in zip(times, [0.9] * len(times) if amps is None else amps):\n", " start = int(t * FS)\n", " for i in range(256):\n", " seed ^= (seed << 13) & MASK64\n", " seed ^= seed >> 7\n", " seed ^= (seed << 17) & MASK64\n", " x[start + i] = amp * decay[i] * ((seed >> 11) / float(1 << 53) * 2 - 1)\n", " return aus.AudioSamples.new_mono(x, sample_rate=FS)" ] }, { "cell_type": "markdown", "id": "c002", "metadata": {}, "source": [ "## Concept\n", "\n", "**Frames.** The signal is analysed in frames hopped by $H$ samples; frame $t$ is centred at\n", "$tH/f_s$ seconds ($f_s$ the sample rate in Hz). At $H = 512$ and $f_s = 44.1$ kHz a frame lasts\n", "$H/f_s = 11.61$ ms and there are $f_s/H = 86.13$ frames per second.\n", "\n", "**Spectral flux.** With $|X_b[t]|$ the magnitude of frequency bin $b$ in frame $t$, the\n", "half-wave-rectified flux is\n", "\n", "$$o[t] = \\sum_b \\max\\left(0,\\ |X_b[t]| - |X_b[t-1]|\\right), \\qquad o[0] = 0$$\n", "\n", "Only *increases* count, so note offsets do not create onsets. This library evaluates it on a\n", "constant-Q transform (CQT) whose $b_o O$ bins ($b_o$ per octave, $O$ octaves) start at $f_{min}$ Hz,\n", "with an analysis window of $N_w = \\lfloor 4f_s/f_{min} \\rfloor$ samples (four periods of the lowest\n", "bin). The quality factor is $Q = 1/(2^{1/b_o} - 1)$ (34.1 at $b_o = 24$): bin $b$'s kernel spans $Q$\n", "periods of its centre frequency, $Qf_s/f_b$ samples, cut to $N_w$ and centred in the frame. The magnitudes are **not** squared, despite the method's name (\"energy\"). Optionally, values\n", "below $\\mu$ times a running median of $L_{med}$ frames are set to zero (`adaptive_threshold`,\n", "$\\mu$ = `adaptive_threshold_multiplier`).\n", "\n", "**Peak picking**, all in **frames**: optional pre-emphasis ($o[i] - \\alpha\\,o[i-1]$) and\n", "median filtering (both off by default); normalisation by the maximum; a threshold\n", "$\\theta[i] = \\operatorname{clamp}(\\max_{|j-i| \\le w/2} o[j] - \\delta,\\ \\theta_{lo},\\ \\theta_{hi})$\n", "(by default window $w = 9$ frames, $\\delta = 0.07$, floor $\\theta_{lo} = 0.1$, $\\theta_{hi} = 1$);\n", "strict local maxima above it; finally peaks are accepted strongest first and dropped if closer\n", "than $s$ frames (3 by default) to an accepted one. A peak at frame $i$ is reported at $t_i = iH/f_s$ seconds.\n", "\n", "**Tempo.** A tempo of $B$ beats per minute is an inter-beat interval of $60/B$ seconds, i.e. a lag\n", "of\n", "\n", "$$L = \\frac{60 f_s}{BH}\\ \\text{frames}, \\qquad B = \\frac{60 f_s}{HL}$$\n", "\n", "`estimate_tempo` smooths the ODF (7-frame moving average), compresses it ($\\ln(1 + 0.5x)$),\n", "removes the mean and computes $a(L) = \\frac{1}{n-L}\\sum_i c[i]\\,c[i-L]$ for the integer lags that\n", "map into 40-240 BPM ($n$ the envelope length, $c$ the centred envelope). Each lag is weighted by a\n", "log-normal prior centred on 120 BPM, $w(B) = \\exp\\left(-\\tfrac{1}{2}\\log_2^2(B/120)\\right)$, and\n", "the lag with the largest $a(L)\\,w(B)$ is chosen. Two consequences: estimates lie on the grid $60f_s/(HL)$, and a\n", "periodic envelope correlates at $2L$ and $3L$ too, so **metrical-level errors** (half the tempo,\n", "an octave error, or a third of it) remain possible: the prior only biases the choice." ] }, { "cell_type": "code", "execution_count": null, "id": "c003", "metadata": {}, "outputs": [], "source": [ "# Numbers quoted above.\n", "assert round(1000 * HOP / FS, 2) == 11.61 and round(FS / HOP, 2) == 86.13" ] }, { "cell_type": "markdown", "id": "c004", "metadata": {}, "source": [ "## With the library\n", "\n", "A click track: four decaying noise bursts, one every 0.5 s. The default `OnsetDetectionConfig`\n", "finds all four. To vary its peak picking below, we rebuild the default `PeakPickingConfig` with a\n", "helper.\n", "\n", "From Python the nested configuration must be **rebuilt and assigned**: `config.peak_picking`\n", "returns a copy, so `config.peak_picking.set_median_filter(False, 3)` changes nothing." ] }, { "cell_type": "code", "execution_count": null, "id": "c005", "metadata": {}, "outputs": [], "source": [ "audio = click_track([0.25, 0.75, 1.25, 1.75], 2.0)\n", "\n", "\n", "def peak_picking(window=9, separation=3, median=False, pre_emphasis=False, floor=0.1):\n", " # The library's default peak picking, with the settings this notebook varies exposed.\n", " threshold = aus.AdaptiveThresholdConfig(\n", " aus.AdaptiveThresholdMethod.delta, delta=0.07, percentile=0.9,\n", " window_size=window, # frames\n", " min_threshold=floor, max_threshold=1.0, # floor: a fraction of the strongest peak\n", " )\n", " return aus.PeakPickingConfig(\n", " adaptive_threshold_config=threshold,\n", " min_peak_separation=separation, # frames\n", " pre_emphasis=pre_emphasis, pre_emphasis_coeff=0.97,\n", " median_filter=median, median_filter_length=3,\n", " normalize_onset_strength=True, normalization_method=aus.NormalizationMethod.peak,\n", " )\n", "\n", "\n", "def onset_config(pp=None, adaptive=True):\n", " config = aus.OnsetDetectionConfig.default()\n", " config.peak_picking = peak_picking() if pp is None else pp\n", " config.adaptive_threshold = adaptive\n", " return config\n", "\n", "\n", "# With no arguments, peak_picking() is exactly the default.\n", "assert repr(peak_picking()) == repr(aus.PeakPickingConfig.default())\n", "assert repr(aus.OnsetDetectionConfig.default().peak_picking) == repr(peak_picking())\n", "# 9 frames is 104.5 ms and 3 frames 34.8 ms at hop 512 and 44.1 kHz.\n", "assert round(1000 * 9 * HOP / FS, 1) == 104.5 and round(1000 * 3 * HOP / FS, 1) == 34.8\n", "\n", "# Mutating the nested object has no effect.\n", "trap = aus.OnsetDetectionConfig.default()\n", "trap.peak_picking.set_median_filter(True, 3)\n", "assert \"median_filter: false\" in repr(trap.peak_picking)\n", "\n", "config = aus.OnsetDetectionConfig.default()\n", "onsets = np.array(audio.detect_onsets(config))\n", "print(\"onsets (s):\", np.round(onsets, 4))\n", "assert len(onsets) == 4\n", "# Peaks fall on frames 21, 64, 107, 151.\n", "frames = np.round(onsets * FS / HOP)\n", "assert list(frames) == [21, 64, 107, 151]\n", "# The first three are the last frame whose centre precedes the burst, 6.2 to 7.7 ms before\n", "# it; the fourth is the frame after, 3.1 ms late. All are within one hop (11.6 ms).\n", "lead = 0.25 + 0.5 * np.arange(4) - onsets\n", "assert np.all(np.abs(lead) < 0.0078) and np.all(lead[:3] > 0.006) and -0.0032 < lead[3] < -0.003" ] }, { "cell_type": "markdown", "id": "c006", "metadata": {}, "source": [ "Onset times are quantised to whole frames: 0.5 s is 43.07 frames, so each burst falls 0.77 ms\n", "later relative to the frame grid than the one before. The long low-bin kernels (the 72.7 ms\n", "window) already respond to a burst that starts after their centre, so the largest increase tends\n", "to come in the frame before the burst, 6.2, 7.0 and 7.7 ms early for the first three. By the\n", "fourth burst that frame is 8.5 ms early and the frame after only 3.1 ms late, and the frame after\n", "has the larger increase." ] }, { "cell_type": "code", "execution_count": null, "id": "c007", "metadata": {}, "outputs": [], "source": [ "assert round(0.5 * FS / HOP, 2) == 43.07\n", "assert np.allclose(np.diff(lead[:3]), 0.5 - 43 * HOP / FS) and round(1000 * (0.5 - 43 * HOP / FS), 2) == 0.77" ] }, { "cell_type": "markdown", "id": "c008", "metadata": {}, "source": [ "**The defaults, in frames.** The default `PeakPickingConfig` applies neither pre-emphasis nor a\n", "median filter, normalises by the maximum and thresholds with a 9-frame window (104.5 ms),\n", "$\\delta = 0.07$ and a floor of 0.1; peaks closer than 3 frames (34.8 ms) are merged. Pre-emphasis\n", "is available but off: the ODF is already a difference of spectra, and pre-emphasising it moves\n", "each peak to the frame where it rises fastest, which comes before the onset.\n", "\n", "The floor has a side effect: after normalisation, no peak weaker than a tenth of the strongest one in\n", "the clip is reported. On eight bursts whose first three are 26 dB quieter than the rest (amplitude\n", "0.045 instead of 0.9) the defaults find only 5: the quiet bursts peak at 0.036, 0.033 and 0.024 of\n", "the largest value. Lowering the floor to 0.01 finds all 8.\n", "\n", "Lengths chosen as if they counted audio samples (threshold window 1024, separation 512, median\n", "length 3) behave very differently when they count frames. Switching each on, one at a time, in\n", "the 0.01-floor configuration: the length-3 median deletes every one-frame peak (0 onsets);\n", "a 1024-frame threshold window, clipped to the signal length, makes the threshold the global\n", "maximum minus $\\delta$ (1 onset); a 512-frame separation, reduced by the library to a quarter of\n", "the signal (91 frames, 1.06 s), keeps only 3. Switching pre-emphasis on (0.97) still finds all 8 on\n", "this signal." ] }, { "cell_type": "code", "execution_count": null, "id": "c009", "metadata": {}, "outputs": [], "source": [ "# The first three bursts are 26 dB quieter than the other five.\n", "amps8 = [0.045] * 3 + [0.9] * 5\n", "assert round(20 * np.log10(0.045 / 0.9), 2) == -26.02\n", "eight = click_track([0.25 + 0.5 * k for k in range(8)], 4.25, amps8)\n", "truth8 = 0.25 + 0.5 * np.arange(8)\n", "default8 = np.array(eight.detect_onsets(aus.OnsetDetectionConfig.default()))\n", "# The defaults find the five loud bursts only, each within one hop.\n", "assert len(default8) == 5 and np.all(np.abs(truth8[3:] - default8) < HOP / FS)\n", "\n", "# What the threshold sees: the peak-normalised ODF at each burst.\n", "_, odf8 = map(np.asarray, eight.onset_detection_function(aus.OnsetDetectionConfig.default()))\n", "pre8 = odf8 / np.max(np.abs(odf8))\n", "seen = [pre8[int(round(t * FS / HOP)) - 6 : int(round(t * FS / HOP)) + 1].max() for t in truth8]\n", "print(\"normalised peaks:\", np.round(seen, 3))\n", "assert list(np.round(seen, 3)) == [0.036, 0.033, 0.024, 0.333, 0.757, 0.794, 1.0, 0.884]\n", "\n", "low = lambda **kw: onset_config(peak_picking(floor=0.01, **kw))\n", "counts = {\n", " \"default\": len(default8),\n", " \"floor 0.01\": len(eight.detect_onsets(low())),\n", " \"+ median 3\": len(eight.detect_onsets(low(median=True))),\n", " \"+ window 1024\": len(eight.detect_onsets(low(window=1024))),\n", " \"+ separation 512\": len(eight.detect_onsets(low(separation=512))),\n", " \"+ pre-emphasis\": len(eight.detect_onsets(low(pre_emphasis=True))),\n", "}\n", "print(counts)\n", "assert list(counts.values()) == [5, 8, 0, 1, 3, 8]\n", "# The 512-frame separation is reduced by the library to a quarter of the 367 frames.\n", "assert len(odf8) == 367 and 367 // 4 == 91 and round(91 * HOP / FS, 2) == 1.06" ] }, { "cell_type": "markdown", "id": "c010", "metadata": {}, "source": [ "The threshold floor, the minimum spacing and the pre-emphasis all live in `peak_picking`;\n", "`OnsetDetectionConfig` itself holds the CQT, the hop and the median-based zeroing of the ODF.\n", "\n", "## How it works\n", "\n", "**The ODF.** Compute the CQT magnitude with the same parameters\n", "(`aus.spectrograms.compute_cqt_magnitude_spectrogram`, window $N_w = \\lfloor 4 \\cdot 44100/55\n", "\\rfloor = 3207$ samples, symmetric Hann, centred frames) and sum the rectified frame-to-frame\n", "increases; with the median-based zeroing switched off, the result must equal\n", "`onset_detection_function`. It returns **`(times, values)`**, in that order." ] }, { "cell_type": "code", "execution_count": null, "id": "c011", "metadata": {}, "outputs": [], "source": [ "raw = onset_config(adaptive=False)\n", "times, odf_lib = map(np.asarray, audio.onset_detection_function(raw))\n", "assert np.allclose(times, np.arange(len(times)) * HOP / FS) # frame t at t H / f_s\n", "\n", "cqt = raw.cqt_params # 24 bins/octave, 6 octaves from 55 Hz: 144 bins\n", "n_w = int(4 * FS / 55.0)\n", "assert n_w == 3207\n", "sp = aus.SpectrogramParams(aus.StftParams(n_w, HOP, aus.WindowType.hanning, True), FS)\n", "mag = np.asarray(aus.spectrograms.compute_cqt_magnitude_spectrogram(audio.to_numpy(), sp, cqt).data)\n", "assert mag.shape[0] == 144\n", "\n", "flux = np.zeros(mag.shape[1])\n", "for t in range(1, mag.shape[1]):\n", " flux[t] = sum(max(0.0, mag[b, t] - mag[b, t - 1]) for b in range(mag.shape[0]))\n", "# Same additions in the same order: exact agreement.\n", "assert np.array_equal(flux, odf_lib)" ] }, { "cell_type": "markdown", "id": "c012", "metadata": {}, "source": [ "**Peak picking**, re-implemented for the default configuration, on the ODF\n", "that `detect_onsets` uses (with the adaptive zeroing on), then frames to seconds." ] }, { "cell_type": "code", "execution_count": null, "id": "c013", "metadata": {}, "outputs": [], "source": [ "def pick_peaks(odf, window=9, delta=0.07, separation=3, lo=0.1, hi=1.0):\n", " o = odf / np.max(np.abs(odf)) # peak normalisation\n", " half = window // 2\n", " thr = np.array([np.clip(o[max(0, i - half) : i + half + 1].max() - delta, lo, hi) for i in range(len(o))])\n", " cand = [i for i in range(1, len(o) - 1) if o[i] > o[i - 1] and o[i] > o[i + 1] and o[i] > thr[i]]\n", " peaks = []\n", " for i in sorted(cand, key=lambda i: -o[i]): # strongest first\n", " if all(abs(i - p) >= separation for p in peaks):\n", " peaks.append(i)\n", " return sorted(peaks), o, thr\n", "\n", "\n", "_, odf = map(np.asarray, audio.onset_detection_function(config))\n", "peaks, o, thr = pick_peaks(odf)\n", "assert np.array_equal(np.array(peaks) * HOP / FS, onsets)\n", "\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "t = np.arange(len(o)) * HOP / FS\n", "ax.plot(t, o, label=\"ODF (normalised)\")\n", "ax.plot(t, thr, ls=\"--\", label=\"threshold\")\n", "ax.plot(onsets, o[peaks], \"o\", label=\"detected onsets\")\n", "for k in range(4):\n", " ax.axvline(0.25 + 0.5 * k, color=\"0.6\", ls=\":\", lw=1)\n", "ax.set(xlabel=\"Time (s)\", ylabel=\"Onset strength\", title=\"Spectral flux and peak picking (grey: true onsets)\")\n", "ax.legend(fontsize=8)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c014", "metadata": {}, "source": [ "The ODF peaks of the five loud bursts, which have the same amplitude, are 1.94, 4.41, 4.62, 5.82\n", "and 5.15: a factor of 3. Each burst is a different noise sample and falls at a different place\n", "relative to the frame grid, and the highest bins' kernels are shorter than a hop, so they see only\n", "part of the time between frames (the onset module documents this). A *local* threshold window\n", "copes with such differences." ] }, { "cell_type": "code", "execution_count": null, "id": "c015", "metadata": {}, "outputs": [], "source": [ "_, odf8 = map(np.asarray, eight.onset_detection_function(onset_config()))\n", "\n", "\n", "def heights(odf, times):\n", " return np.array([odf[int(round(tm * FS / HOP)) - 4 : int(round(tm * FS / HOP)) + 2].max() for tm in times])\n", "\n", "\n", "h8 = heights(odf8, [0.25 + 0.5 * k for k in range(8)])\n", "assert list(np.round(h8, 2)) == [0.21, 0.19, 0.14, 1.94, 4.41, 4.62, 5.82, 5.15]\n", "assert round(h8[3:].max() / h8[3:].min()) == 3 # the five loud bursts" ] }, { "cell_type": "markdown", "id": "c016", "metadata": {}, "source": [ "**Tempo.** `estimate_tempo(BeatTrackingConfig)` uses only the configuration's onset settings (its\n", "`tempo_bpm` is ignored). We rebuild the onset-strength envelope and the prior-weighted\n", "autocorrelation from `onset_detection_function` and compare, for click tracks of 8.5 s at several\n", "tempi (one click every $60/B$ s, $\\lfloor 8B/60 \\rfloor$ clicks from 0.1 s), and for an 80 BPM\n", "track whose off-beats (every other click) have a fifth of the amplitude." ] }, { "cell_type": "code", "execution_count": null, "id": "c017", "metadata": {}, "outputs": [], "source": [ "def tempo_from_odf(odf):\n", " n = len(odf)\n", " smooth = np.array([odf[max(0, i - 3) : min(n, i + 4)].mean() for i in range(n)]) # 7-frame average\n", " env = np.log1p(0.5 * smooth)\n", " c = env - env.mean()\n", " frame_rate = FS / HOP\n", " lo, hi = int(np.floor(60 * frame_rate / 240)), min(int(np.ceil(60 * frame_rate / 40)), n - 1)\n", " ac = {lag: c[lag:] @ c[:-lag] / (n - lag) for lag in range(lo, hi + 1)}\n", " prior = lambda lag: np.exp(-0.5 * np.log2(60 * frame_rate / lag / 120) ** 2)\n", " best = max((lag for lag in ac if ac[lag] > 0), key=lambda lag: ac[lag] * prior(lag))\n", " return 60 * frame_rate / best, best, ac, prior\n", "\n", "\n", "def tempo_track(bpm, off=1.0):\n", " # Clicks every 60/bpm s from 0.1 s; every other click (the off-beats) at `off` of 0.9.\n", " ibi = 60 / bpm\n", " n = int(8 / ibi)\n", " return click_track([0.1 + ibi * k for k in range(n)], 8.5, [0.9 if k % 2 == 0 else 0.9 * off for k in range(n)])\n", "\n", "\n", "beat_cfg = aus.BeatTrackingConfig(120.0, aus.OnsetDetectionConfig.default())\n", "results = {}\n", "for bpm, off in ((60, 1.0), (80, 1.0), (100, 1.0), (120, 1.0), (140, 1.0), (174, 1.0), (80, 0.2)):\n", " ibi = 60 / bpm\n", " track = tempo_track(bpm, off)\n", " est = track.estimate_tempo(beat_cfg)\n", " _, odf_t = map(np.asarray, track.onset_detection_function(aus.OnsetDetectionConfig.default()))\n", " ours, lag, ac, prior = tempo_from_odf(odf_t)\n", " assert abs(ours - est) < 1e-9 # same operations: rounding-level agreement\n", " results[bpm, off] = (est, lag, ac, prior, odf_t, ibi)\n", " label = \" (quiet off-beats)\" if off < 1 else \"\"\n", " print(f\"{bpm:4d} BPM clicks{label}: estimate {est:7.2f} BPM (lag {lag:3d} frames), ratio {est / bpm:.3f}\")\n", "\n", "est = {key: round(r[0], 2) for key, r in results.items()}\n", "assert est == {\n", " (60, 1.0): 60.09, (80, 1.0): 79.51, (100, 1.0): 99.38, (120, 1.0): 120.19,\n", " (140, 1.0): 139.67, (174, 1.0): 172.27, (80, 0.2): 40.06,\n", "}" ] }, { "cell_type": "markdown", "id": "c018", "metadata": {}, "source": [ "Correct (to the grid) at every tempo when the clicks are equal, and **half** the tempo at 80 BPM\n", "when the off-beats are quiet. There the ODF at the ten clicks is 3.83, 1.32, 3.61, 0.49, 5.77,\n", "0.38, 5.9, 0.79, 2.82, 0.73: the envelope does repeat every *two* beats. Its autocorrelation at\n", "lag 129 (0.00607) is 3.35 times that at lag 65 (0.00181), a larger ratio than the prior weights\n", "(0.29 against 0.84) can offset. A listener might well hear the accented clicks as the beat; the\n", "estimator cannot tell which metrical level is meant." ] }, { "cell_type": "code", "execution_count": null, "id": "c019", "metadata": {}, "outputs": [], "source": [ "_, _, ac80, prior, odf80, ibi = results[80, 0.2]\n", "h80 = heights(odf80, [0.1 + ibi * k for k in range(10)])\n", "assert list(np.round(h80, 2)) == [3.83, 1.32, 3.61, 0.49, 5.77, 0.38, 5.9, 0.79, 2.82, 0.73]\n", "assert abs(ac80[129] - 0.00607) < 5e-6 and abs(ac80[65] - 0.00181) < 5e-6\n", "assert round(ac80[129] / ac80[65], 2) == 3.35\n", "assert round(prior(129), 2) == 0.29 and round(prior(65), 2) == 0.84\n", "\n", "lags = np.array(sorted(ac80))\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "ax.plot(lags, [ac80[l] for l in lags], label=\"a(L)\")\n", "ax.plot(lags, [ac80[l] * prior(l) for l in lags], label=\"a(L) w(B)\")\n", "ax.axvline(64.6, color=\"0.5\", ls=\":\", label=\"true beat (64.6 frames)\")\n", "ax.set(xlabel=\"Lag L (frames)\", ylabel=\"Autocorrelation\", title=\"80 BPM clicks, quiet off-beats: the envelope repeats every 2 beats\")\n", "ax.legend(fontsize=8)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c020", "metadata": {}, "source": [ "**An independent reference.** `librosa.feature.tempo` computes its ODF from a mel spectrogram in dB.\n", "On the six click tracks of equal clicks it gives the same estimates as `estimate_tempo` (its grid is\n", "the same at this hop), including 79.51 BPM at 80 and 172.27 BPM at 174. On the track with quiet\n", "off-beats it still gives 79.51 BPM: in dB the off-beats are only 14 dB below the on-beats rather\n", "than a fifth of their amplitude, so its envelope repeats every beat. `estimate_tempo` works on the\n", "linear CQT magnitude, where the off-beats count for much less." ] }, { "cell_type": "code", "execution_count": null, "id": "c021", "metadata": {}, "outputs": [], "source": [ "import librosa\n", "\n", "librosa_bpm = {}\n", "for bpm, off in results:\n", " y = tempo_track(bpm, off).to_numpy()\n", " librosa_bpm[bpm, off] = round(float(librosa.feature.tempo(y=y, sr=FS, hop_length=HOP)[0]), 2)\n", "print(librosa_bpm)\n", "# The same estimates as estimate_tempo for the equal clicks.\n", "assert all(librosa_bpm[key] == est[key] for key in librosa_bpm if key[1] == 1.0)\n", "assert librosa_bpm[80, 0.2] == 79.51 # one beat: see above" ] }, { "cell_type": "markdown", "id": "c022", "metadata": {}, "source": [ "## Ask the library to explain\n", "\n", "`OnsetDetectionConfig.explain(sample_rate)` converts every frame count into milliseconds and flags the\n", "frames-versus-samples confusion of `min_peak_separation`." ] }, { "cell_type": "code", "execution_count": null, "id": "c023", "metadata": {}, "outputs": [], "source": [ "doc = config.explain(44_100.0)\n", "assert doc.quantity(\"Window size\") == 3207\n", "assert abs(doc.quantity(\"Window duration\") - 72.72) < 0.005\n", "assert abs(doc.quantity(\"Time resolution\") - 11.61) < 0.005\n", "assert abs(doc.quantity(\"Minimum peak separation\") - 34.83) < 0.005 # 3 frames\n", "assert doc.quantity(\"CQT bins\") == 144\n", "# The separation is flagged as counting frames, not samples (34.83 ms here, not 0.07 ms).\n", "assert doc.has_warning_containing(\"counts onset-function frames\")\n", "doc" ] }, { "cell_type": "markdown", "id": "c024", "metadata": {}, "source": [ "## Exercises\n", "\n", "**Exercise 1 (units).** You want onsets at least 50 ms apart with $H = 256$ at 44.1 kHz. What\n", "`min_peak_separation` do you set, and what spacing in milliseconds does it actually give? Store the\n", "number of frames in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c025", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c026", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = int(np.ceil(0.05 * 44_100 / 256)) # 8.6 -> 9 frames\n", "assert answer == 9\n", "c = aus.OnsetDetectionConfig.percussive(44_100)\n", "assert c.hop_size == 256\n", "c.peak_picking = peak_picking(separation=answer)\n", "ms = c.explain(44_100.0).quantity(\"Minimum peak separation\")\n", "assert abs(ms - 52.24) < 0.005\n", "print(f\"{answer} frames = {ms:.2f} ms\")" ] }, { "cell_type": "markdown", "id": "c027", "metadata": {}, "source": [ "**Exercise 2 (the tempo grid).** At $H = 512$ and 44.1 kHz, which BPM values can\n", "`estimate_tempo` return between 115 and 125 BPM? Store them (rounded to 0.01, descending) in\n", "`answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c028", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c029", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "bpm = lambda lag: 60 * FS / (HOP * lag)\n", "answer = [round(bpm(lag), 2) for lag in range(30, 60) if 115 <= bpm(lag) <= 125]\n", "assert answer == [123.05, 120.19, 117.45] # lags 42, 43, 44" ] }, { "cell_type": "markdown", "id": "c030", "metadata": {}, "source": [ "**Exercise 3 (choosing the hop).** How would halving the hop to 256 samples change the grid\n", "spacing near 120 BPM? Predict, then compute. Store `(coarse, fine)` spacings in BPM in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c031", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c032", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "bpm = lambda lag, hop: 60 * FS / (hop * lag)\n", "answer = (bpm(43, 512) - bpm(44, 512), bpm(86, 256) - bpm(87, 256))\n", "assert abs(answer[0] - 2.73) < 0.005 and abs(answer[1] - 1.38) < 0.005 # roughly halves" ] }, { "cell_type": "markdown", "id": "c033", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "- **Frames, not samples.** Every peak-picking length counts ODF frames ($H$ samples each). Convert\n", " with frames = seconds $\\times f_s/H$, or use `PeakPickingConfig.set_min_peak_separation_ms`.\n", "- **The default floor hides weak onsets.** The ODF is normalised by its maximum and the default\n", " threshold never drops below 0.1, so an onset whose peak is under a tenth of the\n", " clip's strongest is not reported. Lower the floor (`min_threshold` of `AdaptiveThresholdConfig`)\n", " for material with a wide dynamic range, and check the result with `.explain()`.\n", "- **Nested configs are copies in Python**: build a `PeakPickingConfig` and assign it to\n", " `config.peak_picking`; calling setters on `config.peak_picking` has no effect.\n", "- **`onset_detection_function` returns `(times, values)`**, in that order.\n", "- **Reported times are frame centres**, quantised to $H/f_s$; on clean clicks the peak usually falls\n", " in the last frame before the onset, so the reported time is within one hop and usually early.\n", "- **\"Energy\" flux is magnitude flux** here: magnitudes are not squared.\n", "- **Octave errors in tempo** are expected, not exceptional: check the estimate against $2\\times$,\n", " $\\tfrac{1}{2}\\times$ and $3\\times$ before trusting it. `BeatTrackingConfig.tempo_bpm` is ignored by\n", " `estimate_tempo`.\n", "- **The frame-wise onset functions differ from the detector used here**:\n", " `AudioSamples.onset_strength` uses a mel spectrogram in dB and `rhythm.peak_pick` uses\n", " separate pre/post windows, so their numbers will not match `detect_onsets`.\n", "\n", "## See also\n", "\n", "- Rust guide chapter: [Onsets and tempo](https://docs.rs/audio_samples/latest/audio_samples/guide/c13_onsets_tempo/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 onset module documentation.\n", "- Python API: `AudioSamples.detect_onsets`, `AudioSamples.onset_detection_function`,\n", " `AudioSamples.estimate_tempo`, `AudioSamples.detect_beats`, `OnsetDetectionConfig`,\n", " `PeakPickingConfig`, `AdaptiveThresholdConfig`, `BeatTrackingConfig`\n", " ([API reference](../api/audio_samples.rst)).\n", "- Previous: [12. Dynamics](12_dynamics.ipynb). Next:\n", " [14. Psychoacoustics and codecs](14_psychoacoustics_codecs.ipynb)." ] }, { "cell_type": "markdown", "id": "references", "metadata": {}, "source": [ "## References\n", "\n", "* Bello, J. P., Daudet, L., Abdallah, S., Duxbury, C., Davies, M. and Sandler, M. B. (2005). A tutorial on onset detection in music signals. *IEEE Transactions on Speech and Audio Processing*, 13(5), 1035-1047.\n", "* Dixon, S. (2006). Onset detection revisited. In *Proceedings of the 9th International Conference on Digital Audio Effects (DAFx-06)*, Montreal, 133-137.\n", "* Ellis, D. P. W. (2007). Beat tracking by dynamic programming. *Journal of New Music Research*, 36(1), 51-60. (Autocorrelation tempo estimation with a log-normal tempo prior.)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }