diff --git a/CLAUDE.md b/CLAUDE.md index ecfe247..679e02b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -848,6 +848,29 @@ Two independent apps that talk over HTTP: `NormalizeDialog` (measure / target / ceiling from the app settings `levelMeasure`/`levelTarget`/`levelCeiling`, overridable per run; the per-track plan; the lossless-is-permanent warning), SaveBar's notice. + - **Export: Normalise audio + Auto gain** (the run dialog's two ticks, + remembered on the set: `ExportSet.normalise` (default off), + `auto_gain` (default on — rekordbox plays a track without a gain row at + 0.0 dB), `level` ({measure, target, ceiling}; None = Normalize's app + settings, `main._export_options`)). The preview takes the same body as the + run, so its counts are for the ticks as they stand. `exporter.plan` takes + `store` / `level` / `auto_gain`: each source's FRESH stored loudness + (`PlannedTrack.loudness`), its copy's gain from the shared `plan_gain` + (`set_level`); a source with none is `to_measure` and the run measures it + first, into the store (`_measure_missing`, before the destination is + touched), then settles its level and reuse (`assign_reuse`). The copy step + writes a levelled copy through `level_edit.apply` + `verify` instead of + `copy_file` — the source is never touched. **The manifest records each + copy's `gain_db`** (missing = 0) and `_reusable` requires it equal, so a + re-export at the same level copies nothing and another level re-copies + only the copies whose gain changes. **`_fingerprint` includes a non-zero + gain**: the waveform cache is keyed by the SOURCE, and a levelled copy + draws differently. `ExportTrack.loudness` = the COPY's level (`shifted`), + set only with Auto gain; writers with `writes_auto_gain` + (`PlatformOption.writes_auto_gain`) write it — Traktor replays + `set_auto_gain` after `add_tracks` (kit G1: an AUDIO_ID-less entry keeps + PERCEIVED_DB through Traktor's first analysis), the Rekordbox Library + through its replay store's `set_auto_gain`. No stick target has 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 @@ -1639,6 +1662,17 @@ serialization path.** It enforces: drawn waveforms: OneLibrary (fixture) and rekordbox (temp copy) get the waveform tags rewritten at Save with every other ANLZ tag byte-identical, and the file size follows. +- `test_export_level.py` — an export to Traktor + Rekordbox Library + + OneLibrary at once from generated MP3/FLAC/WAV (one WAV a quiet track with + a hot peak), through the routes: Auto gain offered only where a target + keeps one; every source measured once into the store; sources + byte-identical; each levelled copy == its source at the manifest's gain, + the hot-peak one a byte-identical copy; Traktor's gain = -9.2 and the + Rekordbox Library's = -10 minus the COPY's LUFS; the set remembers its + options; a same-level re-export keeps every file (same inodes); a new + target re-writes only the copy whose gain changed; Normalise off restores + the source bytes with the gain from the source's LUFS; Auto gain off writes + none; a levelled copy has its own waveform-cache key. - `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse` on SYNTHETIC audio with known sections (the intro with a kick is not a drop; no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index 1e9e5c7..41b5641 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -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): diff --git a/backend/konduktor/adapters/traktor/export.py b/backend/konduktor/adapters/traktor/export.py index dca95e2..db8dc6f 100644 --- a/backend/konduktor/adapters/traktor/export.py +++ b/backend/konduktor/adapters/traktor/export.py @@ -68,6 +68,10 @@ class TraktorExporter: drive_root = False #: `LOCK` — honoured from `TrackCues.grid_locked` by `add_tracks`. locks_grids = True + #: `` 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() diff --git a/backend/konduktor/core/export.py b/backend/konduktor/core/export.py index d2c50f7..ff4d8a3 100644 --- a/backend/konduktor/core/export.py +++ b/backend/konduktor/core/export.py @@ -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 diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 97f56ca..b8cbf02 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -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): diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index e13d4c3..22a7576 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -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): diff --git a/backend/konduktor/exports.py b/backend/konduktor/exports.py index b627a41..561a920 100644 --- a/backend/konduktor/exports.py +++ b/backend/konduktor/exports.py @@ -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 diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 7ed5e31..179b099 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -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. diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 6d1301f..5fdb8c9 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -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): diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 6bf13dd..87c7196 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do +for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_export_level.py b/backend/test_export_level.py new file mode 100644 index 0000000..9110b90 --- /dev/null +++ b/backend/test_export_level.py @@ -0,0 +1,252 @@ +"""Export with "Normalise audio" and "Auto gain", through the routes, on a temp +collection pointed at GENERATED audio, exported to Traktor + Rekordbox Library ++ OneLibrary at once. + +What would fail silently, and matter at a gig: + + * a normalised COPY is its source at exactly the planned gain, the source is + never touched, and a copy that needs no change is byte-identical; + * the DJ app's gain is written from the COPY's level (Traktor -9.2 - LUFS, + rekordbox -10 - LUFS), and only where the target keeps one; + * sources with no loudness are measured once, into the store; + * the set remembers its options; a re-export at the same level copies + nothing, one at another level re-copies only the copies whose level + changes, and turning Normalise off puts the source's own bytes back; + * the waveform cache is keyed by the level too (else a stick is drawn from + the un-levelled measurement). +""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import tempfile +import time +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-export-level-appdata-") +os.environ.pop("KONDUKTOR_NML", None) + +import av # noqa: E402 +import numpy as np # noqa: E402 +import soundfile as sf # noqa: E402 +from fastapi.testclient import TestClient # noqa: E402 + +import konduktor.main as main # noqa: E402 +from konduktor import exporter, loudness_store # noqa: E402 +from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 +from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402 +from konduktor.adapters.traktor.store import TraktorStore # noqa: E402 +from konduktor.core import level_edit, loudness # noqa: E402 + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" +ROOT = Path(tempfile.mkdtemp(prefix="konduktor-export-level-")) +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +def music(seconds=8.0, amp=0.3, sr=44100, seed=1): + t = np.arange(int(sr * seconds)) / sr + rng = np.random.default_rng(seed) + beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float) + x = [amp * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.3 * np.sin(2 * np.pi * (440 + 30 * c) * t) + + 0.2 * rng.standard_normal(t.size)) for c in range(2)] + return np.vstack(x).astype(np.float32) + + +def make(path: Path, amp: float, spike: bool = False) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + x = music(amp=amp) + if spike: + x[:, 44100] = 0.99 # a quiet track with one peak over the ceiling + if path.suffix == ".mp3": + with av.open(str(path), "w", format="mp3") as c: + s = c.add_stream("libmp3lame", rate=44100, layout="stereo") + s.bit_rate = 256_000 + for o in range(0, x.shape[1], 1152): + f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo") + f.sample_rate, f.pts = 44100, o + for p in s.encode(f): + c.mux(p) + for p in s.encode(None): + c.mux(p) + else: + sf.write(str(path), x.T, 44100, subtype="PCM_16") + return path + + +FILES = [("hot.mp3", 0.9, False), ("quiet.flac", 0.05, False), ("hot.wav", 0.8, False), + ("spike.wav", 0.02, True)] + + +def library(): + d = ROOT / "lib" + work = d / "collection.nml" + d.mkdir(parents=True) + shutil.copy2(REAL, work) + st = TraktorStore(work) + entries = [e for e in st._nml.collection.entry if e.location and e.stems is None] + ids, files = [], [] + for (f, amp, spike), e in zip(FILES, entries): + path = make(d / "Music" / f, amp, spike) + e.location.volume, e.location.dir, e.location.file = os_path_to_location(path) + e.cue_v2 = [] # the real track's cues mean nothing on 8 s of generated audio + st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location} + ids.append(st._key_of(e)) + files.append(path) + st.save() + return work, ids, files + + +def sha(p: Path) -> str: + return hashlib.sha256(p.read_bytes()).hexdigest() + + +def wait(c, jid, timeout=300): + end = time.time() + timeout + while time.time() < end: + j = c.get(f"/api/jobs/{jid}").json() + if j["state"] != "running": + return j + time.sleep(0.05) + raise AssertionError("job did not finish") + + +def manifest_gains(dest: Path) -> dict[str, float]: + audio = json.loads((dest / exporter.MANIFEST_NAME).read_text())["audio"] + return {Path(rel).name: float(r.get("gain_db") or 0.0) for rel, r in audio.items()} + + +def traktor_gains(dest: Path) -> dict[str, float | None]: + st = TraktorStore(dest / "collection.nml") + return {e.location.file: (e.loudness.perceived_db if e.loudness is not None else None) + for e in st._nml.collection.entry} + + +def rekordbox_gains(dest: Path) -> dict[str, float | None]: + ad = RekordboxAdapter(dest / "master.db") + try: + return {Path(t.filepath).name: t.auto_gain_db for t in ad.tracks} + finally: + ad.close() + + +LEVEL = {"measure": "lufs", "target": -9.0, "ceiling": -1.0} + +work, ids, sources = library() +before = {p.name: sha(p) for p in sources} +dest = ROOT / "STICK" +dest.mkdir() + +with TestClient(main.app) as c: + r = c.post("/api/library/open", json={"path": str(work)}) + assert r.status_code == 200, r.text + s = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor", "rekordbox", "onelibrary"], + "destination": str(dest)}).json() + c.post(f"/api/exports/{s['id']}/add", json={"track_ids": ids}) + check("a new set: Normalise off, Auto gain on", (s["normalise"], s["auto_gain"]) == (False, True), str(s)) + targets = {o["platform"]: o for o in c.get("/api/export-targets").json()} + check("Auto gain is offered for Traktor and the Rekordbox Library, not for a stick", + targets["traktor"]["writes_auto_gain"] and targets["rekordbox"]["writes_auto_gain"] + and not targets["onelibrary"]["writes_auto_gain"] + and not targets["rekordbox_export"]["writes_auto_gain"]) + + print("== the first export: every source measured, the copies levelled ==") + body = {"normalise": True, "auto_gain": True, "level": LEVEL} + pv = c.post(f"/api/exports/{s['id']}/preview", json=body).json() + check("the preview counts the sources the run measures first", + pv["to_measure"] == len(ids) and pv["level_counts"].get("unmeasured") == len(ids), str(pv)) + j = wait(c, c.post(f"/api/exports/{s['id']}/run", json=body).json()["id"]) + check("the export runs", j["state"] == "done", str(j.get("error"))) + store = loudness_store.local() + entries = store.get([str(p) for p in sources]) + check("every source was measured into the store", len(entries) == len(sources), str(list(entries))) + check("the sources are byte-identical", {p.name: sha(p) for p in sources} == before) + gains = manifest_gains(dest) + check("the manifest records each copy's level", set(gains) == {p.name for p in sources}, str(gains)) + check("three copies change level, the spike's does not (hot peak left alone)", + sum(1 for g in gains.values() if g) == 3 and gains["spike.wav"] == 0.0 and j["result"]["normalised"] == 3, + str(gains)) + for p in sources: + copy = dest / "Contents" / p.name + g = gains[p.name] + if g: + try: + level_edit.verify(p, copy, g) + ok = True + except level_edit.LevelEditError as ex: + ok = str(ex) + check(f"{p.name}: the copy is the source at {g:+.2f} dB", ok is True, str(ok)) + else: + check(f"{p.name}: an unchanged level is a byte-identical copy", sha(copy) == before[p.name]) + after = {p.name: shifted for p in sources + if (shifted := entries[str(p)].values.lufs + gains[p.name]) is not None} + tk, rb = traktor_gains(dest), rekordbox_gains(dest) + check("Traktor's gain is -9.2 - the COPY's LUFS", + all(abs(tk[n] - (-9.2 - lufs)) < 1e-3 for n, lufs in after.items()), str(tk)) + check("the Rekordbox Library's gain is -10 - the COPY's LUFS", + all(abs(rb[n] - (-10.0 - lufs)) < 1e-3 for n, lufs in after.items()), str(rb)) + saved = c.get("/api/exports").json() + mine = next(x for x in saved if x["id"] == s["id"]) + check("the set remembers Normalise, Auto gain and the level", + (mine["normalise"], mine["auto_gain"], mine["level"]) == (True, True, LEVEL), str(mine)) + + print("== a re-export at the same level copies nothing ==") + inodes = {p.name: (dest / "Contents" / p.name).stat().st_ino for p in sources} + pv = c.post(f"/api/exports/{s['id']}/preview", json={}).json() + check("nothing left to measure", pv["to_measure"] == 0, str(pv)) + j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={}).json()["id"]) + check("every copy kept", j["state"] == "done" and j["result"]["unchanged"] == len(sources), str(j.get("result"))) + check("…the very same files", {p.name: (dest / "Contents" / p.name).stat().st_ino for p in sources} == inodes) + + print("== another target re-copies only the copies whose level changes ==") + j = wait(c, c.post(f"/api/exports/{s['id']}/run", + json={"level": {**LEVEL, "target": -10.0}}).json()["id"]) + new_gains = manifest_gains(dest) + # At -10 the MP3's nearest step and the ceiling-capped FLAC keep their + # gain; the WAV's changes; the spike stays at 0. + changed = {n for n in gains if abs(new_gains[n] - gains[n]) > 0.01} + kept = set(gains) - changed + check("a copy whose level changes is written again — and only that one", + j["state"] == "done" and changed == {"hot.wav"} + and j["result"]["unchanged"] == len(kept), f"{changed} {j.get('result')}") + check("…the others are the very same files", + all((dest / "Contents" / n).stat().st_ino == inodes[n] for n in kept)) + try: + level_edit.verify(sources[2], dest / "Contents" / "hot.wav", new_gains["hot.wav"]) + ok = True + except level_edit.LevelEditError as ex: + ok = str(ex) + check("…and the re-written one is at the new level", ok is True, str(ok)) + + print("== Normalise off: the source's own bytes, the gain from the source's level ==") + j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={"normalise": False}).json()["id"]) + check("every copy is byte-identical to its source", + j["state"] == "done" and all(sha(dest / "Contents" / p.name) == before[p.name] for p in sources)) + tk = traktor_gains(dest) + check("Traktor's gain follows the SOURCE's LUFS", + all(abs(tk[p.name] - (-9.2 - entries[str(p)].values.lufs)) < 1e-3 for p in sources), str(tk)) + + print("== Auto gain off: none written ==") + j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={"auto_gain": False}).json()["id"]) + check("no LOUDNESS in the exported collection", all(v is None for v in traktor_gains(dest).values())) + check("no auto gain in the Rekordbox Library", all(v is None for v in rekordbox_gains(dest).values())) + +print("== the waveform cache is keyed by the level ==") +p = exporter.PlannedTrack(track_id="t", title="t", source_path=Path("/x.mp3"), destination=None, + size=10, mtime_ns=1) +plain = exporter._fingerprint(p) +p.gain_db = -3.01 +check("a levelled copy gets its own waveform-cache key", exporter._fingerprint(p) != plain) + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +raise SystemExit(1 if failed else 0) diff --git a/frontend/src/api.ts b/frontend/src/api.ts index e38ffc3..27f10d4 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -360,6 +360,8 @@ export interface PlatformOption { computer_only?: boolean /** As an export target: its library can store a grid lock. */ locks_grids?: boolean + /** As an export target: its library keeps the DJ app's auto gain. */ + writes_auto_gain?: boolean } export interface EditState { @@ -832,6 +834,12 @@ export interface ExportSet { /** Lock every exported grid, so Traktor does not re-analyse a track when it * is first loaded. Set from the run dialog and remembered here. */ lock_grids: boolean + /** Normalise the COPIES' audio (the sources are never touched). */ + normalise: boolean + /** Write the DJ app's auto gain, where a target keeps one. */ + auto_gain: boolean + /** Normalise's measure / target / ceiling; null = the app settings. */ + level: NormalizeOptions | null created: number modified: number } @@ -877,6 +885,20 @@ export interface ExportPreview { /** 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: string[] + /** Normalise audio: copies whose level changes, and each outcome's count. */ + normalised: number + level_counts: Record + /** Sources the run measures first (no stored loudness). */ + to_measure: number +} + +/** The run dialog's options; each is remembered on the set. Omitted = the + * set's own answer. */ +export interface ExportRunOptions { + lock_grids?: boolean + normalise?: boolean + auto_gain?: boolean + level?: NormalizeOptions } export interface FsPlace { @@ -1106,10 +1128,11 @@ export const api = { // reason rather than hiding them — an absent option reads as a missing // feature, a disabled one reads as a roadmap. exportTargets: () => getJSON('/api/export-targets'), - exportPreview: (id: string) => - send('POST', `/api/exports/${encodeURIComponent(id)}/preview`, {}), + // The preview takes the run dialog's options as ticked, so its counts match. + exportPreview: (id: string, body: ExportRunOptions = {}) => + send('POST', `/api/exports/${encodeURIComponent(id)}/preview`, body), // The run dialog's options travel with the click; the set remembers them. - runExport: (id: string, body: { lock_grids?: boolean } = {}) => + runExport: (id: string, body: ExportRunOptions = {}) => send('POST', `/api/exports/${encodeURIComponent(id)}/run`, body), // ---- path remapping (per-collection OS-path prefix translation) ---- diff --git a/frontend/src/components/ExportRunDialog.tsx b/frontend/src/components/ExportRunDialog.tsx index 0aae192..236a003 100644 --- a/frontend/src/components/ExportRunDialog.tsx +++ b/frontend/src/components/ExportRunDialog.tsx @@ -1,8 +1,9 @@ import { createPortal } from 'react-dom' import { useEffect, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type ExportPreview, type ExportSet, type JobStatus } from '../api' +import { api, type ExportPreview, type ExportRunOptions, type ExportSet, type JobStatus, type NormalizeOptions } from '../api' import { FolderPicker } from './FolderPicker' +import { LevelInput, useAppSetting } from './AppSettings' /** * Run an export: confirm what is about to happen, then watch it happen. @@ -46,6 +47,15 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { // Remembered on the set (sent with the click), so a stick's next export // starts from the same answer. Older sets without it read as on. const [lockGrids, setLockGrids] = useState(set.lock_grids ?? true) + // Remembered on the set the same way (decided 2026-10-19). The level starts + // from the set's own, else Normalize's app settings. + const [normalise, setNormalise] = useState(set.normalise ?? false) + const [autoGain, setAutoGain] = useState(set.auto_gain ?? true) + const defaultMeasure = useAppSetting('levelMeasure') + const defaultTarget = useAppSetting('levelTarget') + const defaultCeiling = useAppSetting('levelCeiling') + const [level, setLevel] = useState(set.level ?? null) + const levelNow: NormalizeOptions = level ?? { measure: defaultMeasure, target: defaultTarget, ceiling: defaultCeiling } const pollRef = useRef(null) // The set as last saved from here: `set` is a snapshot, and a destination // changed in this dialog must reach the preview and the run. @@ -60,10 +70,20 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { const lockable = set.targets.some( (id) => platforms.data?.find((p) => p.platform === id)?.locks_grids, ) + // Only where a target keeps an auto gain — no stick format does (kit G2). + const gainTargets = set.targets.filter( + (id) => platforms.data?.find((p) => p.platform === id)?.writes_auto_gain, + ) + const options: ExportRunOptions = { + ...(lockable ? { lock_grids: lockGrids } : {}), + normalise, + ...(gainTargets.length ? { auto_gain: autoGain } : {}), + level: levelNow, + } const preview = useQuery({ - queryKey: ['export-preview', set.id, current.destination], - queryFn: () => api.exportPreview(set.id), + queryKey: ['export-preview', set.id, current.destination, options], + queryFn: () => api.exportPreview(set.id, options), enabled: !job, staleTime: 0, gcTime: 0, @@ -124,7 +144,7 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { const start = async () => { setStarting(true) try { - setJob(await api.runExport(set.id, lockable ? { lock_grids: lockGrids } : {})) + setJob(await api.runExport(set.id, options)) qc.invalidateQueries({ queryKey: ['exports'] }) } catch (e) { onError((e as Error).message) @@ -260,6 +280,74 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { )} + + {normalise && ( +
+
+ Level by + +
+
+ Target + setLevel({ ...levelNow, target: v })} /> +
+
+ Peak ceiling + setLevel({ ...levelNow, ceiling: v })} /> +
+
+ {p.normalised} cop{p.normalised === 1 ? 'y changes' : 'ies change'} level + {(p.level_counts.unsupported ?? 0) > 0 && + ` · ${p.level_counts.unsupported} in a format that can’t be changed losslessly`} + {(p.level_counts.hot_peak_left ?? 0) > 0 && ` · ${p.level_counts.hot_peak_left} with a hot peak, left alone`} +
+
+ )} + {gainTargets.length > 0 && ( + + )} + {p.to_measure > 0 && ( +
+ {p.to_measure} track{p.to_measure === 1 ? ' is' : 's are'} measured first (about a second each). +
+ )}
Writes a library for {set.targets.map(nameOf).join(' and ')}, sharing one copy of every track under Contents/, in your own