From 6eecb2288ae16b7812e6a620917dcfe01d4e54f4 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 19 Oct 2026 17:18:05 +0200 Subject: [PATCH] Improved loudness calculation --- CLAUDE.md | 12 +- backend/bench_traktor_gain.py | 156 ++++++++++++++ backend/dev_gain_kit.py | 321 +++++++++++++++++++++++++++ backend/dev_gain_kit_g2.py | 336 +++++++++++++++++++++++++++++ backend/konduktor/core/loudness.py | 60 +++++- backend/test_loudness.py | 15 ++ 6 files changed, 895 insertions(+), 5 deletions(-) create mode 100644 backend/bench_traktor_gain.py create mode 100644 backend/dev_gain_kit.py create mode 100644 backend/dev_gain_kit_g2.py diff --git a/CLAUDE.md b/CLAUDE.md index c912eda..9b6c41d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -164,7 +164,13 @@ Two independent apps that talk over HTTP: uses it as the reference meter) to 0.01 LU; on an inter-sample peak it is closer to exact than FFmpeg's interpolator. Mixed In Key, the requester's reference, shows no RMS or LUFS at all (researched), so nothing was - matched. `VERSION` bumps make stored values stale. + matched. `VERSION` bumps make stored values stale (2: stem files). + **A stem FILE is measured as its four stems SUMMED** (one demux pass, + `_measure_stem_sum`), not its mix stream — what a stem deck plays and + what Traktor's gain measures: commercial mix streams are mastered ~2.8 dB + (up to 5.3) hotter than their stems sum to. `bench_traktor_gain.py` + (any folder Traktor gain-analysed) fits Traktor's auto-gain against it: + `ANALYZED_DB = -9.2 - LUFS`, sd 0.8 dB over 120 tracks (2026-10-19). - `key_detect.py` + `key_model.npz` — **musical key detection**: a small CNN (Korzeniowski & Widmer 2017 — five 5x5 convs, a per-frame dense layer over the WHOLE pitch axis, since a key is not pitch-invariant, logits @@ -1512,8 +1518,8 @@ serialization path.** It enforces: ±0.2 dB, 44.1/48 kHz, mono), the standard's anchors (a -23 dBFS 1 kHz stereo sine = -23.0 LUFS; an inter-sample peak = -6.02 dBTP), RMS's definition (a full-scale sine 0.0, a square +3.01, a long quiet intro moves nothing), - silence / under 3 s = None, chunked feeding equals one pass, and real files - at their own rate and channels. + silence / under 3 s = None, chunked feeding equals one pass, real files + at their own rate and channels, and a stem file read as its stem SUM. - `test_loudness_store.py` — the store (stale on facts or version, remap with the new path winning, concurrent writers) and the routes on generated FLACs: a Files folder measured with BPM refused, preview counts = the run's, skip diff --git a/backend/bench_traktor_gain.py b/backend/bench_traktor_gain.py new file mode 100644 index 0000000..aa1cb77 --- /dev/null +++ b/backend/bench_traktor_gain.py @@ -0,0 +1,156 @@ +"""How Traktor's auto-gain relates to Konduktor's loudness measures. + +Traktor stores its gain per ENTRY as `` (its own +measurement) and `PERCEIVED_DB` (the gain the deck applies; equal to +ANALYZED after Traktor's own analysis — kit G1, 2026-10-19). If Traktor +levels toward a fixed reference, `ANALYZED_DB = reference − loudness`, so +`ANALYZED_DB + LUFS` is that reference, and its spread is how far Konduktor's +measure is from Traktor's. + + python bench_traktor_gain.py FOLDER [--nml collection.nml] + +FOLDER's audio must be in the collection and analysed by Traktor (Gain). +A stem file is measured as its four stems SUMMED, as Traktor measures it. + +Result (2026-10-19, 80 MP3 + 40 commercial stem files, Traktor 4.5): +ANALYZED_DB = -9.2 - LUFS (free slope 0.99), sd 0.80 dB, |miss| p50 0.56 / +p90 1.35; RMS fits worse (sd 1.17); the miss follows nothing measured here +(LRA, PLR, true peak, bass weight: |r| < 0.2) — it is Traktor's own measure. +Fits LUFS and RMS (slope and fixed-slope), then asks whether what is left +over follows something about the music (LRA, PLR, bass weight, format, genre). +""" + +from __future__ import annotations + +import argparse +import html +import re +import sys +import unicodedata +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +DEFAULT_NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml" + + +def _key(path: str) -> str: + return unicodedata.normalize("NFC", path).casefold() + + +def traktor_values(nml: Path) -> dict[str, dict]: + """Absolute path (normalised) -> Traktor's LOUDNESS + genre, for analysed entries.""" + out = {} + text = nml.read_text(encoding="utf-8") + for e in re.findall(r"", text, re.S): + loc = re.search(r']*GENRE="([^"]*)"', e) + out[_key(path)] = { + "peak": float(loud.group(1)), + "perceived": float(loud.group(2)), + "analyzed": float(loud.group(3)), + "genre": html.unescape(genre.group(1)) if genre else "", + } + return out + + +def _measure(path: str): + """`loudness.measure_file` — which measures a stem file as its four stems + summed, as Traktor does (found by this bench: against the mix stream the + reference was -6.6, sd 1.18; against the sum -9.3, sd 0.68).""" + from konduktor.core import loudness + + try: + return path, loudness.measure_file(path) + except Exception as e: # an undecodable file is reported, not fatal + return path, e + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("folder", type=Path) + ap.add_argument("--nml", type=Path, default=DEFAULT_NML) + args = ap.parse_args() + + tk = traktor_values(args.nml) + files = sorted(p for p in args.folder.rglob("*") if p.is_file() and not p.name.startswith(".")) + held = [p for p in files if _key(str(p)) in tk] + print(f"{len(files)} files, {len(held)} analysed by Traktor") + for p in files: + if _key(str(p)) not in tk: + print(f" not in the collection / not analysed: {p.name}") + + rows = [] + with ProcessPoolExecutor(4) as pool: # a stem file holds 4 decoded streams + for path, m in pool.map(_measure, [str(p) for p in held]): + if m is None or isinstance(m, Exception): + print(f" not measured: {Path(path).name}: {m}") + continue + t = tk[_key(path)] + rows.append((Path(path), m, t)) + + name = np.array([r[0].name for r in rows]) + lufs = np.array([r[1].lufs for r in rows]) + rms = np.array([r[1].rms for r in rows]) + tp = np.array([r[1].true_peak for r in rows]) + lra = np.array([r[1].lra for r in rows]) + plr = np.array([r[1].plr for r in rows]) + an = np.array([r[2]["analyzed"] for r in rows]) + pc = np.array([r[2]["perceived"] for r in rows]) + pk = np.array([r[2]["peak"] for r in rows]) + fmt = np.array([r[0].suffix.lower() for r in rows]) + genre = np.array([r[2]["genre"] or "(none)" for r in rows]) + n = len(rows) + + print(f"\n{n} tracks; LUFS {lufs.min():.1f} .. {lufs.max():.1f}, " + f"PERCEIVED == ANALYZED on {int(np.sum(np.isclose(pc, an)))}") + + print("\n== reference = ANALYZED_DB + measure (slope fixed at 1)") + for label, v in (("LUFS", lufs), ("RMS", rms)): + ref = an + v + k, b = np.polyfit(-v, an, 1) + free = an - (k * -v + b) + q = np.percentile(np.abs(ref - np.median(ref)), [50, 90]) + print(f" {label:4s}: mean {ref.mean():6.2f} median {np.median(ref):6.2f} sd {ref.std():.2f} " + f"|miss| p50 {q[0]:.2f} p90 {q[1]:.2f} (free slope {k:.3f}, sd {free.std():.2f})") + + print("\n== PEAK_DB + true peak (Traktor's peak gain vs our true peak)") + d = pk + tp + print(f" mean {d.mean():+.2f} sd {d.std():.2f} min {d.min():+.2f} max {d.max():+.2f}") + + ref = an + lufs + resid = ref - ref.mean() + print("\n== does the LUFS miss follow the music? (correlation with the residual)") + bass = rms - lufs # unweighted vs K-weighted: higher = more low end + for label, v in (("LRA", lra), ("PLR", plr), ("true peak", tp), ("bass weight (RMS-LUFS)", bass), ("LUFS", lufs)): + r = np.corrcoef(v, resid)[0, 1] + k = np.polyfit(v, resid, 1)[0] + print(f" {label:24s} r = {r:+.2f} slope {k:+.3f} dB per unit") + X = np.column_stack([bass, lra, np.ones(n)]) + coef, *_ = np.linalg.lstsq(X, resid, rcond=None) + print(f" bass + LRA together: sd {resid.std():.2f} -> {(resid - X @ coef).std():.2f}") + + print("\n== by format") + for f in sorted(set(fmt)): + s = fmt == f + print(f" {f:5s} n={s.sum():3d} reference mean {ref[s].mean():6.2f} sd {ref[s].std():.2f}") + print("\n== by genre (n >= 3)") + for g in sorted(set(genre), key=lambda g: -np.sum(genre == g)): + s = genre == g + if s.sum() >= 3: + print(f" {g[:24]:24s} n={s.sum():3d} reference mean {ref[s].mean():6.2f} sd {ref[s].std():.2f}") + + print("\n== largest misses (LUFS)") + for i in np.argsort(-np.abs(resid))[:8]: + print(f" {resid[i]:+5.2f} LUFS {lufs[i]:6.2f} LRA {lra[i]:4.1f} bass {bass[i]:+5.2f} {genre[i][:14]:14s} {name[i][:50]}") + + +if __name__ == "__main__": + main() diff --git a/backend/dev_gain_kit.py b/backend/dev_gain_kit.py new file mode 100644 index 0000000..048fbd2 --- /dev/null +++ b/backend/dev_gain_kit.py @@ -0,0 +1,321 @@ +"""Kit G1 — what Traktor 4.5 does with gain (dev only, like dev_stems.py). + +Answers, by measuring in Traktor itself (see +.claude/discussions/discuss-gain-normalization-2026-10-19.md, "Kit G1"): + + 1. Does a LEVEL change to a file make Traktor re-analyse it (LOUDNESS, + BPM/grid, AUDIO_ID)? MP3 by lossless frame gain (same size; + an APE undo + tag; + the mtime put back), FLAC re-written exactly, and a control whose + mtime alone changes. + 2. Does Traktor KEEP a LOUDNESS Konduktor writes — on an entry it analysed + (AUDIO_ID kept), and on one Konduktor added (AUDIO_ID empty)? + 3. Which LOUDNESS attribute drives the deck's auto-gain (the three are set + to values that cannot be confused)? + + python dev_gain_kit.py prepare # build the kit folder + # -> in Traktor: import the folder, analyse, quit + python dev_gain_kit.py apply # change the files + write LOUDNESS + # -> in Traktor: load each G1 track, note the gain knob, quit + python dev_gain_kit.py report # what Traktor changed + +Traktor must be closed for `apply`. The collection is saved through +TraktorStore (backup-first, byte-exact render). +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import numpy as np + +NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml" +KITS = Path.home() / "Music/Konduktor Stem Test" +KIT = KITS / "Kit G1" +STEPS = -2 # global_gain steps of 2^(1/4): -2 = -3.01 dB + +# name -> (source, what happens at `apply`) +FILES = { + "G1-A0 control touch.mp3": (KITS / "Kit 2/K2 01 All I Need.mp3", "mtime only"), + "G1-A1 mp3 framegain.mp3": (KITS / "Kit 2/K1 01 Abyss of Love - Franky Rizardo Remix.mp3", "frame gain"), + "G1-A2 mp3 framegain ape.mp3": (KITS / "Kit 2/K4 Ragga Bomb with Ragga Twins.mp3", "frame gain + APE undo tag"), + "G1-A3 flac exact.flac": (KITS / "Kit 4/K4-3 flac.flac", "exact gain, re-written"), + "G1-A4 mp3 framegain same mtime.mp3": (KITS / "Kit 4/K4-5 mp3 cbr noxing.mp3", "frame gain, mtime restored"), + "G1-B1 loudness written.mp3": (KITS / "Kit 2/K3 01 Motorola.mp3", "LOUDNESS written, AUDIO_ID kept"), +} +# Added by Konduktor at `apply` (so Traktor never analysed it): AUDIO_ID empty. +B2 = ("G1-B2 konduktor added.mp3", KITS / "Kit 4/K4-4 mp3 cbr xing.mp3") + +# Values no real analysis would give, so the deck's knob says which one it read. +B1_LOUDNESS = (2.5, -6.0, 6.0) # PEAK_DB, PERCEIVED_DB, ANALYZED_DB +B2_LOUDNESS = (2.5, -4.0, 4.0) + + +# ── MP3 frame gain (mp3gain's edit) ────────────────────────────────────────── + +_BITRATE = { + True: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320], + False: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], +} +_RATE = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]} + + +def _get(buf: bytearray, bit: int, n: int) -> int: + v = 0 + for i in range(n): + v = (v << 1) | ((buf[(bit + i) >> 3] >> (7 - ((bit + i) & 7))) & 1) + return v + + +def _put(buf: bytearray, bit: int, n: int, v: int) -> None: + for i in range(n): + b = (v >> (n - 1 - i)) & 1 + byte, shift = (bit + i) >> 3, 7 - ((bit + i) & 7) + buf[byte] = (buf[byte] & ~(1 << shift) & 0xFF) | (b << shift) + + +def _header(buf: bytearray, pos: int): + if pos + 4 > len(buf) or buf[pos] != 0xFF or (buf[pos + 1] & 0xE0) != 0xE0: + return None + ver, layer = (buf[pos + 1] >> 3) & 3, (buf[pos + 1] >> 1) & 3 + br_i, sr_i = buf[pos + 2] >> 4, (buf[pos + 2] >> 2) & 3 + if ver == 1 or layer != 1 or br_i in (0, 15) or sr_i == 3: + return None + mpeg1 = ver == 3 + br, sr = _BITRATE[mpeg1][br_i], _RATE[ver][sr_i] + pad = (buf[pos + 2] >> 1) & 1 + length = (144000 if mpeg1 else 72000) * br // sr + pad + return { + "mpeg1": mpeg1, + "crc": (buf[pos + 1] & 1) == 0, + "nch": 1 if (buf[pos + 3] >> 6) == 3 else 2, + "len": length, + } + + +def _gain_bits(h: dict) -> list[int]: + """Bit offsets (from the side info's start) of every granule's global_gain.""" + nch = h["nch"] + if h["mpeg1"]: + start, block, granules = 9 + (5 if nch == 1 else 3) + 4 * nch, 59, 2 + else: + start, block, granules = 8 + (1 if nch == 1 else 2), 63, 1 + return [start + (g * nch + c) * block + 21 for g in range(granules) for c in range(nch)] + + +def mp3_frame_gain(path: Path, steps: int) -> int: + """Add `steps` to every audio granule's global_gain in place; returns frames edited.""" + buf = bytearray(path.read_bytes()) + pos = 0 + if buf[:3] == b"ID3": + size = (buf[6] << 21) | (buf[7] << 14) | (buf[8] << 7) | buf[9] + pos = 10 + size + (10 if buf[5] & 0x10 else 0) + frames = 0 + first = True + while (h := _header(buf, pos)) is not None: + side = pos + 4 + (2 if h["crc"] else 0) + if h["crc"]: + raise SystemExit(f"{path.name}: CRC-protected frames are not handled by the kit") + side_len = (17 if h["nch"] == 1 else 32) if h["mpeg1"] else (9 if h["nch"] == 1 else 17) + tag = bytes(buf[side + side_len : side + side_len + 4]) + if first and (tag in (b"Xing", b"Info") or bytes(buf[pos + 36 : pos + 40]) == b"VBRI"): + pass # the header frame is not audio (Traktor decodes it anyway — leave it as it is) + else: + for off in _gain_bits(h): + g = _get(buf, side * 8 + off, 8) + steps + if not 0 <= g <= 255: + raise SystemExit(f"{path.name}: global_gain would leave 0..255") + _put(buf, side * 8 + off, 8, g) + frames += 1 + first = False + pos += h["len"] + rest = bytes(buf[pos : pos + 8]) + if pos < len(buf) - 128 and not rest.startswith((b"TAG", b"APETAGEX", b"LYRICS")): + raise SystemExit(f"{path.name}: lost frame sync at {pos} of {len(buf)}") + path.write_bytes(buf) + return frames + + +def _decode(path: Path) -> np.ndarray: + from konduktor.core import pyav + + out = [] + with pyav.open_input(path) as c: + for frame in c.decode(audio=0): + a = frame.to_ndarray() + out.append(a if a.ndim == 2 and a.shape[0] <= 2 else a.reshape(1, -1)) + return np.concatenate(out, axis=1).astype(np.float64) + + +def _check_gain(before: np.ndarray, after: Path, db: float, what: str) -> None: + b = before + a = _decode(after) + n = min(b.shape[1], a.shape[1]) + want = 10 ** (db / 20) + err = np.max(np.abs(a[:, :n] - b[:, :n] * want)) / max(np.max(np.abs(b)), 1e-9) + print(f" {what}: decoded = original x {want:.4f} ({db:+.2f} dB), max error {err:.1e} of peak") + if err > 1e-3: + raise SystemExit(" gain check FAILED") + + +def flac_exact_gain(path: Path, db: float) -> None: + import soundfile as sf + from mutagen.flac import FLAC + + info = sf.info(str(path)) + data, rate = sf.read(str(path), dtype="float64", always_2d=True) + old = FLAC(str(path)) + tags, pictures = list(old.tags.items()) if old.tags else [], list(old.pictures) + tmp = path.with_suffix(".tmp.flac") + sf.write(str(tmp), data * 10 ** (db / 20), rate, subtype=info.subtype, format="FLAC") + new = FLAC(str(tmp)) + for k, v in tags: + new[k] = v + for p in pictures: + new.add_picture(p) + new.save() + tmp.replace(path) + + +# ── steps ──────────────────────────────────────────────────────────────────── + + +def _traktor_running() -> bool: + # The executable is "Traktor Pro 4" (an exact "Traktor" never matches). + return subprocess.run(["pgrep", "-f", r"Traktor Pro 4\.app/Contents/MacOS/"], capture_output=True).returncode == 0 + + +def prepare() -> None: + KIT.mkdir(parents=True, exist_ok=True) + for name, (src, what) in FILES.items(): + shutil.copy2(src, KIT / name) + print(f" {name:38s} <- {src.name} [{what} at apply]") + print(f"\nKit at {KIT}\n" + "Next, in Traktor 4.5:\n" + " 1. Preferences > Mixer: note the Autogain setting, and turn ON\n" + " 'Set Autogain when Loading Track' (or the nearest wording).\n" + " 2. Import the Kit G1 folder; select its 6 tracks; Analyze (Async) > All.\n" + " 3. Quit Traktor (it writes the collection on exit).\n" + "Then: python dev_gain_kit.py apply") + + +def _entries(nml_text: str) -> dict[str, str]: + out = {} + for e in re.findall(r"", nml_text, re.S): + m = re.search(r']*FILE="(G1-[^"]+)"', e) + if m: + out[m.group(1)] = e + return out + + +def apply() -> None: + if _traktor_running(): + raise SystemExit("Quit Traktor first.") + text = NML.read_text(encoding="utf-8") + have = _entries(text) + missing = [n for n in FILES if n not in have] + if missing: + raise SystemExit(f"Not in the collection yet (import + analyse in Traktor): {missing}") + unanalysed = [n for n in FILES if " {p.stat().st_size}") + _check_gain(before, p, db, "check") + + from konduktor.adapters.traktor.store import TraktorStore + from konduktor.core import folder + from traktor_nml_utils.models.collection import Loudnesstype + + shutil.copy2(B2[1], KIT / B2[0]) + store = TraktorStore(NML) + store.add_entry(folder.read_track(KIT / B2[0]), KIT / B2[0]) + + def set_loudness(file: str, vals) -> None: + for e in store._nml.collection.entry: + if e.location is not None and e.location.file == file: + e.loudness = Loudnesstype(peak_db=vals[0], perceived_db=vals[1], analyzed_db=vals[2]) + return + raise SystemExit(f"entry {file} not found") + + set_loudness("G1-B1 loudness written.mp3", B1_LOUDNESS) + set_loudness(B2[0], B2_LOUDNESS) + store.save() + shutil.copy2(NML, KIT / "2-after-konduktor-apply.nml") + print(f"\nLOUDNESS written: B1 {B1_LOUDNESS}, B2 (added, AUDIO_ID empty) {B2_LOUDNESS}\n" + "Next, in Traktor 4.5 (do NOT run Analyze):\n" + " 1. Load EACH G1 track into deck A in turn (B1 and B2 first).\n" + " For each, note the GAIN knob's value (hover / the readout) and\n" + " whether Traktor shows it analysing.\n" + " 2. Quit Traktor.\n" + "Then: python dev_gain_kit.py report") + + +_FIELDS = { + "AUDIO_ID": r'AUDIO_ID="([^"]*)"', + "LOUDNESS": r"]*)>", + "TEMPO": r']*TYPE="4"[^>]*START="([^"]*)"', + "MODIFIED": r'MODIFIED_DATE="([^"]*)" MODIFIED_TIME="([^"]*)"', + "FILESIZE": r'FILESIZE="([^"]*)"', + "LAST_PLAYED": r'LAST_PLAYED="([^"]*)"', +} + + +def report() -> None: + if _traktor_running(): + raise SystemExit("Quit Traktor first (it writes the collection on exit).") + shutil.copy2(NML, KIT / "3-after-traktor-load.nml") + stages = [ + ("analysed", _entries((KIT / "1-after-traktor-analysed.nml").read_text(encoding="utf-8"))), + ("applied", _entries((KIT / "2-after-konduktor-apply.nml").read_text(encoding="utf-8"))), + ("loaded", _entries(NML.read_text(encoding="utf-8"))), + ] + for name in [*FILES, B2[0]]: + print(f"\n== {name} [{FILES.get(name, (None, 'added by Konduktor'))[1]}]") + for field, rx in _FIELDS.items(): + vals = [] + for _, ents in stages: + e = ents.get(name) + m = re.search(rx, e) if e else None + vals.append(" ".join(m.groups()) if m else ("-" if e else "(no entry)")) + flag = "" if vals[1] == vals[2] else " <-- CHANGED by Traktor" + print(f" {field:11s} analysed: {vals[0][:60]}\n" + f" {'':11s} applied: {vals[1][:60]}\n" + f" {'':11s} loaded: {vals[2][:60]}{flag}") + + +if __name__ == "__main__": + sys.path.insert(0, str(Path(__file__).resolve().parent)) + {"prepare": prepare, "apply": apply, "report": report}[sys.argv[1] if len(sys.argv) > 1 else "prepare"]() diff --git a/backend/dev_gain_kit_g2.py b/backend/dev_gain_kit_g2.py new file mode 100644 index 0000000..a80ac96 --- /dev/null +++ b/backend/dev_gain_kit_g2.py @@ -0,0 +1,336 @@ +"""Kit G2 — what rekordbox 7 does with auto gain, and whether a stick carries it +(dev only; see .claude/discussions/discuss-gain-normalization-2026-10-19.md). + +Already measured without rekordbox open (2026-10-19, 19 local tracks): +`djmdMixerParam.Gain{High,Low}` are the halves of a big-endian float32, LINEAR, += 10^((-10 - LUFS)/20) to 0.13 dB — rekordbox levels integrated BS.1770 +loudness to -10 LUFS. `Peak{High,Low}` = the linear SAMPLE peak. + +Every SONG in the local library was added by Konduktor (2026-10-01), whose +rekordbox add writes no MixerParam row — so the fit above is rekordbox's +sample pack only. This kit asks rekordbox itself: + A. A track with NO row: does loading it create one (R2, R3)? + B. After rekordbox analyses the songs: is the gain -10 - LUFS on music too? + C. Is a gain Konduktor writes KEPT (R1 at -20 dB)? + D. Does a USB export carry the gain anywhere a CDJ reads (OneLibrary + exportLibrary.db, export.pdb, the ANLZ files)? R1-R3 are exported twice + with different gains and the two exports diffed. + + python dev_gain_kit_g2.py prepare # records state; writes nothing + # A -> rekordbox: Auto Gain on, load R2 + R3, quit + python dev_gain_kit_g2.py status + # B -> rekordbox: Analyze the 7 songs, quit + python dev_gain_kit_g2.py status + python dev_gain_kit_g2.py write # R1 -> -20 dB + # C -> rekordbox: load R1, export R1-R3 to a stick, quit + python dev_gain_kit_g2.py check1 /Volumes/STICK + python dev_gain_kit_g2.py flip + # D -> rekordbox: remove R1-R3 from the stick, export again, quit + python dev_gain_kit_g2.py check2 /Volumes/STICK + python dev_gain_kit_g2.py restore # R1-R3 back to rekordbox's own gains + +rekordbox must be closed whenever this script runs. The local master.db is written directly (it is disposable — but `prepare` +records every row it touches and `restore` puts them back). +""" + +from __future__ import annotations + +import json +import math +import shutil +import sqlite3 +import struct +import sys +import uuid +from datetime import datetime +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +KIT = Path.home() / "Music/Konduktor Stem Test/Kit G2" +STATE = KIT / "state.json" + +FLIP = {"R1": -8.0, "R2": +6.0, "R3": -14.0} # export 2's gains + + +def _halves(x: float) -> tuple[int, int]: + bits = struct.unpack(">I", struct.pack(">f", x))[0] + return bits >> 16, bits & 0xFFFF + + +def _value(hi, lo) -> float | None: + if hi is None or lo is None: + return None + return struct.unpack(">f", struct.pack(">I", ((hi & 0xFFFF) << 16) | (lo & 0xFFFF)))[0] + + +def _db_str(lin: float | None) -> str: + return "—" if lin is None else ("-inf" if lin <= 0 else f"{20 * math.log10(lin):+.2f} dB") + + +def _db(): + from pyrekordbox import masterdb + + from konduktor.adapters.rekordbox.store import rekordbox_probe_suppressed + from pyrekordbox.masterdb import database as rb_database + + if rb_database.get_rekordbox_pid(): + raise SystemExit("Quit rekordbox first.") + return masterdb.MasterDatabase(), rekordbox_probe_suppressed + + +def _row(db, content_id): + from pyrekordbox.masterdb import models + + return db.query(models.DjmdMixerParam).filter_by(ContentID=content_id).one_or_none() + + +def _snapshot_row(r) -> dict | None: + if r is None: + return None + return {c: getattr(r, c) for c in ("ID", "ContentID", "GainHigh", "GainLow", "PeakHigh", "PeakLow", "UUID")} | { + "created_at": str(r.created_at), "updated_at": str(r.updated_at)} + + +def _set_gain(db, content_id: str, db_gain: float) -> None: + r = _row(db, content_id) + r.GainHigh, r.GainLow = _halves(10 ** (db_gain / 20)) + + +SONGS = {"R1": "Faith in You - AC Slater Remix", "R2": "Low Frequency", "R3": "Never Let You Go"} # unlocked: a locked track cannot be analysed + + +def prepare() -> None: + """Record the kit's songs, their LUFS and their MixerParam rows. Writes nothing: + every song in this library was added by Konduktor and has NO MixerParam row.""" + from konduktor.core import loudness + + db, _ = _db() + state = {"tracks": {}, "songs": {}, "created": datetime.now().isoformat()} + KIT.mkdir(parents=True, exist_ok=True) + for c in db.get_content().all(): + if (c.Length or 0) < 120 or not Path(c.FolderPath or "").is_file(): + continue + m = loudness.measure_file(c.FolderPath) + entry = {"content_id": c.ID, "title": c.Title, "artist": c.Artist.Name if c.Artist else "", + "path": c.FolderPath, "lufs": m.lufs if m else None, "true_peak": m.true_peak if m else None, + "original": _snapshot_row(_row(db, c.ID))} + state["songs"][c.Title] = entry + for name, title in SONGS.items(): + if title == c.Title: + state["tracks"][name] = entry + STATE.write_text(json.dumps(state, indent=2)) + status() + print("\nNext, in rekordbox 7 (step A — a track with NO MixerParam row):\n" + " 1. Preferences > Controller > Mixer tab > Auto Gain: Enable.\n" + f" 2. PERFORMANCE mode: load '{SONGS['R2']}', open the deck's GRID EDIT panel and\n" + f" note its Auto Gain value (or that it is blank); then '{SONGS['R3']}'.\n" + " (No Performance mode: EXPORT mode, DUAL PLAYER layout, the AUTO GAIN knob.)\n" + " Do NOT run Analyze and do NOT turn the knob (a manual change is saved).\n" + " 3. Quit rekordbox.\n" + "Then: python dev_gain_kit_g2.py status") + + +def status() -> None: + """Every song's MixerParam row now, against -10 - LUFS.""" + db, _ = _db() + state = json.loads(STATE.read_text()) + print("== songs: MixerParam now (expected if rekordbox levels to -10 LUFS)") + for title, t in state["songs"].items(): + r = _row(db, t["content_id"]) + want = f"{-10 - t['lufs']:+.2f} dB" if t["lufs"] is not None else "?" + if r is None: + print(f" {title[:34]:34s} no row (expect {want})") + else: + g, pk = _value(r.GainHigh, r.GainLow), _value(r.PeakHigh, r.PeakLow) + print(f" {title[:34]:34s} gain {_db_str(g):>10s} peak {_db_str(pk):>10s} (expect {want}; " + f"true peak {t['true_peak']:+.2f}; updated {r.updated_at})") + + +def write() -> None: + """Step C: R1's gain set to -20 dB (it must have a row: run after rekordbox analysed it).""" + db, suppressed = _db() + state = json.loads(STATE.read_text()) + for name, t in state["tracks"].items(): + t["before_write"] = _snapshot_row(_row(db, t["content_id"])) + if state["tracks"]["R1"]["before_write"] is None: + raise SystemExit("R1 has no MixerParam row yet — analyse it in rekordbox first.") + _set_gain(db, state["tracks"]["R1"]["content_id"], -20.0) + with suppressed(): + db.commit(autoinc=True) + STATE.write_text(json.dumps(state, indent=2)) + print(f"R1 '{SONGS['R1']}' gain written -20.0 dB.\n" + "Next, in rekordbox 7 (step C):\n" + " 1. Load R1 and read GRID EDIT > Auto Gain (or the DUAL PLAYER AUTO GAIN\n" + " knob): -20 dB = kept, ~+4.5 dB = recomputed. Do NOT run Analyze.\n" + f" 2. Export R1, R2, R3 ('{SONGS['R1']}', '{SONGS['R2']}', '{SONGS['R3']}') to a USB stick.\n" + " 3. Quit rekordbox.\n" + "Then: python dev_gain_kit_g2.py check1 /Volumes/") + + +def _rows_now(db, state) -> dict: + return {name: _snapshot_row(_row(db, t["content_id"])) for name, t in state["tracks"].items()} + + +def _snapshot_stick(stick: Path, dest: Path) -> None: + rb = stick / "PIONEER/rekordbox" + if not rb.is_dir(): + raise SystemExit(f"No PIONEER/rekordbox on {stick}") + if dest.exists(): + shutil.rmtree(dest) + shutil.copytree(rb, dest / "rekordbox", ignore=shutil.ignore_patterns("*-shm", "*-wal")) + shutil.copytree(stick / "PIONEER/USBANLZ", dest / "USBANLZ") + + +def _report_rows(label: str, rows: dict, state: dict) -> None: + print(f"\n== master.db MixerParam {label}") + for name, r in rows.items(): + t = state["tracks"][name] + orig = t.get("before_write") or t["original"] or {} + if r is None: + print(f" {name}: no row") + continue + g, pk = _value(r["GainHigh"], r["GainLow"]), _value(r["PeakHigh"], r["PeakLow"]) + same_id = "same row" if r["ID"] == orig.get("ID") else "NEW row" + print(f" {name}: gain {_db_str(g)}, peak {_db_str(pk)} ({same_id}, updated {r['updated_at']})") + + +def check1(stick: str) -> None: + db, _ = _db() + state = json.loads(STATE.read_text()) + rows = _rows_now(db, state) + state["after_load"] = rows + STATE.write_text(json.dumps(state, indent=2)) + _report_rows("after rekordbox loaded + exported (R1 written -20 dB)", rows, state) + _snapshot_stick(Path(stick), KIT / "stick-1") + print(f"\nStick snapshot: {KIT / 'stick-1'}\nThen: python dev_gain_kit_g2.py flip") + + +def flip() -> None: + db, suppressed = _db() + state = json.loads(STATE.read_text()) + for name, g in FLIP.items(): + _set_gain(db, state["tracks"][name]["content_id"], g) + with suppressed(): + db.commit(autoinc=True) + print("Gains for export 2: " + ", ".join(f"{n} {g:+.1f} dB" for n, g in FLIP.items()) + + "\n" + "Next, in rekordbox 7:\n" + " 1. In the stick's browser, remove R1, R2, R3 from the device.\n" + " 2. Export R1, R2, R3 to the stick again.\n" + " 3. Quit rekordbox.\n" + "Then: python dev_gain_kit_g2.py check2 /Volumes/") + + +def _onelibrary_rows(snap: Path, titles: list[str]) -> dict: + import sqlcipher3.dbapi2 as sqlcipher + from pyrekordbox.onelibrary.database import BLOB + from pyrekordbox.utils import deobfuscate + + db = snap / "rekordbox/exportLibrary.db" + if not db.is_file(): + return {} + con = sqlcipher.connect(str(db)) + con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'") + cols = [r[1] for r in con.execute("PRAGMA table_info(content)")] + out = {} + for row in con.execute("SELECT * FROM content"): + d = dict(zip(cols, row)) + if d.get("title") in titles: + out[d["title"]] = d + con.close() + return out + + +def _pdb_rows(snap: Path, titles: list[str]) -> dict: + from konduktor.adapters.rekordbox import pdb + + f = snap / "rekordbox/export.pdb" + if not f.is_file(): + return {} + buf = f.read_bytes() + out = {} + for row in pdb.table_rows(buf, pdb.TRACKS): + fields, strings = pdb.track_fields(row) + if strings.get("title") in titles: + out[strings["title"]] = (row[: pdb.track_extent(row)], fields, strings) + return out + + +def _anlz(snap: Path, rel: str | None) -> dict: + from konduktor.adapters.rekordbox import anlz_file + + out = {} + if not rel: + return out + base = snap / "USBANLZ" / Path(rel.lstrip("/")).relative_to("PIONEER/USBANLZ") + for ext in (".DAT", ".EXT", ".2EX"): + p = base.with_suffix(ext) + if p.is_file(): + tags, seen = {}, {} + for t in anlz_file.parse_file(p).tags: # PCOB / PCO2 come twice (hot, memory) + seen[t.type] = seen.get(t.type, 0) + 1 + tags[f"{t.type}#{seen[t.type]}"] = t.data + out[ext] = tags + return out + + +def check2(stick: str) -> None: + db, _ = _db() + state = json.loads(STATE.read_text()) + rows = _rows_now(db, state) + _report_rows("before export 2 (flip), as rekordbox left it", rows, state) + _snapshot_stick(Path(stick), KIT / "stick-2") + titles = [t["title"] for t in state["tracks"].values()] + s1, s2 = KIT / "stick-1", KIT / "stick-2" + + print("\n== OneLibrary content rows: columns that differ between export 1 and 2") + a, b = _onelibrary_rows(s1, titles), _onelibrary_rows(s2, titles) + ids = {"content_id", "analysisDataFilePath", "image_id", "path", "dateAdded"} + for title in titles: + if title not in a or title not in b: + print(f" {title}: missing in an export ({title in a}, {title in b})") + continue + diff = {k: (a[title][k], b[title][k]) for k in a[title] if a[title][k] != b[title].get(k)} + print(f" {title[:40]}: {diff or 'identical'}") + + print("\n== export.pdb track rows: fields / bytes that differ") + a, b = _pdb_rows(s1, titles), _pdb_rows(s2, titles) + for title in titles: + if title not in a or title not in b: + print(f" {title}: missing in a pdb ({title in a}, {title in b})") + continue + fa, fb = a[title][1], b[title][1] + diff = {k: (fa[k], fb[k]) for k in fa if fa[k] != fb.get(k)} + sdiff = {k: (a[title][2][k], b[title][2][k]) for k in a[title][2] if a[title][2][k] != b[title][2].get(k)} + print(f" {title[:40]}: fields {diff or 'identical'}; strings {sdiff or 'identical'}") + + print("\n== ANLZ tags that differ") + oa, ob = _onelibrary_rows(s1, titles), _onelibrary_rows(s2, titles) + for title in titles: + ta = _anlz(s1, (oa.get(title) or {}).get("analysisDataFilePath")) + tb = _anlz(s2, (ob.get(title) or {}).get("analysisDataFilePath")) + changed = [f"{ext}:{k}" for ext in ta for k in ta[ext] if ta[ext][k] != tb.get(ext, {}).get(k)] + missing = [f"{ext}:{k}" for ext in tb for k in tb[ext] if k not in ta.get(ext, {})] + print(f" {title[:40]}: changed {changed or 'none'}; new {missing or 'none'}") + print("\nThen: python dev_gain_kit_g2.py restore") + + +def restore() -> None: + """R1 and R3 back to the gain rekordbox computed (their rows before `write`).""" + db, suppressed = _db() + state = json.loads(STATE.read_text()) + for name, t in state["tracks"].items(): + o, r = t.get("before_write"), _row(db, t["content_id"]) + if o and r is not None: + r.GainHigh, r.GainLow, r.PeakHigh, r.PeakLow = o["GainHigh"], o["GainLow"], o["PeakHigh"], o["PeakLow"] + with suppressed(): + db.commit(autoinc=True) + print("R1-R3 gains restored to rekordbox's own values.") + + +if __name__ == "__main__": + cmd = sys.argv[1] if len(sys.argv) > 1 else "prepare" + fn = {"prepare": prepare, "status": status, "write": write, "check1": check1, "flip": flip, + "check2": check2, "restore": restore}[cmd] + fn(*sys.argv[2:]) diff --git a/backend/konduktor/core/loudness.py b/backend/konduktor/core/loudness.py index 954ad78..8c9441f 100644 --- a/backend/konduktor/core/loudness.py +++ b/backend/konduktor/core/loudness.py @@ -40,7 +40,7 @@ import numpy as np #: Bump when a measurement changes: stored values from an older version count #: as stale and are offered for re-analysis. -VERSION = 1 +VERSION = 2 # 2: a stem file is its four stems summed, not its mix stream _ABS_GATE = -70.0 # LUFS _REL_GATE = -10.0 # LU, integrated @@ -217,7 +217,21 @@ def measure(pcm: np.ndarray, sr: int) -> Loudness | None: def measure_file(path: Path | str) -> Loudness | None: """Decode `path` at its own rate and channel count (more than two are downmixed to stereo; mono stays mono, as BS.1770 and FFmpeg treat it) and - measure it as it streams. Raises if the file cannot be decoded.""" + measure it as it streams. Raises if the file cannot be decoded. + + A stem FILE is measured as its four stems SUMMED — what a stem deck plays + (Traktor's and Konduktor's), and what Traktor's own gain analysis measures + (decided 2026-10-19 after `bench_traktor_gain.py`: commercial stem files' + mix streams are mastered ~2.8 dB, up to 5.3, hotter than their stems sum + to; see the gain-normalisation discussion).""" + from . import stem_file + + if stem_file.is_stem_file(path): + return _measure_stem_sum(path) + return _measure_stream(path) + + +def _measure_stream(path: Path | str) -> Loudness | None: import av from . import pyav @@ -247,3 +261,45 @@ def measure_file(path: Path | str) -> Loudness | None: pending.append(out.to_ndarray()) flush() return meter.result() + + +def _measure_stem_sum(path: Path | str) -> Loudness | None: + """Streams 1-4 of a stem file, decoded in ONE demux pass and summed as they + arrive, so memory stays at seconds of audio. The stems share their encoder + priming (they were muxed in lockstep), so sample n of each is the same + instant; the sum ends where the shortest stem does.""" + import av + + from . import pyav + + with pyav.open_input(path) as container: + stems = list(container.streams.audio[1:5]) + if len(stems) < 4: + raise ValueError(f"{path}: a stem file with {len(stems)} stems") + sr = int(stems[0].codec_context.sample_rate) + resamplers = {s.index: av.AudioResampler(format="fltp", layout="stereo", rate=sr) for s in stems} + queues: dict[int, list[np.ndarray]] = {s.index: [] for s in stems} + meter = _Meter(sr, 2) + + def drain(final: bool = False) -> None: + ready = min(sum(a.shape[1] for a in q) for q in queues.values()) + if ready == 0 or (not final and ready < sr * 5): # ~5 s per feed + return + total = np.zeros((2, ready), dtype=np.float32) + for idx, q in queues.items(): + buf = np.concatenate(q, axis=1) + total += buf[:, :ready] + queues[idx] = [buf[:, ready:]] if buf.shape[1] > ready else [] + meter.feed(total) + + for packet in container.demux(stems): + idx = packet.stream.index + for frame in packet.decode(): + for out in resamplers[idx].resample(frame): + queues[idx].append(out.to_ndarray()) + drain() + for idx, rs in resamplers.items(): + for out in rs.resample(None): + queues[idx].append(out.to_ndarray()) + drain(final=True) + return meter.result() diff --git a/backend/test_loudness.py b/backend/test_loudness.py index a8a6433..0ffbb7d 100644 --- a/backend/test_loudness.py +++ b/backend/test_loudness.py @@ -163,6 +163,21 @@ with tempfile.TemporaryDirectory() as d: r = loudness.measure_file(mono) check("a mono file is measured as ONE channel (3 dB under its stereo twin)", r is not None and abs(r.lufs + 23.0) <= 0.1, str(r)) + # A stem file is its four stems SUMMED (what a stem deck plays, and what + # Traktor measures), not its mix stream — commercial mixes are mastered + # hotter than their stems. Here each stem is an eighth of the mix, so the + # sum is the mix at half amplitude: -6.02 dB. + from konduktor.core import stem_file + + src = Path(d) / "src.flac" + sf.write(src, np.vstack([tone(1000, 10, 44100, 0.5)] * 2).T, 44100) + stem = Path(d) / "s.stem.m4a" + stem_file.build(src, stem, lambda pcm: [pcm * 0.125] * 4) + mix = loudness._measure_stream(stem) + summed = loudness.measure_file(stem) + check("a stem file measures its stem SUM (6.02 dB under its mix stream)", + summed is not None and mix is not None and abs((mix.lufs - summed.lufs) - 6.02) <= 0.1, + f"mix {mix and mix.lufs:.2f}, sum {summed and summed.lufs:.2f}") try: loudness.measure_file(Path(d) / "missing.flac") check("a missing file raises", False)