Implemented normalization and auto gain export options

This commit is contained in:
patben8 committed 2026-10-19 21:20:57 +02:00
1 parent 64b0396d66
commit 4cb630d0d5
13 files changed
+677 -35

No files matched your search

@@ -111,6 +111,9 @@ class RekordboxExporter:
drive_root = False
#: `djmdContent.Analysed` bit 0x80 — from `TrackCues.grid_locked`.
locks_grids = True
#: `djmdMixerParam` from `ExportTrack.loudness` (without a row a track
#: plays at 0.0 dB in rekordbox; kit G2).
writes_auto_gain = True
def capabilities(self):
"""What a Rekordbox library can hold, with no library to read.
@@ -209,7 +212,12 @@ class RekordboxExporter:
try:
for item in payload.tracks:
track_id = ids.get(item.source_id)
if track_id is None or not item.cues:
if track_id is None:
continue
if item.loudness is not None:
# The same row an Analyze writes (`RekordboxStore.set_auto_gain`).
store.set_auto_gain(track_id, item.loudness)
if not item.cues:
continue
memory = 0
for cue in sorted(item.cues.cues, key=lambda c: c.start):
@@ -68,6 +68,10 @@ class TraktorExporter:
drive_root = False
#: `LOCK` — honoured from `TrackCues.grid_locked` by `add_tracks`.
locks_grids = True
#: `<LOUDNESS>` from `ExportTrack.loudness` (kit G1: an entry with no
#: AUDIO_ID keeps the PERCEIVED_DB the deck reads through Traktor's first
#: analysis, which overwrites only ANALYZED_DB).
writes_auto_gain = True
def capabilities(self):
"""What a Traktor library can hold — answered with no library to read.
@@ -101,6 +105,10 @@ class TraktorExporter:
# Source id -> the id it got here. Both are Traktor primary keys derived
# from a LOCATION, and the location changed, so they are never equal.
moved = {t.source_id: new_id for t, new_id in zip(payload.tracks, new_ids)}
# The auto gain, through the same command an Analyze uses.
for t, new_id in zip(payload.tracks, new_ids):
if t.loudness is not None:
adapter.set_auto_gain(new_id, t.loudness)
self._write_playlists(adapter, payload, moved)
adapter.save()
+8
View File
@@ -32,6 +32,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Callable, Protocol, runtime_checkable
from .capabilities import Capabilities
from .loudness import Loudness
from .model import Track, TrackCues
if TYPE_CHECKING:
@@ -58,6 +59,13 @@ class ExportTrack:
#: not decode an unchanged track again. Either may be None.
fingerprint: str | None = None
analysis_cache: "AnalysisCache | None" = field(default=None, repr=False)
#: The COPY's loudness (the source's, moved by `gain_db` when the run
#: normalised it), set only when the run writes the DJ app's auto gain —
#: a writer whose platform keeps one (`writes_auto_gain`) writes it from
#: this; None = write none.
loudness: Loudness | None = None
#: The level change the copy got (0.0: copied as it is).
gain_db: float = 0.0
def waveform(self, *, lead: float = 0.0):
"""`waveform.analyse()` of the copied audio — the call every exporter that
+3
View File
@@ -241,6 +241,9 @@ class PlatformOption(BaseModel):
#: As an export TARGET: its library can store a grid lock, so the export's
#: "Lock beatgrids" option means something there.
locks_grids: bool = False
#: As an export TARGET: its library keeps the DJ app's auto gain, so the
#: export's "Auto gain" option means something there (no stick format does).
writes_auto_gain: bool = False
class RemapSample(BaseModel):
+142 -15
View File
@@ -81,6 +81,7 @@ from . import exports
from .core import registry
from .core.analysis_cache import CACHE_DIR, AnalysisCache, fingerprint
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
from .core.level_plan import Measure, plan_gain, shifted
from .core.pathmap import common_dir_prefix
from .core.places import is_drive_root, is_os_housekeeping
from .importer import SPACE_HEADROOM, copy_file, free_bytes
@@ -116,6 +117,26 @@ class PlannedTrack:
#: kept instead of copied again — possibly a different path from
#: `destination`, in which case it is moved. None means copy.
reuse: Path | None = None
#: The source's stored loudness when fresh (None: not measured, or stale —
#: the run measures it when it needs one).
loudness: object | None = None
#: The level the copy is written at (`level_plan.plan_gain`; 0.0 = copied
#: as it is) and why (None: the run does not normalise).
gain_db: float = 0.0
level_outcome: str | None = None
#: The run needs this source's loudness (it normalises, or writes auto gain).
needs_loudness: bool = False
@dataclass(frozen=True)
class Level:
"""The run's "Normalise audio": every copy brought to `target` in `measure`,
a raise stopping at the true-peak `ceiling` — Normalize's rules exactly
(`level_plan`), applied to the copy and never to the source."""
measure: Measure = "lufs"
target: float = -9.0
ceiling: float = -1.0
@dataclass
@@ -147,7 +168,17 @@ class ExportPlan:
return sum(1 for t in self.exportable if t.reuse is not None)
def as_dict(self, free: int | None = None) -> dict:
exportable = self.exportable
levels: dict[str, int] = {}
for t in exportable:
if t.level_outcome:
levels[t.level_outcome] = levels.get(t.level_outcome, 0) + 1
return {
# Normalise audio: copies whose level changes, tracks the run
# measures first, and every outcome (`level_plan`) by count.
"normalised": sum(1 for t in exportable if t.gain_db),
"to_measure": sum(1 for t in exportable if t.needs_loudness and t.loudness is None),
"level_counts": levels,
"tracks": len(self.tracks),
"exportable": len(self.exportable),
"unchanged": self.unchanged,
@@ -287,6 +318,9 @@ def _record(planned: PlannedTrack, copy: Path) -> dict:
"mtime_ns": planned.mtime_ns,
"copy_size": st.st_size,
"copy_mtime_ns": st.st_mtime_ns,
# The level the copy was written at: a copy kept by a later export must
# be at the level THAT export wants (missing = 0, every older manifest).
"gain_db": planned.gain_db,
}
@@ -314,6 +348,11 @@ def _reusable(planned: PlannedTrack, previous: dict[str, tuple[Path, dict]]) ->
copy, record = found
if (record.get("size"), record.get("mtime_ns")) != (planned.size, planned.mtime_ns):
return None
try:
if abs(float(record.get("gain_db") or 0.0) - planned.gain_db) > 0.01:
return None # written at another level (Normalise audio changed)
except (TypeError, ValueError):
return None
try:
st = copy.stat()
except OSError:
@@ -328,8 +367,15 @@ def _reusable(planned: PlannedTrack, previous: dict[str, tuple[Path, dict]]) ->
# ---- planning ----------------------------------------------------------------
def plan(adapter, export_set) -> ExportPlan:
"""Resolve the set and work out where every file lands. Reads only."""
def plan(adapter, export_set, *, store=None, level: Level | None = None,
auto_gain: bool = False) -> ExportPlan:
"""Resolve the set and work out where every file lands. Reads only.
With `level` (Normalise audio) each copy's gain comes from the source's
STORED loudness in `store`; with `auto_gain` that loudness is also what the
DJ app's gain is written from. A source with none (or a stale one) is
measured by the run — and its copy decided then, since whether the
previous one can be kept depends on its level."""
destination = Path(export_set.destination).expanduser()
built = ExportPlan(destination=destination)
@@ -357,7 +403,8 @@ def plan(adapter, export_set) -> ExportPlan:
root = common_dir_prefix(present) if present else ""
previous = _previous_copies(destination)
claimed: set[Path] = set()
wants_loudness = store is not None and (level is not None or auto_gain)
entries = store.get([f.key for f in facts.values() if f is not None]) if wants_loudness else {}
for track in tracks:
source = sources.get(track.id)
fact = facts.get(track.id)
@@ -371,15 +418,15 @@ def plan(adapter, export_set) -> ExportPlan:
size=size,
mtime_ns=mtime_ns,
missing=not exists,
needs_loudness=exists and wants_loudness,
)
if exists:
reuse = _reusable(planned, previous)
# One kept copy can serve one planned file: two entries sharing a
# source would otherwise both try to move it.
if reuse is not None and reuse not in claimed:
planned.reuse = reuse
claimed.add(reuse)
if planned.needs_loudness:
entry = entries.get(fact.key)
planned.loudness = entry.values if entry is not None and not entry.stale(fact) else None
if exists and level is not None:
set_level(planned, level)
built.tracks.append(planned)
assign_reuse(built, previous)
names = {p.id: p for p in resolved.playlists}
folders = _folder_paths(adapter)
@@ -404,6 +451,31 @@ def plan(adapter, export_set) -> ExportPlan:
return built
def set_level(planned: PlannedTrack, level: Level) -> None:
"""The copy's gain from the source's loudness (`level_plan.plan_gain`)."""
suffix = planned.source_path.suffix if planned.source_path else ""
step = plan_gain(planned.loudness, suffix, measure=level.measure, target=level.target,
ceiling=level.ceiling)
planned.gain_db, planned.level_outcome = step.gain_db, step.outcome
def assign_reuse(built: ExportPlan, previous: dict[str, tuple[Path, dict]]) -> None:
"""Which planned files keep the previous export's copy. A file whose level
is still undecided (normalising, not yet measured) is copied unless the run
decides otherwise once it has measured it."""
claimed: set[Path] = set()
for planned in built.tracks:
planned.reuse = None
if planned.missing or planned.level_outcome == "unmeasured":
continue
reuse = _reusable(planned, previous)
# One kept copy can serve one planned file: two entries sharing a
# source would otherwise both try to move it.
if reuse is not None and reuse not in claimed:
planned.reuse = reuse
claimed.add(reuse)
def _relative(source: Path, root: str) -> Path:
"""Where `source` sits under the export root, mirroring its own folders."""
text = str(source).replace("\\", "/")
@@ -450,13 +522,18 @@ def _locked(cues, lock_grids: bool):
def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
root_folder: bool = False, lock_grids: bool = False) -> dict:
root_folder: bool = False, lock_grids: bool = False, store=None,
level: Level | None = None, auto_gain: bool = False) -> dict:
"""Copy what changed, then write every target's library over the audio.
`root_folder` nests the playlists in a folder named after the export (the
"Put exported playlists in a folder" setting); otherwise they sit at the top.
`lock_grids` locks every exported track that HAS a grid (`_locked`); off,
each track keeps the source's own lock.
each track keeps the source's own lock. `level` (Normalise audio) writes
each copy at its planned gain (`core.level_edit`, decode-verified); the
source is never touched. `auto_gain` hands every writer the COPY's loudness
for the DJ app's gain. Sources with no stored loudness are measured first,
into `store` — the same measurement the Mastering columns show.
Rolls back EVERYTHING this run wrote on cancel or on any failure —
including the libraries of targets that had already been written when a
@@ -491,6 +568,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
done = 0
try:
destination.mkdir(parents=True, exist_ok=True)
_measure_missing(adapter, built, handle, store=store, level=level)
if is_ours(destination):
handle.progress(message="Replacing the previous export…")
old = _read_manifest(destination).get("audio") or {}
@@ -507,7 +585,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
for planned in items:
planned.reuse = None
reused = [t for t in items if t.reuse is not None]
handle.progress(total=built.total_bytes)
handle.progress(done=0, total=built.total_bytes, unit="bytes")
# Written before anything moves or is copied, listing every path this
# run may leave behind, so even a crash (not a cancel — nothing gets to
# clean up after a crash) leaves a folder the next export can clear.
@@ -542,7 +620,18 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
# The file to READ: on this machine that is the source itself;
# on a library held by a server, a downloaded copy of it.
local = adapter.audio_path(planned.track_id) or planned.source_path
copy_file(local, partial, handle, advance)
if planned.gain_db:
from .core import level_edit
handle.progress(message=f"Normalising {planned.title} ({planned.gain_db:+.1f} dB)")
level_edit.apply(local, partial, planned.gain_db)
handle.raise_if_cancelled()
# A copy carried to a gig must be the source at the gain,
# nothing else: decode both and compare.
level_edit.verify(local, partial, planned.gain_db)
advance(planned.size)
else:
copy_file(local, partial, handle, advance)
os.replace(partial, target)
payload_tracks.append(
ExportTrack(
@@ -552,6 +641,9 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
art=_cover(adapter, planned.track_id),
fingerprint=_fingerprint(planned),
analysis_cache=cache,
loudness=(shifted(planned.loudness, planned.gain_db)
if auto_gain and planned.loudness is not None else None),
gain_db=planned.gain_db,
)
)
@@ -605,6 +697,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
return {
"tracks": len(payload_tracks),
"unchanged": len(reused),
"normalised": sum(1 for t in items if t.gain_db),
"playlists": len(built.playlists),
"skipped": len(built.tracks) - len(items),
"destination": str(destination),
@@ -685,7 +778,41 @@ def _rel(path: Path, destination: Path) -> str:
def _fingerprint(planned: PlannedTrack) -> str:
return fingerprint(planned.source_path, planned.size, planned.mtime_ns)
# The waveform cache is keyed by the SOURCE; a copy written at another
# level draws differently, so its gain is part of the key — else a
# normalised stick would be drawn from the un-levelled measurement.
source = planned.source_path if not planned.gain_db else f"{planned.source_path}#gain={planned.gain_db:.4f}"
return fingerprint(source, planned.size, planned.mtime_ns)
def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, level: Level | None) -> None:
"""Measure the sources the run needs a loudness for and has none, store
each, then settle their copies' levels and which previous copies can be
kept. Before anything at the destination changes, so a cancel here
leaves the previous export as it was."""
todo = [t for t in built.exportable if t.needs_loudness and t.loudness is None]
if not todo or store is None:
return
from .core import loudness
for n, planned in enumerate(todo, start=1):
handle.raise_if_cancelled()
handle.progress(done=n - 1, total=len(todo), unit="tracks",
message=f"Measuring {planned.title} ({n}/{len(todo)})")
local = adapter.audio_path(planned.track_id) or planned.source_path
try:
values = loudness.measure_file(local)
except Exception as ex: # noqa: BLE001 — copied as it is, with no gain
log.warning("could not measure %s: %s", planned.title, ex)
values = None
planned.loudness = values
if values is not None:
fact = adapter.audio_facts([planned.track_id]).get(planned.track_id)
if fact is not None:
store.put(fact, values)
if level is not None:
set_level(planned, level)
assign_reuse(built, _previous_copies(Path(built.destination)))
def _cover(adapter, track_id: str):
+32 -2
View File
@@ -66,6 +66,16 @@ class ExportSet:
#: first load (it re-measures the BPM — 174 can come back as 87 — and the
#: grid drifts). Remembered per set: it is a decision about this stick.
lock_grids: bool = True
#: The run's "Normalise audio": the copies (never the sources) brought to
#: one level. Off by default — it changes the audio on the stick.
normalise: bool = False
#: The run's "Auto gain": the DJ app's gain written from each copy's
#: loudness, where the target keeps one. On by default, like the lock:
#: without it rekordbox plays an exported track at 0.0 dB.
auto_gain: bool = True
#: Normalise's measure / target / ceiling for this set ({"measure",
#: "target", "ceiling"}); None = the app settings at run time.
level: dict | None = None
created: float = 0.0
modified: float = 0.0
@@ -158,6 +168,20 @@ def _write_doc(library_id: str, doc: dict) -> None:
paths.write_json(_store_path(library_id), doc)
def _level(raw) -> dict | None:
"""A stored level, checked: anything malformed reads as None (the app
settings), never as a half-filled one."""
if not isinstance(raw, dict):
return None
try:
measure = raw.get("measure", "lufs")
if measure not in ("lufs", "rms"):
return None
return {"measure": measure, "target": float(raw["target"]), "ceiling": float(raw["ceiling"])}
except (KeyError, TypeError, ValueError):
return None
def _load(library_id: str) -> dict[str, ExportSet]:
data = _read_doc(library_id)
raw = data.get("sets") if isinstance(data, dict) else None
@@ -175,6 +199,9 @@ def _load(library_id: str) -> dict[str, ExportSet]:
playlist_ids=list(values.get("playlist_ids") or []),
track_ids=list(values.get("track_ids") or []),
lock_grids=bool(values.get("lock_grids", True)),
normalise=bool(values.get("normalise", False)),
auto_gain=bool(values.get("auto_gain", True)),
level=_level(values.get("level")),
created=float(values.get("created") or 0.0),
modified=float(values.get("modified") or 0.0),
)
@@ -267,8 +294,11 @@ def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
setattr(found, key, fields[key])
if fields.get("targets"):
found.targets = list(dict.fromkeys(fields["targets"]))
if fields.get("lock_grids") is not None:
found.lock_grids = bool(fields["lock_grids"])
for key in ("lock_grids", "normalise", "auto_gain"):
if fields.get(key) is not None:
setattr(found, key, bool(fields[key]))
if fields.get("level") is not None:
found.level = _level(fields["level"])
found.modified = time.time()
_save(library_id, sets)
return found
+43 -7
View File
@@ -669,6 +669,9 @@ def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut:
targets=body.targets,
destination=body.destination,
lock_grids=body.lock_grids,
normalise=body.normalise,
auto_gain=body.auto_gain,
level=body.level.model_dump() if body.level is not None else None,
)
return ExportSetOut(**updated.as_dict())
@@ -769,11 +772,36 @@ def export_playlist_tracks(set_id: str, playlist_id: str) -> list[Track]:
return tracks
def _export_options(found, body: RunExport | None) -> dict:
"""The run's options: the body's where given, else the set's own; a level
the set does not keep comes from the app settings (Normalize's defaults)."""
normalise = body.normalise if body is not None and body.normalise is not None else found.normalise
auto_gain = body.auto_gain if body is not None and body.auto_gain is not None else found.auto_gain
if body is not None and body.level is not None:
raw = body.level.model_dump()
elif found.level is not None:
raw = found.level
else:
p = prefs.load_prefs()
raw = {"measure": p.get("levelMeasure", "lufs"), "target": p.get("levelTarget", -9.0),
"ceiling": p.get("levelCeiling", -1.0)}
try:
level = exporter.Level(measure=raw["measure"] if raw["measure"] in ("lufs", "rms") else "lufs",
target=float(raw["target"]), ceiling=float(raw["ceiling"]))
except (KeyError, TypeError, ValueError):
level = exporter.Level()
# Only where some target keeps an auto gain — a stick has none to write.
writes_gain = any(getattr(core_export.for_platform(t), "writes_auto_gain", False) for t in found.targets)
return {"store": STATE.loudness, "level": level if normalise else None,
"auto_gain": bool(auto_gain and writes_gain)}
@app.post("/api/exports/{set_id}/preview", response_model=ExportPreview)
def preview_export(set_id: str) -> ExportPreview:
"""What this export would do, right now. Never cached — the set is live."""
def preview_export(set_id: str, body: RunExport | None = None) -> ExportPreview:
"""What this export would do, right now, with the run dialog's options as
ticked. Never cached — the set is live."""
found = _require_set(set_id)
built = exporter.plan(require_adapter(), found)
built = exporter.plan(require_adapter(), found, **_export_options(found, body))
return ExportPreview(**built.as_dict(exporter.space_for(built)))
@@ -789,16 +817,22 @@ def run_export(set_id: str, body: RunExport | None = None) -> JobStatus:
so the next export of the same stick starts from the same answer.
"""
found = _require_set(set_id)
if body is not None and body.lock_grids is not None and body.lock_grids != found.lock_grids:
found = exports.update(_require_library_id(), set_id, lock_grids=body.lock_grids)
if body is not None:
changes = {k: v for k, v in (("lock_grids", body.lock_grids), ("normalise", body.normalise),
("auto_gain", body.auto_gain)) if v is not None}
if body.level is not None:
changes["level"] = body.level.model_dump()
if changes:
found = exports.update(_require_library_id(), set_id, **changes)
adapter = require_adapter()
built = exporter.plan(adapter, found)
options = _export_options(found, None)
built = exporter.plan(adapter, found, **options)
if built.blocked:
raise HTTPException(409, built.blocked)
# A Konduktor setting, read when the export starts.
root_folder = bool(prefs.load_prefs().get("exportRootFolder", False))
job = JOBS.submit("export", lambda handle: exporter.run(
adapter, found, built, handle, root_folder=root_folder, lock_grids=found.lock_grids))
adapter, found, built, handle, root_folder=root_folder, lock_grids=found.lock_grids, **options))
return JobStatus(**job.as_dict())
@@ -849,6 +883,7 @@ def export_targets() -> list[PlatformOption]:
drive_root=bool(getattr(exporter, "drive_root", False)),
computer_only=bool(getattr(exporter, "computer_only", False)),
locks_grids=bool(getattr(exporter, "locks_grids", False)),
writes_auto_gain=bool(getattr(exporter, "writes_auto_gain", False)),
))
# Targets with no reader of their own (the stick's legacy Device Library):
# listed too, or registering one would not make it selectable.
@@ -868,6 +903,7 @@ def export_targets() -> list[PlatformOption]:
drive_root=bool(getattr(exporter, "drive_root", False)),
computer_only=bool(getattr(exporter, "computer_only", False)),
locks_grids=bool(getattr(exporter, "locks_grids", False)),
writes_auto_gain=bool(getattr(exporter, "writes_auto_gain", False)),
))
# Each exporter states its own place; a platform with no exporter (not yet a
# target, shown disabled) goes last. Stable, so equal places keep their order.
+27 -2
View File
@@ -407,6 +407,9 @@ class ExportSetOut(BaseModel):
playlist_ids: list[str] = []
track_ids: list[str] = [] # loose tracks only
lock_grids: bool = True
normalise: bool = False
auto_gain: bool = True
level: dict | None = None
created: float = 0.0
modified: float = 0.0
@@ -417,17 +420,31 @@ class CreateExportSet(BaseModel):
destination: str
class ExportLevel(BaseModel):
"""Normalise audio's measure / target / ceiling (see `exporter.Level`)."""
measure: Literal["lufs", "rms"] = "lufs"
target: float = Field(-9.0, ge=-30.0, le=0.0)
ceiling: float = Field(-1.0, ge=-12.0, le=0.0)
class UpdateExportSet(BaseModel):
name: str | None = None
targets: list[str] | None = None
destination: str | None = None
lock_grids: bool | None = None
normalise: bool | None = None
auto_gain: bool | None = None
level: ExportLevel | None = None
class RunExport(BaseModel):
#: The run dialog's "Lock beatgrids" — remembered on the set. None keeps the
#: set's own answer.
#: The run dialog's options — each remembered on the set. None keeps the
#: set's own answer. The preview takes the same body, so its counts are
#: for the options as ticked.
lock_grids: bool | None = None
normalise: bool | None = None
auto_gain: bool | None = None
level: ExportLevel | None = None
class ExportSetMembers(BaseModel):
@@ -461,6 +478,8 @@ class ExportPreview(BaseModel):
tracks: int = 0
exportable: int = 0
#: Copies from the last export kept rather than copied again.
unchanged: int = 0
missing: list[str] = []
playlists: list[str] = []
total_bytes: int = 0
@@ -475,6 +494,12 @@ class ExportPreview(BaseModel):
#: Targets whose library is only found at a drive's root, when the
#: destination is not one. A warning — the export can still run.
not_drive_root: list[str] = []
#: Normalise audio: copies whose level changes, and every `level_plan`
#: outcome by count. `to_measure`: sources the run measures first (no
#: stored loudness), for Normalise or Auto gain.
normalised: int = 0
to_measure: int = 0
level_counts: dict[str, int] = {}
class FsPlace(BaseModel):