From 284a7514fe35506217884b915e9ea5e8fc4f73ec Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 19 Oct 2026 18:20:13 +0200 Subject: [PATCH] Implemented auto gain analysis --- CLAUDE.md | 63 ++++++++++++-- .../konduktor/adapters/onelibrary/adapter.py | 6 ++ .../konduktor/adapters/rekordbox/adapter.py | 30 +++++-- .../adapters/rekordbox/capabilities.py | 2 + backend/konduktor/adapters/rekordbox/gain.py | 32 +++++++ .../adapters/rekordbox/new_content.py | 5 +- .../adapters/rekordbox/projection.py | 4 +- backend/konduktor/adapters/rekordbox/store.py | 45 +++++++++- backend/konduktor/adapters/remote/adapter.py | 6 +- backend/konduktor/adapters/traktor/adapter.py | 6 ++ .../adapters/traktor/capabilities.py | 1 + backend/konduktor/adapters/traktor/gain.py | 32 +++++++ .../konduktor/adapters/traktor/projection.py | 2 + backend/konduktor/adapters/traktor/store.py | 24 +++++- backend/konduktor/app_state.py | 11 +++ backend/konduktor/core/adapter.py | 14 ++- backend/konduktor/core/add_analysis.py | 16 +++- backend/konduktor/core/capabilities.py | 3 + backend/konduktor/core/model.py | 4 + backend/konduktor/main.py | 86 +++++++++++++++---- backend/konduktor/remote_protocol.py | 16 +++- backend/konduktor/schemas.py | 11 ++- backend/test_grid_batch.py | 43 ++++++++++ backend/test_rekordbox_fidelity.py | 60 ++++++++++++- backend/test_remote_adapter.py | 19 ++++ backend/test_save_fidelity.py | 51 +++++++++++ frontend/src/App.tsx | 34 +++++++- frontend/src/api.ts | 13 +++ frontend/src/components/AnalyzeDialog.tsx | 80 ++++++++++++----- frontend/src/lib/trackColumns.tsx | 25 +++++- 30 files changed, 673 insertions(+), 71 deletions(-) create mode 100644 backend/konduktor/adapters/rekordbox/gain.py create mode 100644 backend/konduktor/adapters/traktor/gain.py diff --git a/CLAUDE.md b/CLAUDE.md index 9b6c41d..faa3903 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -778,6 +778,34 @@ Two independent apps that talk over HTTP: the true peak; never carried over): `convert.stem_loudness` after the build, stored at publish by the shared `_end_step` — remotely, the value rides `/v1/stems/stage`. + - **Auto gain** — the DJ app's OWN per-track gain, written from Konduktor's + loudness (decided + MEASURED 2026-10-19, [the discussion](.claude/discussions/discuss-gain-normalization-2026-10-19.md), + kits G1/G2: `backend/dev_gain_kit.py`, `dev_gain_kit_g2.py`). Generic + command `set_auto_gain(track_id, loudness)` (gated on + `tracks.auto_gain`; `Track.auto_gain_db` = the app's current value, None = + none): the ADAPTER turns a measurement into its own value, so no platform + constant reaches `core/`. Always from LUFS (the measure both apps level on). + **Traktor** (`adapters/traktor/gain.py`): the deck reads `LOUDNESS@ + PERCEIVED_DB`; Traktor's own = -9.2 - LUFS (sd 0.8 over 120 tracks, + `backend/bench_traktor_gain.py` — a stem file measured as its stem SUM); + written PERCEIVED = ANALYZED, PEAK = -true peak; collection-only (no file + tag). A written value is KEPT; on an AUDIO_ID-empty entry Traktor's first + analysis overwrites only ANALYZED; its Analyze > Gain overwrites all three. + **rekordbox** (`adapters/rekordbox/gain.py`): one `djmdMixerParam` row, + Gain = float32 halves, linear, = 10^((-10 - LUFS)/20) (exact on its WAVs, + +0.24 dB on MP3 songs); Peak = the CLIPPED sample peak (<= 0 dB); rows + created through the ORM (`ID` and `UUID` both UUID strings, `rb_local_usn` + stamped); the projection reads all rows in ONE query (`mixer_gains`). A + track with no row plays at 0.0 dB and loading never creates one, so + **rekordbox's add measures loudness and writes the row** (`add_analysis. + prepare(measure_loudness=True)`, `PreparedAnalysis.loudness` — on a remote + it rides the packed analysis), and the measurement reaches this computer's + store through the adapter's optional `on_loudness` hook, set by `AppState`. + **No stick format carries a gain** (diffed across two exports), so + OneLibrary has no `auto_gain`. Analyze's **Gain** tick (`gain` / + `replace_gain`): fills tracks without one unless Replace, measuring first + where the loudness is missing or stale (a fresh measurement is reused — + no decode, no download); the deck's Analyze fills a missing one. - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data dir). Last-opened collection (global AND per-platform), library column layout, prep-deck zoom, import destination. Best-effort, but **every @@ -1057,7 +1085,10 @@ Two independent apps that talk over HTTP: where loudness is all that can be done it is pre-ticked. The Replace questions (loudness: "Measure again") are inside the dialog, never a second popup, and never remembered: the grid's only when BPM AND Grid are - ticked, since with one tick adjusting the grid is the point. Every count + ticked, since with one tick adjusting the grid is the point. A **Gain** + tick (`gainWhy`) writes the DJ app's auto gain (see "Auto gain"); the + context menu's **Mastering ▸** opens the same dialog for ONE option + (`preset`: Auto gain… / Measure loudness), which saves no ticks. Every count and the "Analyze N" button come from `/api/tracks/analyze/preview`, i.e. the backend's own `plan_grid`. The finished job's toast says what was written and skipped, by reason. The deck's one-click Analyze writes the @@ -1243,6 +1274,9 @@ Two independent apps that talk over HTTP: every unmeasured track loudest. `Track.loudness` is NOT the backend's: App joins `/api/loudness` into the rows (`['loudness', origin, hash of ids]`), only while a Mastering column is visible; analyses invalidate `['loudness']`. + A sixth, **Auto Gain** (`Track.auto_gain_db`, the DJ app's own value, `—` + when none), sits in the same submenu but is NOT in `MASTERING_COLUMNS`: it + comes with the track, so showing it fetches nothing. - Data flow: the whole library is fetched once (`/api/tracks?limit=20000`); filtering and sorting happen **client-side** for instant interaction. Edits apply in-memory (server holds them) and the sidebar **Save to Traktor** @@ -1327,6 +1361,10 @@ serialization path.** It enforces: entry's ``, with `COLOR` last as Traktor writes it; aqua is stored as Blue; clearing restores the original bytes; and a Traktor 4.5 collection holding coloured tracks (when on the machine) renders byte-identically. + And **auto gain** (S): `set_auto_gain` changes one line, that entry's + ``, in Traktor's 6-decimal form (PERCEIVED = ANALYZED = -9.2 - + LUFS); an entry without one gains a single line between TEMPO and + MUSICAL_KEY; the same value again is not dirty; never a file tag. The guard that catches serialization regressions like the lxml reformatting bug. - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays Traktor-valid, backup-first, COLLECTION byte-identical, original untouched; @@ -1433,7 +1471,11 @@ serialization path.** It enforces: mirror in ROW order, rename touching only `Comment` (+ the USN pyrekordbox stamps on every cue write — rekordbox's own leave it NULL, and it has accepted ours), the 11th refused with nothing changed, delete removing the - row outright. + row outright. And **auto gain** (M): a track without one gains exactly one + `djmdMixerParam` INSERT (UUID-string `ID`/`UUID`, USN stamped, Gain = + 10^((-10 - LUFS)/20) as float32 halves, Peak clipped at 1.0) + the counter; + the same value is not dirty, a new one UPDATES that row only, it projects + after a reopen; and every track ADDED (J) arrives with its row. - `test_onelibrary_adapter.py` — the third adapter against the same contract. Unlike the Rekordbox tests it needs **nothing installed and nothing plugged in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed @@ -1559,9 +1601,13 @@ serialization path.** It enforces: the run's (BPM alone: single grids adjusted, flexible skipped, bare in full); a skipped track is never decoded and grid+key share ONE decode; a grid that cannot be fitted still gets its key; the deck's Analyze writes - the key too and never fails on it. The decode is `main._decode_for_analysis` + the key too and never fails on it. And **Gain**: the preview's counts match + the run's; a track without an auto gain gets -9.2 - LUFS, measured first, + one with one is left alone unless `replace_gain`, and a fresh measurement is + reused rather than decoded again. The decode is `main._decode_for_analysis` (the seam the fakes replace); `test_key_detect.py` runs the route once with - the REAL decode and detectors on a generated F-minor 124 BPM WAV. + the REAL decode and detectors on a generated F-minor 124 BPM WAV. (Its + app-data is a temp folder: the routes write the loudness store.) - `test_bulk_remove.py` — the context menu's **Remove ▸** routes (`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`): locked grids are kept, clearing hotcues empties the whole bank (loops and the @@ -1674,7 +1720,8 @@ serialization path.** It enforces: content folder as a drive: listed first, confined, held files ticked off, auditioned with one download, an add IN PLACE (no upload, the held one not added twice, both into the playlist, analysed here when the server reports - a lead). + a lead). And auto gain: computed here from the SERVER's stored measurement + (no new download), written on the server, saved into its collection. - `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine: the plan's transfer and two-machine space, Replace parks and swaps ON THE SERVER (saved file untouched until Save, which deletes the parked @@ -1983,8 +2030,10 @@ that number and nothing else — everything derives from it: files and artwork (`NewTrack.art`, else the file's embedded cover) are held until save and written BEFORE the grids and commit, then `contentFile` rows hash what was written (`_m`/`_s` unlisted, as - Rekordbox does); a failed save removes them. Key, mixer gain and phrases - are Rekordbox's own analysis and are not written. The row and file + Rekordbox does); a failed save removes them. The key is detected and the + mixer gain measured (`djmdMixerParam`, see "Auto gain" — without a row a + track plays at 0.0 dB); mixer phrases are Rekordbox's own analysis and are + not written. The row and file builders live in `adapters/rekordbox/new_content.py`, shared with the Rekordbox Library exporter. - **`jobs.py` + `importer.py`** — the app's first long-running operation. diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index c3de7a7..fdb6a03 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -410,6 +410,12 @@ class OneLibraryAdapter: self._refresh(track_id) return self._index.get(track_id) + def set_auto_gain(self, track_id: str, loudness) -> Track | None: + # Measured (kit G2): no stick format carries an auto gain — not the + # database, not export.pdb, not the analysis files. `tracks.auto_gain` + # is False, so nothing offers it. + raise Unsupported("A OneLibrary drive has no auto gain: level a stick by normalising its audio") + def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: self._refuse("Editing cover art") diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index d12c544..f50c078 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -45,10 +45,12 @@ class RekordboxAdapter: # ---- projection maintenance ----------------------------------------- def _rebuild(self) -> None: kinds = self._store.cue_kinds() + gains = self._store.mixer_gains() self._index.rebuild( [ projection.to_track(row, kinds.get(str(row.ID), ()), - stem=self._store.is_stem(str(row.ID))) + stem=self._store.is_stem(str(row.ID)), + auto_gain_db=gains.get(str(row.ID))) for row in self._store.iter_content() ] ) @@ -71,7 +73,8 @@ class RekordboxAdapter: kinds = self._store.cue_kinds() row = self._store.content(track_id) self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()), - stem=self._store.is_stem(str(row.ID)))) + stem=self._store.is_stem(str(row.ID)), + auto_gain_db=self._store.mixer_gain(str(row.ID)))) def close(self) -> None: """Release the database connection. @@ -266,6 +269,12 @@ class RekordboxAdapter: self._refresh(track_id) return self._index.get(track_id) + def set_auto_gain(self, track_id: str, loudness) -> Track | None: + self._require_writable("Setting the auto gain") + self._store.set_auto_gain(track_id, loudness) + self._refresh(track_id) + return self._index.get(track_id) + # ---- commands: playlists ---------------------------------------------- def create_playlist(self, name: str, parent_id: str | None = None) -> str: self._require_writable("Creating playlists") @@ -545,17 +554,22 @@ class RekordboxAdapter: else: analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio), detect=not markers, - detect_key=item.track.key_wheel is None) + detect_key=item.track.key_wheel is None, + measure_loudness=True) markers = markers or list(analysed.markers) measured = analysed.measured # A file with no key of its own gets one, as it gets a grid # (decided: arrive ready to prep). Rekordbox's own add analyses one. track = add_analysis.with_key(item.track, analysed.key) art = item.art or audio_tags.read_cover(audio) - prepared.append((item, track, audio, measured, markers, art[0] if art else None)) + prepared.append((item, track, audio, measured, markers, art[0] if art else None, + getattr(analysed, "loudness", None))) + # The app's loudness store, where one is attached (see `AppState`): a + # measurement made here is worth keeping for the Mastering columns. + on_loudness = getattr(self, "on_loudness", None) added: list[str] = [] - for item, track, audio, measured, markers, art in prepared: + for item, track, audio, measured, markers, art, loud in prepared: track_id = self._store.add_track( audio, track, measured=measured, with_grid=bool(markers), art=art) self._index.add(projection.to_track(self._store.content(track_id), (), @@ -564,6 +578,12 @@ class RekordboxAdapter: self._store.replace_grid(track_id, markers) if item.cues is not None: self._place_imported_cues(track_id, item.cues) + if loud is not None: + # rekordbox's own add analyses an auto gain; without a row the + # track plays at 0.0 dB and loading never creates one (kit G2). + self._store.set_auto_gain(track_id, loud) + if on_loudness is not None: + on_loudness(audio, loud) self._refresh(track_id) added.append(track_id) return added diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index e6ed4af..a6e9205 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -95,6 +95,8 @@ def capabilities_for( key_writable=True, # `djmdContent.ColorID`, rekordbox's eight (see `track_palette`). colors=list(track_palette.SWATCHES), + # djmdMixerParam (measured, see `gain`). + auto_gain=True, artwork=False, artwork_note=None, ), diff --git a/backend/konduktor/adapters/rekordbox/gain.py b/backend/konduktor/adapters/rekordbox/gain.py new file mode 100644 index 0000000..53846bf --- /dev/null +++ b/backend/konduktor/adapters/rekordbox/gain.py @@ -0,0 +1,32 @@ +"""rekordbox's auto gain: one `djmdMixerParam` row per track. + +MEASURED (kit G2, 2026-10-19 — `backend/dev_gain_kit_g2.py` and the +gain-normalisation discussion): + + * `GainHigh/GainLow` are the two 16-bit halves of a big-endian float32, a + LINEAR gain; pyrekordbox's `DjmdMixerParam.Gain` reads and writes it in dB. + It is what PERFORMANCE mode's GRID EDIT > Auto Gain (and EXPORT mode's + DUAL PLAYER AUTO GAIN knob) shows, with Preferences > Controller > Mixer > + Auto Gain enabled. + * rekordbox's own analysis sets it to `-10 - LUFS` (BS.1770 integrated): + exact on its 19 WAV samples (sd 0.13 dB), +0.24 dB (sd 0.17) on 5 MP3 songs. + * `PeakHigh/PeakLow`: the linear SAMPLE peak, of a CLIPPED decode — never + above 1.0 (a track with a true peak of +3.9 dBTP stored 0.00 dB). + * A row Konduktor writes is kept on load. A track with NO row plays at + Auto Gain 0.0 dB, and loading it creates none — so a track Konduktor adds + gets its row at add time, as rekordbox's own add analyses one. + * No USB export carries it (diffed across two exports with different gains). +""" + +from __future__ import annotations + +from ...core.loudness import Loudness + +#: The level rekordbox's auto gain brings a track to, in LUFS. +REFERENCE_LUFS = -10.0 + + +def values(loudness: Loudness) -> tuple[float, float]: + """(gain dB, peak dB) for a measured track — the peak clipped at 0 dBFS as + rekordbox's own is.""" + return REFERENCE_LUFS - loudness.lufs, min(0.0, loudness.true_peak) diff --git a/backend/konduktor/adapters/rekordbox/new_content.py b/backend/konduktor/adapters/rekordbox/new_content.py index bff1d6f..95f9ffb 100644 --- a/backend/konduktor/adapters/rekordbox/new_content.py +++ b/backend/konduktor/adapters/rekordbox/new_content.py @@ -10,7 +10,10 @@ What a track Rekordbox itself adds looks like was MEASURED (two files dragged into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a `djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own -analysis results — key, mixer gain, phrases — which nothing here can produce. +analysis results — key, mixer gain, phrases. Phrases nothing here produces; the +key comes from `key_detect` and the mixer gain from a loudness measurement +(`djmdMixerParam`, written by the adapter's add through `RekordboxStore. +set_auto_gain` — see `gain`). """ from __future__ import annotations diff --git a/backend/konduktor/adapters/rekordbox/projection.py b/backend/konduktor/adapters/rekordbox/projection.py index a5073de..bd48751 100644 --- a/backend/konduktor/adapters/rekordbox/projection.py +++ b/backend/konduktor/adapters/rekordbox/projection.py @@ -64,7 +64,7 @@ def _name_of(related) -> str | None: return None -def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track: +def to_track(row, cue_kinds=(), *, stem: bool = False, auto_gain_db: float | None = None) -> Track: """Project one ``DjmdContent`` row. `cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single @@ -129,6 +129,8 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track: media_kind="stem" if stem else "audio", color=track_palette.color_for(getattr(row, "ColorID", None)), color_hex=track_palette.hex_for(getattr(row, "ColorID", None)), + # From the store's one `djmdMixerParam` query (see `gain`). + auto_gain_db=auto_gain_db, ) diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index d648a3a..61a46c4 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -47,7 +47,7 @@ from ...core.adapter import ( from ...core.edit_journal import EditJournal from ...core.grid_edit import ReplaceGridCommands from ...core.pathmap import PathMapping, stored_form -from . import memory_palette, timebase, track_palette +from . import gain, memory_palette, timebase, track_palette from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot log = logging.getLogger(__name__) @@ -574,6 +574,49 @@ class RekordboxStore(ReplaceGridCommands): self._db.flush() self._db.session.expire(row) + # ---- auto gain ------------------------------------------------------------ + def _mixer_row(self, track_id: str): + return (self._db.query(self._tables.DjmdMixerParam) + .filter(self._tables.DjmdMixerParam.ContentID == str(track_id)).first()) + + def mixer_gains(self) -> dict[str, float]: + """``{track_id: auto gain dB}`` for every track with a row — ONE query, so + the projection never lazy-loads a relationship per track.""" + t = self._tables.DjmdMixerParam + out = {} + for content_id, low, high in self._db.query(t.ContentID, t.GainLow, t.GainHigh).all(): + if content_id is not None and low is not None and high is not None: + out[str(content_id)] = t._get_db(low, high) + return out + + def mixer_gain(self, track_id: str) -> float | None: + row = self._mixer_row(track_id) + if row is None or row.GainLow is None or row.GainHigh is None: + return None + return row.Gain + + def set_auto_gain(self, track_id: str, loudness) -> None: + """The track's `djmdMixerParam` row (see `gain`), created as rekordbox + creates its own — `ID` and `UUID` both UUID strings — and through the + ORM, so `commit()` stamps `rb_local_usn`. Writing the halves already + there leaves the library clean.""" + self.content(track_id) # NotFound for an unknown track + gain_db, peak_db = gain.values(loudness) + t = self._tables.DjmdMixerParam + g_low, g_high = t._set_db(gain_db) + p_low, p_high = t._set_db(peak_db) + row = self._mixer_row(track_id) + before = None if row is None else (row.GainHigh, row.GainLow, row.PeakHigh, row.PeakLow) + after = (g_high, g_low, p_high, p_low) + if before == after: + return + if row is None: + row = t(ID=str(uuid.uuid4()), ContentID=str(track_id), UUID=str(uuid.uuid4())) + self._db.add(row) + row.GainHigh, row.GainLow, row.PeakHigh, row.PeakLow = after + self._journal.record("track", "set", track_id, "auto_gain", before, after) + self._db.flush() + # ---- writes: playlists ------------------------------------------------ def _playlist(self, node_id: str): t = self._tables diff --git a/backend/konduktor/adapters/remote/adapter.py b/backend/konduktor/adapters/remote/adapter.py index ee0c314..93949ca 100644 --- a/backend/konduktor/adapters/remote/adapter.py +++ b/backend/konduktor/adapters/remote/adapter.py @@ -221,6 +221,9 @@ class RemoteAdapter: def set_track_color(self, track_id, color): return self._call("set_track_color", track_id=track_id, color=color) + def set_auto_gain(self, track_id, loudness): + return self._call("set_auto_gain", track_id=track_id, loudness=loudness) + def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None): return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec, cue_type=cue_type, length_sec=length_sec, role=role, name=name) @@ -332,7 +335,8 @@ class RemoteAdapter: checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total) has_grid = bool(item.cues and item.cues.grid_markers) analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid, - detect_key=item.track.key_wheel is None) + detect_key=item.track.key_wheel is None, + measure_loudness=self.capabilities().tracks.auto_gain) art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \ if item.art else None wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art, diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 0db9fad..861b7bc 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -162,6 +162,12 @@ class TraktorAdapter: self._refresh(track_id) return self._index.get(track_id) + def set_auto_gain(self, track_id: str, loudness) -> Track | None: + with _translate(): + self._store.set_auto_gain(track_id, loudness) + self._refresh(track_id) + return self._index.get(track_id) + def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: with _translate(): self._store.set_track_art(track_id, data, mime) diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index 11b7a2a..5075475 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -71,6 +71,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: key_writable=True, # INFO@COLOR, seven colours (measured, see `track_palette`). colors=list(track_palette.SWATCHES), + auto_gain=True, # `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # but only on Windows, and a file added on one OS must play on both. audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"], diff --git a/backend/konduktor/adapters/traktor/gain.py b/backend/konduktor/adapters/traktor/gain.py new file mode 100644 index 0000000..e30ff6d --- /dev/null +++ b/backend/konduktor/adapters/traktor/gain.py @@ -0,0 +1,32 @@ +"""Traktor's auto gain: `` per ENTRY. + +MEASURED in Traktor 4.5 (kit G1, 2026-10-19 — `backend/dev_gain_kit.py` and +the gain-normalisation discussion): + + * The deck's gain knob reads **PERCEIVED_DB** (an entry written with + PERCEIVED -6 / ANALYZED +6 / PEAK 2.5 loaded at -6.0). + * ANALYZED_DB is Traktor's own measurement. On an entry with an empty + AUDIO_ID, Traktor's first analysis overwrites only ANALYZED_DB and keeps + PERCEIVED_DB and PEAK_DB; its Analyze > Gain overwrites all three. + * Traktor's own value is `-9.2 - LUFS` (BS.1770 integrated; stem files + measured as their stems summed): sd 0.8 dB over 120 tracks + (`backend/bench_traktor_gain.py`), the miss following nothing measurable. + * PEAK_DB is the gain that brings the peak to 0 dBFS (= -peak; Traktor's is + a sample peak, ours a true peak — within ~0.4 dB). + +Konduktor writes PERCEIVED and ANALYZED equal, as Traktor's own analysis does. +""" + +from __future__ import annotations + +from ...core.loudness import Loudness + +#: The level Traktor's auto gain brings a track to, in LUFS. +REFERENCE_LUFS = -9.2 + + +def values(loudness: Loudness) -> tuple[float, float, float]: + """(PEAK_DB, PERCEIVED_DB, ANALYZED_DB) for a measured track, rounded to + Traktor's six decimals so a re-write of the same measurement is a no-op.""" + gain = round(REFERENCE_LUFS - loudness.lufs, 6) + return round(-loudness.true_peak, 6), gain, gain diff --git a/backend/konduktor/adapters/traktor/projection.py b/backend/konduktor/adapters/traktor/projection.py index d28de6b..be13cde 100644 --- a/backend/konduktor/adapters/traktor/projection.py +++ b/backend/konduktor/adapters/traktor/projection.py @@ -174,6 +174,8 @@ def to_track(e) -> Track: media_kind="stem" if getattr(e, "stems", None) is not None else "audio", color=track_palette.color_for(info.color if info else None), color_hex=track_palette.hex_for(info.color if info else None), + # The deck's gain knob reads PERCEIVED_DB (kit G1). + auto_gain_db=e.loudness.perceived_db if e.loudness is not None else None, ) diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index e9dbbeb..ecbbf4b 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -38,6 +38,7 @@ from traktor_nml_utils.models.collection import ( Infotype, MusicalKeytype, Locationtype, + Loudnesstype, Nodetype, Playlisttype, Primarykeytype, @@ -54,7 +55,7 @@ from ...core.pathmap import PathMapping, stored_form from ...core.relocate import PathGroup from ...core.stem_file import NML_STEMS_JSON, nml_stems_for from ...schemas import PlaylistNode -from . import beatgrid, timebase, track_palette +from . import beatgrid, gain, timebase, track_palette from .locations import os_path_to_location, resolve_path from ...core import musical_key from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids @@ -448,7 +449,8 @@ class TraktorStore: # Fields that live only in the collection: Traktor itself writes no file tag # for "Comment 2" (verified on an m4a it had just edited), so neither do we. # Nor for the track colour (kit T1: no audio file's mtime moved). - _COLLECTION_ONLY_FIELDS = {"comment2", "color"} + # Nor for its auto gain (LOUDNESS is Traktor's own analysis output). + _COLLECTION_ONLY_FIELDS = {"comment2", "color", "auto_gain"} def set_track_metadata(self, track_id: str, fields: dict) -> None: with self._lock: @@ -567,6 +569,24 @@ class TraktorStore: self._journal.record("track", "set", track_id, "color", before, code) self.dirty = True + # ---- auto gain -------------------------------------------------------- + def set_auto_gain(self, track_id: str, loudness) -> None: + """`` from a measurement (see `gain`). The element is replaced + whole; a write of the values already there leaves the store clean.""" + peak, perceived, analyzed = gain.values(loudness) + with self._lock: + entry = self._entry_by_key.get(track_id) + if entry is None: + raise PlaylistError(f"Track not found: {track_id}") + old = entry.loudness + before = None if old is None else (old.peak_db, old.perceived_db, old.analyzed_db) + after = (peak, perceived, analyzed) + if before == after: + return + entry.loudness = Loudnesstype(peak_db=peak, perceived_db=perceived, analyzed_db=analyzed) + self._journal.record("track", "set", track_id, "auto_gain", before, after) + self.dirty = True + # ---- adding tracks -------------------------------------------------- def add_entry(self, track, audio_path: Path) -> str: """Append a brand-new ENTRY for `audio_path` and return its track id. diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py index d3ac9a9..dcd5af3 100644 --- a/backend/konduktor/app_state.py +++ b/backend/konduktor/app_state.py @@ -158,6 +158,9 @@ class AppState: if saved: adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) self.path, self.adapter = path, adapter + # A measurement the adapter makes while adding a track (rekordbox's add + # writes the auto gain from one) is kept for the Mastering columns. + adapter.on_loudness = self._keep_loudness caps = adapter.capabilities() # No sidecar beside a removable library: writing to a user's USB stick to # satisfy Konduktor's own bookkeeping is not a trade worth making. Those @@ -188,6 +191,14 @@ class AppState: for hook in self.open_hooks: hook(adapter) + def _keep_loudness(self, path, values) -> None: + from . import loudness_store + + try: + self.loudness.put(loudness_store.file_facts(path), values) + except OSError: + log.warning("could not store the loudness of %s", path, exc_info=True) + def _release_previous(self) -> None: previous = self.adapter # Leaving a library discards its unsaved edits (the UI has confirmed), so diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index a10e2f3..55026aa 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -23,6 +23,7 @@ from pathlib import Path from typing import Protocol, runtime_checkable from .capabilities import Capabilities, TrackColor +from .loudness import Loudness from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage from .pathmap import PathMapping from .relocate import PathGroup @@ -110,13 +111,16 @@ class PreparedAnalysis: its own copy and the result travels with the track. `measured` is a `core.waveform.Analysis` measured with the file's own time-base lead, `markers` the detected grid (empty: none found) and `key` the detected - `core.key_detect.KeyResult` (None: not asked for, or none found). Absent, - the adapter decodes as before. + `core.key_detect.KeyResult` (None: not asked for, or none found), and + `loudness` the file's `core.loudness.Loudness` where the platform keeps an + auto gain (None: not asked for, or not measurable). Absent, the adapter + decodes as before. """ measured: object markers: list = field(default_factory=list) key: object | None = None + loudness: object | None = None @dataclass @@ -299,6 +303,12 @@ class LibraryAdapter(Protocol): # The track's colour tag (None clears it), mapped onto the platform's own # palette by name. Gated on `tracks.colors` being non-empty. def set_track_color(self, track_id: str, color: TrackColor | None) -> Track | None: ... + # The DJ app's auto gain, computed BY THE ADAPTER from the track's measured + # loudness (the platform's reference level is platform knowledge: Traktor + # levels to -9.2 LUFS, rekordbox to -10, both measured 2026-10-19). Writes + # whatever is there; whether to (fill vs replace) is the caller's call. + # Gated on `tracks.auto_gain`. + def set_auto_gain(self, track_id: str, loudness: Loudness) -> Track | None: ... def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ... def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ... diff --git a/backend/konduktor/core/add_analysis.py b/backend/konduktor/core/add_analysis.py index b9f5589..f923312 100644 --- a/backend/konduktor/core/add_analysis.py +++ b/backend/konduktor/core/add_analysis.py @@ -18,9 +18,11 @@ from .model import GridMarker def prepare(path: Path, *, lead: float, detect: bool = True, - detect_key: bool = False) -> PreparedAnalysis: + detect_key: bool = False, measure_loudness: bool = False) -> PreparedAnalysis: """Decode `path` once: its waveform at `lead`, and (with `detect`) a grid, - (with `detect_key`) a key.""" + (with `detect_key`) a key. `measure_loudness` adds the file's loudness — + a decode of its own, at the file's rate and channels (BS.1770 cannot use + the analysis decode; see `core.loudness`), ~1 s a track.""" from . import grid_detect, waveform samples = waveform.decode(Path(path)) @@ -40,7 +42,15 @@ def prepare(path: Path, *, lead: float, detect: bool = True, key = key_detect.detect_key_samples(samples, waveform.SR) except Exception: # noqa: BLE001 - a missing key is not worth failing an add over logging.getLogger(__name__).warning("key detection failed", exc_info=True) - return PreparedAnalysis(measured=measured, markers=markers, key=key) + measured_loudness = None + if measure_loudness: + from . import loudness + + try: + measured_loudness = loudness.measure_file(path) + except Exception: # noqa: BLE001 - a missing gain is not worth failing an add over + logging.getLogger(__name__).warning("loudness measurement failed", exc_info=True) + return PreparedAnalysis(measured=measured, markers=markers, key=key, loudness=measured_loudness) def with_key(track, key): diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index c3b348e..766c56b 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -124,6 +124,9 @@ class TrackCapabilities(BaseModel): # The track colours this library can store (`set_track_color`), in its own # menu order. Empty: the platform has no track colour. colors: list[ColorSwatch] = [] + # The library keeps a per-track auto gain the DJ app applies on load + # (`set_auto_gain`). False on a stick: no stick format has one (measured). + auto_gain: bool = False class PlaylistCapabilities(BaseModel): diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index ae261cf..97f56ca 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -76,6 +76,10 @@ class Track(BaseModel): # code by the adapter. None = no colour. color: TrackColor | None = None color_hex: str | None = None + # The DJ app's own auto gain for the track in dB (Traktor's deck gain, + # rekordbox's Auto Gain), as the adapter reads it. None = the track has + # none, which is what "fill where missing" looks for. + auto_gain_db: float | None = None class TrackPage(BaseModel): diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 0847ef1..d723184 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -1557,7 +1557,13 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: try: # so is loudness, into Konduktor's own store — always re-measured here looked = _loud_lookup("collection", [body.track_id]).get(body.track_id) if looked is not None: - _measure_loudness(looked[0], looked[1], path) + values = _measure_loudness(looked[0], looked[1], path) + # ...and the DJ app's auto gain, where the track has none yet. + track = a.track(body.track_id) + caps = a.capabilities() + if (values is not None and caps.tracks.auto_gain and caps.writable + and track is not None and track.auto_gain_db is None): + a.set_auto_gain(body.track_id, values) except _AnalysisError as ex: log.warning("no loudness for %s: %s", body.track_id, ex) except Exception: # noqa: BLE001 @@ -1655,17 +1661,19 @@ def _analyse_grid(a, track_id: str, step: GridStep = GridStep("full"), *, def _require_analysable(body: AnalyzeRequest) -> None: - if not (body.bpm or body.grid or body.key or body.loudness): - raise HTTPException(400, "Nothing to analyse: tick BPM, Grid, Key or Loudness") - if not (body.bpm or body.grid or body.key): + if not (body.bpm or body.grid or body.key or body.loudness or body.gain): + raise HTTPException(400, "Nothing to analyse: tick BPM, Grid, Key, Gain or Loudness") + if not (body.bpm or body.grid or body.key or body.gain): return # loudness: Konduktor's own store, so any track, any library if body.origin != "collection": - raise HTTPException(400, "BPM, grid and key are analysed only for the library's own tracks") + raise HTTPException(400, "BPM, grid, key and gain are analysed only for the library's own tracks") caps = require_adapter().capabilities() if (body.bpm or body.grid) and not caps.grid.editable: raise HTTPException(422, "This library's beatgrids cannot be edited") if body.key and not caps.tracks.key_writable: raise HTTPException(422, "This library's keys cannot be written") + if body.gain and not (caps.tracks.auto_gain and caps.writable): + raise HTTPException(422, "This library has no auto gain to write") def _grid_step(a, track, body: AnalyzeRequest, *, exact: bool) -> GridStep: @@ -1686,6 +1694,10 @@ def _wants_key(track, body: AnalyzeRequest) -> bool: return body.key and (track.key_wheel is None or body.replace_key) +def _wants_gain(track, body: AnalyzeRequest) -> bool: + return body.gain and (track.auto_gain_db is None or body.replace_gain) + + @app.post("/api/tracks/analyze/preview", response_model=AnalyzePreview) def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview: """Counts for the Analyze dialog, from the same `plan_grid` the run uses @@ -1693,6 +1705,8 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview: a = require_adapter() if body.origin == "collection" else None looked = _loud_lookup(body.origin, body.track_ids) if body.loudness or a is None else {} out = AnalyzePreview(total=0) + # Gain needs a measurement; one the run would make anyway is not "busy" + # twice, so only the gain's own decision is counted here. for tid in dict.fromkeys(body.track_ids): if a is not None: track = a.track(tid) @@ -1718,6 +1732,14 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview: out.key_set += 1 else: out.key_existing += 1 + if track.auto_gain_db is not None: + out.with_gain += 1 + if body.gain: + if _wants_gain(track, body): + out.gain_set += 1 + busy = True + else: + out.gain_existing += 1 if body.loudness: _target, facts, entry = looked.get(tid, (None, None, None)) fresh = entry is not None and not entry.stale(facts) @@ -1749,7 +1771,8 @@ def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None: reported and does not stop the others: a track whose grid cannot be fitted (a one-shot) can still have a key, and the reverse.""" try: - looked = _loud_lookup(body.origin, [track_id]).get(track_id) if body.loudness or a is None else None + wanted = body.loudness or body.gain or a is None + looked = _loud_lookup(body.origin, [track_id]).get(track_id) if wanted else None except HTTPException: # the source went away mid-run looked = None if a is not None: @@ -1775,13 +1798,25 @@ def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None: want_loud = body.replace_loudness or entry is None or entry.stale(facts) if not want_loud: result["loudness"]["existing"] += 1 + want_gain = a is not None and _wants_gain(track, body) + if body.gain and not want_gain: + result["gain"]["existing"] += 1 + gain_values = None + if want_gain and looked is not None and not want_loud: + _target, facts, entry = looked + if entry is not None and not entry.stale(facts): + gain_values = entry.values # measured and fresh: no decode for the gain want_grid = step.action in ("full", "bpm", "phase") - if not (want_grid or want_key or want_loud): - return - path = src.audio_path(sid) - if path is None or not path.exists(): - result["failed"].append({"title": title, "reason": "Audio file not found (is the drive mounted?)"}) + if not (want_grid or want_key or want_loud or want_gain): return + # A gain from a fresh measurement needs no audio (on a remote library, + # asking for the path would download the file). + path = None + if want_grid or want_key or want_loud or gain_values is None: + path = src.audio_path(sid) + if path is None or not path.exists(): + result["failed"].append({"title": title, "reason": "Audio file not found (is the drive mounted?)"}) + return wrote = False if want_grid or want_key: try: @@ -1807,15 +1842,31 @@ def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None: wrote = True except (AdapterError, ValueError) as ex: result["failed"].append({"title": title, "reason": f"Key: {ex}"}) - if want_loud: + measured_now = False + if want_loud or (want_gain and gain_values is None): try: - if _measure_loudness(looked[0], looked[1], path) is None: - result["loudness"]["none"] += 1 - else: - result["loudness"]["measured"] += 1 - wrote = True + gain_values = _measure_loudness(looked[0], looked[1], path) if looked is not None else None + measured_now = True + if want_loud: + if gain_values is None: + result["loudness"]["none"] += 1 + else: + result["loudness"]["measured"] += 1 + wrote = True except (_AnalysisError, AdapterError) as ex: result["failed"].append({"title": title, "reason": f"Loudness: {ex}"}) + want_gain = False + if want_gain: + if gain_values is None: + if measured_now or looked is not None: + result["gain"]["none"] += 1 + else: + try: + a.set_auto_gain(track_id, gain_values) + result["gain"]["set"] += 1 + wrote = True + except AdapterError as ex: + result["failed"].append({"title": title, "reason": f"Gain: {ex}"}) if wrote: result["analysed"].append(track_id) @@ -1829,6 +1880,7 @@ def _analyze_job(a, body: AnalyzeRequest): "grid": {"full": 0, "bpm": 0, "phase": 0, "locked": 0, "existing": 0, "flexible": 0}, "key": {"set": 0, "existing": 0, "none": 0}, "loudness": {"measured": 0, "existing": 0, "none": 0}, + "gain": {"set": 0, "existing": 0, "none": 0}, } handle.progress(done=0, total=len(ids)) for i, track_id in enumerate(ids): diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index c60795b..9a9bf7b 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -41,7 +41,8 @@ from .core.model import AutoHotcue, Track, TrackCues #: 1.4 — track colour: `set_track_color`, `Track.color` / `color_hex`. #: 1.5 — loudness: `/v1/loudness/get`, `PUT /v1/loudness`, and `loudness` on #: `/v1/stems/stage` (the server keeps a remote library's measurements). -API_VERSION: tuple[int, int] = (1, 5) +#: 1.6 — auto gain: `set_auto_gain`, `Track.auto_gain_db`. +API_VERSION: tuple[int, int] = (1, 6) #: How long a session survives without a heartbeat, and how often the holder #: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback @@ -81,7 +82,7 @@ _READ = ( _MUTATING = ( "create_playlist", "create_folder", "rename_playlist", "delete_playlist", "move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", - "set_track_color", "set_cue", + "set_track_color", "set_auto_gain", "set_cue", "set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_memory_cue", "rename_memory_cue", "set_memory_cue_type", "set_memory_cue_color", "delete_memory_cue", "add_grid_marker", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid", @@ -248,6 +249,9 @@ def pack_analysis(prepared) -> str | None: **({} if prepared.key is None else { "key": np.array([prepared.key.pitch_class, prepared.key.wheel, prepared.key.mode == "minor", prepared.key.confidence], dtype=np.float64)}), + **({} if getattr(prepared, "loudness", None) is None else { + "loudness": np.array([prepared.loudness.lufs, prepared.loudness.rms, prepared.loudness.true_peak, + prepared.loudness.lra, prepared.loudness.plr], dtype=np.float64)}), ) return base64.b64encode(buf.getvalue()).decode("ascii") @@ -276,4 +280,10 @@ def unpack_analysis(text: str | None): pitch, wheel, minor, confidence = z["key"] key = KeyResult(pitch_class=int(pitch), mode="minor" if minor else "major", wheel=int(wheel), confidence=float(confidence)) - return PreparedAnalysis(measured=measured, markers=markers, key=key) + loud = None + if "loudness" in z: + from .core.loudness import Loudness + + lufs, rms, tp, lra, plr = (float(v) for v in z["loudness"]) + loud = Loudness(lufs=lufs, rms=rms, true_peak=tp, lra=lra, plr=plr) + return PreparedAnalysis(measured=measured, markers=markers, key=key, loudness=loud) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 078b122..34c9e3b 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -171,15 +171,19 @@ class AnalyzeRequest(BaseModel): `replace_key` lets detection overwrite a key the track already has. Loudness is measured into Konduktor's own store (`loudness_store.py`), so it needs no capability and works for any `origin`; BPM / Grid / Key only - for the loaded library.""" + for the loaded library. `gain` writes the DJ app's own auto gain from the + track's loudness (measured first where it has none, or a stale one) — + only where the track has none, unless `replace_gain`.""" track_ids: list[str] bpm: bool = True grid: bool = True key: bool = False loudness: bool = False + gain: bool = False replace_grid: bool = False replace_key: bool = False replace_loudness: bool = False + replace_gain: bool = False origin: LoudnessOrigin = "collection" @@ -207,6 +211,11 @@ class AnalyzePreview(BaseModel): loudness_measure: int = 0 loudness_existing: int = 0 # skipped: measured, Replace not ticked with_loudness: int = 0 # tracks measured and not stale (the Replace tick's count) + # Auto gain (the DJ app's own field): a track that has one is skipped + # unless Replace is ticked. + gain_set: int = 0 + gain_existing: int = 0 # skipped: has an auto gain, Replace not ticked + with_gain: int = 0 # tracks that have one (the Replace tick's count) class LoudnessRequest(BaseModel): diff --git a/backend/test_grid_batch.py b/backend/test_grid_batch.py index f79f0c4..36b17e9 100644 --- a/backend/test_grid_batch.py +++ b/backend/test_grid_batch.py @@ -20,6 +20,9 @@ from types import SimpleNamespace import numpy as np REAL = Path(__file__).resolve().parents[1] / "collection.nml" +# Loudness (and its store) is measured by these routes too: keep it out of the +# real app-data. Set before konduktor is imported. +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-grid-batch-appdata-") failed = False @@ -338,6 +341,46 @@ with tempfile.TemporaryDirectory() as d: main.key_detect.detect_key_samples = lambda y, sr: (_ for _ in ()).throw(RuntimeError("boom")) r = c.post("/api/tracks/grid/auto", json={"track_id": bare[1]}) check("…and a failing key never fails the grid", r.status_code == 200, r.text[:200]) + + # Gain: the DJ app's auto gain from the stored loudness — measured + # first where there is none, skipped where the track has a gain unless + # Replace. Traktor's value is -9.2 - LUFS (kit G1). + from konduktor.core.loudness import Loudness + + measured: list[str] = [] + main.loudness.measure_file = lambda p: (measured.append(str(p)) + or Loudness(lufs=-12.0, rms=-10.0, true_peak=-1.0, lra=5.0, plr=11.0)) + has = [t.id for t in a.tracks if t.auto_gain_db is not None][:2] + lacks = [t.id for t in a.tracks if t.auto_gain_db is None][:2] + # A file of its own per track: the store is keyed by the FILE. + files = {} + for n, tid in enumerate(has + lacks): + files[tid] = Path(d) / f"gain-{n}.bin" + files[tid].write_bytes(b"x" * (100 + n)) + a.audio_path = lambda tid: files.get(tid, Path(__file__)) + gain_only = {"bpm": False, "grid": False, "key": False, "gain": True} + pv = c.post("/api/tracks/analyze/preview", json={"track_ids": has + lacks, **gain_only}).json() + check("preview: Gain fills the tracks without one, skips the rest", + (pv["gain_set"], pv["gain_existing"], pv["with_gain"], pv["tracks_to_analyze"]) + == (len(lacks), len(has), len(has), len(lacks)), str(pv)) + before_has = {t: a.track(t).auto_gain_db for t in has} + res = run(track_ids=has + lacks, **gain_only) + check("the run's counts match the preview", + (res["gain"]["set"], res["gain"]["existing"]) == (len(lacks), len(has)), str(res["gain"])) + check("…a missing gain is written as -9.2 - LUFS", + all(abs(a.track(t).auto_gain_db - 2.8) < 1e-6 for t in lacks), + str([a.track(t).auto_gain_db for t in lacks])) + check("…measuring each track first (it had no loudness)", len(measured) == len(lacks), str(measured)) + check("…and an existing gain is left alone", {t: a.track(t).auto_gain_db for t in has} == before_has) + measured.clear() + res = run(track_ids=has, replace_gain=True, **gain_only) + check("Replace gain overwrites them", res["gain"]["set"] == len(has) + and all(abs(a.track(t).auto_gain_db - 2.8) < 1e-6 for t in has), str(res["gain"])) + check("…measuring the tracks that had no loudness", len(measured) == len(has), str(measured)) + measured.clear() + res = run(track_ids=lacks, replace_gain=True, **gain_only) + check("a fresh measurement is reused, not decoded again", + res["gain"]["set"] == len(lacks) and measured == [], str(measured)) check("nothing reached disk", work.read_bytes() == REAL.read_bytes()) print("== BPM alone / Grid alone write through the hand-edit commands ==") diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 68f12cd..8d8f3dd 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -833,8 +833,14 @@ with tempfile.TemporaryDirectory() as d: == {("agentRegistry", "UPDATE")}, describe(changes)) check("into the tables Rekordbox writes for a new track", new_rows <= {"djmdContent", "djmdCue", "contentCue", "contentFile", - "djmdArtist", "djmdKey"}, str(sorted(new_rows))) + "djmdArtist", "djmdKey", "djmdMixerParam"}, str(sorted(new_rows))) after = dump(work) + # rekordbox's own add analyses an auto gain; without a row a track plays at + # 0.0 dB and loading never creates one (kit G2). The generated kick tracks + # are measurable, so each gets its row. + gains = {r["ContentID"] for r in after["djmdMixerParam"].values()} + check("every added track arrives with an auto gain (a djmdMixerParam row)", + all(i in gains for i in ids), str(sorted(set(ids) - gains))) rows = {i: after["djmdContent"][i] for i in ids} plain_row, prepped_row = rows[ids[0]], rows[ids[1]] check("the row is filled from the file", @@ -976,5 +982,57 @@ with tempfile.TemporaryDirectory() as d: describe(changes)) adapter.close() + print("== M: auto gain is one djmdMixerParam row (+ the counter), as rekordbox writes it ==") + # Measured (kit G2): Gain = 10^((-10 - LUFS)/20) as float32 halves; Peak = + # the clipped sample peak; a track with no row plays at 0.0 dB. + import struct as _struct + + from konduktor.core.loudness import Loudness + + def _lin(hi, lo): + return _struct.unpack(">f", _struct.pack(">I", ((hi & 0xFFFF) << 16) | (lo & 0xFFFF)))[0] + + clean_copy(REAL, work) + before = dump(work) + adapter = RekordboxAdapter(work) + bare = next((t for t in adapter.tracks if t.auto_gain_db is None), None) + if bare is None: + print(" [SKIP] every track already has a MixerParam row") + else: + measured = Loudness(lufs=-13.0, rms=-11.0, true_peak=2.5, lra=6.0, plr=15.5) + got = adapter.set_auto_gain(bare.id, measured) + check("the projection updates immediately", got is not None and abs(got.auto_gain_db - 3.0) < 1e-4, + str(got and got.auto_gain_db)) + adapter.save() + after = dump(work) + changes = diff(before, after) + check("exactly one MixerParam INSERT and the counter", + {t for t, _, _, _ in changes} == {"djmdMixerParam", "agentRegistry"} and len(changes) == 2, + describe(changes)) + new = [c for c in changes if c[0] == "djmdMixerParam"] + if new: + row = new[0][3] + check("ContentID, UUID-string ID and UUID, stamped with a USN", + row["ContentID"] == bare.id and len(row["ID"]) == 36 and len(row["UUID"]) == 36 + and row["rb_local_usn"] is not None, str(row)) + check("Gain = 10^((-10 - LUFS)/20) as float32 halves", + abs(_lin(row["GainHigh"], row["GainLow"]) - 10 ** (3.0 / 20)) < 1e-6, str(row)) + check("Peak clipped at 0 dBFS (1.0) as rekordbox's own is", + abs(_lin(row["PeakHigh"], row["PeakLow"]) - 1.0) < 1e-6, str(row)) + before = after + adapter.set_auto_gain(bare.id, measured) + check("writing the same gain again is not an edit", not adapter.dirty) + adapter.set_auto_gain(bare.id, Loudness(lufs=-8.0, rms=-6.0, true_peak=-1.0, lra=4.0, plr=7.0)) + adapter.save() + changes = diff(before, dump(work)) + check("a new value UPDATES that row only (+ the counter)", + sorted((t, k) for t, _, k, _ in changes) == [("agentRegistry", "UPDATE"), ("djmdMixerParam", "UPDATE")], + describe(changes)) + reopened = RekordboxAdapter(work) + check("the gain projects after a reopen (-2.0 dB)", + abs((reopened.track(bare.id).auto_gain_db or 0) + 2.0) < 1e-4) + reopened.close() + adapter.close() + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/backend/test_remote_adapter.py b/backend/test_remote_adapter.py index 92ffa42..7bbfda6 100644 --- a/backend/test_remote_adapter.py +++ b/backend/test_remote_adapter.py @@ -263,6 +263,25 @@ with tempfile.TemporaryDirectory() as d: check("storing without the session is refused (423)", r.status_code == 423, r.text[:200]) check("…and a measurement leaves nothing unsaved", not c.get("/api/state").json()["dirty"]) + print("== auto gain: computed here from the server's measurement, written on the server ==") + r = c.post("/api/tracks/analyze", json={"track_ids": [target], "bpm": False, "grid": False, + "gain": True, "replace_gain": True}) + job = r.json() + for _ in range(200): + j = c.get(f"/api/jobs/{job['id']}").json() + if j["state"] != "running": + break + time.sleep(0.05) + lufs = vals[target]["lufs"] + got = c.get("/api/tracks", params={"limit": 20000}).json() + row = next((t for t in got["items"] if t["id"] == target), None) + check("the gain is -9.2 - LUFS, from the stored measurement (no new download)", + j["state"] == "done" and j["result"]["gain"]["set"] == 1 and row is not None + and abs(row["auto_gain_db"] - (-9.2 - lufs)) < 1e-4 and downloads == [target], str(j)[:300]) + c.post("/api/save") + check("…and Save writes it into the server's collection", + b'PERCEIVED_DB="%.6f"' % round(-9.2 - lufs, 6) in work.read_bytes()) + print("== export, from the server's library ==") dest = root / "stick" r = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"], "destination": str(dest)}) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index d978e19..acd0814 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -1391,5 +1391,56 @@ if _KIT.exists() and b'COLOR="' in _KIT.read_bytes(): else: print(" [SKIP] no coloured Traktor 4.5 collection on this machine") +print("== S. auto gain () is localized, Traktor's shape, never a file tag ==") +# Measured in Traktor 4.5 (kit G1): the deck reads PERCEIVED_DB; Traktor's own +# value is -9.2 - LUFS; Konduktor writes PERCEIVED = ANALYZED as Traktor does. +from konduktor.core.loudness import Loudness # noqa: E402 + +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + original = work.read_bytes() + store = TraktorStore(work) + keyed = next(e for e in store._nml.collection.entry if e.loudness is not None and e.info is not None) + loc = keyed.location + tid = f"{loc.volume}{loc.dir}{loc.file}" + measured = Loudness(lufs=-11.5, rms=-9.0, true_peak=-0.75, lra=5.0, plr=10.75) + store.set_auto_gain(tid, measured) + store.save() + out = work.read_bytes() + o_s, o_e = _entry_span_by_file(original, loc.file) + c_s, c_e = _entry_span_by_file(out, loc.file) + check("only that ENTRY changes", + original[:o_s] + original[o_e:] == out[:c_s] + out[c_e:]) + check("in one line: its , in Traktor's 6-decimal form", + diff_count(original[o_s:o_e], out[c_s:c_e]) == 2 + and b'' + in out[c_s:c_e]) + store = TraktorStore(work) + check("the projection reads PERCEIVED_DB", abs(store._entry_by_key[tid].loudness.perceived_db - 2.3) < 1e-9) + store.set_auto_gain(tid, measured) + check("writing the same gain again is not an edit", store.dirty is False) + check("auto gain is collection-only: no file tag", "auto_gain" in TraktorStore._COLLECTION_ONLY_FIELDS) + + bare = next((e for e in store._nml.collection.entry if e.loudness is None and e.tempo is not None + and e.musical_key is not None), None) + if bare is None: + print(" [SKIP] no entry without LOUDNESS in this collection") + else: + bloc = bare.location + bid = f"{bloc.volume}{bloc.dir}{bloc.file}" + before = work.read_bytes() + store.set_auto_gain(bid, measured) + store.save() + after = work.read_bytes() + b_s, b_e = _entry_span_by_file(after, bloc.file) + span = after[b_s:b_e] + line = (b'' + b'\n') + check("an entry without one gains a single line, nothing else", + after[:b_s] + span.replace(line, b"", 1) + after[b_e:] == before) + check("…between TEMPO and MUSICAL_KEY, where Traktor puts it", + span.find(b"(null) + const [analyzing, setAnalyzing] = useState< + { ids: string[]; origin: TrackOrigin; preset?: 'loudness' | 'gain' } | null + >(null) const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null) const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null) // Convert to Stems: the dialog's selection, a finished run's Details, and a @@ -779,6 +781,7 @@ export default function App() { g.phase ? `${plural(g.phase, 'grid')} at its BPM` : '', r.key.set ? plural(r.key.set, 'key') : '', r.loudness?.measured ? `loudness of ${r.loudness.measured}` : '', + r.gain?.set ? `auto gain of ${r.gain.set}` : '', ].filter(Boolean) const skipped = [ g.existing ? `${g.existing} with a grid` : '', @@ -786,6 +789,7 @@ export default function App() { g.flexible ? `${g.flexible} multi-tempo` : '', r.key.existing ? `${r.key.existing} with a key` : '', r.loudness?.existing ? `${r.loudness.existing} already measured` : '', + r.gain?.existing ? `${r.gain.existing} with an auto gain` : '', ].filter(Boolean) parts = [ `${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}` + @@ -793,6 +797,7 @@ export default function App() { skipped.length ? `skipped ${skipped.join(', ')}` : '', r.key.none ? `no key found in ${r.key.none}` : '', r.loudness?.none ? `nothing to measure in ${r.loudness.none} (silent or under 3 s)` : '', + r.gain?.none ? `no auto gain for ${r.gain.none} (silent or under 3 s)` : '', ] } else { const r = job.result as unknown as CueBatchResult @@ -1000,6 +1005,7 @@ export default function App() { // Grid / Key with a reason where they cannot be stored. const canAnalyzeGrid = !!capabilities.data?.grid.editable const canAnalyzeKey = !!capabilities.data?.tracks.key_writable + const canAutoGain = !!capabilities.data?.tracks.auto_gain const analyzeOrigin = (ids: string[]): TrackOrigin => viewingDevice ? 'device' : viewingFolder && ids.some((id) => !folderFiles[id]) ? 'folder' : 'collection' /** Why BPM / Grid / Key cannot be analysed for these tracks at all, if so. */ @@ -1329,6 +1335,30 @@ export default function App() { disabled: !!batchJob, onClick: () => setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids) }), }, + // Level work in one place: the same Analyze run, opened for one + // option (its remembered ticks untouched). + { + label: 'Mastering', + submenu: [ + { + label: 'Auto gain…', + hint: batchJob ? 'busy' : undefined, + disabled: !!batchJob || analyzeRefusal(analyzeOrigin(menu.ids)) !== null || !canAutoGain, + title: + analyzeRefusal(analyzeOrigin(menu.ids)) ?? + (canAutoGain ? undefined : 'This library has no auto gain'), + onClick: () => + setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids), preset: 'gain' }), + }, + { + label: 'Measure loudness', + hint: batchJob ? 'busy' : undefined, + disabled: !!batchJob, + onClick: () => + setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids), preset: 'loudness' }), + }, + ], + }, // The deck's ✨ Auto covers a single loaded track, with its // existing cues shown; this is the same template over the selection. ...(canAutoCue @@ -1460,6 +1490,8 @@ export default function App() { origin={analyzing.origin} gridWhy={analyzeRefusal(analyzing.origin) ?? (canAnalyzeGrid ? null : "This library's beatgrids cannot be edited")} keyWhy={analyzeRefusal(analyzing.origin) ?? (canAnalyzeKey ? null : 'This library cannot store a key')} + gainWhy={analyzeRefusal(analyzing.origin) ?? (canAutoGain ? null : 'This library has no auto gain')} + preset={analyzing.preset} onRun={(opts) => runAnalysis(analyzing.ids, opts)} onClose={() => setAnalyzing(null)} onError={onError} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 6f6b78d..be6b94a 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -43,6 +43,9 @@ export interface Track { * library's own display colour for it; both null when uncoloured. */ color: TrackColor | null color_hex: string | null + /** The DJ app's own auto gain in dB (Traktor's deck gain, rekordbox's Auto + * Gain); null = the track has none. */ + auto_gain_db: number | null /** The Mastering columns' values — NOT part of the backend's `Track`: joined * in client-side from `/api/loudness` (Konduktor's own store, keyed by the * FILE), and only while a Mastering column is shown. Absent = unmeasured. */ @@ -311,6 +314,8 @@ export interface Capabilities { reference: boolean /** The track colours this library can store; empty = no track colour. */ colors: ColorSwatch[] + /** The library keeps a per-track auto gain (`Track.auto_gain_db`). */ + auto_gain: boolean } playlists: { folders: boolean @@ -617,9 +622,12 @@ export interface AnalyzeOptions { grid: boolean key: boolean loudness: boolean + /** Write the DJ app's auto gain from the loudness (measured first if needed). */ + gain: boolean replace_grid: boolean replace_key: boolean replace_loudness: boolean + replace_gain: boolean origin: TrackOrigin } @@ -643,6 +651,10 @@ export interface AnalyzePreview { loudness_existing: number /** Measured and not stale — the loudness Replace tick's count. */ with_loudness: number + gain_set: number + gain_existing: number + /** Tracks with an auto gain — the gain Replace tick's count. */ + with_gain: number } /** What an Analyze run did. */ @@ -652,6 +664,7 @@ export interface AnalyzeResult { grid: { full: number; bpm: number; phase: number; locked: number; existing: number; flexible: number } key: { set: number; existing: number; none: number } loudness: { measured: number; existing: number; none: number } + gain: { set: number; existing: number; none: number } } /** What a batch Auto Hotcues run did. `tracks` got the template (whatever it diff --git a/frontend/src/components/AnalyzeDialog.tsx b/frontend/src/components/AnalyzeDialog.tsx index 182fa88..854cea4 100644 --- a/frontend/src/components/AnalyzeDialog.tsx +++ b/frontend/src/components/AnalyzeDialog.tsx @@ -13,22 +13,28 @@ interface Props { gridWhy: string | null /** Why a key cannot be stored here; null = it can. */ keyWhy: string | null + /** Why the DJ app's auto gain cannot be written here; null = it can. */ + gainWhy: string | null + /** Opened for ONE option (the context menu's Mastering ▸ Auto gain… / + * Measure loudness): only it is ticked, and the remembered ticks are left + * as they were. */ + preset?: keyof What onRun: (opts: AnalyzeOptions) => Promise onClose: () => void onError: (msg: string) => void } -type What = Pick +type What = Pick const PREF_KEY = 'analyzeWhat' -// Loudness off unless asked for once: it adds a decode per track. -const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true, loudness: false } +// Loudness and gain off unless asked for once: they add a decode per track. +const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true, loudness: false, gain: false } /** The remembered ticks; anything malformed falls back to the default. */ function loadWhat(prefs: Record | undefined): What { const saved = prefs?.[PREF_KEY] as Partial | undefined if (!saved || typeof saved !== 'object') return DEFAULT_WHAT const pick = (k: keyof What) => (typeof saved[k] === 'boolean' ? (saved[k] as boolean) : DEFAULT_WHAT[k]) - return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key'), loudness: pick('loudness') } + return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key'), loudness: pick('loudness'), gain: pick('gain') } } const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}` @@ -40,48 +46,58 @@ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? o * halves of a beatgrid — BPM alone keeps the downbeat, Grid alone keeps the * tempo — and the grid Replace tick only guards a FULL re-analysis (both * ticked). Loudness goes to Konduktor's own store, so it is never disabled - * (decided 2026-10-19). The ticks are remembered; the Replace ticks never - * are — overwriting is a decision about THESE tracks. + * (decided 2026-10-19). Gain writes the DJ app's own auto gain from the + * loudness, only where a track has none unless Replace. The ticks are + * remembered; the Replace ticks never are — overwriting is a decision about + * THESE tracks. */ -export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, onError }: Props) { +export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, onRun, onClose, onError }: Props) { const qc = useQueryClient() const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const [what, setWhat] = useState(null) const [replaceGrid, setReplaceGrid] = useState(false) const [replaceKey, setReplaceKey] = useState(false) const [replaceLoudness, setReplaceLoudness] = useState(false) + const [replaceGain, setReplaceGain] = useState(false) const [busy, setBusy] = useState(false) const gridEditable = gridWhy === null const keyWritable = keyWhy === null + const gainWritable = gainWhy === null // Hydrate once from prefs, masked by what can be stored here. Where loudness // is ALL that can be done (a device, loose files), it is ticked. useEffect(() => { if (what || prefs.isPending) return + if (preset) { + setWhat({ bpm: false, grid: false, key: false, loudness: false, gain: false, [preset]: true }) + return + } const w = loadWhat(prefs.data as Record | undefined) setWhat({ bpm: w.bpm && gridEditable, grid: w.grid && gridEditable, key: w.key && keyWritable, - loudness: w.loudness || (!gridEditable && !keyWritable), + gain: w.gain && gainWritable, + loudness: w.loudness || (!gridEditable && !keyWritable && !gainWritable), }) - }, [what, prefs.isPending, prefs.data, gridEditable, keyWritable]) + }, [what, preset, prefs.isPending, prefs.data, gridEditable, keyWritable, gainWritable]) const opts: AnalyzeOptions | null = what && { ...what, replace_grid: what.bpm && what.grid && replaceGrid, replace_key: what.key && replaceKey, replace_loudness: what.loudness && replaceLoudness, + replace_gain: what.gain && replaceGain, origin, } const preview = useQuery({ queryKey: ['analyze-preview', ids, opts], queryFn: () => api.analyzePreview(ids, opts!), - enabled: !!opts && (opts.bpm || opts.grid || opts.key || opts.loudness), + enabled: !!opts && (opts.bpm || opts.grid || opts.key || opts.loudness || opts.gain), placeholderData: keepPreviousData, }) const p: AnalyzePreview | undefined = preview.data - const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness) + const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness || what.gain) const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0) useEffect(() => { @@ -94,19 +110,22 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, on if (!opts || busy || count === 0) return setBusy(true) // A tick that was disabled here keeps what it was: analysing a device's - // loudness must not forget that the collection's keys are wanted. + // loudness must not forget that the collection's keys are wanted. A + // one-option run (a preset) remembers nothing. const saved = loadWhat(prefs.data as Record | undefined) - api - .patchPrefs({ - [PREF_KEY]: { - bpm: gridEditable ? opts.bpm : saved.bpm, - grid: gridEditable ? opts.grid : saved.grid, - key: keyWritable ? opts.key : saved.key, - loudness: opts.loudness, - }, - }) - .then((x) => qc.setQueryData(['prefs'], x)) - .catch(() => {}) + if (!preset) + api + .patchPrefs({ + [PREF_KEY]: { + bpm: gridEditable ? opts.bpm : saved.bpm, + grid: gridEditable ? opts.grid : saved.grid, + key: keyWritable ? opts.key : saved.key, + gain: gainWritable ? opts.gain : saved.gain, + loudness: opts.loudness, + }, + }) + .then((x) => qc.setQueryData(['prefs'], x)) + .catch(() => {}) try { await onRun(opts) } catch (e) { @@ -184,6 +203,8 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, on {toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, gridWhy ?? '')} {toggle('key', 'Key', 'Detect the musical key', keyWritable, keyWhy ?? '')} {toggle('loudness', 'Loudness', 'Measure LUFS, RMS, true peak and dynamics', true, '')} + {toggle('gain', 'Auto gain', "Set the DJ app's own gain from the loudness (measured first if needed)", + gainWritable, gainWhy ?? '')}
@@ -211,6 +232,19 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, on
)} + {p && what?.gain && p.with_gain > 0 && ( +
+ + {p.with_gain}{' '} + {p.with_gain === 1 ? 'already has an auto gain' : 'already have an auto gain'} + + +
+ )} {nothingTicked &&
Tick what to analyze.
} diff --git a/frontend/src/lib/trackColumns.tsx b/frontend/src/lib/trackColumns.tsx index 443d83f..90783c8 100644 --- a/frontend/src/lib/trackColumns.tsx +++ b/frontend/src/lib/trackColumns.tsx @@ -367,6 +367,24 @@ export const TRACK_COLUMNS: ColumnDef[] = [ loudnessColumn('true_peak', 'True Peak', 'dBTP', true), loudnessColumn('lra', 'LRA', 'LU'), loudnessColumn('plr', 'PLR', 'dB'), + // The DJ app's own auto gain (Traktor's deck gain, rekordbox's Auto Gain), + // from the backend's Track — not Konduktor's loudness store — so showing it + // fetches nothing. None sorts last, like an unmeasured loudness. + col.accessor((t) => t.auto_gain_db ?? undefined, { + id: 'auto_gain', + header: 'Auto Gain', + size: 104, + sortUndefined: 'last', + cell: (c) => { + const v = c.getValue() as number | undefined + if (v == null) return — + return ( + + {formatLoudness(v, 'dB', true)} + + ) + }, + }), ] function loudnessColumn(field: 'lufs' | 'rms' | 'true_peak' | 'lra' | 'plr', header: string, unit: string, @@ -392,14 +410,17 @@ function loudnessColumn(field: 'lufs' | 'rms' | 'true_peak' | 'lra' | 'plr', hea }) } -/** The Mastering columns, in order: the column chooser's "Mastering ▸". */ +/** The loudness columns: shown, they fetch `/api/loudness` (see App). */ export const MASTERING_COLUMNS: readonly string[] = ['lufs', 'rms', 'true_peak', 'lra', 'plr'] +/** The column chooser's "Mastering ▸", in order: loudness, then auto gain. */ +const MASTERING_MENU: readonly string[] = [...MASTERING_COLUMNS, 'auto_gain'] const MASTERING_LABELS: Record = { lufs: 'LUFS (integrated loudness)', rms: 'RMS (loudest sections)', true_peak: 'True Peak', lra: 'LRA (loudness range)', plr: 'PLR (peak to loudness)', + auto_gain: "Auto Gain (the DJ app's)", } // Traktor dates arrive as "YYYY/M/D" strings; show them compactly (or raw). @@ -414,7 +435,7 @@ function formatDate(v: string | null): string { * `group` puts a column in a submenu (the Mastering columns). */ export const COLUMN_MENU: { id: string; label: string; group?: 'mastering' }[] = TRACK_COLUMNS.map((c) => { const id = c.id as string - const mastering = MASTERING_COLUMNS.includes(id) + const mastering = MASTERING_MENU.includes(id) return { id, label: MASTERING_LABELS[id] ?? (typeof c.header === 'string' ? c.header : id),