From 6cc73267a62035a7e2fd2b51d27f06b67142c6ce Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Wed, 23 Sep 2026 17:25:37 +0200 Subject: [PATCH] Improved beat and grid detection --- CLAUDE.md | 20 ++ backend/bench_grid_detect.py | 183 ++++++++++++ backend/konduktor/core/auto_hotcues.py | 18 -- backend/konduktor/core/grid_detect.py | 387 +++++++++++++++++++++++++ backend/konduktor/main.py | 13 +- backend/run_tests.sh | 2 +- backend/test_grid_detect.py | 149 ++++++++++ 7 files changed, 748 insertions(+), 24 deletions(-) create mode 100644 backend/bench_grid_detect.py create mode 100644 backend/konduktor/core/grid_detect.py create mode 100644 backend/test_grid_detect.py diff --git a/CLAUDE.md b/CLAUDE.md index f51dd64..a83f3f5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,6 +47,20 @@ Two independent apps that talk over HTTP: - `registry.py` — adapter selection by **`can_open()` probe**, not extension (Rekordbox is a `.db`, Serato is a directory). - `audio_tags.py`, `pathmap.py`, `auto_hotcues.py` — format-agnostic helpers. + - `grid_detect.py` — **beatgrid detection** (the deck's Analyze button, + `POST /api/tracks/grid/auto`). Fits ONE constant tempo + anchor to the whole + track rather than tracking beats: `librosa.beat.beat_track`, which it + replaced, quantises tempo to 23 ms frames and can only return 117.45 / + 123.05 / 129.20 / 136.00 between 115 and 140 BPM. Timing comes from a + 1–8 kHz attack band, and which attack is the beat from whether a kick's + low end follows it — each band alone lost a real track to an off-beat hat + or a syncopated bassline. Positions are in the **decoded audio's** time + base (libsndfile = CoreAudio to the sample on MP3). **Rekordbox's grids sit + a constant ~25 ms later on lossy files** and at 0 on WAV — a platform + time-base difference, deliberately NOT corrected here; Traktor's is + unmeasured. `backend/bench_grid_detect.py` scores it against any library's + single-marker grids and reports that constant separately from detection + error (29 Rekordbox references: old 1/29 BPMs, new 27/29). - `places.py` — where a person keeps things on THIS computer: the user's own folders (via `platformdirs` — hardcoding is wrong on every OS differently: `~/Videos` is `Movies` on macOS, Linux's are user-configurable localised @@ -416,6 +430,12 @@ serialization path.** It enforces: companion cue is invented), that the existing 8,485 entries render byte-identically, that the job registry runs/fails/cancels, and that a cancelled import leaves **no orphaned audio and an untouched collection**. +- `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the + tempo and first beat are known rather than borrowed from another analyser: + exact integer and non-integer BPMs, the 125 BPM the old detector could not + return, octave choice, and the loud off-beat hat and syncopated bassline that + each fooled one band on real music. Accuracy on REAL music is + `bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio). - `test_picker.py` — the picker's routes. Pins the scoping, because the bug it replaced was invisible: `/api/library/options` flattened every driver's detections and returned `[0]`, so a plugged-in USB stick could be offered as diff --git a/backend/bench_grid_detect.py b/backend/bench_grid_detect.py new file mode 100644 index 0000000..aa8f4a6 --- /dev/null +++ b/backend/bench_grid_detect.py @@ -0,0 +1,183 @@ +"""Benchmark beatgrid detection against grids a DJ platform already analysed. + +NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to +compare rather than a pass/fail. Every open is read-only — nothing is saved. + + python bench_grid_detect.py # the local Rekordbox library + python bench_grid_detect.py path/to/collection.nml path/to/master.db + python bench_grid_detect.py --legacy # score the old librosa beat_track + +The reference is each track's own grid, and only single-marker grids are used: +a multi-marker grid is either a real tempo change (which a constant-tempo +detector cannot match by design) or a hand edit, and neither is ground truth +for "what is this track's tempo". + +Per track it reports: + - BPM error, and whether it is an octave error (half/double tempo); + - PHASE error at 30 s in and 30 s before the end — the distance between the + detected grid's nearest beat and the reference's, in ms. Measuring at two + ends is what separates "anchor wrong" (both off by the same amount) from + "BPM wrong" (error grows along the track), which one number would conflate. +""" +from __future__ import annotations + +import argparse +import os +import sys +import tempfile +import time +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") +os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-")) + +import konduktor.adapters # noqa: E402,F401 — registers the drivers +from konduktor.core import registry # noqa: E402 + +BPM_OK = 0.02 # a grid this close drifts < 1/50 beat per minute... +PHASE_OK_MS = 10.0 # roughly where a DJ starts to hear flamming + + +def _phase_error_ms(t: float, ref: tuple[float, float], det: tuple[float, float]) -> float: + """Signed distance (ms) from the reference's nearest beat at ``t`` to the + detected grid's nearest beat, wrapped to half the reference beat.""" + r0, rb = ref + d0, db = det + rp, dp = 60.0 / rb, 60.0 / db + ref_beat = r0 + round((t - r0) / rp) * rp + det_beat = d0 + round((ref_beat - d0) / dp) * dp + e = det_beat - ref_beat + e = (e + rp / 2) % rp - rp / 2 + return e * 1000.0 + + +def _octave(det: float, ref: float) -> str: + for k, name in ((2.0, "x2"), (0.5, "/2"), (1.5, "x1.5"), (2 / 3, "/1.5")): + if abs(det - ref * k) < 0.5: + return name + return "" + + +def legacy_detect(audio_path: str): + """The detector `core/grid_detect.py` replaced (librosa ``beat_track``), kept + here so the two can still be compared on the same references.""" + import librosa + import numpy as np + from konduktor.core.grid_detect import GridResult + + y, sr = librosa.load(audio_path, sr=22050, mono=True) + tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False) + return GridResult(float(np.ravel(tempo)[0]), float(librosa.frames_to_time(beats, sr=sr)[0]), len(y) / sr) + + +def references(paths: list[Path]) -> list[tuple[str, Path, float, float]]: + out = [] + for p in paths: + a = registry.open_library(p) + try: + for t in a.tracks: + cues = a.track_cues(t.id) + if cues is None or len(cues.grid_markers) != 1: + continue + audio = a.audio_path(t.id) + if audio is None or not audio.exists(): + continue + m = cues.grid_markers[0] + out.append((f"{t.artist or ''} - {t.title or audio.stem}".strip(" -"), audio, m.start, m.bpm)) + finally: + close = getattr(a, "close", None) + if close: + close() + # One row per audio file: the same file in two libraries would count twice. + seen, uniq = set(), [] + for r in out: + if r[1] not in seen: + seen.add(r[1]) + uniq.append(r) + return uniq + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("libraries", nargs="*", type=Path) + ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector") + args = ap.parse_args() + + libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"] + refs = references(libs) + if not refs: + print("No single-marker reference grids with reachable audio.") + return 1 + + if args.legacy: + detect = legacy_detect + else: + from konduktor.core.grid_detect import detect_grid as detect + + rows = [] + for name, audio, r0, rb in refs: + t0 = time.perf_counter() + try: + res = detect(str(audio)) + except Exception as ex: # a failure is a data point, not a crash + print(f" FAIL {name[:48]:48} {ex}") + rows.append(None) + continue + dt = time.perf_counter() - t0 + bpm, first = res.bpm, res.anchor + import soundfile as sf + try: + dur = sf.info(str(audio)).duration + except Exception: + dur = res.duration + early = _phase_error_ms(min(30.0, dur / 3), (r0, rb), (first, bpm)) + late = _phase_error_ms(max(dur - 30.0, 2 * dur / 3), (r0, rb), (first, bpm)) + oct_ = _octave(bpm, rb) if abs(bpm - rb) >= 0.5 else "" + ok = abs(bpm - rb) <= BPM_OK and abs(early) <= PHASE_OK_MS and abs(late) <= PHASE_OK_MS + lossy = audio.suffix.lower() not in (".wav", ".aif", ".aiff", ".flac") + rows.append((abs(bpm - rb), early, late, oct_, ok, dt, lossy)) + conf = f"{res.drift_ms:5.1f}" if res.drift_ms is not None else " -" + print( + f" {'ok ' if ok else 'BAD '} {name[:48]:48} ref {rb:7.3f} got {bpm:8.3f} {oct_:5}" + f" phase {early:+7.1f} / {late:+7.1f} ms drift {conf} ms {dt:4.1f}s" + ) + + good = [r for r in rows if r] + n = len(rows) + same_octave = [r for r in good if not r[3]] + print() + print(f"tracks {n}") + print(f"all correct {sum(r[4] for r in good)}/{n}") + print(f"BPM within {BPM_OK} {sum(r[0] <= BPM_OK for r in good)}/{n}") + print(f"octave errors {sum(bool(r[3]) for r in good)}/{n}") + if same_octave: + import statistics as st + print(f"median |phase| early {st.median(abs(r[1]) for r in same_octave):.1f} ms") + print(f"median |phase| late {st.median(abs(r[2]) for r in same_octave):.1f} ms") + print(f"phase within {PHASE_OK_MS:.0f} ms " + f"{sum(abs(r[1]) <= PHASE_OK_MS and abs(r[2]) <= PHASE_OK_MS for r in same_octave)}/{n}") + print(f"mean time per track {sum(r[5] for r in good) / max(1, len(good)):.2f} s") + + # A platform's MP3/AAC time base can differ from the decoded audio's by a + # constant (Rekordbox: ~+26 ms, the decoder delay it does not trim). That + # is not detection error, and it would swamp it — so report the constant + # per format, and how tightly the tracks sit around it. + import statistics as st + print() + for label, want in (("lossless", False), ("lossy", True)): + grp = [r for r in same_octave if r[6] == want and r[0] <= BPM_OK] + if len(grp) < 2: + continue + offs = [(r[1] + r[2]) / 2 for r in grp] + med = st.median(offs) + spread = [abs(o - med) for o in offs] + within = sum(abs(r[1] - med) <= PHASE_OK_MS and abs(r[2] - med) <= PHASE_OK_MS for r in grp) + print(f"{label:9} n={len(grp):2} constant offset {med:+6.1f} ms " + f"|deviation| median {st.median(spread):4.1f} max {max(spread):5.1f} ms " + f"within {PHASE_OK_MS:.0f} ms of it: {within}/{len(grp)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/konduktor/core/auto_hotcues.py b/backend/konduktor/core/auto_hotcues.py index 46e0f5d..a8a32b6 100644 --- a/backend/konduktor/core/auto_hotcues.py +++ b/backend/konduktor/core/auto_hotcues.py @@ -96,24 +96,6 @@ def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, return out, duration -def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]: - """Detect a track's tempo and the time of its first beat. - - Returns ``(bpm, first_beat_sec)`` for building a Traktor beatgrid (BPM + - anchor). Uses librosa beat tracking. Half/double-tempo octave errors are - left for the user to fix with the ×2 / ÷2 controls (per product decision). - """ - import librosa - - y, sr = librosa.load(audio_path, sr=sr, mono=True) - tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False) - bpm = float(np.ravel(tempo)[0]) - if bpm <= 0 or len(beats) == 0: - raise ValueError("Could not detect a tempo/beat") - first_beat = float(librosa.frames_to_time(beats, sr=sr)[0]) - return bpm, first_beat - - def _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]: """The ``(start, bpm)`` of the beatgrid segment containing ``t``. diff --git a/backend/konduktor/core/grid_detect.py b/backend/konduktor/core/grid_detect.py new file mode 100644 index 0000000..040e973 --- /dev/null +++ b/backend/konduktor/core/grid_detect.py @@ -0,0 +1,387 @@ +"""Beatgrid detection: one constant tempo + anchor, fitted to the whole track. + +Why not a beat tracker. The previous detector was ``librosa.beat.beat_track``, +and it could not be right: its tempo comes from an autocorrelation over +~23 ms frames, so it can only return ``60 / (k * 23 ms)`` — between 115 and +140 BPM the ONLY values it can produce are 117.45, 123.05, 129.20 and 136.00. +A 125 BPM track came back as 123.05 and drifted ~2 beats per minute, and its +first beat carried the onset curve's own ~23 ms lag. Against 29 grids +Rekordbox analysed (``bench_grid_detect.py``) it got 1 BPM and 0 grids right. + +Dance music makes a much stronger assumption available, the one Traktor's and +Rekordbox's analysers make: the tempo is CONSTANT. So instead of tracking +beats, this fits one pulse train to every onset in the track: + +1. **Onset curves at 1 kHz from zero-phase band filters** (``sosfiltfilt`` + adds no group delay): a kick band, a mid band and the full signal. +2. **Tempo from the whole track's spectrum.** A pulse train at ``f`` Hz has + energy at ``f, 2f, 3f …``; the onset spectrum's magnitude summed over those + harmonics peaks at the tempo, as finely as ``1 / track length`` allows, + then parabolic refinement goes further. +3. **Octave by comb score**: a comb at half the tempo hits every kick too, so + the FASTEST candidate scoring nearly as well as the best wins, inside + ``bpm_range``. Halftime genres stay genuinely ambiguous — ×2 / ÷2 exist. +4. **Phase from attacks that are followed by low end.** Timing comes from a + 1–8 kHz attack band, whose onset is sharp (a kick's low end swells for ~25 ms after + its attack, so the kick band alone lands late). Which attack is the beat is + decided by whether low end follows it: that rejects the off-beat hat (no low + end) and the syncopated bassline (no attack), each of which won a benchmark + track when judged by one band alone. +5. **Round BPMs are snapped** only if the round tempo keeps every section of + the track on the beat — a direct test, rather than a score ratio. + +Positions are in the DECODED audio's time base — the one Konduktor's deck +plays (libsndfile and macOS CoreAudio agree to the sample on MP3). A platform +may disagree for lossy files: Rekordbox's grids sit a constant ~25 ms later on +every MP3/AAC in the benchmark (the decoder delay it does not trim) and at 0 on +WAV. That is a platform time-base difference, not a detection error, and it is +deliberately not corrected here. + +``drift_ms`` reports how far the fitted grid strays from the beat in its +worst section — the number that says a slowly wandering tempo is not being +described by one marker. A sudden tempo change is out of its reach (that is +flexible-grid detection, not built). +""" +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + +_SR = 22050 # plenty for a kick; halves decode + filter cost vs 44.1k +_FR = 1000 # onset-curve frame rate (Hz) — 1 ms timing resolution +_TEMPO_FR = 250 # the tempo spectrum only needs content up to ~15 Hz +_HARMONICS = 8 # pulse-train harmonics summed for the tempo score + +# The band an attack's timing is read from. A kick's beater click reaches well +# above 1 kHz; a bass note's leakage does not, which is what stops a +# syncopated bassline (whose low end is as loud as the kick's) from posing as +# one. The hat lives here too, but has no low end to follow it. +_ATTACK_LO_HZ = 1000.0 +_ATTACK_HI_HZ = 8000.0 +# How long after an attack a kick's low end is looked for (ms). +_KICK_FOLLOW_MS = 45 +# Measured, not derived: on WAV loops that start exactly on the beat, the +# mid-band onset peak lands this far before the true attack (the centred +# smoothing's leading edge). Added back so the grid sits ON the transient. +_ONSET_BIAS_S = 0.002 + +# The detected range. Anything outside is folded in by octaves, which is where +# half/double-tempo answers come from — and what ×2 / ÷2 are for. +DEFAULT_BPM_RANGE = (70.0, 180.0) + + +@dataclass(frozen=True) +class GridResult: + bpm: float + anchor: float # seconds: the first beat at or after the music starts + duration: float # seconds + # Worst distance between the grid and the beat over any ~30 s section with + # a clear beat. A few ms on a produced track; tens of ms means the tempo + # wanders (a live drummer, a vinyl rip). A sudden tempo CHANGE is not seen. + drift_ms: float | None = None + + +# ---- onset curves ------------------------------------------------------------- +def _band_env( + y: np.ndarray, sr: int, lo: float | None, hi: float | None, smooth_ms: int = 11 +) -> np.ndarray: + """Log-energy envelope of one band at ``_FR`` Hz, zero-phase throughout.""" + from scipy.signal import butter, sosfiltfilt + + if lo and hi: + sos = butter(4, [lo, hi], btype="bandpass", fs=sr, output="sos") + elif hi: + sos = butter(4, hi, btype="lowpass", fs=sr, output="sos") + elif lo: + sos = butter(4, lo, btype="highpass", fs=sr, output="sos") + else: + sos = None + x = sosfiltfilt(sos, y) if sos is not None else y + hop = sr / _FR + n = int(len(x) / hop) + # Block energy on a fractional hop, so frame i is centred on time i / _FR. + edges = np.round(np.arange(n + 1) * hop).astype(np.int64) + c = np.concatenate(([0.0], np.cumsum(x.astype(np.float64) ** 2))) + e = (c[edges[1:]] - c[edges[:-1]]) / np.maximum(1, np.diff(edges)) + # A centred smooth removes a band's carrier ripple (a 50 Hz kick needs + # ~10 ms) without moving anything in time. + if smooth_ms > 1: + e = np.convolve(e, np.ones(smooth_ms) / smooth_ms, mode="same") + return np.log1p(e / (np.percentile(e, 90) + 1e-12) * 100.0) + + +def _onset(env: np.ndarray) -> np.ndarray: + """Positive slope of a log envelope, centred so a peak sits ON the attack.""" + d = np.zeros_like(env) + d[1:-1] = (env[2:] - env[:-2]) / 2 + d = np.maximum(d, 0.0) + # Remove a slowly varying floor so long crescendos don't read as onsets. + from scipy.ndimage import uniform_filter1d + d = np.maximum(d - uniform_filter1d(d, size=_FR // 4), 0.0) + return d / (d.max() + 1e-12) + + +# ---- tempo -------------------------------------------------------------------- +def _decimate(o: np.ndarray, factor: int) -> np.ndarray: + n = len(o) // factor + return o[: n * factor].reshape(n, factor).sum(axis=1) + + +def _dft(o: np.ndarray, fr: float, freqs: np.ndarray) -> np.ndarray: + """|DFT| of ``o`` at arbitrary frequencies (Hz), chunked to bound memory.""" + t = np.arange(len(o)) / fr + out = np.empty(len(freqs)) + step = max(1, 4_000_000 // max(1, len(o))) + for i in range(0, len(freqs), step): + f = freqs[i : i + step, None] + out[i : i + step] = np.abs(np.exp(-2j * np.pi * f * t) @ o) + return out + + +def _harmonic_score(o: np.ndarray, fr: float, bpms: np.ndarray, n_harm: int = _HARMONICS) -> np.ndarray: + f0 = bpms / 60.0 + return sum(_dft(o, fr, f0 * k) for k in range(1, n_harm + 1)) + + +def _coarse_candidates(o_t: np.ndarray, lo: float, hi: float) -> list[float]: + """Local maxima of the harmonic tempo score over [lo/2, hi*2] BPM.""" + n = 1 << int(np.ceil(np.log2(len(o_t) * 8))) + spec = np.abs(np.fft.rfft(o_t - o_t.mean(), n)) + df = _TEMPO_FR / n + bpms = np.arange(lo / 2, hi * 2, 0.05) + score = np.zeros_like(bpms) + for k in range(1, _HARMONICS + 1): + idx = np.round(bpms / 60.0 * k / df).astype(np.int64) + idx = idx[idx < len(spec)] + score[: len(idx)] += spec[idx] + from scipy.signal import find_peaks + peaks, _ = find_peaks(score, distance=int(1.0 / 0.05)) + peaks = peaks[np.argsort(score[peaks])[::-1][:8]] + return [float(bpms[p]) for p in peaks] + + +def _refine(o_t: np.ndarray, bpm: float, width: float, step: float) -> tuple[float, float]: + grid = np.arange(bpm - width, bpm + width + step / 2, step) + s = _harmonic_score(o_t, _TEMPO_FR, grid) + i = int(np.argmax(s)) + # Parabolic interpolation between the three samples around the max. + if 0 < i < len(s) - 1: + a, b, c = s[i - 1], s[i], s[i + 1] + den = a - 2 * b + c + off = 0.5 * (a - c) / den if den != 0 else 0.0 + return float(grid[i] + off * step), float(b) + return float(grid[i]), float(s[i]) + + +def _fold(o: np.ndarray, period_s: float, smooth_ms: int = 11, start: int = 0) -> np.ndarray: + """Onset curve folded onto one period: mean strength at each phase (1 ms bins). + + ``start`` is the frame ``o`` begins at, so a slice of the track folds onto + the same phase axis as the whole of it. + """ + bins = max(8, int(round(period_s * _FR))) + t = (np.arange(len(o)) + start) / _FR + ph = ((t / period_s) % 1.0 * bins).astype(np.int64) % bins + h = np.bincount(ph, weights=o, minlength=bins) + cnt = np.bincount(ph, minlength=bins) + h = h / np.maximum(cnt, 1) + # Circular triangle smoothing, centred, so one jittery frame cannot win. + w = np.bartlett(smooth_ms + 2)[1:-1] + w /= w.sum() + kern = np.roll(np.pad(w, (0, bins - len(w))), -(len(w) // 2)) + return np.real(np.fft.ifft(np.fft.fft(h) * np.fft.fft(kern))) + + +def _comb(o: np.ndarray, bpm: float) -> float: + """Peak of the folded onset curve: the mean onset strength ON the beat.""" + return float(_fold(o, 60.0 / bpm).max()) + + +def _in_range(bpm: float, lo: float, hi: float) -> float: + while bpm < lo: + bpm *= 2 + while bpm >= hi: + bpm /= 2 + return bpm + + +# ---- entry point -------------------------------------------------------------- +def detect_grid( + audio_path: str, + bpm_range: tuple[float, float] = DEFAULT_BPM_RANGE, + *, + y: np.ndarray | None = None, + sr: int = _SR, +) -> GridResult: + """Detect a track's constant tempo and first beat. + + ``y``/``sr`` let a caller (or a test) pass decoded mono audio directly. + Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot). + """ + if y is None: + import librosa + y, sr = librosa.load(audio_path, sr=sr, mono=True) + y = np.asarray(y, dtype=np.float32) + duration = len(y) / sr + if duration < 1.5: + raise ValueError("Track is too short to detect a tempo") + + lo, hi = bpm_range + low = _onset(_band_env(y, sr, 30.0, 150.0)) + mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3)) + attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3)) + full = _onset(_band_env(y, sr, None, None, smooth_ms=3)) + o_tempo = low + mid + 0.5 * full + if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0: + raise ValueError("No onsets found") + + o_t = _decimate(o_tempo, _FR // _TEMPO_FR) + cands = _coarse_candidates(o_t, lo, hi) + if not cands: + raise ValueError("Could not detect a tempo") + + # Refine every coarse candidate, fold each into the range, and score it + # with the comb (onset strength on the beat, best phase). + refined: dict[float, tuple[float, float]] = {} + for c in cands: + b, _ = _refine(o_t, c, 0.1, 0.01) + b = _in_range(b, lo, hi) + key = round(b, 1) + if key not in refined: + refined[key] = (b, _comb(o_tempo, b)) + best = max(s for _, s in refined.values()) + # Octave rule: prefer the FASTEST tempo that explains the onsets nearly as + # well as the best — a slower comb hits a subset of the same beats. + viable = [(b, s) for b, s in refined.values() if s >= 0.9 * best] + bpm = max(viable)[0] + + # Final refinement at full precision around the chosen tempo. + bpm, _ = _refine(o_t, bpm, 0.02, 0.001) + phase = _phase(low, attack, 60.0 / bpm) + drift = _drift(attack, bpm, phase) + bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration) + + period = 60.0 / bpm + return GridResult( + bpm=round(bpm, 4), + anchor=round(_first_beat(low + attack, phase, period), 4), + duration=duration, + drift_ms=round(drift * 1000.0, 1), + ) + + +def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]: + """The ``k`` highest local maxima of a circular curve, ``min_sep`` apart.""" + n = len(f) + is_max = (f >= np.roll(f, 1)) & (f >= np.roll(f, -1)) + out: list[int] = [] + for i in np.flatnonzero(is_max)[np.argsort(f[is_max])[::-1]]: + if all(min(abs(i - j), n - abs(i - j)) >= min_sep for j in out): + out.append(int(i)) + if len(out) == k: + break + return out + + +def _phase(low: np.ndarray, attack: np.ndarray, period: float) -> float: + """Seconds into the beat period at which the beat lands. + + Timing comes from the attack band, whose onset is sharp; the kick band's + is not — a kick's low end swells for tens of ms after its attack. But the + loudest attack is not always the beat (an off-beat hat), and the loudest + low-band onset is not always the kick (a bassline note between beats). So + each sharp attack is scored by whether LOW END FOLLOWS it: a kick has both, + a hat has no low end, a bass note has no attack. + """ + fine = _fold(attack, period, smooth_ms=3) + low_f = _fold(low, period) + n = len(fine) + floor = 0.1 * low_f.max() # a track with no kick still picks its best attack + + def score(c: int) -> float: + follow = max(low_f[(c + d) % n] for d in range(-5, _KICK_FOLLOW_MS + 1)) + return float(fine[c] * (floor + follow)) + + best = max(_peaks(fine, 6, 20), key=score) + return (best / n * period + _ONSET_BIAS_S) % period + + +def _segment_offsets(attack: np.ndarray, period: float, phase: float) -> list[float]: + """Where the beat lands in each ~30 s section, relative to ``phase`` (s). + + Only sections with a clear attack within 40 ms of the grid count. That + makes this a measure of SLOW drift — a fit a few hundredths of a BPM out, + which is what the round-BPM snap must judge. It cannot see a tempo change + (a section whose beat is far off the grid looks the same as a kickless + breakdown with hats over it, and on real music treating those as drift + reported 100–250 ms on tracks whose grid was right end to end). Detecting + tempo changes is flexible-grid detection, and a different job. + """ + n = len(attack) + seg = min(30 * _FR, n // 4) + if seg < 6 * _FR: + return [] + out = [] + for s0 in range(0, n - seg + 1, seg): + f = _fold(attack[s0 : s0 + seg], period, smooth_ms=3, start=s0) + bins = len(f) + c = int(round(phase / period * bins)) % bins + i = max(((c + d) % bins for d in range(-40, 41)), key=lambda j: f[j]) + if f[i] < 2.0 * np.median(f): + continue + d = (i - c + bins / 2) % bins - bins / 2 + out.append(d / bins * period) + return out + + +def _drift(attack: np.ndarray, bpm: float, phase: float) -> float: + """Distance (s) between the grid and the beat in the worst section but one. + + One section is allowed to disagree: an intro whose nearest attack is not + the kick shows up as a single ~30 ms outlier on otherwise flat tracks, and + blocked two round-BPM snaps on the benchmark. Real drift cannot hide behind + that — it grows with distance from the anchor, so it is at both ends. + """ + offs = sorted((abs(o) for o in _segment_offsets(attack, 60.0 / bpm, phase)), reverse=True) + if len(offs) >= 4: + offs = offs[1:] + return offs[0] if offs else 0.0 + + +def _snap_round(low, attack, bpm: float, phase: float, drift: float, duration: float): + """Snap to a round (or half) BPM if it keeps the whole track on the beat. + + The test is the thing that matters, not a score ratio: at the round tempo, + does every section of the track stay within a few ms of its onsets? A real + 124.01 BPM track snapped to 124 would drift ~30 ms over six minutes and + fails; a 124.0 track whose fit came out at 124.012 passes. + + How far to look scales with 1/duration, because so does the fit's + precision: the window is the tempo error that would move the LAST beat by + 10 ms, floored at 0.05 BPM. A four-bar loop gets a wide one; a track that + is long enough to have a precise fit relies on the drift test instead. + """ + tol = max(0.05, 0.01 * bpm / max(duration, 1.0)) + for r in (float(round(bpm)), round(bpm * 2) / 2): + if abs(bpm - r) < tol: + ph = _phase(low, attack, 60.0 / r) + dr = _drift(attack, r, ph) + if dr <= max(drift, 0.004) + 0.003: + return r, ph, dr + return bpm, phase, drift + + +def _first_beat(o: np.ndarray, phase: float, period: float) -> float: + """The first grid beat at which the music has started. + + A grid anchored in the silence before a track is still correct, but a DJ + reads the first marker as "the track starts here", as Traktor draws it. + """ + pos = o[o > 0] + thr = 0.15 * np.percentile(pos, 99) if len(pos) else 0.0 + hits = np.flatnonzero(o > thr) + start = hits[0] / _FR if len(hits) else 0.0 + # The beat nearest the music's first onset, never before the track starts. + n = round((start - phase) / period) + return max(phase + n * period, phase % period) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 59a699a..83c3f31 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -16,6 +16,7 @@ from fastapi.responses import FileResponse, JSONResponse from . import __version__, exporter, exports, history, prefs from .app_state import STATE from .core import auto_hotcues as ah +from .core import grid_detect from . import importer from .core import export as core_export from .core import places, registry @@ -855,9 +856,11 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: @app.post("/api/tracks/grid/auto", response_model=TrackCues) def auto_grid(body: AutoGridRequest) -> TrackCues: - """Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1 - (slot 0) to the first beat, and anchors the grid to that position. Octave - (half/double) errors are left for the user to fix with the ×2/÷2 controls.""" + """Detect tempo + first beat and build a beatgrid (see `core/grid_detect`). + + One constant-tempo marker, written the way the platform's own analyser would + (on Traktor that also sets hotcue 1 to the first beat). Octave (half/double) + ambiguity in halftime genres is left for the ×2 / ÷2 controls.""" a = require_adapter() if a.track(body.track_id) is None: raise HTTPException(404, "Track not found") @@ -865,12 +868,12 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: if path is None or not path.exists(): raise HTTPException(400, "Audio file not found (is the drive mounted?)") try: - bpm, first_beat = ah.detect_grid(str(path)) + found = grid_detect.detect_grid(str(path)) except Exception as ex: # analysis is best-effort; never 500 the UI raise HTTPException(400, f"Analysis failed: {ex}") # "Analysed", not "replace": each platform writes an analysis result in its # own shape (Traktor pairs the first marker with a beat-1 cue). - return a.set_analysed_grid(body.track_id, [(first_beat, bpm)]) + return a.set_analysed_grid(body.track_id, [(found.anchor, found.bpm)]) @app.patch("/api/tracks/cue", response_model=TrackCues) diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 9b808c2..8a69d61 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_grid_detect.py b/backend/test_grid_detect.py new file mode 100644 index 0000000..36c6db4 --- /dev/null +++ b/backend/test_grid_detect.py @@ -0,0 +1,149 @@ +"""Tests for beatgrid detection (`core/grid_detect.py`) on synthetic audio. + +Needs no audio files and no library: every track here is generated, so its +tempo and first beat are KNOWN rather than taken from another analyser. That +is what these can pin that `bench_grid_detect.py` (real music, scored against +Rekordbox) cannot: exactness, and each trap that fooled a band in isolation — +the loud off-beat hat, the syncopated bassline, and the frame-quantised tempo +the previous detector could not escape. +""" +import warnings + +import numpy as np + +warnings.filterwarnings("ignore") + +from konduktor.core.grid_detect import detect_grid # noqa: E402 + +SR = 22050 +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +rng = np.random.default_rng(0) + + +def _faded(x: np.ndarray) -> np.ndarray: + """End a sound smoothly: a hard cut is itself a click, half a beat after the + kick, which no real sample has and which would test the generator instead.""" + n = min(len(x), int(0.02 * SR)) + x = x.copy() + x[-n:] *= np.linspace(1.0, 0.0, n) + return x + + +def _kick() -> np.ndarray: + t = np.arange(int(0.25 * SR)) / SR + body = np.sin(2 * np.pi * (50 * t + 60 * (1 - np.exp(-t / 0.02)) * 0.02)) * np.exp(-t / 0.12) + click = np.zeros_like(t) + click[: int(0.002 * SR)] = rng.standard_normal(int(0.002 * SR)) * 0.5 + return _faded(body + click) + + +def _hat(amp: float) -> np.ndarray: + n = int(0.04 * SR) + noise = np.diff(rng.standard_normal(n + 1)) # tilt up: hat-like + return _faded(amp * noise * np.exp(-np.arange(n) / SR / 0.012)) + + +def _bass(amp: float) -> np.ndarray: + t = np.arange(int(0.2 * SR)) / SR + ramp = np.minimum(1.0, t / 0.015) # a bass note swells; it has no click + return _faded(amp * np.sin(2 * np.pi * 70 * t) * ramp * np.exp(-t / 0.15)) + + +def track(bpm, first=0.3, seconds=180.0, hat=0.0, bass=0.0, tempo_b=None): + """Kick on every beat from ``first``; optional off-beat hat and a bass note + 60% of the way to the next beat. ``tempo_b`` is the tempo at the END: the + tempo glides linearly from ``bpm`` to it, as a live drummer's does.""" + y = np.zeros(int(seconds * SR)) + + def put(x, at): + i = int(round(at * SR)) + if 0 <= i < len(y): + j = min(len(y), i + len(x)) + y[i:j] += x[: j - i] + + t, beat = first, 60.0 / bpm + k, h, b = _kick(), _hat(hat), _bass(bass) + while t < seconds: + put(k, t) + if hat: + put(h, t + beat / 2) + if bass: + put(b, t + 0.6 * beat) + if tempo_b: + beat = 60.0 / (bpm + (tempo_b - bpm) * t / seconds) + t += beat + return (0.3 * y).astype(np.float32) + + +def detect(y, **kw): + return detect_grid("", y=y, sr=SR, **kw) + + +def beat_error_ms(res, bpm, first, at): + """Distance from the true beat nearest ``at`` to the detected grid's.""" + p = 60.0 / bpm + true = first + round((at - first) / p) * p + dp = 60.0 / res.bpm + got = res.anchor + round((true - res.anchor) / dp) * dp + return (got - true) * 1000.0 + + +print("== round tempo: exact BPM, anchor on the first kick ==") +r = detect(track(124, first=0.3)) +check("124 BPM detected as exactly 124", r.bpm == 124.0, f"got {r.bpm}") +check("anchor on the first kick (±3 ms)", abs(r.anchor - 0.3) <= 0.003, f"got {r.anchor}") +check("still on the beat at the end (±3 ms)", abs(beat_error_ms(r, 124, 0.3, 175)) <= 3) +check("a constant track reports little drift", r.drift_ms is not None and r.drift_ms <= 5, f"{r.drift_ms}") + +print("== the old detector's blind spot: 125 BPM ==") +# librosa's frame-quantised tempo could only return 123.05 or 129.20 here. +r = detect(track(125, first=0.05)) +check("125 BPM is 125, not 123.05", r.bpm == 125.0, f"got {r.bpm}") + +print("== non-round tempo is fitted, not snapped ==") +r = detect(track(123.37, first=0.2)) +check("123.37 within 0.005", abs(r.bpm - 123.37) <= 0.005, f"got {r.bpm}") +check("…and on the beat at the end (±5 ms)", abs(beat_error_ms(r, 123.37, 0.2, 175)) <= 5) + +print("== octave: a four-on-the-floor kick is not half or double tempo ==") +r = detect(track(128)) +check("128 BPM, not 64 or 256", r.bpm == 128.0, f"got {r.bpm}") +r = detect(track(90), bpm_range=(100.0, 200.0)) +check("bpm_range folds 90 up to 180", r.bpm == 180.0, f"got {r.bpm}") + +print("== phase traps: each fooled one band on real music ==") +r = detect(track(126, first=0.4, hat=1.5)) +check("an off-beat hat louder than the kick does not take the beat", + abs(beat_error_ms(r, 126, 0.4, 60)) <= 3, f"{beat_error_ms(r, 126, 0.4, 60):+.1f} ms") +r = detect(track(124, first=0.25, bass=1.5)) +check("a syncopated bassline does not take the beat", + abs(beat_error_ms(r, 124, 0.25, 60)) <= 3, f"{beat_error_ms(r, 124, 0.25, 60):+.1f} ms") +r = detect(track(124, first=0.25, hat=1.2, bass=1.2)) +check("…nor both together", abs(beat_error_ms(r, 124, 0.25, 60)) <= 3, + f"{beat_error_ms(r, 124, 0.25, 60):+.1f} ms") + +print("== a wandering tempo is reported, not hidden ==") +# 124 → 124.15 over three minutes: any one constant grid is ~25 ms off somewhere. +r = detect(track(124, tempo_b=124.15)) +check("drift is reported when one grid cannot fit", r.drift_ms is not None and r.drift_ms >= 12, f"{r.drift_ms}") + +print("== nothing to fit ==") +for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short", np.zeros(SR, dtype=np.float32))): + try: + detect(y) + check(f"{label} raises ValueError", False, "returned a grid") + except ValueError: + check(f"{label} raises ValueError", True) + +print() +print("FAILED" if failed else "OK") +raise SystemExit(1 if failed else 0)