Implemented auto gain analysis

This commit is contained in:
patben8 committed 2026-10-19 18:20:13 +02:00
1 parent 6eecb2288a
commit 284a7514fe
30 files changed
+673 -71

No files matched your search

@@ -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")
@@ -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
@@ -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,
),
@@ -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)
@@ -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
@@ -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,
)
+44 -1
View File
@@ -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
+5 -1
View File
@@ -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,
@@ -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)
@@ -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"],
@@ -0,0 +1,32 @@
"""Traktor's auto gain: `<LOUDNESS PEAK_DB PERCEIVED_DB ANALYZED_DB>` 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
@@ -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,
)
+22 -2
View File
@@ -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:
"""`<LOUDNESS>` 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.
+11
View File
@@ -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
+12 -2
View File
@@ -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: ...
+13 -3
View File
@@ -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):
+3
View File
@@ -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):
+4
View File
@@ -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):
+69 -17
View File
@@ -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):
+13 -3
View File
@@ -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)
+10 -1
View File
@@ -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):