From 932923695572965aca3d8f60b78138f7781c51cb Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 19 Oct 2026 10:48:59 +0200 Subject: [PATCH 01/11] Implemented export track grid locking --- CLAUDE.md | 28 +++++++++-- .../konduktor/adapters/rekordbox/export.py | 6 ++- .../adapters/rekordbox/new_content.py | 6 +++ backend/konduktor/adapters/rekordbox/store.py | 2 +- backend/konduktor/adapters/traktor/adapter.py | 4 ++ backend/konduktor/adapters/traktor/export.py | 2 + backend/konduktor/adapters/traktor/store.py | 11 +++++ backend/konduktor/core/model.py | 3 ++ backend/konduktor/exporter.py | 22 ++++++++- backend/konduktor/exports.py | 10 +++- backend/konduktor/main.py | 13 ++++- backend/konduktor/schemas.py | 8 ++++ backend/test_export.py | 48 +++++++++++++++++-- backend/test_export_pioneer.py | 10 ++++ frontend/src/api.ts | 15 ++++-- frontend/src/components/ExportRunDialog.tsx | 27 ++++++++++- 16 files changed, 196 insertions(+), 19 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7611846..a048cb3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1536,8 +1536,13 @@ serialization path.** It enforces: above all that **`` is volume-relative** — an export writing host paths would work perfectly on the machine that made it and resolve to nothing at the gig. Also that a flexible multi-marker grid and hot-cue PADS survive, - grids are not locked, loose tracks get their "Other" playlist, and re-exporting - into the same folder replaces rather than appends. + each grid keeps its source's lock, loose tracks get their "Other" playlist, and + re-exporting into the same folder replaces rather than appends. **Lock + beatgrids** (the run's option): a new set locks by default and remembers being + told not to; on, every exported track WITH a grid is locked (never one without + — Traktor would never give it a grid), written as Traktor 4.5 writes it + (`LOCK="1"` then `LOCK_MODIFICATION_TIME`, ISO, UTC); `test_export_pioneer.py` + pins the Rekordbox Library's `Analysed` 233 vs 105. It then runs a real export end to end (the source library is built with the exporter itself, so its LOCATIONs point at audio that exists) and pins the safety rules with teeth: a folder Konduktor did NOT write is refused, and @@ -1948,8 +1953,23 @@ that number and nothing else — everything derives from it: target** for v1, source is whatever library is loaded, **mirror the source folder structure** (so filename collisions cannot happen), playlists are **live links removable only as a whole**, re-export **clears the destination first**, - cancel **rolls back**, key notation **mirrors the source**, grids are **not - locked**, no whole-library export. + cancel **rolls back**, key notation **mirrors the source**, no whole-library + export. Grids were first left **unlocked**, and that went wrong: an exported + Traktor entry has no `AUDIO_ID` (Traktor's analysis fingerprint, which cannot + be computed), so Traktor re-analyses it on its first load — re-measuring the + BPM (a 174 track came back as 87) and drifting the grid. So the run dialog has + **Lock beatgrids** (decided 2026-10-19; `ExportSet.lock_grids`, default on, + sent with the run and remembered on the set; shown where a target's + `PlatformOption.locks_grids`). It rides on the generic `TrackCues.grid_locked` + (`exporter._locked`), the flag a source's own lock already arrives in, so off + still carries each track's own lock; Traktor writes `LOCK` + + `LOCK_MODIFICATION_TIME` (UTC), the Rekordbox Library sets bit 0x80 of + `djmdContent.Analysed` (105 -> 233, measured by locking tracks in rekordbox + 7). The stick formats carry NO lock: rekordbox 7's own device export of two + locked tracks left OneLibrary `analysedBits` and the pdb's `u5` at 41, as on + every unlocked track (measured on Hardy, 2026-10-19), so neither stick + exporter sets `locks_grids`. The Rekordbox ADAPTER does not yet + read or write that bit (`grid.lockable` stays false). Verified against the real collection: Traktor stores `VOLUME="Hardy"` plus a **volume-relative** `DIR`, never a host path — so a USB export is portable by construction, and the `.nml` cannot be written until the destination is known. diff --git a/backend/konduktor/adapters/rekordbox/export.py b/backend/konduktor/adapters/rekordbox/export.py index c5f93a1..1e9e5c7 100644 --- a/backend/konduktor/adapters/rekordbox/export.py +++ b/backend/konduktor/adapters/rekordbox/export.py @@ -109,6 +109,8 @@ class RekordboxExporter: computer_only = True library_filename = "master.db" drive_root = False + #: `djmdContent.Analysed` bit 0x80 — from `TrackCues.grid_locked`. + locks_grids = True def capabilities(self): """What a Rekordbox library can hold, with no library to read. @@ -332,7 +334,9 @@ class RekordboxExporter: """ rel = new_content.anlz_rel(str(content.UUID)) content.AnalysisDataPath = rel - content.Analysed = 105 # what a rekordbox-analysed track carries + content.Analysed = new_content.ANALYSED + if item.cues is not None and item.cues.grid_locked: + content.Analysed |= new_content.ANALYSED_LOCKED content.AnalysisUpdated = 1 db.flush() diff --git a/backend/konduktor/adapters/rekordbox/new_content.py b/backend/konduktor/adapters/rekordbox/new_content.py index f8e39c5..bff1d6f 100644 --- a/backend/konduktor/adapters/rekordbox/new_content.py +++ b/backend/konduktor/adapters/rekordbox/new_content.py @@ -34,6 +34,12 @@ from . import artwork #: only what is written: 0x2C060E. CONTENT_LINK = 2885134 +#: `djmdContent.Analysed` as a rekordbox-analysed track carries it, and the bit +#: rekordbox 7 sets beside it when the grid is LOCKED (the padlock in Grid Edit): +#: measured 2026-10-19 by locking two tracks — 105 -> 233, nothing else changed. +ANALYSED = 105 +ANALYSED_LOCKED = 0x80 + def anlz_rel(track_uuid: str) -> str: """`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index b39b6ac..d648a3a 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -788,7 +788,7 @@ class RekordboxStore(ReplaceGridCommands): track_uuid = str(content.UUID) rel = new_content.anlz_rel(track_uuid) content.AnalysisDataPath = rel - content.Analysed = 105 # what a rekordbox-analysed track carries + content.Analysed = new_content.ANALYSED content.AnalysisUpdated = 1 files = new_content.anlz_files(audio, measured, [] if with_grid else None) for suffix, data in files.items(): diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 8476db9..0db9fad 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -242,6 +242,10 @@ class TraktorAdapter: # invent one outside Auto Grid), and it occupies pad A — which # silently displaced the imported track's own pad A cue. self.replace_grid(track_id, markers) + if cues.grid_locked: + # The source's lock, or an export's "Lock beatgrids". Unlocked, an + # added entry (no AUDIO_ID) is re-analysed on its first load. + self._store.set_lock(track_id, True) slots = self.capabilities().cues.hotcue_slots taken = {c.slot for c in self.track_cues(track_id).cues if c.slot is not None} diff --git a/backend/konduktor/adapters/traktor/export.py b/backend/konduktor/adapters/traktor/export.py index 66b2739..dca95e2 100644 --- a/backend/konduktor/adapters/traktor/export.py +++ b/backend/konduktor/adapters/traktor/export.py @@ -66,6 +66,8 @@ class TraktorExporter: menu_order = 20 library_filename = "collection.nml" drive_root = False + #: `LOCK` — honoured from `TrackCues.grid_locked` by `add_tracks`. + locks_grids = True def capabilities(self): """What a Traktor library can hold — answered with no library to read. diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index dbab1f6..e9dbbeb 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -22,6 +22,7 @@ import copy import math import threading import uuid as uuidlib +from datetime import datetime, timezone from pathlib import Path from traktor_nml_utils import ( @@ -1210,9 +1211,19 @@ class TraktorStore: self.dirty = True def set_lock(self, track_id: str, locked: bool) -> None: + """Lock or unlock a track's grid. + + Locking writes what Traktor 4.5 writes (measured 2026-10-19): + ``LOCK="1"`` plus ``LOCK_MODIFICATION_TIME``, an ISO time in UTC to the + second. What Traktor leaves on UNLOCK is unmeasured, so unlocking only + removes ``LOCK``, as it always has. + """ with self._lock: entry = self._entry_or_raise(track_id) entry.lock = 1 if locked else None + if locked: + entry.lock_modification_time = ( + datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")) self._note("lock", "on" if locked else "off", track_id) self.dirty = True diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 7bfe2c9..ae261cf 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -234,6 +234,9 @@ class PlatformOption(BaseModel): #: As an export TARGET: its library is only ever read on a computer, never #: from a drive — so it does nothing beside a stick format. computer_only: bool = False + #: 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 class RemapSample(BaseModel): diff --git a/backend/konduktor/exporter.py b/backend/konduktor/exporter.py index 9cebdec..e13d4c3 100644 --- a/backend/konduktor/exporter.py +++ b/backend/konduktor/exporter.py @@ -433,12 +433,30 @@ def _folder_paths(adapter) -> dict[str, list[str]]: # ---- running ----------------------------------------------------------------- +def _locked(cues, lock_grids: bool): + """The cues as exported: with `lock_grids`, a grid is LOCKED. + + The lock rides on the generic `TrackCues.grid_locked`, the same flag a + source's own lock arrives in, so a writer reads one signal and never learns + which of the two set it. Unlocked Traktor re-analyses an exported track on + its first load (it has no AUDIO_ID, which cannot be computed), re-measuring + the BPM — a 174 track can come back as 87 — and drifting the grid; a + locked grid is left alone. A track with no grid is never locked: that + would stop Traktor ever giving it one. + """ + if lock_grids and cues is not None and cues.grid_markers and not cues.grid_locked: + return cues.model_copy(update={"grid_locked": True}) + return cues + + def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *, - root_folder: bool = False) -> dict: + root_folder: bool = False, lock_grids: 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. Rolls back EVERYTHING this run wrote on cancel or on any failure — including the libraries of targets that had already been written when a @@ -530,7 +548,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *, ExportTrack( track=adapter.track(planned.track_id), destination=target, - cues=adapter.track_cues(planned.track_id), + cues=_locked(adapter.track_cues(planned.track_id), lock_grids), art=_cover(adapter, planned.track_id), fingerprint=_fingerprint(planned), analysis_cache=cache, diff --git a/backend/konduktor/exports.py b/backend/konduktor/exports.py index 2ae40fb..b627a41 100644 --- a/backend/konduktor/exports.py +++ b/backend/konduktor/exports.py @@ -62,6 +62,10 @@ class ExportSet: destination: str = "" # OS path of the folder the export is written into playlist_ids: list[str] = field(default_factory=list) track_ids: list[str] = field(default_factory=list) # loose tracks only + #: Lock every exported grid, so Traktor does not re-analyse a track on its + #: 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 created: float = 0.0 modified: float = 0.0 @@ -170,6 +174,7 @@ def _load(library_id: str) -> dict[str, ExportSet]: destination=values.get("destination") or "", playlist_ids=list(values.get("playlist_ids") or []), track_ids=list(values.get("track_ids") or []), + lock_grids=bool(values.get("lock_grids", True)), created=float(values.get("created") or 0.0), modified=float(values.get("modified") or 0.0), ) @@ -251,7 +256,8 @@ def create(library_id: str, *, name: str, targets: list[str], destination: str) def update(library_id: str, set_id: str, **fields) -> ExportSet | None: - """Rename, retarget or relocate a set. Unknown fields are ignored.""" + """Rename, retarget or relocate a set, or change its options. Unknown fields + are ignored.""" sets = _load(library_id) found = sets.get(set_id) if found is None: @@ -261,6 +267,8 @@ 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"]) found.modified = time.time() _save(library_id, sets) return found diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index d48cfe0..7de093c 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -78,6 +78,7 @@ from .schemas import ( FsListing, FsPlace, UpdateExportSet, + RunExport, AddGridMarker, GridMarkerEdit, ReplaceGrid, @@ -655,6 +656,7 @@ def update_export(set_id: str, body: UpdateExportSet) -> ExportSetOut: name=body.name, targets=body.targets, destination=body.destination, + lock_grids=body.lock_grids, ) return ExportSetOut(**updated.as_dict()) @@ -764,14 +766,19 @@ def preview_export(set_id: str) -> ExportPreview: @app.post("/api/exports/{set_id}/run", response_model=JobStatus) -def run_export(set_id: str) -> JobStatus: +def run_export(set_id: str, body: RunExport | None = None) -> JobStatus: """Start the export on a background thread; poll `/api/jobs/{id}`. Planned again HERE rather than trusting whatever the preview showed: a playlist can be edited, a file deleted or a drive unplugged between looking and clicking, and the plan carries the destination-safety check. + + The dialog's options arrive with the click and are remembered on the set, + 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) adapter = require_adapter() built = exporter.plan(adapter, found) if built.blocked: @@ -779,7 +786,7 @@ def run_export(set_id: str) -> JobStatus: # 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)) + adapter, found, built, handle, root_folder=root_folder, lock_grids=found.lock_grids)) return JobStatus(**job.as_dict()) @@ -829,6 +836,7 @@ def export_targets() -> list[PlatformOption]: removable=bool(getattr(d, "removable", False)), drive_root=bool(getattr(exporter, "drive_root", False)), computer_only=bool(getattr(exporter, "computer_only", False)), + locks_grids=bool(getattr(exporter, "locks_grids", False)), )) # Targets with no reader of their own (the stick's legacy Device Library): # listed too, or registering one would not make it selectable. @@ -847,6 +855,7 @@ def export_targets() -> list[PlatformOption]: removable=bool(getattr(exporter, "drive_root", False)), drive_root=bool(getattr(exporter, "drive_root", False)), computer_only=bool(getattr(exporter, "computer_only", False)), + locks_grids=bool(getattr(exporter, "locks_grids", 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 30f8c9d..99d9619 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -347,6 +347,7 @@ class ExportSetOut(BaseModel): destination: str playlist_ids: list[str] = [] track_ids: list[str] = [] # loose tracks only + lock_grids: bool = True created: float = 0.0 modified: float = 0.0 @@ -361,6 +362,13 @@ class UpdateExportSet(BaseModel): name: str | None = None targets: list[str] | None = None destination: str | None = None + lock_grids: bool | None = None + + +class RunExport(BaseModel): + #: The run dialog's "Lock beatgrids" — remembered on the set. None keeps the + #: set's own answer. + lock_grids: bool | None = None class ExportSetMembers(BaseModel): diff --git a/backend/test_export.py b/backend/test_export.py index 0f16060..ee40e9b 100644 --- a/backend/test_export.py +++ b/backend/test_export.py @@ -174,10 +174,14 @@ check("with its tempo changes", check("and its marker positions", [round(m.start, 3) for m in out_grid.grid_markers] == [round(m.start, 3) for m in src_grid.grid_markers]) -# Ben's decision: exported grids are NOT locked, so they stay editable like any -# other track. If Traktor turns out to re-analyse and flatten them, this is what -# makes that visible rather than hidden behind a lock. -check("grids are not locked", not by_title[flexible.title].grid_locked) +# A grid crosses with the lock it had: unlocked at the source, unlocked here. +# Locking every grid is the run's "Lock beatgrids" option (below), because +# Traktor DID turn out to re-analyse an unlocked exported track on first load. +check("each track keeps its source's lock", + [by_title[t.title].grid_locked for t in chosen] == [t.grid_locked for t in chosen], + str([(t.title, t.grid_locked, by_title[t.title].grid_locked) for t in chosen])) +check("and only a locked one has LOCK written", + text.count(' LOCK="1"') == sum(1 for t in chosen if t.grid_locked)) src_cues = src.track_cues(cued.id) out_cues = back.track_cues(by_title[cued.title].id) @@ -278,6 +282,42 @@ check("the audio is really there", check("the result re-opens as a library", len(TraktorDriver().open(dest / "collection.nml").tracks) == len(built.exportable)) +print("== Lock beatgrids ==") +check("a new export set locks by default", exports.get(LIB, eset.id).lock_grids is True) +check("and remembers being told not to", + exports.update(LIB, eset.id, lock_grids=False).lock_grids is False + and exports.get(LIB, eset.id).lock_grids is False) +exports.update(LIB, eset.id, lock_grids=True) +gridded = src.track_cues(flexible.id).model_copy(update={"grid_locked": False}) +bare = gridded.model_copy(update={"grid_markers": []}) +check("on: a grid is locked", exporter._locked(gridded, True).grid_locked) +check("on: a track with no grid is not (Traktor would never give it one)", + not exporter._locked(bare, True).grid_locked) +check("off: the source's own lock is kept", + exporter._locked(gridded.model_copy(update={"grid_locked": True}), False).grid_locked + and not exporter._locked(gridded, False).grid_locked) +lock_dest = Path(tempfile.mkdtemp()) / "LOCKED" +lset = exports.create(LIB, name="LOCKED", targets=["traktor"], destination=str(lock_dest)) +exports.add(LIB, lset.id, playlist_ids=[source_pl.id], track_ids=[ad.tracks[3].id]) +lset = exports.get(LIB, lset.id) +ljob = JOBS.submit("export", lambda h: exporter.run( + ad, lset, exporter.plan(ad, lset), h, lock_grids=True)) +while not ljob.finished: + time.sleep(0.02) +check("a locked export finishes", ljob.state == "done", f"{ljob.state}: {ljob.error}") +ltext = (lock_dest / "collection.nml").read_text(encoding="utf-8") +lback = TraktorDriver().open(lock_dest / "collection.nml") +with_grid = [t for t in lback.tracks if t.grid_marker_count] +check("every exported track with a grid is locked", + with_grid and all(t.grid_locked for t in with_grid), + str([(t.title, t.grid_locked) for t in lback.tracks])) +check("none without one is", + not any(t.grid_locked for t in lback.tracks if not t.grid_marker_count)) +# Measured in Traktor 4.5: LOCK="1" then LOCK_MODIFICATION_TIME, ISO, UTC. +check("written as Traktor writes it: LOCK then an ISO LOCK_MODIFICATION_TIME", + len(re.findall(r' LOCK="1" LOCK_MODIFICATION_TIME="\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d"', + ltext)) == len(with_grid)) + print("== Konduktor only ever deletes what Konduktor wrote ==") mine = dest / "MY OWN NOTES.txt" mine.write_text("do not delete") diff --git a/backend/test_export_pioneer.py b/backend/test_export_pioneer.py index 3ad1f2d..3e05052 100644 --- a/backend/test_export_pioneer.py +++ b/backend/test_export_pioneer.py @@ -146,6 +146,16 @@ for platform, reopen in ( [by_title[t.title].color for t in chosen] == COLOURS[:len(chosen)], str([by_title[t.title].color for t in chosen])) + if platform == "rekordbox": + # Measured 2026-10-19: rekordbox 7's grid padlock sets bit 0x80 of + # `djmdContent.Analysed` (105 -> 233) and nothing else. + analysed = {c.Title: c.Analysed for c in back._store._db.get_content()} + check("a locked grid is Analysed 233, an unlocked one 105", + [analysed[t.title] for t in chosen] + == [233 if src.track_cues(t.id).grid_locked else 105 for t in chosen] + and any(src.track_cues(t.id).grid_locked for t in chosen), + str([(t.title, analysed[t.title]) for t in chosen])) + print(f"-- {platform}: the key was CONVERTED, not copied") for track in chosen: if not track.key: diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 2ee17d5..0068820 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -334,6 +334,8 @@ export interface PlatformOption { drive_root?: boolean /** As an export target: only ever read on a computer, never from a drive. */ computer_only?: boolean + /** As an export target: its library can store a grid lock. */ + locks_grids?: boolean } export interface EditState { @@ -740,6 +742,9 @@ export interface ExportSet { playlist_ids: string[] /** LOOSE tracks only — tracks a referenced playlist supplies are not listed. */ track_ids: string[] + /** 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 created: number modified: number } @@ -982,7 +987,10 @@ export const api = { exports: () => getJSON('/api/exports'), createExport: (body: { name: string; targets: string[]; destination: string }) => send('POST', '/api/exports', body), - updateExport: (id: string, body: Partial>) => + updateExport: ( + id: string, + body: Partial>, + ) => send('PATCH', `/api/exports/${encodeURIComponent(id)}`, body), deleteExport: (id: string) => send<{ deleted: boolean }>('DELETE', `/api/exports/${encodeURIComponent(id)}`), @@ -1013,8 +1021,9 @@ export const api = { exportTargets: () => getJSON('/api/export-targets'), exportPreview: (id: string) => send('POST', `/api/exports/${encodeURIComponent(id)}/preview`, {}), - runExport: (id: string) => - send('POST', `/api/exports/${encodeURIComponent(id)}/run`, {}), + // The run dialog's options travel with the click; the set remembers them. + runExport: (id: string, body: { lock_grids?: boolean } = {}) => + send('POST', `/api/exports/${encodeURIComponent(id)}/run`, body), // ---- path remapping (per-collection OS-path prefix translation) ---- getPathMapping: () => getJSON('/api/library/path-mapping'), diff --git a/frontend/src/components/ExportRunDialog.tsx b/frontend/src/components/ExportRunDialog.tsx index 1d27bf9..53a2de3 100644 --- a/frontend/src/components/ExportRunDialog.tsx +++ b/frontend/src/components/ExportRunDialog.tsx @@ -36,11 +36,18 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { const qc = useQueryClient() const [job, setJob] = useState(null) const [starting, setStarting] = useState(false) + // 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) const pollRef = useRef(null) // Platform names for wording the facts the preview and result carry as ids. const platforms = useQuery({ queryKey: ['export-targets'], queryFn: api.exportTargets }) const nameOf = (id: string) => platforms.data?.find((p) => p.platform === id)?.name ?? id + // Offered only where a target can store a lock — a stick format cannot. + const lockable = set.targets.some( + (id) => platforms.data?.find((p) => p.platform === id)?.locks_grids, + ) const preview = useQuery({ queryKey: ['export-preview', set.id], @@ -83,7 +90,8 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { const start = async () => { setStarting(true) try { - setJob(await api.runExport(set.id)) + setJob(await api.runExport(set.id, lockable ? { lock_grids: lockGrids } : {})) + qc.invalidateQueries({ queryKey: ['exports'] }) } catch (e) { onError((e as Error).message) } finally { @@ -178,6 +186,23 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { folder’s contents to a drive’s top level. )} + {lockable && ( + + )}
Writes a library for {set.targets.map(nameOf).join(' and ')}, sharing one copy of every track under Contents/, in your own From 5c9387f1360fad27deaa84d70b770a07351f8e2c Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 19 Oct 2026 11:33:23 +0200 Subject: [PATCH 02/11] Added quick target location change button in export dialog --- frontend/src/components/ExportRunDialog.tsx | 448 +++++++++++--------- 1 file changed, 253 insertions(+), 195 deletions(-) diff --git a/frontend/src/components/ExportRunDialog.tsx b/frontend/src/components/ExportRunDialog.tsx index 53a2de3..0aae192 100644 --- a/frontend/src/components/ExportRunDialog.tsx +++ b/frontend/src/components/ExportRunDialog.tsx @@ -2,6 +2,7 @@ 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 { FolderPicker } from './FolderPicker' /** * Run an export: confirm what is about to happen, then watch it happen. @@ -15,6 +16,12 @@ import { api, type ExportPreview, type ExportSet, type JobStatus } from '../api' * folder Konduktor did not write is REFUSED rather than confirmed. There is no * "do it anyway" — the whole point is that Konduktor never deletes what it did * not put there. + * + * The destination can be changed HERE, without going back to Edit: a wrong + * folder is usually noticed at this last look. The change is SAVED on the set, + * not used for this run only — a set is bound to its destination, and a run + * somewhere the set does not know would leave its next export (and the + * incremental re-export's manifest) pointing at the old folder. */ const POLL_MS = 300 @@ -40,6 +47,11 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { // starts from the same answer. Older sets without it read as on. const [lockGrids, setLockGrids] = useState(set.lock_grids ?? true) 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. + const [current, setCurrent] = useState(set) + const [browsing, setBrowsing] = useState(false) + const [moving, setMoving] = useState(false) // Platform names for wording the facts the preview and result carry as ids. const platforms = useQuery({ queryKey: ['export-targets'], queryFn: api.exportTargets }) @@ -50,7 +62,7 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { ) const preview = useQuery({ - queryKey: ['export-preview', set.id], + queryKey: ['export-preview', set.id, current.destination], queryFn: () => api.exportPreview(set.id), enabled: !job, staleTime: 0, @@ -87,6 +99,28 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { } }, [job, qc, set.id, onDone, onError]) + // Another set writing here would have its output replaced — the same warning + // the Edit dialog gives, since a folder can now be chosen here too. + const conflict = useQuery({ + queryKey: ['export-conflict', set.id, current.destination], + queryFn: () => api.exportContents(set.id), + enabled: !job, + }).data?.destination_conflict + + const changeDestination = async (destination: string) => { + if (destination === current.destination) return + setMoving(true) + try { + setCurrent(await api.updateExport(set.id, { destination })) + qc.invalidateQueries({ queryKey: ['exports'] }) + qc.invalidateQueries({ queryKey: ['export-contents', set.id] }) + } catch (e) { + onError((e as Error).message) + } finally { + setMoving(false) + } + } + const start = async () => { setStarting(true) try { @@ -122,212 +156,236 @@ export function ExportRunDialog({ set, onClose, onDone, onError }: Props) { const blocked = p?.blocked ?? null return createPortal( -
-
-
-

Export “{set.name}”

-
+ <> + {browsing && ( + setBrowsing(false)} + /> + )} +
+
+
+

Export “{set.name}”

+
-
- {!job && ( - <> -
- To -
- {set.destination} -
-
- - {preview.isLoading &&
Checking…
} - {preview.isError && ( -
{(preview.error as Error).message}
- )} - - {p && !blocked && ( -
-
- {p.exportable} track{p.exportable === 1 ? '' : 's'} - {p.playlists.length > 0 && - ` · ${p.playlists.length} playlist${p.playlists.length === 1 ? '' : 's'}`} - - {p.unchanged > 0 && ` · ${p.unchanged} unchanged`} · {gb(p.total_bytes)} to copy - +
+ {!job && ( + <> +
+ To +
+
+ {current.destination} +
+
- {p.free_bytes != null && ( -
- {gb(p.free_bytes)} free - {p.enough_space === false && ' — not enough space'} + {conflict && ( +
+ “{conflict}” already exports here. Exporting replaces whatever the other one + wrote.
)} - {/* Reported and skipped, not a failure halfway through a long - copy. A gig stick short four tracks must never be silent. */} - {p.missing.length > 0 && ( -
- {p.missing.length} track{p.missing.length === 1 ? '' : 's'} will be skipped — - the audio file is not on this disk: -
{p.missing.slice(0, 4).join(', ')}
-
- )} - {p.replacing && ( -
- This folder already holds an export. Tracks that haven’t changed are kept; everything else is replaced. -
- )} - {/* A warning, not a block: the other targets are fine anywhere, - and staging a stick's contents in a folder is legitimate. */} - {p.not_drive_root.length > 0 && ( -
- {p.not_drive_root.map(nameOf).join(' and ')} is only found at the top of a - drive, and this folder isn’t one — players won’t see it unless you move the - folder’s contents to a drive’s top level. -
- )} - {lockable && ( -
+ + {preview.isLoading &&
Checking…
} + {preview.isError && ( +
{(preview.error as Error).message}
+ )} + + {p && !blocked && ( +
+
+ {p.exportable} track{p.exportable === 1 ? '' : 's'} + {p.playlists.length > 0 && + ` · ${p.playlists.length} playlist${p.playlists.length === 1 ? '' : 's'}`} + + {p.unchanged > 0 && ` · ${p.unchanged} unchanged`} · {gb(p.total_bytes)} to copy - - )} -
- Writes a library for {set.targets.map(nameOf).join(' and ')}, sharing one copy - of every track under Contents/, in your own - folder structure. -
-
- )} - - {blocked === 'destination_not_empty' && ( -
- That folder already has files in it that Konduktor didn’t put there. An export - replaces what it wrote last time, so it will only write into an empty folder or - one of its own. Edit the export and choose somewhere else. -
- )} - {blocked === 'nothing_to_export' && p && p.tracks === 0 && ( -
- There’s nothing to export yet — add some tracks or a playlist. -
- )} - {/* Tracks exist but none of their audio does: saying "nothing to - export" here sends the user looking in the wrong place. */} - {blocked === 'nothing_to_export' && p && p.tracks > 0 && ( -
- None of the {p.tracks} track{p.tracks === 1 ? '' : 's'} can be exported — their - audio files are not on this disk: -
{p.missing.slice(0, 4).join(', ')}
-
- )} - {blocked === 'unsupported_target' && ( -
- Konduktor can’t write that kind of library yet. -
- )} - - )} - - {job && ( -
-
- {job.state === 'done' ? finishedLine(job.result) : job.message || 'Working…'} -
-
-
-
- {/* Tracks say their count in the message ("Analysing … (12/207)"). */} - {pct != null && running && job.unit === 'bytes' && ( -
- {gb(job.done)} of {gb(job.total)} -
- )} - {job.state === 'cancelled' && ( -
- Cancelled. Everything this export copied was removed, and no library was - written. -
- )} - {job.state === 'failed' && ( -
- {job.error} — nothing was left behind: no audio, and no library for any platform. -
- )} - {job.state === 'done' && ( -
-
Done — the folder is ready.
- {( - (job.result as { libraries?: { platform: string; library: string }[] } | null) - ?.libraries ?? [] - ).map((l) => ( -
- {nameOf(l.platform)}: {l.library}
- ))} -
- )} -
- )} -
+ {p.free_bytes != null && ( +
+ {gb(p.free_bytes)} free + {p.enough_space === false && ' — not enough space'} +
+ )} + {/* Reported and skipped, not a failure halfway through a long + copy. A gig stick short four tracks must never be silent. */} + {p.missing.length > 0 && ( +
+ {p.missing.length} track{p.missing.length === 1 ? '' : 's'} will be skipped — + the audio file is not on this disk: +
{p.missing.slice(0, 4).join(', ')}
+
+ )} + {p.replacing && ( +
+ This folder already holds an export. Tracks that haven’t changed are kept; everything else is replaced. +
+ )} + {/* A warning, not a block: the other targets are fine anywhere, + and staging a stick's contents in a folder is legitimate. */} + {p.not_drive_root.length > 0 && ( +
+ {p.not_drive_root.map(nameOf).join(' and ')} is only found at the top of a + drive, and this folder isn’t one — players won’t see it unless you move the + folder’s contents to a drive’s top level. +
+ )} + {lockable && ( + + )} +
+ Writes a library for {set.targets.map(nameOf).join(' and ')}, sharing one copy + of every track under Contents/, in your own + folder structure. +
+
+ )} -
- {running ? ( - <> - - - - ) : ( - <> - - {!finished && ( + {blocked === 'destination_not_empty' && ( +
+ That folder already has files in it that Konduktor didn’t put there. An export + replaces what it wrote last time, so it will only write into an empty folder or + one of its own. Choose another folder. +
+ )} + {blocked === 'nothing_to_export' && p && p.tracks === 0 && ( +
+ There’s nothing to export yet — add some tracks or a playlist. +
+ )} + {/* Tracks exist but none of their audio does: saying "nothing to + export" here sends the user looking in the wrong place. */} + {blocked === 'nothing_to_export' && p && p.tracks > 0 && ( +
+ None of the {p.tracks} track{p.tracks === 1 ? '' : 's'} can be exported — their + audio files are not on this disk: +
{p.missing.slice(0, 4).join(', ')}
+
+ )} + {blocked === 'unsupported_target' && ( +
+ Konduktor can’t write that kind of library yet. +
+ )} + + )} + + {job && ( +
+
+ {job.state === 'done' ? finishedLine(job.result) : job.message || 'Working…'} +
+
+
+
+ {/* Tracks say their count in the message ("Analysing … (12/207)"). */} + {pct != null && running && job.unit === 'bytes' && ( +
+ {gb(job.done)} of {gb(job.total)} +
+ )} + {job.state === 'cancelled' && ( +
+ Cancelled. Everything this export copied was removed, and no library was + written. +
+ )} + {job.state === 'failed' && ( +
+ {job.error} — nothing was left behind: no audio, and no library for any platform. +
+ )} + {job.state === 'done' && ( +
+
Done — the folder is ready.
+ {( + (job.result as { libraries?: { platform: string; library: string }[] } | null) + ?.libraries ?? [] + ).map((l) => ( +
+ {nameOf(l.platform)}: {l.library} +
+ ))} +
+ )} +
+ )} +
+ +
+ {running ? ( + <> - )} - - )} + + + ) : ( + <> + + {!finished && ( + + )} + + )} +
-
, + , document.body, ) } From d70a7c5de26ae4395083444ccc5ec01f2a89ed68 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 19 Oct 2026 14:07:54 +0200 Subject: [PATCH 03/11] Implemented track loudness analysis --- CLAUDE.md | 73 ++++- backend/konduktor/adapters/remote/__init__.py | 5 +- backend/konduktor/adapters/remote/adapter.py | 5 +- backend/konduktor/adapters/remote/client.py | 14 +- backend/konduktor/adapters/remote/services.py | 43 ++- backend/konduktor/app_state.py | 29 ++ backend/konduktor/core/loudness.py | 249 +++++++++++++++ backend/konduktor/loudness_store.py | 192 +++++++++++ backend/konduktor/main.py | 302 ++++++++++++++---- backend/konduktor/remote_protocol.py | 4 +- backend/konduktor/schemas.py | 47 ++- backend/konduktor/server/app.py | 40 ++- backend/konduktor/stems/convert.py | 46 ++- backend/konduktor/stems/remote_convert.py | 7 +- backend/requirements.txt | 3 + backend/run_tests.sh | 2 +- backend/test_loudness.py | 176 ++++++++++ backend/test_loudness_store.py | 250 +++++++++++++++ backend/test_remote_adapter.py | 24 ++ backend/test_remote_stems.py | 8 + backend/test_stems_batch.py | 19 ++ frontend/src/App.tsx | 98 ++++-- frontend/src/api.ts | 37 ++- frontend/src/components/AnalyzeDialog.tsx | 84 +++-- frontend/src/components/PrepStrip.tsx | 21 +- frontend/src/lib/format.test.ts | 21 ++ frontend/src/lib/format.ts | 11 + frontend/src/lib/trackColumns.tsx | 66 +++- 28 files changed, 1732 insertions(+), 144 deletions(-) create mode 100644 backend/konduktor/core/loudness.py create mode 100644 backend/konduktor/loudness_store.py create mode 100644 backend/test_loudness.py create mode 100644 backend/test_loudness_store.py create mode 100644 frontend/src/lib/format.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index a048cb3..c912eda 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -149,6 +149,22 @@ Two independent apps that talk over HTTP: always skipped. `main._analyse_grid` writes each through the hand-edit command for the same thing — `set_grid_marker_bpm(0)` / `move_grid_marker(0)` — so companions, marker names and time bases behave as for a hand edit. + - `loudness.py` — **loudness measurement**, the Mastering columns + (decided 2026-10-19, [the discussion](.claude/discussions/discuss-loudness-analysis-2026-10-19.md)): + integrated LUFS (BS.1770-4 / R128 gating), LRA (Tech 3342), true peak + (4x oversampled below 96 kHz), PLR (= true peak − LUFS) and **RMS = the + DR meter's convention**: power in non-overlapping 3 s blocks, channels + averaged, the mean of the LOUDEST 20%, AES17 sine-referenced (a full-scale + sine reads 0 dB, a square +3) — unweighted, so beside LUFS it shows bass + weight, and a long intro does not pull it down. It decodes on its OWN, at + the file's rate and channels: the analysis decode (mono 22.05 kHz) cannot + serve BS.1770 (it sums channel POWERS) nor true peak. Streams in chunks + from per-100 ms sums, so memory stays at seconds of audio; ~1 s per + track. Matches FFmpeg's `ebur128` (in PyAV's wheel — `test_loudness.py` + uses it as the reference meter) to 0.01 LU; on an inter-sample peak it is + closer to exact than FFmpeg's interpolator. Mixed In Key, the requester's + reference, shows no RMS or LUFS at all (researched), so nothing was + matched. `VERSION` bumps make stored values stale. - `key_detect.py` + `key_model.npz` — **musical key detection**: a small CNN (Korzeniowski & Widmer 2017 — five 5x5 convs, a per-frame dense layer over the WHOLE pitch axis, since a key is not pitch-invariant, logits @@ -733,6 +749,29 @@ Two independent apps that talk over HTTP: `RelocateDialog` always asks — found volumes ticked, ambiguous ones a radio with nothing preselected, missing ones "Not connected" with a "Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss. + - `loudness_store.py` — **where loudness lives: Konduktor's own store, keyed + by the audio file's PATH** (SQLite in app-data; stdlib, so the server has it + too) — never the library, never file tags (a measurement can be redone + from the audio, and nothing but Konduktor would read a tag). Size + mtime + are recorded but are NOT the key: a changed file keeps its value, shown + STALE (dimmed, still sorted on, offered for re-analysis), because a changed + mtime almost always means another app rewrote the tags. `AppState._save` + `refresh`es the facts of every file Konduktor itself just tagged, so its + own writes never stale a value; `/api/library/remap-paths` `remap`s the + keys. Written AT ONCE, outside the edit/Save cycle — never dirty, survives + Discard. `STATE.loudness` is this computer's store, or for a remote library + `RemoteLoudnessStore` (the SERVER's: `/v1/loudness/get`, `PUT /v1/loudness` + — session required, not `touch`ed). `main._loud_target(origin, id)` picks + source + store per id: collection = the library's; device / Files folder = + this computer's; a folder id that is not a listed file falls back to the + collection (a folder view's held rows). `/api/loudness` serves a list's + values through `audio_facts` (never downloads); Analyze's Loudness tick and + `/api/tracks/loudness` (the deck where no grid can be written) measure, for + ANY origin — BPM / Grid / Key stay collection-only (400 otherwise). Convert + to Stems RE-measures a stem file whose original was measured (AAC can move + the true peak; never carried over): `convert.stem_loudness` after the + build, stored at publish by the shared `_end_step` — remotely, the value + rides `/v1/stems/stage`. - `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 @@ -1004,9 +1043,13 @@ Two independent apps that talk over HTTP: shown where Save is pressed). `Toast` takes an optional `action`; `StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares. `AnalyzeDialog` (the context menu's **Analyze…**, decided 2026-10-04: - BPM / Grid / Key ticks, remembered as `analyzeWhat`, each disabled with a - reason where the library cannot store it — offered when EITHER grids or - keys are writable; the Replace questions are inside the dialog, never a + BPM / Grid / Key / Loudness ticks, remembered as `analyzeWhat` (a tick that + was disabled keeps its saved value), BPM / Grid / Key each disabled with a + reason where they cannot be stored (`gridWhy` / `keyWhy`: a device, loose + files, a read-only library). Loudness is never disabled, so the item is + offered for ANY selection, with the selection's `origin` (2026-10-19); + where loudness is all that can be done it is pre-ticked. The Replace + questions (loudness: "Measure again") are inside the dialog, never a second popup, and never remembered: the grid's only when BPM AND Grid are ticked, since with one tick adjusting the grid is the point. Every count and the "Analyze N" button come from `/api/tracks/analyze/preview`, i.e. @@ -1186,6 +1229,14 @@ Two independent apps that talk over HTTP: - `lib/trackColumns.tsx` — single source of truth for the library table's columns (defs, default widths/visibility/order, the Columns-menu list, the inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). + The five **Mastering** columns (LUFS, RMS, True Peak, LRA, PLR; hidden by + default) sit in the header chooser's first submenu (`COLUMN_MENU`'s + `group`); cells carry their unit (`formatLoudness`), stale = dimmed with a + tooltip. Their accessor returns `undefined` when unmeasured with + `sortUndefined: 'last'` — TanStack sorts `null` as 0, which would rank + every unmeasured track loudest. `Track.loudness` is NOT the backend's: App + joins `/api/loudness` into the rows (`['loudness', origin, hash of ids]`), + only while a Mastering column is visible; analyses invalidate `['loudness']`. - Data flow: the whole library is fetched once (`/api/tracks?limit=20000`); filtering and sorting happen **client-side** for instant interaction. Edits apply in-memory (server holds them) and the sidebar **Save to Traktor** @@ -1456,6 +1507,22 @@ serialization path.** It enforces: model), loudness / sample-rate invariance, None for silence, and the numpy convolution against a direct implementation. Accuracy on real music is `bench_key_detect.py`'s job (GiantSteps + any folder of key-tagged files). +- `test_loudness.py` — loudness measurement on GENERATED signals against + FFmpeg's `ebur128` through PyAV (integrated ±0.1 LU, LRA ±0.3, true peak + ±0.2 dB, 44.1/48 kHz, mono), the standard's anchors (a -23 dBFS 1 kHz stereo + sine = -23.0 LUFS; an inter-sample peak = -6.02 dBTP), RMS's definition (a + full-scale sine 0.0, a square +3.01, a long quiet intro moves nothing), + silence / under 3 s = None, chunked feeding equals one pass, and real files + at their own rate and channels. +- `test_loudness_store.py` — the store (stale on facts or version, remap with + the new path winning, concurrent writers) and the routes on generated FLACs: + a Files folder measured with BPM refused, preview counts = the run's, skip + unless Replace, a touched file stale with its value kept, the deck route, + the same file's value seen from the collection, a Save's own tag write not + staling it, Discard keeping it, a remap carrying it, a device's undecodable + stubs reported per track. `test_stems_batch.py` / `test_remote_stems.py` + pin the stem re-measure, `test_remote_adapter.py` the server-side store + (423 without the session, 503 once taken over). - `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/remote/__init__.py b/backend/konduktor/adapters/remote/__init__.py index cca00fe..53f4403 100644 --- a/backend/konduktor/adapters/remote/__init__.py +++ b/backend/konduktor/adapters/remote/__init__.py @@ -18,7 +18,7 @@ from ... import exports from . import config from .adapter import RemoteAdapter from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch -from .services import RemotePending, RemoteServices, RemoteSetStore +from .services import RemoteLoudnessStore, RemotePending, RemoteServices, RemoteSetStore from .session import RemoteSession __all__ = [ @@ -38,6 +38,8 @@ class Opened: pending: object | None #: Edits another computer left unsaved: {machine, summary}, or None. pending_edits: dict | None + #: The server's loudness store (`RemoteLoudnessStore`). + loudness: object | None = None def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=None, @@ -71,6 +73,7 @@ def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=No remote=remote, path=Path(hello.get("path") or remote.name), adapter=adapter, services=RemoteServices(client), session=session, library_id=library_id, pending=RemotePending(client), pending_edits=acquired.get("pending_edits"), + loudness=RemoteLoudnessStore(client, session), ) diff --git a/backend/konduktor/adapters/remote/adapter.py b/backend/konduktor/adapters/remote/adapter.py index c10b7dd..ee0c314 100644 --- a/backend/konduktor/adapters/remote/adapter.py +++ b/backend/konduktor/adapters/remote/adapter.py @@ -360,7 +360,7 @@ class RemoteAdapter: return self.client.stems_plan(body) def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int, - duration: float, progress=None) -> dict: + duration: float, loudness: dict | None = None, progress=None) -> dict: import hashlib digest = hashlib.sha256() @@ -369,7 +369,8 @@ class RemoteAdapter: digest.update(chunk) try: return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(), - bit_rate=bit_rate, duration=duration, progress=progress) + bit_rate=bit_rate, duration=duration, loudness=loudness, + progress=progress) except SessionLost as ex: self.session.lost(ex.holder) raise diff --git a/backend/konduktor/adapters/remote/client.py b/backend/konduktor/adapters/remote/client.py index 9e45487..79920e9 100644 --- a/backend/konduktor/adapters/remote/client.py +++ b/backend/konduktor/adapters/remote/client.py @@ -13,6 +13,8 @@ remote library's refusal exactly as it would a local one's. """ from __future__ import annotations +import json + import logging import threading from pathlib import Path @@ -277,7 +279,7 @@ class RemoteClient: return self.request("POST", "/v1/stems/plan", json=body, timeout=None).json() def stems_stage(self, track_id: str, target: str, source: Path, *, sha256: str, - bit_rate: int, duration: float, progress=None) -> dict: + bit_rate: int, duration: float, loudness: dict | None = None, progress=None) -> dict: def body(): with open(source, "rb") as f: while chunk := f.read(1 << 20): @@ -288,7 +290,8 @@ class RemoteClient: return self.request( "PUT", "/v1/stems/stage", params={"track_id": track_id, "target": target, "sha256": sha256, - "bit_rate": bit_rate, "duration": duration}, + "bit_rate": bit_rate, "duration": duration, + **({"loudness": json.dumps(loudness)} if loudness else {})}, content=body(), retry=False, timeout=None, ).json() @@ -323,3 +326,10 @@ class RemoteClient: def put_export_sets(self, doc: dict) -> None: self.request("PUT", "/v1/export-sets", json=doc) + + # ---- loudness ---------------------------------------------------------------------- + def loudness_get(self, paths: list[str]) -> list[dict]: + return self.request("POST", "/v1/loudness/get", json={"paths": paths}).json()["entries"] + + def loudness_put(self, entries: list[dict]) -> None: + self.request("PUT", "/v1/loudness", json={"entries": entries}) diff --git a/backend/konduktor/adapters/remote/services.py b/backend/konduktor/adapters/remote/services.py index df96bc1..a22b7ca 100644 --- a/backend/konduktor/adapters/remote/services.py +++ b/backend/konduktor/adapters/remote/services.py @@ -9,7 +9,7 @@ from __future__ import annotations from ...core.adapter import NotFound from ...history import HistoryEntry -from .client import RemoteClient +from .client import RemoteClient, SessionLost class RemoteServices: @@ -83,3 +83,44 @@ class RemotePending: def commit(self) -> dict: return {} + + +class RemoteLoudnessStore: + """A remote library's loudness measurements, kept in the SERVER's store + (`loudness_store.py`) so every computer that opens it sees them. This + computer measures (the server never decodes) and sends the values; storing + needs the session, like every write to the server.""" + + available = True + _CHUNK = 2000 + + def __init__(self, client: RemoteClient, session=None): + self.client = client + self.session = session + + def get(self, paths: list[str]): + from ...loudness_store import Entry + + out = {} + for i in range(0, len(paths), self._CHUNK): + for d in self.client.loudness_get(paths[i:i + self._CHUNK]): + out[d["path"]] = Entry.from_wire(d) + return out + + def put(self, facts, values) -> None: + from ...core import loudness + + entry = {"path": facts.key, "size": facts.size, "mtime_ns": facts.mtime_ns, + "version": loudness.VERSION, **values.as_dict()} + try: + self.client.loudness_put([entry]) + except SessionLost as ex: + if self.session is not None: + self.session.lost(ex.holder) + raise + + def refresh(self, paths: list[str]) -> None: + """The server's own save refreshes after its tag writes.""" + + def remap(self, mapping) -> int: + return 0 # a remote library's paths are the server's business diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py index 1220921..d3ac9a9 100644 --- a/backend/konduktor/app_state.py +++ b/backend/konduktor/app_state.py @@ -24,6 +24,7 @@ human summary, and this module versions them. """ from __future__ import annotations +import logging import os import threading from pathlib import Path @@ -35,6 +36,8 @@ from .core.pathmap import PathMapping from .relocation import RelocationCheck from .services import LibraryServices, LocalServices +log = logging.getLogger(__name__) + class AppState: """Holds the currently-loaded library (selectable at runtime).""" @@ -74,6 +77,21 @@ class AppState: # restore, which reopens): how a Konduktor SERVER re-applies the path # mapping its configuration names, which lives in no prefs file. self.open_hooks: list = [] + # A remote library's loudness store (on its server); None = this + # computer's own. Read through `loudness`. + self._remote_loudness = None + + @property + def loudness(self): + """Where the loaded library's loudness measurements live: the server's + store for a remote library, this computer's otherwise (see + `loudness_store.py`). Not tied to the adapter: a measurement belongs to + the FILE, so it outlives opening another library.""" + if self._remote_loudness is not None: + return self._remote_loudness + from . import loudness_store + + return loudness_store.local() @property def loaded(self) -> bool: @@ -189,6 +207,7 @@ class AppState: self.adapter = None self.remote = None self.remote_config = None + self._remote_loudness = None def open_remote(self, opened) -> None: """Make an already-connected remote library THE library. @@ -211,6 +230,7 @@ class AppState: # The server keeps its own ledger of converted tracks; nothing of a # remote library's lives in this computer's. self.pending = opened.pending + self._remote_loudness = opened.loudness self.recovery = None # A remote library's files are not on this computer's drives. self.relocation = None @@ -229,6 +249,15 @@ class AppState: def _save(self): outcome = self.adapter.save() commit = self.services.commit_save(self.adapter, outcome) + # Konduktor itself just rewrote these files' tags: a loudness value + # measured before must not read as stale because of it. (On a remote + # library the server's own save does this; the client's store skips it.) + written = [r.file for r in outcome.tag_results if getattr(r, "ok", False) and getattr(r, "file", None)] + if written: + try: + self.loudness.refresh(written) + except Exception: # noqa: BLE001 — bookkeeping must never fail a save + log.warning("could not refresh loudness facts after save", exc_info=True) # The swap is now on disk: what it replaced can go. After the library # write, so a failed save deletes nothing; here rather than in the save # route, because import and path remap save too. diff --git a/backend/konduktor/core/loudness.py b/backend/konduktor/core/loudness.py new file mode 100644 index 0000000..954ad78 --- /dev/null +++ b/backend/konduktor/core/loudness.py @@ -0,0 +1,249 @@ +"""Loudness measurement: integrated LUFS, RMS, true peak, LRA and PLR. + +The Mastering columns. Each value is a property of the AUDIO, measured once per +file and kept in Konduktor's own store (`konduktor/loudness_store.py`) — never +in the library and never in file tags (decided 2026-10-19, see +`.claude/discussions/discuss-loudness-analysis-2026-10-19.md`). + +- **Integrated loudness** (LUFS): ITU-R BS.1770-4 / EBU R128 — K-weighting, + 400 ms blocks every 100 ms, the absolute gate at -70 LUFS and the relative + one 10 LU below the absolute-gated mean. +- **LRA** (LU): EBU Tech 3342 — 3 s short-term loudness every 100 ms, gated at + -70 LUFS and 20 LU below their mean, then P95 - P10. +- **True peak** (dBTP): BS.1770 Annex 2 — the signal oversampled (4x below + 96 kHz, 2x below 192 kHz), the largest magnitude over every channel. +- **PLR** (dB): true peak minus integrated loudness. Low = a crushed master. +- **RMS** (dB): the DR meter's convention (foobar2000 / TT DR / FFmpeg + `drmeter`) — power in non-overlapping 3 s blocks, channels averaged, the mean + of the LOUDEST 20% of blocks. Unweighted, so beside LUFS it shows bass + weight; over the loud blocks only, so a long intro does not pull it down + ("how hot does the drop hit"). AES17 sine-referenced: a full-scale sine + reads 0 dB, a full-scale square +3 dB (square-referenced meters read 3 dB + lower — the usual source of disagreeing RMS figures). + +Everything is computed from per-100 ms sums of the K-weighted and of the raw +signal's power, so a track streams through in chunks: memory stays at a few +seconds of audio however long the file. The decode is the file's OWN rate and +channels — not the analysis decode (`waveform.load`, mono 22.05 kHz), which +BS.1770 cannot use (it sums channel POWERS) and which would hide true peaks. + +`test_loudness.py` checks it against FFmpeg's `ebur128` filter (bundled in +PyAV's wheel) on generated signals. +""" +from __future__ import annotations + +import math +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np + +#: Bump when a measurement changes: stored values from an older version count +#: as stale and are offered for re-analysis. +VERSION = 1 + +_ABS_GATE = -70.0 # LUFS +_REL_GATE = -10.0 # LU, integrated +_LRA_REL_GATE = -20.0 # LU, loudness range +_RMS_TOP = 0.2 # the loudest fifth of the 3 s blocks +_AES17 = 10.0 * math.log10(2.0) # +3.01 dB: a sine's mean square is half its peak squared +_TP_PAD = 32 # samples of context either side of an oversampled chunk + + +@dataclass(frozen=True) +class Loudness: + lufs: float + rms: float + true_peak: float + lra: float + plr: float + + def as_dict(self) -> dict[str, float]: + return asdict(self) + + @classmethod + def from_dict(cls, d: dict) -> "Loudness": + return cls(**{k: float(d[k]) for k in ("lufs", "rms", "true_peak", "lra", "plr")}) + + +def _k_weighting(sr: int) -> np.ndarray: + """BS.1770's two K-weighting biquads at any rate, as second-order sections. + The analogue prototype's constants are libebur128's (and FFmpeg's), which + reproduce the standard's 48 kHz coefficients exactly.""" + # Stage 1: the high shelf (+4 dB above ~1.7 kHz) modelling the head. + f0, gain, q = 1681.974450955533, 3.999843853973347, 0.7071752369554196 + k = math.tan(math.pi * f0 / sr) + vh = 10.0 ** (gain / 20.0) + vb = vh ** 0.4996667741545416 + a0 = 1.0 + k / q + k * k + shelf = [(vh + vb * k / q + k * k) / a0, 2.0 * (k * k - vh) / a0, (vh - vb * k / q + k * k) / a0, + 1.0, 2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0] + # Stage 2: the RLB high-pass (~38 Hz). + f0, q = 38.13547087602444, 0.5003270373238773 + k = math.tan(math.pi * f0 / sr) + a0 = 1.0 + k / q + k * k + highpass = [1.0, -2.0, 1.0, 1.0, 2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0] + return np.array([shelf, highpass]) + + +class _Meter: + """Consumes `(channels, n)` float blocks in order; `result()` measures.""" + + def __init__(self, sr: int, channels: int): + from scipy import signal + + self._signal = signal + self.sr = sr + self.seg = max(1, round(sr / 10)) # 100 ms + self._sos = _k_weighting(sr) + self._zi = np.zeros((self._sos.shape[0], channels, 2)) + self._pending = np.zeros((channels, 0), dtype=np.float32) + self._k_sums: list[np.ndarray] = [] # (channels, segs) K-weighted energy + self._raw_sums: list[np.ndarray] = [] # (channels, segs) raw energy + self._up = 4 if sr < 96000 else 2 if sr < 192000 else 1 + self._tp_tail = np.zeros((channels, _TP_PAD), dtype=np.float32) + self._peak = 0.0 + + def feed(self, block: np.ndarray) -> None: + self._true_peak(block) + self._pending = np.concatenate([self._pending, block.astype(np.float32, copy=False)], axis=1) + whole = (self._pending.shape[1] // self.seg) * self.seg + if whole: + self._segments(self._pending[:, :whole]) + self._pending = self._pending[:, whole:] + + def _segments(self, x: np.ndarray) -> None: + ch = x.shape[0] + y, self._zi = self._signal.sosfilt(self._sos, x, axis=1, zi=self._zi) + n = x.shape[1] // self.seg + self._k_sums.append(np.square(y, dtype=np.float64).reshape(ch, n, self.seg).sum(axis=2)) + self._raw_sums.append(np.square(x, dtype=np.float64).reshape(ch, n, self.seg).sum(axis=2)) + + def _true_peak(self, block: np.ndarray, final: bool = False) -> None: + """The oversampled peak of every sample whose context has arrived: the + last `_TP_PAD` samples wait for the next block (or the end).""" + buf = np.concatenate([self._tp_tail, block.astype(np.float32, copy=False)], axis=1) + if final: + buf = np.concatenate([buf, np.zeros((buf.shape[0], _TP_PAD), dtype=np.float32)], axis=1) + valid = buf.shape[1] - 2 * _TP_PAD + if valid <= 0: + self._tp_tail = buf if not final else self._tp_tail + return + if self._up > 1: + over = self._signal.resample_poly(buf, self._up, 1, axis=1) + region = over[:, _TP_PAD * self._up:(_TP_PAD + valid) * self._up] + else: + region = buf[:, _TP_PAD:_TP_PAD + valid] + sample = buf[:, _TP_PAD:_TP_PAD + valid] + self._peak = max(self._peak, float(np.max(np.abs(region))), float(np.max(np.abs(sample)))) + self._tp_tail = buf[:, -2 * _TP_PAD:] + + def result(self) -> Loudness | None: + self._true_peak(np.zeros((self._tp_tail.shape[0], 0), dtype=np.float32), final=True) + if not self._k_sums: + return None + k = np.concatenate(self._k_sums, axis=1).sum(axis=0) # channel powers summed (G = 1) + raw = np.concatenate(self._raw_sums, axis=1).mean(axis=0) + segs = k.shape[0] + if segs < 30: # under 3 s: no short-term block + return None + lufs = _integrated(k, self.seg) + if lufs is None: + return None + lra = _loudness_range(k, self.seg) + rms = _rms(raw, self.seg) + if self._peak <= 0.0 or rms is None: + return None + true_peak = 20.0 * math.log10(self._peak) + return Loudness(lufs=lufs, rms=rms, true_peak=true_peak, lra=lra, plr=true_peak - lufs) + + +def _windows(segment_sums: np.ndarray, width: int, seg: int) -> np.ndarray: + """Mean square of every `width`-segment window, one window per segment.""" + c = np.concatenate([[0.0], np.cumsum(segment_sums)]) + return (c[width:] - c[:-width]) / (width * seg) + + +def _lufs(z: np.ndarray) -> np.ndarray: + with np.errstate(divide="ignore"): + return -0.691 + 10.0 * np.log10(z) + + +def _integrated(k: np.ndarray, seg: int) -> float | None: + z = _windows(k, 4, seg) # 400 ms blocks, 100 ms apart + z = z[_lufs(z) > _ABS_GATE] + if not z.size: + return None + threshold = _lufs(np.array([z.mean()]))[0] + _REL_GATE + z = z[_lufs(z) > threshold] + return float(_lufs(np.array([z.mean()]))[0]) if z.size else None + + +def _loudness_range(k: np.ndarray, seg: int) -> float: + z = _windows(k, 30, seg) # 3 s short-term, 100 ms apart + z = z[_lufs(z) > _ABS_GATE] + if not z.size: + return 0.0 + threshold = _lufs(np.array([z.mean()]))[0] + _LRA_REL_GATE + levels = _lufs(z) + levels = levels[levels > threshold] + if not levels.size: + return 0.0 + lo, hi = np.percentile(levels, [10, 95]) + return float(hi - lo) + + +def _rms(raw: np.ndarray, seg: int) -> float | None: + blocks = raw.shape[0] // 30 # non-overlapping 3 s blocks + if not blocks: + return None + power = raw[:blocks * 30].reshape(blocks, 30).sum(axis=1) / (30 * seg) + top = np.sort(power)[::-1][:max(1, int(round(blocks * _RMS_TOP)))] + mean = float(top.mean()) + return 10.0 * math.log10(mean) + _AES17 if mean > 0 else None + + +def measure(pcm: np.ndarray, sr: int) -> Loudness | None: + """Measure `(channels, n)` (or mono `(n,)`) float audio at `sr`. None for + silence or anything under 3 s.""" + pcm = np.atleast_2d(np.asarray(pcm, dtype=np.float32)) + meter = _Meter(sr, pcm.shape[0]) + step = meter.seg * 100 + for start in range(0, pcm.shape[1], step): + meter.feed(pcm[:, start:start + step]) + return meter.result() + + +def measure_file(path: Path | str) -> Loudness | None: + """Decode `path` at its own rate and channel count (more than two are + downmixed to stereo; mono stays mono, as BS.1770 and FFmpeg treat it) and + measure it as it streams. Raises if the file cannot be decoded.""" + import av + + from . import pyav + + with pyav.open_input(path) as container: + stream = container.streams.audio[0] + sr = int(stream.codec_context.sample_rate) + channels = 1 if stream.codec_context.channels == 1 else 2 + resampler = av.AudioResampler(format="fltp", layout="mono" if channels == 1 else "stereo", rate=sr) + meter = _Meter(sr, channels) + pending: list[np.ndarray] = [] + size = 0 + + def flush() -> None: + nonlocal pending, size + if pending: + meter.feed(np.concatenate(pending, axis=1)) + pending, size = [], 0 + + for frame in container.decode(stream): + for out in resampler.resample(frame): + pending.append(out.to_ndarray()) + size += out.samples + if size >= sr * 5: # ~5 s per feed + flush() + for out in resampler.resample(None): + pending.append(out.to_ndarray()) + flush() + return meter.result() diff --git a/backend/konduktor/loudness_store.py b/backend/konduktor/loudness_store.py new file mode 100644 index 0000000..a44c23b --- /dev/null +++ b/backend/konduktor/loudness_store.py @@ -0,0 +1,192 @@ +"""Where loudness measurements live: Konduktor's own store, keyed by file PATH. + +Not the library and not the file's tags (decided 2026-10-19, +`.claude/discussions/discuss-loudness-analysis-2026-10-19.md`): a measurement +can always be made again from the audio, so it is cache-shaped, and nothing but +Konduktor would read a tag. Keyed by the audio file's path — on a remote +library the SERVER's path, in the server's own store — with the file's size and +mtime recorded beside the values. Those facts are NOT part of the key: a file +whose facts changed keeps its values, shown STALE until re-analysed, because a +changed mtime almost always means another app rewrote the tags (keying on the +facts, as `analysis_cache` / `stream_cache` do, would orphan the value on every +tag edit). Konduktor's own tag writes `refresh` the facts, so they never stale +a value; a path remap `remap`s the keys. + +Writing is immediate and outside the edit/Save cycle: a measurement is not an +edit, so it never makes the library dirty and Discard does not remove it. + +SQLite (stdlib, so the lightweight server image has it too) rather than JSON: +a batch writes one row per track over a store that holds the whole library. +""" +from __future__ import annotations + +import os +import sqlite3 +import threading +from dataclasses import dataclass +from pathlib import Path +from typing import Protocol + +from .core import loudness +from .core.adapter import AudioFacts +from .core.loudness import Loudness +from .core.pathmap import PathMapping + +_FILE = "loudness.sqlite3" +_CHUNK = 500 # paths per IN (...) query + + +@dataclass(frozen=True) +class Entry: + values: Loudness + size: int + mtime_ns: int + version: int + + def stale(self, facts: AudioFacts | None) -> bool: + """The file changed since it was measured, or the measurement has.""" + if self.version < loudness.VERSION: + return True + return facts is not None and (facts.size != self.size or facts.mtime_ns != self.mtime_ns) + + def wire(self, path: str) -> dict: + return {"path": path, "size": self.size, "mtime_ns": self.mtime_ns, + "version": self.version, **self.values.as_dict()} + + @classmethod + def from_wire(cls, d: dict) -> "Entry": + return cls(values=Loudness.from_dict(d), size=int(d["size"]), + mtime_ns=int(d["mtime_ns"]), version=int(d["version"])) + + +class LoudnessStore(Protocol): + #: False only for a remote server too old to hold measurements. + available: bool + + def get(self, paths: list[str]) -> dict[str, Entry]: ... + + def put(self, facts: AudioFacts, values: Loudness) -> None: ... + + def refresh(self, paths: list[str]) -> None: ... + + def remap(self, mapping: PathMapping) -> int: ... + + +def _norm(path: str) -> str: + return os.path.normpath(path) + + +class LocalLoudnessStore: + """The store on this machine (on a server: the server's).""" + + available = True + + def __init__(self, db_path: Path): + db_path.parent.mkdir(parents=True, exist_ok=True) + self._lock = threading.Lock() + self._db = sqlite3.connect(str(db_path), check_same_thread=False) + with self._lock, self._db: + self._db.execute("PRAGMA journal_mode=WAL") + self._db.execute( + "CREATE TABLE IF NOT EXISTS loudness (" + " path TEXT PRIMARY KEY, size INTEGER NOT NULL, mtime_ns INTEGER NOT NULL," + " version INTEGER NOT NULL, lufs REAL NOT NULL, rms REAL NOT NULL," + " true_peak REAL NOT NULL, lra REAL NOT NULL, plr REAL NOT NULL)") + + def get(self, paths: list[str]) -> dict[str, Entry]: + """Entries for those of `paths` that were measured, keyed as ASKED.""" + asked = {_norm(p): p for p in paths} + keys = list(asked) + out: dict[str, Entry] = {} + with self._lock: + for i in range(0, len(keys), _CHUNK): + chunk = keys[i:i + _CHUNK] + rows = self._db.execute( + "SELECT path, size, mtime_ns, version, lufs, rms, true_peak, lra, plr" + f" FROM loudness WHERE path IN ({','.join('?' * len(chunk))})", chunk) + for path, size, mtime_ns, version, *values in rows: + out[asked[path]] = Entry(Loudness(*values), size, mtime_ns, version) + return out + + def put(self, facts: AudioFacts, values: Loudness) -> None: + self.put_many([(facts, values)]) + + def put_many(self, items: list[tuple[AudioFacts, Loudness]]) -> None: + rows = [(_norm(f.key), f.size, f.mtime_ns, loudness.VERSION, v.lufs, v.rms, v.true_peak, v.lra, v.plr) + for f, v in items] + with self._lock, self._db: + self._db.executemany("INSERT OR REPLACE INTO loudness VALUES (?,?,?,?,?,?,?,?,?)", rows) + + def put_entries(self, entries: list[dict]) -> None: + """Wire entries (a remote client's measurements), versions as sent.""" + rows = [] + for d in entries: + e = Entry.from_wire(d) + v = e.values + rows.append((_norm(str(d["path"])), e.size, e.mtime_ns, e.version, + v.lufs, v.rms, v.true_peak, v.lra, v.plr)) + with self._lock, self._db: + self._db.executemany("INSERT OR REPLACE INTO loudness VALUES (?,?,?,?,?,?,?,?,?)", rows) + + def refresh(self, paths: list[str]) -> None: + """Konduktor itself just rewrote these files (tags at Save): take their + current facts, so its own writes never stale a value. Only rows that + exist are touched.""" + rows = [] + for p in paths: + try: + st = os.stat(p) + except OSError: + continue + rows.append((st.st_size, st.st_mtime_ns, _norm(p))) + if rows: + with self._lock, self._db: + self._db.executemany("UPDATE loudness SET size = ?, mtime_ns = ? WHERE path = ?", rows) + + def remap(self, mapping: PathMapping) -> int: + """A path remap moved the library's files from `from` to `to`: carry + every value measured under `from` across. A value already measured at + the new path wins. Returns how many moved.""" + if mapping.empty: + return 0 + moved = 0 + with self._lock, self._db: + paths = [r[0] for r in self._db.execute("SELECT path FROM loudness")] + for old in paths: + if not mapping.matches(Path(old)): + continue + new = _norm(str(mapping.apply(Path(old)))) + if new == old: + continue + if self._db.execute("SELECT 1 FROM loudness WHERE path = ?", (new,)).fetchone(): + self._db.execute("DELETE FROM loudness WHERE path = ?", (old,)) + else: + self._db.execute("UPDATE loudness SET path = ? WHERE path = ?", (new, old)) + moved += 1 + return moved + + def close(self) -> None: + with self._lock: + self._db.close() + + +_LOCAL: dict[str, LocalLoudnessStore] = {} +_LOCAL_LOCK = threading.Lock() + + +def local() -> LocalLoudnessStore: + """This machine's store — one per data directory, so a test (or the server) + pointing `KONDUKTOR_DATA_DIR` elsewhere gets its own.""" + from . import paths + + db = paths.app_data_dir() / _FILE + with _LOCAL_LOCK: + store = _LOCAL.get(str(db)) + if store is None: + store = _LOCAL[str(db)] = LocalLoudnessStore(db) + return store + + +def file_facts(path: Path | str) -> AudioFacts: + st = os.stat(path) + return AudioFacts(key=str(path), size=st.st_size, mtime_ns=st.st_mtime_ns) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 7de093c..0847ef1 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -8,6 +8,7 @@ from __future__ import annotations import logging import os +from dataclasses import dataclass from pathlib import Path from types import SimpleNamespace @@ -15,10 +16,10 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse -from . import __version__, exporter, exports, prefs +from . import __version__, exporter, exports, loudness_store, prefs from .app_state import STATE from .core import auto_hotcues as ah -from .core import grid_detect, key_detect, structure +from .core import grid_detect, key_detect, loudness, structure from .core.grid_plan import GridStep, plan_grid from . import importer from .core import export as core_export @@ -44,6 +45,10 @@ from .schemas import ( RelocationVolume, AnalyzePreview, AnalyzeRequest, + LoudnessRequest, + LoudnessValue, + LoudnessValues, + MeasureLoudnessRequest, AutoGridBatchRequest, AutoGridRequest, AutoCueOutcome, @@ -456,6 +461,12 @@ def remap_paths(body: PathMappingInfo) -> RemapResult: return RemapResult(rewritten=0, commit=None) if moved and STATE.library_id: exports.retarget(STATE.library_id, moved) + # The files now live under `to`: carry their loudness values across (they + # are keyed by the path they were measured at). Not an edit, so not saved. + try: + STATE.loudness.remap(mapping) + except Exception: # noqa: BLE001 — bookkeeping must never fail a remap + log.warning("could not move loudness values for %s", mapping, exc_info=True) # Through AppState, not the adapter: this is the one route besides /api/save # that writes, and skipping it would leave a gap in the version history. _outcome, commit = STATE.save() @@ -1543,6 +1554,14 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: a.set_key(body.track_id, found.wheel, found.mode) except Exception: # noqa: BLE001 — the grid is written; a key is a bonus log.warning("key detection failed for %s", body.track_id, exc_info=True) + 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) + except _AnalysisError as ex: + log.warning("no loudness for %s: %s", body.track_id, ex) + except Exception: # noqa: BLE001 + log.warning("loudness measurement failed for %s", body.track_id, exc_info=True) return cues @@ -1635,10 +1654,14 @@ def _analyse_grid(a, track_id: str, step: GridStep = GridStep("full"), *, # ---- Analyze (the context menu's "Analyze…": BPM / Grid / Key) ------------- -def _require_analysable(a, body: AnalyzeRequest) -> None: - caps = a.capabilities() +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): - raise HTTPException(400, "Nothing to analyse: tick BPM, Grid or Key") + 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") + 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: @@ -1665,30 +1688,46 @@ def _wants_key(track, body: AnalyzeRequest) -> bool: @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.""" - a = require_adapter() + """Counts for the Analyze dialog, from the same `plan_grid` the run uses + (and, for loudness, the same store lookups).""" + 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) for tid in dict.fromkeys(body.track_ids): - track = a.track(tid) - if track is None: + if a is not None: + track = a.track(tid) + if track is None: + continue + elif tid not in looked: continue out.total += 1 - if track.grid_marker_count and not track.grid_locked: - out.with_grid += 1 - step = _grid_step(a, track, body, exact=False) - if step.action in ("full", "bpm", "phase") or _wants_key(track, body): - out.tracks_to_analyze += 1 - if step.action in ("full", "bpm", "phase"): - setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1) - elif step.action == "skip": - setattr(out, f"grid_{step.reason}", getattr(out, f"grid_{step.reason}") + 1) - if track.key_wheel is not None: - out.with_key += 1 - if body.key: - if _wants_key(track, body): - out.key_set += 1 + busy = False + if a is not None: + if track.grid_marker_count and not track.grid_locked: + out.with_grid += 1 + step = _grid_step(a, track, body, exact=False) + busy = step.action in ("full", "bpm", "phase") or _wants_key(track, body) + if step.action in ("full", "bpm", "phase"): + setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1) + elif step.action == "skip": + setattr(out, f"grid_{step.reason}", getattr(out, f"grid_{step.reason}") + 1) + if track.key_wheel is not None: + out.with_key += 1 + if body.key: + if _wants_key(track, body): + out.key_set += 1 + else: + out.key_existing += 1 + if body.loudness: + _target, facts, entry = looked.get(tid, (None, None, None)) + fresh = entry is not None and not entry.stale(facts) + out.with_loudness += fresh + if fresh and not body.replace_loudness: + out.loudness_existing += 1 else: - out.key_existing += 1 + out.loudness_measure += 1 + busy = True + out.tracks_to_analyze += busy return out @@ -1703,50 +1742,80 @@ def _decode_for_analysis(path: Path): def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None: """Analyse one track as `body` asks, folding the outcome into `result`. - The file is decoded ONCE and shared by grid and key. A failing half is - reported and does not stop the other: a track whose grid cannot be fitted + `a` is the loaded library for BPM / Grid / Key (None for a device's or a + folder's tracks, which can only have their loudness measured). The file is + decoded ONCE and shared by grid and key; loudness decodes on its own, at + the file's own rate and channels (`core/loudness.py`). A failing part is + 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.""" - track = a.track(track_id) + try: + looked = _loud_lookup(body.origin, [track_id]).get(track_id) if body.loudness or a is None else None + except HTTPException: # the source went away mid-run + looked = None + if a is not None: + track, src, sid = a.track(track_id), a, track_id + elif looked is not None: + src, sid = looked[0].src, looked[0].sid + track = src.track(sid) + else: + track = None title = (track.title or track_id) if track else track_id if track is None: result["failed"].append({"title": title, "reason": "Track not found"}) return - step = _grid_step(a, track, body, exact=True) + step = _grid_step(a, track, body, exact=True) if a is not None else GridStep("none") if step.action == "skip": result["grid"][step.reason] += 1 - want_key = _wants_key(track, body) + want_key = a is not None and _wants_key(track, body) if body.key and not want_key: result["key"]["existing"] += 1 - if step.action not in ("full", "bpm", "phase") and not want_key: + want_loud = False + if body.loudness and looked is not None: + _target, facts, entry = looked + want_loud = body.replace_loudness or entry is None or entry.stale(facts) + if not want_loud: + result["loudness"]["existing"] += 1 + want_grid = step.action in ("full", "bpm", "phase") + if not (want_grid or want_key or want_loud): return - path = a.audio_path(track_id) + 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 - try: - y, sr = _decode_for_analysis(path) - except Exception as ex: # noqa: BLE001 — an undecodable file is one failure - result["failed"].append({"title": title, "reason": f"Could not decode: {ex}"}) - return wrote = False - if step.action in ("full", "bpm", "phase"): + if want_grid or want_key: try: - _analyse_grid(a, track_id, step, y=y, sr=sr) - result["grid"][step.action] += 1 - wrote = True - except (_AnalysisError, AdapterError) as ex: - result["failed"].append({"title": title, "reason": f"Grid: {ex}"}) - if want_key: - try: - found = key_detect.detect_key_samples(y, sr) - if found is None: - result["key"]["none"] += 1 - else: - a.set_key(track_id, found.wheel, found.mode) - result["key"]["set"] += 1 + y, sr = _decode_for_analysis(path) + except Exception as ex: # noqa: BLE001 — an undecodable file is one failure + result["failed"].append({"title": title, "reason": f"Could not decode: {ex}"}) + return + if want_grid: + try: + _analyse_grid(a, track_id, step, y=y, sr=sr) + result["grid"][step.action] += 1 wrote = True - except (AdapterError, ValueError) as ex: - result["failed"].append({"title": title, "reason": f"Key: {ex}"}) + except (_AnalysisError, AdapterError) as ex: + result["failed"].append({"title": title, "reason": f"Grid: {ex}"}) + if want_key: + try: + found = key_detect.detect_key_samples(y, sr) + if found is None: + result["key"]["none"] += 1 + else: + a.set_key(track_id, found.wheel, found.mode) + result["key"]["set"] += 1 + wrote = True + except (AdapterError, ValueError) as ex: + result["failed"].append({"title": title, "reason": f"Key: {ex}"}) + if want_loud: + try: + if _measure_loudness(looked[0], looked[1], path) 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}"}) if wrote: result["analysed"].append(track_id) @@ -1759,13 +1828,14 @@ def _analyze_job(a, body: AnalyzeRequest): "analysed": [], "failed": [], "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}, } handle.progress(done=0, total=len(ids)) for i, track_id in enumerate(ids): if handle.cancelled: break # keep what is done; return it rather than raise - track = a.track(track_id) - handle.progress(message=(track.title or track_id) if track else track_id) + track = a.track(track_id) if a is not None else None + handle.progress(message=(track.title or track_id) if track else Path(track_id).name) _analyse_one(a, track_id, body, result) handle.progress(done=i + 1) # The names the context menu's toast read before the dialog existed. @@ -1781,11 +1851,14 @@ def analyze_batch(body: AnalyzeRequest) -> JobStatus: Each track is written as it finishes, into the in-memory model like any other edit — so a cancel keeps what is done (it is all unsaved until Save), - and the result is returned even from a cancelled run. A track that fails is - reported and skipped, never fatal: one unmounted drive must not stop 400 - other tracks.""" - a = require_adapter() - _require_analysable(a, body) + and the result is returned even from a cancelled run. Loudness is stored + as each track is measured and is not an edit at all (`loudness_store.py`). + A track that fails is reported and skipped, never fatal: one unmounted + drive must not stop 400 other tracks.""" + _require_analysable(body) + if body.origin == "device": + require_source() + a = require_adapter() if body.origin == "collection" else None _require_no_batch() job = _submit_batch(GRID_JOB, _analyze_job(a, body)) return JobStatus(**job.as_dict()) @@ -1799,6 +1872,117 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: key=False, replace_grid=body.replace_existing)) +# ---- Loudness (the Mastering columns) -------------------------------------- +# +# Measured by `core/loudness.py` into Konduktor's own store (`loudness_store.py`), +# keyed by the FILE: the loaded library's (on a remote library, the server's), +# this computer's for a device's or a Files folder's tracks. Never an edit. + + +@dataclass +class _LoudTarget: + src: object # .track / .audio_facts / .audio_path for `sid` + sid: str + store: object # loudness_store.LoudnessStore + + +def _loud_target(origin: str, track_id: str) -> _LoudTarget | None: + """Where a track's file and its loudness value live, by whose id it is.""" + if origin == "device": + source = require_source() + return _LoudTarget(source, track_id, loudness_store.local()) if source.track(track_id) else None + if origin == "folder": + raw = _on_server(track_id) + if raw is not None: + if STATE.remote is None or STATE.adapter is None: + return None + files = STATE.adapter.listed_files([raw]) + return _LoudTarget(files, raw, STATE.loudness) if files else None + source = FOLDERS.source_for_file(track_id) + if source is not None: + return _LoudTarget(source, track_id, loudness_store.local()) + if not STATE.loaded: + return None + # Not a listed file: a folder view's held row, which IS a library track. + a = require_adapter() + return _LoudTarget(a, track_id, STATE.loudness) if a.track(track_id) else None + + +def _loud_lookup(origin: str, track_ids) -> dict: + """`{id: (target, facts | None, entry | None)}` for the known ids. Each + source is asked for its facts once and each store once — a whole library's + worth for the table's columns. Facts never download (`audio_facts`); a + file that is missing has none, and so no value.""" + targets = {tid: t for tid in dict.fromkeys(track_ids) if (t := _loud_target(origin, tid)) is not None} + facts: dict[str, object] = {} + by_source: dict[int, list[str]] = {} + for tid, t in targets.items(): + by_source.setdefault(id(t.src), []).append(tid) + for tids in by_source.values(): + src = targets[tids[0]].src + found = src.audio_facts([targets[tid].sid for tid in tids]) + for tid in tids: + facts[tid] = found.get(targets[tid].sid) + entries: dict[str, object] = {} + by_store: dict[int, list[str]] = {} + for tid, t in targets.items(): + if facts[tid] is not None: + by_store.setdefault(id(t.store), []).append(tid) + for tids in by_store.values(): + store = targets[tids[0]].store + got = store.get([facts[tid].key for tid in tids]) + for tid in tids: + entries[tid] = got.get(facts[tid].key) + return {tid: (t, facts[tid], entries.get(tid)) for tid, t in targets.items()} + + +def _measure_loudness(target: _LoudTarget, facts, path: Path | None = None): + """Measure one file and store it (None: silent, or under 3 s). Raises + `_AnalysisError` with a user-facing reason. The facts stored are the ones + read BEFORE decoding, so a file changing meanwhile reads as stale.""" + if not getattr(target.store, "available", True): + raise _AnalysisError("This Konduktor server is too old to keep loudness — update it") + if facts is None: + raise _AnalysisError("Audio file not found (is the drive mounted?)") + if path is None: + path = target.src.audio_path(target.sid) + if path is None or not Path(path).exists(): + raise _AnalysisError("Audio file not found (is the drive mounted?)") + try: + values = loudness.measure_file(path) + except Exception as ex: # noqa: BLE001 — an undecodable file is one failure + raise _AnalysisError(f"Could not decode: {ex}") + if values is not None: + target.store.put(facts, values) + return values + + +@app.post("/api/loudness", response_model=LoudnessValues) +def loudness_values(body: LoudnessRequest) -> LoudnessValues: + """The Mastering columns' values for a list's tracks — measured ones only.""" + values = {} + for tid, (_target, facts, entry) in _loud_lookup(body.origin, body.track_ids).items(): + if entry is not None: + values[tid] = LoudnessValue(**entry.values.as_dict(), stale=entry.stale(facts)) + return LoudnessValues(values=values) + + +@app.post("/api/tracks/loudness", response_model=LoudnessValue) +def measure_loudness(body: MeasureLoudnessRequest) -> LoudnessValue: + """The deck's Analyze where it cannot write a grid (a read-only library, a + device, a loose file): measure loudness alone, always afresh.""" + looked = _loud_lookup(body.origin, [body.track_id]).get(body.track_id) + if looked is None: + raise HTTPException(404, "Track not found") + try: + values = _measure_loudness(looked[0], looked[1]) + except _AnalysisError as ex: + raise HTTPException(400, str(ex)) + if values is None: + raise HTTPException(400, "Nothing to measure: the track is silent or under 3 seconds") + return LoudnessValue(**values.as_dict()) + + @app.post("/api/tracks/cue/auto-batch", response_model=JobStatus) def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus: """Place one Auto Hotcues template on many tracks, as a JOB. diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index 13e978f..c60795b 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -39,7 +39,9 @@ from .core.model import AutoHotcue, Track, TrackCues #: 1.3 — memory cues: `add_memory_cue`, `rename_memory_cue`, #: `set_memory_cue_type`, `set_memory_cue_color`, `delete_memory_cue`. #: 1.4 — track colour: `set_track_color`, `Track.color` / `color_hex`. -API_VERSION: tuple[int, int] = (1, 4) +#: 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) #: 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 diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 99d9619..078b122 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -157,17 +157,30 @@ class AutoGridRequest(BaseModel): track_id: str +#: Whose ids a loudness request names: the loaded library's, the open device's +#: (the sidebar's Devices), or the Files trees' (a file path; `server:` + the +#: path on a remote's server). A folder id that is not a listed file is taken +#: as the loaded library's — a folder view's held rows ARE collection tracks. +LoudnessOrigin = Literal["collection", "device", "folder"] + + class AnalyzeRequest(BaseModel): """The Analyze dialog's choices. BPM and Grid are independent halves of a beatgrid (`core/grid_plan`); `replace_grid` only guards a FULL re-analysis (both ticked), since with one tick adjusting the grid is the point. - `replace_key` lets detection overwrite a key the track already has.""" + `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.""" track_ids: list[str] bpm: bool = True grid: bool = True key: bool = False + loudness: bool = False replace_grid: bool = False replace_key: bool = False + replace_loudness: bool = False + origin: LoudnessOrigin = "collection" class AnalyzePreview(BaseModel): @@ -189,6 +202,38 @@ class AnalyzePreview(BaseModel): key_set: int = 0 key_existing: int = 0 # skipped: has a key, Replace not ticked with_key: int = 0 # tracks that have a key (the Replace tick's count) + # Loudness (Konduktor's own store): a measured, not stale track is skipped + # unless Replace is ticked. + 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) + + +class LoudnessRequest(BaseModel): + origin: LoudnessOrigin = "collection" + track_ids: list[str] + + +class LoudnessValue(BaseModel): + """One file's measurement (`core/loudness.py`). `stale`: the file changed + since it was measured (or the measurement has) — shown dimmed, still sorted + on, and offered for re-analysis.""" + lufs: float + rms: float + true_peak: float + lra: float + plr: float + stale: bool = False + + +class LoudnessValues(BaseModel): + """Measured tracks only, by the ids asked for.""" + values: dict[str, LoudnessValue] = {} + + +class MeasureLoudnessRequest(BaseModel): + origin: LoudnessOrigin = "collection" + track_id: str class AutoGridBatchRequest(BaseModel): diff --git a/backend/konduktor/server/app.py b/backend/konduktor/server/app.py index ca0d239..3827e6f 100644 --- a/backend/konduktor/server/app.py +++ b/backend/konduktor/server/app.py @@ -20,6 +20,7 @@ it. """ from __future__ import annotations +import json import logging import mimetypes import os @@ -32,7 +33,7 @@ from fastapi import Body, Depends, FastAPI, Header, HTTPException, Query, Reques from fastapi.responses import FileResponse, JSONResponse from fastapi.security import HTTPBasic, HTTPBasicCredentials -from .. import __version__, exports +from .. import __version__, exports, loudness_store from .. import remote_protocol as rp from ..app_state import AppState from ..core import registry @@ -528,6 +529,31 @@ def create_app(server: Server) -> FastAPI: {"library_id": server.state.library_id, "sets": doc["sets"]}) return {"status": "saved"} + # ---- loudness (the Mastering columns) ------------------------------------------ + # The server KEEPS a remote library's measurements (`loudness_store.py`, in + # its data folder) so every computer sees them; the computer that opened + # the library measures, since the server never decodes. + @app.post("/v1/loudness/get") + def loudness_get(body: dict = Body(...)) -> dict: + paths = body.get("paths") + if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths): + raise HTTPException(400, "Expected {'paths': [...]}") + found = loudness_store.local().get(paths) + return {"entries": [entry.wire(path) for path, entry in found.items()]} + + @app.put("/v1/loudness") + def loudness_put(body: dict = Body(...), + token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict: + session(token) # not `touch`ed: a measurement is not an edit to leave unsaved + entries = body.get("entries") + if not isinstance(entries, list): + raise HTTPException(400, "Expected {'entries': [...]}") + try: + loudness_store.local().put_entries(entries) + except (ValueError, KeyError, TypeError): + raise HTTPException(400, "Unreadable loudness entries") + return {"status": "saved", "count": len(entries)} + # ---- Convert to Stems: the library side --------------------------------------- # The SEPARATION runs on the computer that opened the library (the server # never decodes audio); what lives here is everything about the FILES and the @@ -586,13 +612,20 @@ def create_app(server: Server) -> FastAPI: @app.put("/v1/stems/stage") async def stems_stage(request: Request, track_id: str, target: str, sha256: str, - bit_rate: int, duration: float, + bit_rate: int, duration: float, loudness: str | None = None, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict: import hashlib + from ..core.loudness import Loudness from ..stems.pending import partial_name, source_facts session(token) + measured = None + if loudness: # the stem file's measurement, stored when it is published + try: + measured = Loudness.from_dict(json.loads(loudness)).as_dict() + except (ValueError, KeyError, TypeError): + raise HTTPException(400, "Unreadable loudness") source, dest = stem_item(track_id, target) if dest.exists(): raise HTTPException(409, f"A stem file already exists: {dest.name}") @@ -617,7 +650,8 @@ def create_app(server: Server) -> FastAPI: pending.leftovers = [lo for lo in pending.leftovers if lo["partial"] != str(partial)] pending.leftovers.append({ "source": str(source), "facts": source_facts(source), "partial": str(partial), - "written": {"bit_rate": bit_rate, "duration": duration, "size": size}, + "written": {"bit_rate": bit_rate, "duration": duration, "size": size, + **({"loudness": measured} if measured else {})}, }) pending._write() return {"partial": str(partial), "size": size} diff --git a/backend/konduktor/stems/convert.py b/backend/konduktor/stems/convert.py index 5f5acbe..89b14f1 100644 --- a/backend/konduktor/stems/convert.py +++ b/backend/konduktor/stems/convert.py @@ -17,13 +17,15 @@ fails keeps its original and is reported; the rest carry on. from __future__ import annotations import contextlib +import logging import shutil import sys from dataclasses import dataclass, field from pathlib import Path from typing import Callable -from .. import paths +from .. import loudness_store, paths +from ..core import loudness from ..core import stem_file as sf from ..core.adapter import AdapterError, StemSwap from ..core.pathmap import common_dir_prefix @@ -32,6 +34,8 @@ from . import engine_manager as em from .engine_process import EngineCancelled, EngineProcess, keep_awake from .pending import Pending, _replace_no_overwrite, _retrying, parked_name, partial_name, source_facts +log = logging.getLogger(__name__) + _LOSSLESS = (".wav", ".aif", ".aiff", ".flac") #: Five AAC streams at up to 320 kbps plus container overhead. _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 * 1.03} @@ -259,9 +263,12 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *, if item.reuse is not None: written = sf.Written(path=partial, **{k: item.reuse["written"][k] for k in ("bit_rate", "duration", "size")}, tags={}) + kept = dict(item.reuse["written"]) + if "loudness" not in kept and (loud := stem_loudness(str(item.source), partial, loudness_store.local())): + kept["loudness"] = loud pitem = pending.add({"track_id": item.track_id, "mode": opts.collection, "source": str(item.source), "stem": str(item.target), "state": "converted", "facts": source_facts(item.source), - "written": item.reuse["written"]}) + "written": kept}) pending.forget_leftover(item.reuse, delete=False) finished.append((item, pitem, written)) continue @@ -300,8 +307,10 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *, if isinstance(ex, em.EngineError) and engine.proc.poll() is not None: engine = None # it died: the next track starts a fresh one continue - pending.update(pitem, state="converted", - written={"bit_rate": written.bit_rate, "duration": written.duration, "size": written.size}) + kept = {"bit_rate": written.bit_rate, "duration": written.duration, "size": written.size} + if loud := stem_loudness(str(item.source), partial, loudness_store.local()): + kept["loudness"] = loud + pending.update(pitem, state="converted", written=kept) finished.append((item, pitem, written)) except (_Cancel, EngineCancelled): # Cancel = delete what this run made; nothing else was touched. @@ -376,11 +385,40 @@ def _end_step(adapter, finished, opts: Options, pending: Pending, result: dict) for item, pitem in staged: new_id = res.renamed[item.track_id] pending.update(pitem, state="swapped", new_id=new_id) + _store_stem_loudness(item.target, pitem) result["converted"].append({"track_id": item.track_id, "new_id": new_id, "title": item.title}) (result["renamed"] if opts.collection == "repoint" else result["added"])[item.track_id] = new_id result["clamped"] = res.clamped +def stem_loudness(source_key: str, stem: Path, store) -> dict | None: + """The stem file's loudness, measured when its ORIGINAL had been measured + (`source_key`: the original's path as `store` keys it) — re-measured, never + carried over, since the AAC re-encode can move the true peak (decided + 2026-10-19). None when the original was not measured, or on any failure: + a conversion never fails over a measurement.""" + try: + if not store.get([source_key]): + return None + values = loudness.measure_file(stem) + except Exception: # noqa: BLE001 + log.warning("could not measure the loudness of %s", stem, exc_info=True) + return None + return values.as_dict() if values is not None else None + + +def _store_stem_loudness(target: Path, pitem: dict) -> None: + """Store a swapped-in stem file's measurement under its published path + (publishing renames, so its size and mtime are the measured file's).""" + loud = (pitem.get("written") or {}).get("loudness") + if not loud: + return + try: + loudness_store.local().put(loudness_store.file_facts(target), loudness.Loudness.from_dict(loud)) + except Exception: # noqa: BLE001 + log.warning("could not store the loudness of %s", target, exc_info=True) + + def _hide(path: Path) -> None: """Windows ignores dot-names; set the hidden attribute so a parked original does not show in Explorer (or a naive folder scan).""" diff --git a/backend/konduktor/stems/remote_convert.py b/backend/konduktor/stems/remote_convert.py index 98952b1..5ef846d 100644 --- a/backend/konduktor/stems/remote_convert.py +++ b/backend/konduktor/stems/remote_convert.py @@ -23,6 +23,7 @@ from dataclasses import dataclass, field from pathlib import Path from ..core import stem_file as sf +from ..adapters.remote.services import RemoteLoudnessStore from ..core.adapter import AdapterError from ..importer import SPACE_HEADROOM from . import convert @@ -111,6 +112,8 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu work.mkdir(parents=True, exist_ok=True) staged: list[dict] = [] uploaded: list[str] = [] # targets THIS run uploaded (a cancel deletes them) + # The server's store: a stem file is measured when its original was. + loudness_store = RemoteLoudnessStore(adapter.client, adapter.session) if any(i.get("reuse") is None for i in items) and not mgr.ready(): raise convert.ConvertError("The stem engine is not installed") @@ -169,6 +172,8 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu if isinstance(ex, em.EngineError) and engine.proc.poll() is not None: engine = None continue + handle.progress(status="measuring loudness") + loud = convert.stem_loudness(item["source"], partial, loudness_store) sent = 0 def uploading(k: int) -> None: @@ -180,7 +185,7 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu try: adapter.stage_stem(item["track_id"], item["target"], partial, bit_rate=written.bit_rate, - duration=written.duration, progress=uploading) + duration=written.duration, loudness=loud, progress=uploading) finally: partial.unlink(missing_ok=True) uploaded.append(item["target"]) diff --git a/backend/requirements.txt b/backend/requirements.txt index 887d50b..b73f125 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -16,6 +16,9 @@ platformdirs>=4.0 # ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build. librosa>=0.11 scikit-learn>=1.5 +# Imported directly (not only through librosa): loudness K-weighting and +# true-peak oversampling (core/loudness.py), grid detection, structure. +scipy>=1.11 # Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0), # NOT the stale PyPI release (3.1.0), which cannot parse v4 files. # diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 8515917..85fde0f 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_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_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 echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_loudness.py b/backend/test_loudness.py new file mode 100644 index 0000000..a8a6433 --- /dev/null +++ b/backend/test_loudness.py @@ -0,0 +1,176 @@ +"""Loudness measurement (`core/loudness.py`) on GENERATED signals. + +Integrated loudness, LRA and true peak are checked against FFmpeg's own +`ebur128` filter, run through the PyAV wheel the app already ships — a +reference meter nothing has to be installed for. True peak is also checked +against the exact answer on an inter-sample peak, where FFmpeg's cheaper +interpolator overshoots. RMS has no reference meter here, so its definition is +pinned on signals whose answer is known: a full-scale sine reads 0 dB (AES17), +a square +3 dB, and a long quiet intro moves it not at all (it is the loudest +fifth of the 3 s blocks). +""" +from __future__ import annotations + +import math +import tempfile +from pathlib import Path + +import av +import numpy as np +import soundfile as sf + +from konduktor.core import loudness + +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 ebur128(pcm: np.ndarray, sr: int) -> dict: + """FFmpeg's measurement of `pcm` (channels, n): the last frame's metadata.""" + from av.filter import Graph + + pcm = np.ascontiguousarray(np.atleast_2d(pcm).astype(np.float32)) + layout = "mono" if pcm.shape[0] == 1 else "stereo" + graph = Graph() + src = graph.add_abuffer(format="fltp", sample_rate=sr, layout=layout) + meter = graph.add("ebur128", "peak=true:metadata=1") + sink = graph.add("abuffersink") + src.link_to(meter) + meter.link_to(sink) + graph.configure() + last = None + + def drain(): + nonlocal last + while True: + try: + last = sink.pull() + except (av.BlockingIOError, av.EOFError): + return + + pts = 0 + for start in range(0, pcm.shape[1], 4096): + block = pcm[:, start:start + 4096] + frame = av.AudioFrame.from_ndarray(np.ascontiguousarray(block), format="fltp", layout=layout) + frame.sample_rate, frame.pts = sr, pts + pts += block.shape[1] + src.push(frame) + drain() + try: + src.push(None) + except Exception: # noqa: BLE001 — some builds raise at EOF; the frames are out + pass + drain() + m = last.metadata + return {"lufs": float(m["lavfi.r128.I"]), "lra": float(m["lavfi.r128.LRA"]), + "true_peak": 20 * math.log10(float(m["lavfi.r128.true_peak"]))} + + +rng = np.random.default_rng(7) + + +def tone(freq, seconds, sr, amp=0.5, phase=0.0): + t = np.arange(int(sr * seconds)) / sr + return amp * np.sin(2 * np.pi * freq * t + phase) + + +def signals(sr): + t = np.arange(sr * 30) / sr + loud_quiet = np.where((t % 10) < 5, 1.0, 0.05) + kick = np.exp(-(t % 0.5) * 20) * np.sin(2 * np.pi * 55 * t) + return { + "1 kHz sine": np.vstack([tone(1000, 30, sr, 0.1)] * 2), + "noise": 0.2 * rng.standard_normal((2, t.size)), + "loud/quiet sections": np.vstack([loud_quiet * tone(220, 30, sr, 0.3), loud_quiet * tone(330, 30, sr, 0.3)]), + "kick + noise": np.vstack([0.9 * kick + 0.05 * rng.standard_normal(t.size)] * 2), + "mono noise": (0.2 * rng.standard_normal(t.size))[None], + } + + +print("== against FFmpeg's ebur128 ==") +for sr in (44100, 48000): + for name, x in signals(sr).items(): + ours = loudness.measure(x.astype(np.float32), sr) + ref = ebur128(x, sr) + check(f"{sr} {name}: integrated within 0.1 LU ({ours.lufs:.2f} vs {ref['lufs']:.2f})", + abs(ours.lufs - ref["lufs"]) <= 0.1) + check(f"{sr} {name}: LRA within 0.3 LU ({ours.lra:.2f} vs {ref['lra']:.2f})", + abs(ours.lra - ref["lra"]) <= 0.3) + check(f"{sr} {name}: true peak within 0.2 dB ({ours.true_peak:.2f} vs {ref['true_peak']:.2f})", + abs(ours.true_peak - ref["true_peak"]) <= 0.2) + +print("== the standard's anchors ==") +sr = 48000 +r = loudness.measure(np.vstack([tone(1000, 20, sr, 10 ** (-23 / 20))] * 2), sr) +check("a stereo 1 kHz sine at -23 dBFS is -23.0 LUFS", abs(r.lufs + 23.0) <= 0.1, f"{r.lufs:.2f}") +# A sine at a quarter of the rate, 45 degrees off the samples: every sample is +# 0.707 of the peak, which only oversampling can see. Exact: -6.02 dBTP. +r = loudness.measure(np.vstack([tone(sr / 4, 20, sr, 0.5, math.pi / 4)] * 2), sr) +check("an inter-sample peak is found (exact -6.02 dBTP)", abs(r.true_peak + 6.02) <= 0.2, f"{r.true_peak:.2f}") +check("…well above the sample peak (-9.03 dB)", r.true_peak > -8.0) +check("PLR is true peak minus integrated", abs(r.plr - (r.true_peak - r.lufs)) < 1e-9) +steps = signals(sr)["loud/quiet sections"] +r = loudness.measure(steps, sr) +check("alternating loud and quiet sections have a wide LRA", r.lra > 5, f"{r.lra:.2f}") + +print("== RMS: AES17, loudest fifth of 3 s blocks ==") +r = loudness.measure(np.vstack([tone(997, 30, sr, 1.0)] * 2), sr) +check("a full-scale sine reads 0.0 dB", abs(r.rms) <= 0.05, f"{r.rms:.3f}") +square = np.sign(tone(997, 30, sr, 1.0)) +r = loudness.measure(np.vstack([square] * 2), sr) +check("a full-scale square reads +3.01 dB", abs(r.rms - 3.01) <= 0.05, f"{r.rms:.3f}") +body = np.vstack([tone(440, 60, sr, 0.5)] * 2) +intro = np.vstack([tone(440, 120, sr, 0.02)] * 2) +plain = loudness.measure(body, sr) +long_intro = loudness.measure(np.concatenate([intro, body], axis=1), sr) +check("a long quiet intro leaves RMS where it was", abs(plain.rms - long_intro.rms) <= 0.05, + f"{plain.rms:.2f} vs {long_intro.rms:.2f}") +check("…and RMS is the loud part's: a -6 dBFS sine reads -6 dB", abs(plain.rms + 6.02) <= 0.05, f"{plain.rms:.2f}") + +print("== nothing to measure ==") +check("silence is None", loudness.measure(np.zeros((2, sr * 10), dtype=np.float32), sr) is None) +check("under 3 s is None", loudness.measure(np.vstack([tone(440, 2.5, sr)] * 2), sr) is None) +check("a mono (n,) array is accepted", loudness.measure(tone(440, 10, sr), sr) is not None) + +print("== streaming: chunked feeding equals one pass ==") +x = signals(44100)["kick + noise"].astype(np.float32) +whole = loudness.measure(x, 44100) +meter = loudness._Meter(44100, 2) +for start in range(0, x.shape[1], 1153): # odd, frame-like chunks + meter.feed(x[:, start:start + 1153]) +chunked = meter.result() +check("identical to the last digit that matters", + all(abs(getattr(whole, k) - getattr(chunked, k)) < 1e-6 for k in ("lufs", "rms", "true_peak", "lra")), + f"{whole} vs {chunked}") + +print("== measure_file: the file's own rate and channels ==") +with tempfile.TemporaryDirectory() as d: + for sr_, suffix in ((44100, "flac"), (48000, "wav")): + x = np.vstack([tone(1000, 10, sr_, 0.1), tone(1000, 10, sr_, 0.1)]).T + path = Path(d) / f"t.{suffix}" + sf.write(path, x, sr_) + r = loudness.measure_file(path) + check(f"a {sr_} Hz {suffix} reads as its samples do", r is not None and abs(r.lufs + 20.0) <= 0.1, + str(r)) + mono = Path(d) / "mono.flac" + sf.write(mono, tone(1000, 10, 44100, 0.1), 44100) + r = loudness.measure_file(mono) + check("a mono file is measured as ONE channel (3 dB under its stereo twin)", + r is not None and abs(r.lufs + 23.0) <= 0.1, str(r)) + try: + loudness.measure_file(Path(d) / "missing.flac") + check("a missing file raises", False) + except Exception: # noqa: BLE001 + check("a missing file raises", True) + +print() +if failed: + print("FAILED") + raise SystemExit(1) +print("All loudness checks passed.") diff --git a/backend/test_loudness_store.py b/backend/test_loudness_store.py new file mode 100644 index 0000000..88dd1ab --- /dev/null +++ b/backend/test_loudness_store.py @@ -0,0 +1,250 @@ +"""Where loudness lives (`loudness_store.py`) and the routes that fill and read it. + +Runs on a temp app-data dir, a temp copy of the real collection and FLACs +generated here. Pins the decisions that would otherwise fail silently: + + * values are keyed by PATH; a changed file keeps its value but reads STALE + (dimmed, still sorted on) — never silently dropped, never silently trusted; + * Konduktor's OWN tag write at Save does not stale a value; + * a measurement is not an edit: the library stays clean and Discard keeps it; + * loudness works where nothing can be written (a Files folder, a device), + while BPM / Grid / Key for those are refused; + * a path remap carries values to the files' new paths; + * Analyze skips a measured track unless Replace is ticked, and the preview's + counts match what the run does. +""" +from __future__ import annotations + +import os +import shutil +import tempfile +import threading +import time +from pathlib import Path + +import numpy as np +import soundfile as sf + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary" +_DATA = tempfile.TemporaryDirectory() +os.environ["KONDUKTOR_DATA_DIR"] = _DATA.name + +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 + + +from konduktor import loudness_store # noqa: E402 +from konduktor.core.adapter import AudioFacts # noqa: E402 +from konduktor.core.loudness import VERSION, Loudness # noqa: E402 +from konduktor.core.pathmap import PathMapping # noqa: E402 + +V = Loudness(lufs=-8.0, rms=-7.5, true_peak=0.3, lra=5.0, plr=8.3) + +print("== the store ==") +store = loudness_store.LocalLoudnessStore(Path(tempfile.mkdtemp()) / "l.sqlite3") +f = AudioFacts(key="/music/a.mp3", size=100, mtime_ns=5) +store.put(f, V) +got = store.get(["/music/a.mp3", "/music/none.mp3"]) +check("a measured path answers, an unmeasured one does not", list(got) == ["/music/a.mp3"], str(got)) +e = got["/music/a.mp3"] +check("values round-trip", e.values == V and e.version == VERSION) +check("fresh while the facts match", not e.stale(f)) +check("stale once the size or mtime moves", e.stale(AudioFacts(f.key, 100, 6)) and e.stale(AudioFacts(f.key, 101, 5))) +check("an older measurement version is stale", loudness_store.Entry(V, 100, 5, VERSION - 1).stale(f)) +check("keyed as asked, normalised underneath", "/music//a.mp3" in store.get(["/music//a.mp3"])) +n = store.remap(PathMapping.make("/music", "/Volumes/SSD/music")) +check("a remap moves values under the old prefix", n == 1 and "/Volumes/SSD/music/a.mp3" in store.get( + ["/Volumes/SSD/music/a.mp3"]) and not store.get(["/music/a.mp3"])) +store.put(AudioFacts("/x/b.mp3", 1, 1), V) +store.put(AudioFacts("/y/b.mp3", 2, 2), V) +store.remap(PathMapping.make("/x", "/y")) +check("…a value already at the new path wins", store.get(["/y/b.mp3"])["/y/b.mp3"].size == 2 + and not store.get(["/x/b.mp3"])) +check("…and only under the prefix, segment-aware", + store.remap(PathMapping.make("/Volumes/SS", "/elsewhere")) == 0) +errors = [] + + +def burst(k): + try: + for i in range(50): + store.put(AudioFacts(f"/t/{k}/{i}.mp3", i, i), V) + except Exception as ex: # noqa: BLE001 + errors.append(ex) + + +threads = [threading.Thread(target=burst, args=(k,)) for k in range(8)] +[t.start() for t in threads] +[t.join() for t in threads] +check("concurrent writers lose nothing", not errors and len(store.get( + [f"/t/{k}/{i}.mp3" for k in range(8) for i in range(50)])) == 400, str(errors[:1])) + + +# ---- generated audio ------------------------------------------------------ +def tone_flac(path: Path, amp: float, seconds: float = 8.0, **tags) -> Path: + from mutagen.flac import FLAC + + path.parent.mkdir(parents=True, exist_ok=True) + t = np.arange(int(44100 * seconds)) / 44100 + x = (amp * np.sin(2 * np.pi * 440 * t)).astype("float32") + sf.write(path, np.stack([x, x], axis=1), 44100, format="FLAC") + audio = FLAC(path) + for k, v in tags.items(): + audio[k] = str(v) + audio.save() + return path + + +root = Path(tempfile.mkdtemp()) +music = root / "Loose" +loud = tone_flac(music / "loud.flac", 0.5, title="Loud One") +quiet = tone_flac(music / "quiet.flac", 0.05, title="Quiet One") +short = tone_flac(music / "short.flac", 0.5, seconds=2.0, title="Too Short") + +work = Path(tempfile.mkdtemp()) / "collection.nml" +shutil.copy2(REAL, work) +os.environ["KONDUKTOR_NML"] = str(work) + +from fastapi.testclient import TestClient # noqa: E402 + +import konduktor.main as main # noqa: E402 +from konduktor.app_state import STATE # noqa: E402 + + +def wait(c, job): + while job["state"] == "running": + time.sleep(0.05) + job = c.get(f"/api/jobs/{job['id']}").json() + return job + + +with TestClient(main.app, raise_server_exceptions=False) as c: + a = main.require_adapter() + files = [str(loud), str(quiet), str(short)] + c.get("/api/folder/tracks", params={"path": str(music)}) + + print("== a Files folder: loudness only ==") + check("nothing is measured yet", + c.post("/api/loudness", json={"origin": "folder", "track_ids": files}).json()["values"] == {}) + p = c.post("/api/tracks/analyze/preview", json={ + "origin": "folder", "track_ids": files, "bpm": False, "grid": False, "loudness": True}).json() + check("the preview counts three to measure", (p["total"], p["loudness_measure"], p["tracks_to_analyze"]) + == (3, 3, 3), str(p)) + r = c.post("/api/tracks/analyze", json={"origin": "folder", "track_ids": files, "bpm": True, "grid": False}) + check("BPM for a folder's files is refused", r.status_code == 400, r.text) + r = c.post("/api/tracks/analyze", json={"origin": "folder", "track_ids": files, "bpm": False, + "grid": False, "loudness": False}) + check("nothing ticked is refused", r.status_code == 400) + job = wait(c, c.post("/api/tracks/analyze", json={ + "origin": "folder", "track_ids": files, "bpm": False, "grid": False, "loudness": True}).json()) + res = job["result"] + check("the job finishes", job["state"] == "done", str(job)) + check("two measured, the 2-second file has nothing to measure", + res["loudness"] == {"measured": 2, "existing": 0, "none": 1}, str(res)) + vals = c.post("/api/loudness", json={"origin": "folder", "track_ids": files}).json()["values"] + check("the table reads both", set(vals) == {str(loud), str(quiet)}, str(vals)) + check("the louder file reads 20 dB louder", + abs((vals[str(loud)]["lufs"] - vals[str(quiet)]["lufs"]) - 20.0) < 0.1, str(vals)) + check("a -6 dBFS sine's RMS is -6 dB", abs(vals[str(loud)]["rms"] + 6.02) < 0.05, str(vals[str(loud)])) + check("fresh", not vals[str(loud)]["stale"]) + check("the library is not dirty: a measurement is not an edit", not c.get("/api/state").json()["dirty"]) + + print("== skip measured, unless Replace ==") + body = {"origin": "folder", "track_ids": files, "bpm": False, "grid": False, "loudness": True} + p = c.post("/api/tracks/analyze/preview", json=body).json() + check("measured tracks are skipped", (p["loudness_existing"], p["with_loudness"], p["loudness_measure"]) + == (2, 2, 1), str(p)) + job = wait(c, c.post("/api/tracks/analyze", json=body).json()) + check("…and the run agrees", job["result"]["loudness"] == {"measured": 0, "existing": 2, "none": 1}, + str(job["result"])) + p = c.post("/api/tracks/analyze/preview", json={**body, "replace_loudness": True}).json() + check("Replace measures them again", (p["loudness_existing"], p["loudness_measure"]) == (0, 3), str(p)) + + print("== a changed file reads stale, and is offered again ==") + was = vals[str(quiet)]["lufs"] + st = os.stat(quiet) + os.utime(quiet, ns=(st.st_atime_ns, st.st_mtime_ns + 10_000_000_000)) + vals = c.post("/api/loudness", json={"origin": "folder", "track_ids": files}).json()["values"] + check("stale, value kept", vals[str(quiet)]["stale"] and vals[str(quiet)]["lufs"] == was, + str(vals[str(quiet)])) + p = c.post("/api/tracks/analyze/preview", json=body).json() + check("the preview offers it again", p["loudness_measure"] == 2, str(p)) + + print("== the deck's Analyze where nothing can be written ==") + r = c.post("/api/tracks/loudness", json={"origin": "folder", "track_id": str(quiet)}) + check("measures and answers the values", r.status_code == 200 and not r.json()["stale"], r.text) + vals = c.post("/api/loudness", json={"origin": "folder", "track_ids": [str(quiet)]}).json()["values"] + check("…and the value is fresh again", not vals[str(quiet)]["stale"]) + r = c.post("/api/tracks/loudness", json={"origin": "folder", "track_id": str(short)}) + check("too short to measure is a 400 with a reason", r.status_code == 400 and "3 seconds" in r.text, r.text) + r = c.post("/api/tracks/loudness", json={"origin": "folder", "track_id": "/etc/passwd"}) + check("a file no scan found is a 404", r.status_code == 404) + + print("== in the collection: the same file, the same value ==") + job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(loud)], "mode": "reference"}).json()) + tid = job["result"]["track_ids"][0] + vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [tid]}).json()["values"] + check("the collection track shows the folder's measurement", tid in vals and not vals[tid]["stale"], str(vals)) + held = c.post("/api/loudness", json={"origin": "folder", "track_ids": [tid]}).json()["values"] + check("a folder view's held row (a collection id) resolves too", tid in held, str(held)) + + print("== Konduktor's own tag write does not stale it ==") + r = c.patch("/api/tracks", json={"track_id": tid, "fields": {"title": "Loud Renamed"}}) + check("edit accepted", r.status_code == 200, r.text) + before = os.stat(loud).st_mtime_ns + r = c.post("/api/save") + check("saved", r.status_code == 200, r.text) + check("the save wrote the file's tags", os.stat(loud).st_mtime_ns != before) + vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [tid]}).json()["values"] + check("…and the value is still fresh", tid in vals and not vals[tid]["stale"], str(vals)) + + print("== Discard keeps measurements ==") + c.patch("/api/tracks", json={"track_id": tid, "fields": {"comment": "dirty"}}) + r = c.post("/api/tracks/loudness", json={"origin": "collection", "track_id": tid}) + check("measured while dirty", r.status_code == 200, r.text) + check("discarded", c.post("/api/discard").status_code == 200) + vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [tid]}).json()["values"] + check("the value survived", tid in vals, str(vals)) + + print("== the collection's Analyze measures alongside the grid ==") + p = c.post("/api/tracks/analyze/preview", json={ + "track_ids": [tid], "bpm": False, "grid": False, "key": False, "loudness": True, + "replace_loudness": True}).json() + check("collection preview counts it", p["loudness_measure"] == 1 and p["with_loudness"] == 1, str(p)) + + print("== a path remap carries values to the new paths ==") + moved = root / "Moved" + shutil.move(str(music), str(moved)) + r = c.post("/api/library/remap-paths", json={"from": str(music), "to": str(moved)}) + check("remapped", r.status_code == 200 and r.json()["rewritten"] >= 1, r.text) + new_id = next(t.id for t in a.tracks if a.audio_path(t.id) == moved / "loud.flac") + vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [new_id]}).json()["values"] + check("the moved file keeps its value, fresh (a move keeps size and mtime)", + new_id in vals and not vals[new_id]["stale"], str(vals)) + + print("== a device: loudness only, failures reported per track ==") + fixture = Path(tempfile.mkdtemp()) / "onelibrary" + shutil.copytree(FIXTURE, fixture) + check("the stick opens as a source", c.post("/api/source/open", json={"path": str(fixture)}).status_code == 200) + ids = [t["id"] for t in c.get("/api/source/tracks", params={"limit": 3}).json()["items"]] + r = c.post("/api/tracks/analyze", json={"origin": "device", "track_ids": ids, "bpm": False, + "grid": False, "key": True}) + check("a key for a device's tracks is refused", r.status_code == 400, r.text) + job = wait(c, c.post("/api/tracks/analyze", json={"origin": "device", "track_ids": ids, "bpm": False, + "grid": False, "loudness": True}).json()) + # The fixture's demo MP3s are 12-byte stubs: each is one reported failure. + check("the job finishes, each undecodable stub reported, not fatal", + job["state"] == "done" and len(job["result"]["failed"]) == len(ids), str(job)[:300]) + +print() +if failed: + print("FAILED") + raise SystemExit(1) +print("All loudness store checks passed.") diff --git a/backend/test_remote_adapter.py b/backend/test_remote_adapter.py index 460d21e..92ffa42 100644 --- a/backend/test_remote_adapter.py +++ b/backend/test_remote_adapter.py @@ -241,6 +241,28 @@ with tempfile.TemporaryDirectory() as d: check("…with no second download", downloads == [target], downloads) c.post("/api/save") + print("== loudness: measured here, kept on the server ==") + import httpx + + puts = [] + real_put = adapter.client.loudness_put + adapter.client.loudness_put = lambda entries: (puts.append(entries), real_put(entries))[1] + r = c.post("/api/tracks/loudness", json={"track_id": target}) + check("the deck's loudness runs here, on the cached copy", r.status_code == 200 and downloads == [target], + r.text[:200]) + server_path = str(mapped / file_name) + check("…and is sent to the server, keyed by the SERVER's path", + puts and puts[-1][0]["path"] == server_path, str(puts)[:300]) + vals = c.post("/api/loudness", json={"track_ids": [target]}).json()["values"] + check("the table reads it back through the server", target in vals and not vals[target]["stale"], str(vals)) + direct = httpx.post(f"http://127.0.0.1:{port}/v1/loudness/get", json={"paths": [server_path]}, + auth=("dj", "secret")).json() + check("…the server holds it", [e["path"] for e in direct["entries"]] == [server_path], str(direct)) + r = httpx.put(f"http://127.0.0.1:{port}/v1/loudness", json={"entries": direct["entries"]}, + auth=("dj", "secret")) + check("storing without the session is refused (423)", r.status_code == 423, r.text[:200]) + check("…and a measurement leaves nothing unsaved", not c.get("/api/state").json()["dirty"]) + print("== export, from the server's library ==") dest = root / "stick" r = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"], "destination": str(dest)}) @@ -399,6 +421,8 @@ with tempfile.TemporaryDirectory() as d: and st["remote"]["machine"] == "Studio iMac") caps = c.get("/api/capabilities").json() check("…through its capabilities", not caps["writable"] and caps["readonly_cause"] == "taken_over") + r = c.post("/api/tracks/loudness", json={"track_id": target}) + check("…and a measurement can no longer be stored", r.status_code == 503, r.text[:200]) check("the server still has the genre this computer saved", server_adapter.track(target).genre == "Remote Edit") r = c.post("/api/library/open-remote", json={"remote_id": remote_id}) check("reopening says who holds it", r.status_code == 409 diff --git a/backend/test_remote_stems.py b/backend/test_remote_stems.py index 732bfbd..525df75 100644 --- a/backend/test_remote_stems.py +++ b/backend/test_remote_stems.py @@ -137,6 +137,8 @@ with TestClient(main.app) as c: and any(s["volume"].startswith("the server") for s in p["space"]), p["space"]) print("== a Replace batch ==") + r = c.post("/api/tracks/loudness", json={"track_id": ids[0]}) + check("(setup) the original's loudness is measured, kept on the server", r.status_code == 200, r.text[:200]) saved_bytes = work.read_bytes() r = c.post("/api/tracks/stems/convert", json={"track_ids": ids[:1], "mode": "replace"}) job = wait(c, r.json()["id"]) @@ -150,6 +152,12 @@ with TestClient(main.app) as c: check("the server's entry now names the stem file", new_id and server_adapter.track(new_id) is not None) check("…and the mirror here follows", main.require_adapter().track(new_id) is not None) check("the SAVED collection is untouched until Save", work.read_bytes() == saved_bytes) + import httpx + + held = httpx.post(f"http://127.0.0.1:{port}/v1/loudness/get", json={"paths": [str(target)]}, + auth=("dj", "pw")).json()["entries"] + check("the stem file was measured HERE and its value stored on the server with it", + [e["path"] for e in held] == [str(target)], str(held)) st_ = c.get("/api/state").json() check("the state reports the conversion awaiting Save (from the server's ledger)", st_["pending_stems"] and st_["pending_stems"]["tracks"] == 1, st_.get("pending_stems")) diff --git a/backend/test_stems_batch.py b/backend/test_stems_batch.py index 4e477e9..337cb49 100644 --- a/backend/test_stems_batch.py +++ b/backend/test_stems_batch.py @@ -241,6 +241,25 @@ with TestClient(main.app) as c: check("the original entries are still plain tracks", all(a.track(t).media_kind != "stem" for t in ids)) c.post("/api/discard") + print("== loudness: a stem file is measured when its original was ==") + from konduktor import loudness_store + + work, ids, music = library("loud", ["m.mp3", "n.mp3"]) + open_lib(c, work) + r = c.post("/api/tracks/loudness", json={"track_id": ids[0]}) + check("the first original is measured", r.status_code == 200, r.text[:200]) + j = convert(c, ids) + res = j["result"] + check("both convert", len(res["renamed"]) == 2, str(res)[:300]) + stems = [str(music / "m.stem.m4a"), str(music / "n.stem.m4a")] + got = loudness_store.local().get(stems) + check("the measured original's stem file has a value of its own", stems[0] in got, str(list(got))) + check("the unmeasured original's stem file is left unmeasured", stems[1] not in got) + new = res["renamed"][ids[0]] + vals = c.post("/api/loudness", json={"track_ids": [new]}).json()["values"] + check("…shown on the converted track, fresh", new in vals and not vals[new]["stale"], str(vals)) + c.post("/api/discard") + print("== after a crash: restore from the saved file, keep the work, reuse it ==") work, ids, music = library("crash", ["a.mp3", "b.mp3"]) open_lib(c, work) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 9f48c59..1b90ef5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { createPortal } from 'react-dom' -import { useQuery, useQueryClient } from '@tanstack/react-query' +import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' import { CapabilitiesContext, slotLabeller } from './lib/capabilities' import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy' @@ -13,6 +13,7 @@ import { confirmDiscardUnsaved } from './lib/unsaved' import { askConfirm } from './lib/confirm' import { COLUMN_MENU, + MASTERING_COLUMNS, DEFAULT_COLUMN_ORDER, DEFAULT_COLUMN_VISIBILITY, } from './lib/trackColumns' @@ -101,7 +102,9 @@ export default function App() { // job, polled into the status bar. ONE at a time across both kinds — the // backend refuses a second, since a grid run would move the beats a hotcue // run is placing cues on. - const [analyzing, setAnalyzing] = useState(null) // the Analyze dialog's selection + // The Analyze dialog's selection, and whose ids they are (a device's or a + // folder's loose files can only have their loudness measured). + const [analyzing, setAnalyzing] = useState<{ ids: string[]; origin: TrackOrigin } | null>(null) const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null) const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null) // Convert to Stems: the dialog's selection, a finished run's Details, and a @@ -143,6 +146,12 @@ export default function App() { setColumnOrder(DEFAULT_COLUMN_ORDER) setColumnSizing({}) }, []) + /** One checkbox row of the header's column chooser. */ + const columnToggle = (id: string, label: string) => ({ + label, + checked: columnVisibility[id] !== false, + onToggle: () => setColumnVisibility((v) => ({ ...v, [id]: v[id] === false })), + }) // Hydrate the saved layout once, tolerating partial / stale (new columns // added since) data by merging against the current defaults. @@ -563,7 +572,7 @@ export default function App() { : source.name const isAll = source.kind === 'all' - const tracks: Track[] = viewingFolder + const listed: Track[] = viewingFolder ? (folderView.data?.tracks ?? []) : viewingDevice ? source.kind === 'device' @@ -578,6 +587,30 @@ export default function App() { : isAll ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? []) + // The Mastering columns' values: Konduktor's own store, keyed by the FILE + // (`/api/loudness`), joined into the rows — and only fetched while one of + // those columns is shown, since it stats every listed file. Keyed by a hash + // of the ids, so a list whose membership changes asks again; an analysis + // invalidates `['loudness']` itself. + const viewOrigin: TrackOrigin = viewingFolder ? 'folder' : viewingDevice ? 'device' : 'collection' + const masteringShown = MASTERING_COLUMNS.some((id) => columnVisibility[id] === true) + const listedIds = useMemo(() => listed.map((t) => t.id), [listed]) + const listedKey = useMemo(() => { + let h = 5381 + for (const id of listedIds) for (let i = 0; i < id.length; i++) h = ((h << 5) + h + id.charCodeAt(i)) | 0 + return `${listedIds.length}:${h}` + }, [listedIds]) + const loudness = useQuery({ + queryKey: ['loudness', viewOrigin, listedKey], + queryFn: () => api.loudness(viewOrigin, listedIds), + enabled: masteringShown && listedIds.length > 0, + placeholderData: keepPreviousData, + }) + const tracks: Track[] = useMemo(() => { + const values = masteringShown ? loudness.data?.values : undefined + if (!values) return listed + return listed.map((t) => (values[t.id] ? { ...t, loudness: values[t.id] } : t)) + }, [listed, loudness.data, masteringShown]) // The deck holds a SNAPSHOT of its track, taken when it was loaded. When the // view it came from refetches (Analyze wrote its key, Edit Tags its title), // follow the fresh copy so the deck's KEY readout and header are current. @@ -729,6 +762,7 @@ export default function App() { if (!job.result) return invalidateTrackLists(qc) qc.invalidateQueries({ queryKey: ['facets'] }) + qc.invalidateQueries({ queryKey: ['loudness'] }) const cancelled = job.state === 'cancelled' const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}` let touched: string[] @@ -744,18 +778,21 @@ export default function App() { g.bpm ? `${plural(g.bpm, 'BPM')} (downbeat kept)` : '', g.phase ? `${plural(g.phase, 'grid')} at its BPM` : '', r.key.set ? plural(r.key.set, 'key') : '', + r.loudness?.measured ? `loudness of ${r.loudness.measured}` : '', ].filter(Boolean) const skipped = [ g.existing ? `${g.existing} with a grid` : '', g.locked ? `${g.locked} locked` : '', g.flexible ? `${g.flexible} multi-tempo` : '', r.key.existing ? `${r.key.existing} with a key` : '', + r.loudness?.existing ? `${r.loudness.existing} already measured` : '', ].filter(Boolean) parts = [ `${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}` + (wrote.length ? `: ${wrote.join(', ')}` : ''), skipped.length ? `skipped ${skipped.join(', ')}` : '', r.key.none ? `no key found in ${r.key.none}` : '', + r.loudness?.none ? `nothing to measure in ${r.loudness.none} (silent or under 3 s)` : '', ] } else { const r = job.result as unknown as CueBatchResult @@ -958,11 +995,22 @@ export default function App() { setBatchCancelling(false) setBatchJob({ id: job.id, kind: 'grid' }) } - // Offered where ANY of BPM / Grid / Key can be stored; the dialog disables - // the rest with a reason. + // Offered for ANY selection: loudness goes to Konduktor's own store, so it + // can always be measured (decided 2026-10-19). The dialog disables BPM / + // Grid / Key with a reason where they cannot be stored. const canAnalyzeGrid = !!capabilities.data?.grid.editable const canAnalyzeKey = !!capabilities.data?.tracks.key_writable - const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey) + const analyzeOrigin = (ids: string[]): TrackOrigin => + viewingDevice ? 'device' : viewingFolder && ids.some((id) => !folderFiles[id]) ? 'folder' : 'collection' + /** Why BPM / Grid / Key cannot be analysed for these tracks at all, if so. */ + const analyzeRefusal = (origin: TrackOrigin): string | null => + origin === 'device' + ? 'A device is read-only: only its loudness can be measured' + : origin === 'folder' + ? 'Add these files to your collection first' + : !canEdit + ? ((capabilities.data && readOnlyNotice(capabilities.data)) ?? 'This library is read-only') + : null const startCueBatch = (ids: string[]) => { const byId = new Map(tracks.map((t) => [t.id, t])) @@ -1273,16 +1321,14 @@ export default function App() { }, ] : []), - ...(canAnalyze - ? [ - { - label: 'Analyze…', - hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, - disabled: !!batchJob, - onClick: gated(() => setAnalyzing(menu.ids)), - }, - ] - : []), + // No "add it first" detour for loose files: their loudness can be + // measured where they are; the dialog explains the rest. + { + label: 'Analyze…', + hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, + disabled: !!batchJob, + onClick: () => setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids) }), + }, // The deck's ✨ Auto covers a single loaded track, with its // existing cues shown; this is the same template over the selection. ...(canAutoCue @@ -1356,12 +1402,11 @@ export default function App() { items={[ { heading: 'Columns' }, // Default-visible unless explicitly hidden, as in the Columns menu. - ...COLUMN_MENU.map((c) => ({ - label: c.label, - checked: columnVisibility[c.id] !== false, - onToggle: () => - setColumnVisibility((v) => ({ ...v, [c.id]: v[c.id] === false })), - })), + ...COLUMN_MENU.filter((c) => !c.group).map((c) => columnToggle(c.id, c.label)), + { + label: 'Mastering', + submenu: COLUMN_MENU.filter((c) => c.group === 'mastering').map((c) => columnToggle(c.id, c.label)), + }, { separator: true as const }, { label: 'Reset to defaults', onClick: resetColumns }, ]} @@ -1411,10 +1456,11 @@ export default function App() { )} {analyzing && ( runAnalysis(analyzing, opts)} + ids={analyzing.ids} + origin={analyzing.origin} + gridWhy={analyzeRefusal(analyzing.origin) ?? (canAnalyzeGrid ? null : "This library's beatgrids cannot be edited")} + keyWhy={analyzeRefusal(analyzing.origin) ?? (canAnalyzeKey ? null : 'This library cannot store a key')} + onRun={(opts) => runAnalysis(analyzing.ids, opts)} onClose={() => setAnalyzing(null)} onError={onError} /> diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 0068820..6f6b78d 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -43,6 +43,23 @@ export interface Track { * library's own display colour for it; both null when uncoloured. */ color: TrackColor | null color_hex: string | null + /** The Mastering columns' values — NOT part of the backend's `Track`: joined + * in client-side from `/api/loudness` (Konduktor's own store, keyed by the + * FILE), and only while a Mastering column is shown. Absent = unmeasured. */ + loudness?: Loudness +} + +/** One file's loudness (`core/loudness.py`): integrated LUFS, RMS of the + * loudest 3 s blocks (dB, AES17), true peak (dBTP), loudness range (LU) and + * PLR (true peak − LUFS, dB). `stale`: the file changed since it was measured + * — shown dimmed, still sorted on. */ +export interface Loudness { + lufs: number + rms: number + true_peak: number + lra: number + plr: number + stale: boolean } /** One occupied hotcue slot, as the library table previews it. */ @@ -590,16 +607,20 @@ export interface JobStatus { finished_at: number | null } -/** What a batch grid analysis did, per track outcome. */ /** What the Analyze dialog asks for. BPM and Grid are independent halves of * a beatgrid: BPM alone keeps the downbeat, Grid alone keeps the tempo. - * `replace_grid` only guards a FULL re-analysis (both ticked). */ + * `replace_grid` only guards a FULL re-analysis (both ticked). Loudness goes + * to Konduktor's own store, so it works for any `origin`; BPM / Grid / Key + * only for the loaded library's tracks. */ export interface AnalyzeOptions { bpm: boolean grid: boolean key: boolean + loudness: boolean replace_grid: boolean replace_key: boolean + replace_loudness: boolean + origin: TrackOrigin } /** What an Analyze run WOULD do — the backend's `plan_grid`, per track. */ @@ -618,6 +639,10 @@ export interface AnalyzePreview { key_existing: number /** Tracks with a key — the key Replace tick's count. */ with_key: number + loudness_measure: number + loudness_existing: number + /** Measured and not stale — the loudness Replace tick's count. */ + with_loudness: number } /** What an Analyze run did. */ @@ -626,6 +651,7 @@ export interface AnalyzeResult { failed: { title: string; reason: string }[] grid: { full: number; bpm: number; phase: number; locked: number; existing: number; flexible: number } key: { set: number; existing: number; none: number } + loudness: { measured: number; existing: number; none: number } } /** What a batch Auto Hotcues run did. `tracks` got the template (whatever it @@ -1140,6 +1166,13 @@ export const api = { * lands on the track, so refetch the track lists. */ autoGrid: (trackId: string) => send('POST', '/api/tracks/grid/auto', { track_id: trackId }), + /** The Mastering columns' values for these tracks — measured ones only. */ + loudness: (origin: TrackOrigin, trackIds: string[]) => + send<{ values: Record }>('POST', '/api/loudness', { origin, track_ids: trackIds }), + /** Measure one track's loudness now (the deck's Analyze where it cannot + * write a grid: a read-only library, a device, a loose file). */ + measureLoudness: (origin: TrackOrigin, trackId: string) => + send('POST', '/api/tracks/loudness', { origin, track_id: trackId }), /** Auto Hotcues over many tracks, one template for all, as a job. A track * without a grid gets one analysed first. The finished job's `result` is a * `CueBatchResult`. */ diff --git a/frontend/src/components/AnalyzeDialog.tsx b/frontend/src/components/AnalyzeDialog.tsx index beed3eb..182fa88 100644 --- a/frontend/src/components/AnalyzeDialog.tsx +++ b/frontend/src/components/AnalyzeDialog.tsx @@ -1,71 +1,87 @@ import { createPortal } from 'react-dom' import { useEffect, useState, type ReactNode } from 'react' import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type AnalyzeOptions, type AnalyzePreview } from '../api' +import { api, type AnalyzeOptions, type AnalyzePreview, type TrackOrigin } from '../api' interface Props { /** The selected tracks. */ ids: string[] - /** The library can write beatgrids (BPM and Grid). */ - gridEditable: boolean - /** The library can store a key. */ - keyWritable: boolean + /** Whose ids they are: a device's or a folder's loose files can only have + * their loudness measured. */ + origin: TrackOrigin + /** Why BPM and Grid cannot be analysed here; null = they can. */ + gridWhy: string | null + /** Why a key cannot be stored here; null = it can. */ + keyWhy: string | null onRun: (opts: AnalyzeOptions) => Promise onClose: () => void onError: (msg: string) => void } -type What = Pick +type What = Pick const PREF_KEY = 'analyzeWhat' -const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true } +// Loudness off unless asked for once: it adds a decode per track. +const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true, loudness: false } /** The remembered ticks; anything malformed falls back to the default. */ function loadWhat(prefs: Record | undefined): What { const saved = prefs?.[PREF_KEY] as Partial | undefined if (!saved || typeof saved !== 'object') return DEFAULT_WHAT const pick = (k: keyof What) => (typeof saved[k] === 'boolean' ? (saved[k] as boolean) : DEFAULT_WHAT[k]) - return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key') } + return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key'), loudness: pick('loudness') } } const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}` /** * The context menu's "Analyze…" (decided 2026-10-04): which of BPM / Grid / - * Key to analyse, with the "already has one — replace?" questions folded in so - * there is never a second popup. BPM and Grid are independent halves of a - * beatgrid — BPM alone keeps the downbeat, Grid alone keeps the tempo — and - * the grid Replace tick only guards a FULL re-analysis (both ticked). The - * ticks are remembered; the Replace ticks never are — overwriting is a - * decision about THESE tracks. + * Key / Loudness to analyse, with the "already has one — replace?" questions + * folded in so there is never a second popup. BPM and Grid are independent + * halves of a beatgrid — BPM alone keeps the downbeat, Grid alone keeps the + * tempo — and the grid Replace tick only guards a FULL re-analysis (both + * ticked). Loudness goes to Konduktor's own store, so it is never disabled + * (decided 2026-10-19). The ticks are remembered; the Replace ticks never + * are — overwriting is a decision about THESE tracks. */ -export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose, onError }: Props) { +export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, onError }: Props) { const qc = useQueryClient() const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const [what, setWhat] = useState(null) const [replaceGrid, setReplaceGrid] = useState(false) const [replaceKey, setReplaceKey] = useState(false) + const [replaceLoudness, setReplaceLoudness] = useState(false) const [busy, setBusy] = useState(false) + const gridEditable = gridWhy === null + const keyWritable = keyWhy === null - // Hydrate once from prefs, masked by what this library can store. + // Hydrate once from prefs, masked by what can be stored here. Where loudness + // is ALL that can be done (a device, loose files), it is ticked. useEffect(() => { if (what || prefs.isPending) return const w = loadWhat(prefs.data as Record | undefined) - setWhat({ bpm: w.bpm && gridEditable, grid: w.grid && gridEditable, key: w.key && keyWritable }) + setWhat({ + bpm: w.bpm && gridEditable, + grid: w.grid && gridEditable, + key: w.key && keyWritable, + loudness: w.loudness || (!gridEditable && !keyWritable), + }) }, [what, prefs.isPending, prefs.data, gridEditable, keyWritable]) const opts: AnalyzeOptions | null = what && { ...what, replace_grid: what.bpm && what.grid && replaceGrid, replace_key: what.key && replaceKey, + replace_loudness: what.loudness && replaceLoudness, + origin, } const preview = useQuery({ queryKey: ['analyze-preview', ids, opts], queryFn: () => api.analyzePreview(ids, opts!), - enabled: !!opts && (opts.bpm || opts.grid || opts.key), + enabled: !!opts && (opts.bpm || opts.grid || opts.key || opts.loudness), placeholderData: keepPreviousData, }) const p: AnalyzePreview | undefined = preview.data - const nothingTicked = !!what && !(what.bpm || what.grid || what.key) + const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness) const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0) useEffect(() => { @@ -77,8 +93,18 @@ export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose, const run = async () => { if (!opts || busy || count === 0) return setBusy(true) + // A tick that was disabled here keeps what it was: analysing a device's + // loudness must not forget that the collection's keys are wanted. + const saved = loadWhat(prefs.data as Record | undefined) api - .patchPrefs({ [PREF_KEY]: { bpm: opts.bpm, grid: opts.grid, key: opts.key } }) + .patchPrefs({ + [PREF_KEY]: { + bpm: gridEditable ? opts.bpm : saved.bpm, + grid: gridEditable ? opts.grid : saved.grid, + key: keyWritable ? opts.key : saved.key, + loudness: opts.loudness, + }, + }) .then((x) => qc.setQueryData(['prefs'], x)) .catch(() => {}) try { @@ -154,9 +180,10 @@ export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose,
- {toggle('bpm', 'BPM', 'Detect the tempo', gridEditable, "This library's beatgrids cannot be edited")} - {toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, "This library's beatgrids cannot be edited")} - {toggle('key', 'Key', 'Detect the musical key', keyWritable, "This library cannot store a key")} + {toggle('bpm', 'BPM', 'Detect the tempo', gridEditable, gridWhy ?? '')} + {toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, gridWhy ?? '')} + {toggle('key', 'Key', 'Detect the musical key', keyWritable, keyWhy ?? '')} + {toggle('loudness', 'Loudness', 'Measure LUFS, RMS, true peak and dynamics', true, '')}
@@ -173,6 +200,17 @@ export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose,
)} + {p && what?.loudness && p.with_loudness > 0 && ( +
+ + {p.with_loudness} already measured + + +
+ )} {nothingTicked &&
Tick what to analyze.
}
diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index ab362f5..0cc4569 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -18,7 +18,7 @@ import { import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid' import { slotLabeller, useCaps } from '../lib/capabilities' import { CUE_TYPE_LABELS, cueTypeColor } from '../lib/cues' -import { keyColor } from '../lib/format' +import { formatLoudness, keyColor } from '../lib/format' import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy' import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform' import type { RawWave } from '../lib/rawWave' @@ -1220,11 +1220,20 @@ export function PrepStrip({ // deck the fresh copy. const runAnalyzeGrid = async () => { if (!track || gridBusy) return - if (refuseGridEdit()) return setGridBusy(true) try { - applyCueEdit(await api.autoGrid(track.id)) - onNotify?.('success', caps.tracks.key_writable ? 'Analyzed — set BPM, grid and key' : 'Analyzed — set BPM and grid') + if (canEditGrid) { + applyCueEdit(await api.autoGrid(track.id)) + onNotify?.('success', caps.tracks.key_writable + ? 'Analyzed — set BPM, grid and key, measured loudness' + : 'Analyzed — set BPM and grid, measured loudness') + } else { + // Nothing here can take a grid (a read-only library, a device, a loose + // file) — but loudness goes to Konduktor's own store, so measure that. + const l = await api.measureLoudness(origin, track.id) + onNotify?.('success', `Measured loudness — ${formatLoudness(l.lufs, 'LUFS')}, ${formatLoudness(l.true_peak, 'dBTP', true)}`) + } + qc.invalidateQueries({ queryKey: ['loudness'] }) } catch (e) { onError?.((e as Error).message) } finally { @@ -1529,7 +1538,9 @@ export function PrepStrip({
@@ -211,6 +232,19 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, on
)} + {p && what?.gain && p.with_gain > 0 && ( +
+ + {p.with_gain}{' '} + {p.with_gain === 1 ? 'already has an auto gain' : 'already have an auto gain'} + + +
+ )} {nothingTicked &&
Tick what to analyze.
}
diff --git a/frontend/src/lib/trackColumns.tsx b/frontend/src/lib/trackColumns.tsx index 443d83f..90783c8 100644 --- a/frontend/src/lib/trackColumns.tsx +++ b/frontend/src/lib/trackColumns.tsx @@ -367,6 +367,24 @@ export const TRACK_COLUMNS: ColumnDef[] = [ loudnessColumn('true_peak', 'True Peak', 'dBTP', true), loudnessColumn('lra', 'LRA', 'LU'), loudnessColumn('plr', 'PLR', 'dB'), + // The DJ app's own auto gain (Traktor's deck gain, rekordbox's Auto Gain), + // from the backend's Track — not Konduktor's loudness store — so showing it + // fetches nothing. None sorts last, like an unmeasured loudness. + col.accessor((t) => t.auto_gain_db ?? undefined, { + id: 'auto_gain', + header: 'Auto Gain', + size: 104, + sortUndefined: 'last', + cell: (c) => { + const v = c.getValue() as number | undefined + if (v == null) return — + return ( + + {formatLoudness(v, 'dB', true)} + + ) + }, + }), ] function loudnessColumn(field: 'lufs' | 'rms' | 'true_peak' | 'lra' | 'plr', header: string, unit: string, @@ -392,14 +410,17 @@ function loudnessColumn(field: 'lufs' | 'rms' | 'true_peak' | 'lra' | 'plr', hea }) } -/** The Mastering columns, in order: the column chooser's "Mastering ▸". */ +/** The loudness columns: shown, they fetch `/api/loudness` (see App). */ export const MASTERING_COLUMNS: readonly string[] = ['lufs', 'rms', 'true_peak', 'lra', 'plr'] +/** The column chooser's "Mastering ▸", in order: loudness, then auto gain. */ +const MASTERING_MENU: readonly string[] = [...MASTERING_COLUMNS, 'auto_gain'] const MASTERING_LABELS: Record = { lufs: 'LUFS (integrated loudness)', rms: 'RMS (loudest sections)', true_peak: 'True Peak', lra: 'LRA (loudness range)', plr: 'PLR (peak to loudness)', + auto_gain: "Auto Gain (the DJ app's)", } // Traktor dates arrive as "YYYY/M/D" strings; show them compactly (or raw). @@ -414,7 +435,7 @@ function formatDate(v: string | null): string { * `group` puts a column in a submenu (the Mastering columns). */ export const COLUMN_MENU: { id: string; label: string; group?: 'mastering' }[] = TRACK_COLUMNS.map((c) => { const id = c.id as string - const mastering = MASTERING_COLUMNS.includes(id) + const mastering = MASTERING_MENU.includes(id) return { id, label: MASTERING_LABELS[id] ?? (typeof c.header === 'string' ? c.header : id), From 64b0396d667a7475634f0ba146f7092af1ace089 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 19 Oct 2026 20:45:35 +0200 Subject: [PATCH 06/11] Implemented basic track normalizing --- CLAUDE.md | 70 ++- .../konduktor/adapters/onelibrary/adapter.py | 13 + .../adapters/onelibrary/capabilities.py | 3 + .../konduktor/adapters/onelibrary/store.py | 35 ++ .../konduktor/adapters/rekordbox/adapter.py | 6 + .../adapters/rekordbox/capabilities.py | 1 + backend/konduktor/adapters/rekordbox/store.py | 45 ++ backend/konduktor/adapters/traktor/adapter.py | 6 + .../adapters/traktor/capabilities.py | 3 + backend/konduktor/adapters/traktor/store.py | 17 + backend/konduktor/app_state.py | 51 ++- backend/konduktor/core/adapter.py | 19 + backend/konduktor/core/capabilities.py | 3 + backend/konduktor/core/level_edit.py | 428 ++++++++++++++++++ backend/konduktor/core/level_plan.py | 104 +++++ backend/konduktor/gain/__init__.py | 1 + backend/konduktor/gain/normalize.py | 267 +++++++++++ backend/konduktor/main.py | 85 +++- backend/konduktor/pending.py | 378 ++++++++++++++++ backend/konduktor/remote_protocol.py | 1 + backend/konduktor/schemas.py | 14 + backend/konduktor/server/app.py | 6 +- backend/konduktor/stems/convert.py | 6 + backend/konduktor/stems/pending.py | 241 +--------- backend/run_tests.sh | 2 +- backend/test_level_edit.py | 201 ++++++++ backend/test_level_plan.py | 77 ++++ backend/test_normalize.py | 373 +++++++++++++++ frontend/src/App.tsx | 62 ++- frontend/src/api.ts | 53 +++ frontend/src/components/AppSettings.tsx | 66 +++ frontend/src/components/NormalizeDialog.tsx | 194 ++++++++ frontend/src/components/SaveBar.tsx | 15 + 33 files changed, 2584 insertions(+), 262 deletions(-) create mode 100644 backend/konduktor/core/level_edit.py create mode 100644 backend/konduktor/core/level_plan.py create mode 100644 backend/konduktor/gain/__init__.py create mode 100644 backend/konduktor/gain/normalize.py create mode 100644 backend/konduktor/pending.py create mode 100644 backend/test_level_edit.py create mode 100644 backend/test_level_plan.py create mode 100644 backend/test_normalize.py create mode 100644 frontend/src/components/NormalizeDialog.tsx diff --git a/CLAUDE.md b/CLAUDE.md index faa3903..ecfe247 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -555,7 +555,9 @@ Two independent apps that talk over HTTP: preflighted per volume (both copies coexist until Save) and for the work folder. Replace implies repoint; destination mode mirrors the tree (full path, volume first, when the tracks share no folder) and may repoint or add - (+ existing / new playlist). **`pending.py` — the ledger** of conversions + (+ existing / new playlist). **`pending.py` — the ledger** (now + `konduktor/pending.py`, `stems/pending.py` a re-export: it holds + Normalize's "gain" items too, see "Normalize") of conversions awaiting Save (per library id, atomic): `AppState._save` COMMITS (deletes parked originals, retargets export sets — inside `_save`, so import and remap saves count too), `discard()` and opening another library RESTORE, @@ -806,6 +808,46 @@ Two independent apps that talk over HTTP: `replace_gain`): fills tracks without one unless Replace, measuring first where the loudness is missing or stale (a fresh measurement is reused — no decode, no download); the deck's Analyze fills a missing one. + - **Normalize** — the track menu's **Mastering ▸ Normalize…** changes the + audio FILES' level in place (decided 2026-10-19, same discussion). + `core/level_plan.py` (`plan_gain`, pure, shared by preview and run — and + the export next): the user's measure (LUFS / loud-section RMS) to a + target; up and down, a raise stopping at the TRUE-PEAK ceiling (outcome + `capped`, `short_by`); a peak already over the ceiling at/below target is + left alone (`hot_peak_left`); MP3 in whole steps of 2^(1/4) (1.505 dB), + rounding a raise DOWN under the ceiling; ALAC/AAC/Ogg `unsupported` (AAC + is Phase 5). `core/level_edit.py` writes a NEW file: MP3 by the lossless + frame-gain edit (mp3gain's `global_gain`, CRC-16 recomputed on protected + frames, the Xing/Info/VBRI frame untouched, mp3gain's APEv2 + `MP3GAIN_UNDO`/`MINMAX` tag, accumulating); WAV/AIFF scaled IN their + data/SSND chunk (same size, every other chunk byte-identical); FLAC + re-encoded at its depth with every Vorbis comment, picture and + application block copied back; 16-bit TPDF-dithered unless exact + (seeded: the same edit writes the same bytes). `verify` decodes both in + step: result == source x 10^(g/20). `gain/normalize.py`: measure where + the loudness is missing/stale, rewrite into `.konduktor-partial`, + verify, then ONE end step under `STATE.mutation` — park the original + (`..konduktor-parked`), rename the partial onto the original's OWN + name (the path never changes), `audio_changed` (protocol member, gated + on `tracks.normalizable`: Traktor FILESIZE; rekordbox `FileSize` + the + drawn waveform tags regenerated into the existing ANLZ files at save, + `_flush_waveforms`; OneLibrary `fileSize` + the same tags into its edited + ANLZ copies, `.2EX` included), the DJ app's auto gain RECOMPUTED from the + new level, Konduktor's loudness SHIFTED (`level_plan.shifted`). Ledger + states writing -> written -> parked -> published -> swapped -> saving -> + saved; `AppState._save` brackets `adapter.save()` with + `begin_save`/`mark_saved`, so only a crash INSIDE the save asks the + library (`app_state._committed`: auto gain == the new value and != the + old; no auto gain = restore). Discard/restore removes the normalised file + only if it is recognisably ours and puts `loudness_before` back. + `_require_no_pending` (was `_require_no_pending_stems`) covers both kinds + and `NORMALIZE_JOB`; a track with a pending item is neither normalised nor + converted again. Remote libraries: refused (Phase 4). Routes + `/api/tracks/normalize/preview` and `/api/tracks/normalize`; + `/api/state.pending_gain` {tracks, lossless} + `normalize_job`. UI: + `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. - `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 @@ -1571,6 +1613,32 @@ serialization path.** It enforces: stubs reported per track. `test_stems_batch.py` / `test_remote_stems.py` pin the stem re-measure, `test_remote_adapter.py` the server-side store (423 without the session, 503 once taken over). +- `test_level_plan.py` — `plan_gain`'s every outcome: exact lossless gains, + the ceiling (capped, short_by), hot peaks left alone (but lowered when hot), + MP3 steps (nearest when lowering, never past the ceiling when raising, + under one step = nothing), RMS as the measure, the shifted loudness. +- `test_level_edit.py` — on GENERATED files: MP3 (CBR + Xing + ID3 art, + no Xing, ABR, mono, MPEG-2 22 kHz) at -2/+1 steps decodes exactly x 2^(n/4), + same frames + only the APE undo tag, source untouched, undo accumulating; + non-step gains, out-of-range and existing targets refused leaving nothing; + CRC-16's check value; WAV 16/24/float and AIFF 16/24 at -3.7/+2.5 dB keep + their size and every other chunk byte-identical, 24-bit rounded not + dithered, 16-bit dithered reproducibly; FLAC 16/24 keeps depth, rate, tags + and picture. +- `test_normalize.py` — through the routes on temp collections pointed at + generated MP3/FLAC/WAV: unmeasured tracks counted to measure first; MP3 + gains whole steps; a raise held by the ceiling; the preview's lossless + count; the run = the preview, the SAVED collection untouched, each file at + its own path = the original at the gain with the original parked unchanged, + dirty + `pending_gain`, loudness shifted and fresh, auto gain = -9.2 - new + LUFS; reload 409, no second Normalize or stem conversion of a pending + track; Save deletes the parked files, writes the new LOUDNESS, changes + nothing outside those ENTRYs; Discard restores bytes and loudness; crash + recovery for an unsaved change (restored + reported), a save that landed + ("saving" + new gain: finished) and one that did not (restored). And the + 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_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/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index fdb6a03..b80e2d4 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -410,6 +410,19 @@ class OneLibraryAdapter: self._refresh(track_id) return self._index.get(track_id) + def analysis_lead(self, audio: Path) -> float: + """rekordbox's clock against the decoded audio (as for the Rekordbox + adapter): what a regenerated waveform is measured at.""" + from ..rekordbox import timebase + + return timebase.offset(Path(audio)) + + def audio_changed(self, track_id: str, change) -> Track | None: + self._require_writable("Changing a track's level") + self._store.audio_changed(track_id, change) + 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` diff --git a/backend/konduktor/adapters/onelibrary/capabilities.py b/backend/konduktor/adapters/onelibrary/capabilities.py index b200970..0dabf11 100644 --- a/backend/konduktor/adapters/onelibrary/capabilities.py +++ b/backend/konduktor/adapters/onelibrary/capabilities.py @@ -87,6 +87,9 @@ def capabilities_for( addable=not read_only, removable=not read_only, key_writable=not read_only, + # A stick has no auto gain, so normalising its audio is how it is + # levelled (its drawn waveforms are regenerated). + normalizable=not read_only, # `content.color_id`, rekordbox's eight; the pdb row follows at Save. colors=[] if read_only else list(track_palette.SWATCHES), places_audio=True, diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py index 6a53d24..abdc9cf 100644 --- a/backend/konduktor/adapters/onelibrary/store.py +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -583,6 +583,41 @@ class OneLibraryStore(ReplaceGridCommands): db.flush() db.session.expire(row) + # ---- writes: a level change (Normalize) ------------------------------------- + def audio_changed(self, track_id: str, change) -> None: + """The file changed level in place: `fileSize` follows (and the pdb's + row with it, at Save), and the drawn waveforms are regenerated into + the track's ANLZ files as edited copies — `.2EX` too — which Save + fingerprints and writes like any cue or grid edit.""" + from ..rekordbox import anlz_writer + + db = self._require_db() + row = self.content(track_id) + before = row.fileSize + row.fileSize = int(change.size) + measured = change.measured + if measured is not None: + dat, ext = self._editing(track_id) + for data in anlz_writer.preview_tags(measured.columns.rms, measured.columns.brightness): + dat.put(data[:4].decode("latin-1"), data, after=("PPTH", "PVBR", "PQTZ")) + ext_tags, two_tags = anlz_writer.waveform_tags(measured.frames.bands) + for data in ext_tags: + ext.put(data[:4].decode("latin-1"), data, after=("PPTH",)) + dat_path, _ext_path = self._anlz_paths(track_id) + two = dat_path.with_suffix(".2EX") + if two in self._pending_anlz or two.is_file(): + pending = self._pending_anlz.get(two) + if pending is None: + try: + pending = (anlz_file.parse_file(two), _fingerprint_file(two)) + except (OSError, anlz_file.AnlzError) as ex: + raise InvalidCommand(f"Cannot read the analysis file {two.name}: {ex}") from ex + self._pending_anlz[two] = pending + for data in two_tags: + pending[0].put(data[:4].decode("latin-1"), data, after=("PPTH",)) + self._journal.record("track", "audio", track_id, "level", before, change.gain_db) + db.flush() + # ---- writes: playlists -------------------------------------------------- def _playlist(self, node_id: str): from pyrekordbox.onelibrary import models diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index f50c078..77e59f3 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -269,6 +269,12 @@ class RekordboxAdapter: self._refresh(track_id) return self._index.get(track_id) + def audio_changed(self, track_id: str, change) -> Track | None: + self._require_writable("Changing a track's level") + self._store.audio_changed(track_id, change) + 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) diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index a6e9205..1c8a6d2 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -97,6 +97,7 @@ def capabilities_for( colors=list(track_palette.SWATCHES), # djmdMixerParam (measured, see `gain`). auto_gain=True, + normalizable=True, artwork=False, artwork_note=None, ), diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 61a46c4..e8500e0 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -28,6 +28,7 @@ from __future__ import annotations import json import logging +import os import uuid from contextlib import contextmanager from datetime import datetime @@ -124,6 +125,9 @@ class RekordboxStore(ReplaceGridCommands): # Grid edits buffered until save(): ANLZ files are written to disk, so # applying them at command time would break the save contract. self._pending_grids: dict[str, tuple[list, list, list]] = {} + # Normalize: drawn waveforms regenerated from the new audio, written + # into the track's ANLZ files at save (cues, grid, phrases untouched). + self._pending_waveforms: dict[str, object] = {} # Analysis/artwork files of removed tracks, `share`-relative, deleted # by save() AFTER the commit — a failed commit must leave them in place. self._pending_file_removals: set[str] = set() @@ -163,6 +167,7 @@ class RekordboxStore(ReplaceGridCommands): self.close() self._journal = EditJournal() self._pending_grids.clear() + self._pending_waveforms.clear() self._pending_file_removals.clear() self._pending_new_files.clear() self._load() @@ -1063,6 +1068,7 @@ class RekordboxStore(ReplaceGridCommands): # rows after, which hash what was finally written. written = self._write_new_files() try: + self._flush_waveforms() self._flush_grids() self._add_content_files(written) self._commit() @@ -1552,6 +1558,45 @@ class RekordboxStore(ReplaceGridCommands): row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0 self._journal.record("grid", "replace" if ordered else "delete", track_id) + def audio_changed(self, track_id: str, change) -> None: + """The file changed level in place (Normalize): `FileSize` follows, and + the drawn waveforms are regenerated from the new audio at save (they + are drawn from the audio's level; cues, grid and phrases stay).""" + row = self.content(track_id) + before = row.FileSize + row.FileSize = int(change.size) + if change.measured is not None: + self._pending_waveforms[str(track_id)] = change.measured + self._journal.record("track", "audio", track_id, "level", before, change.gain_db) + self._db.flush() + + def _flush_waveforms(self) -> None: + """Write regenerated waveform tags into existing ANLZ files: `.DAT` + PWAV/PWV2, `.EXT` PWV3/PWV5/PWV4, `.2EX` PWV7/PWV6/PWVC — each replaced + in place (`AnlzFile.put`), every other tag kept byte for byte.""" + from . import anlz_file, anlz_writer + + for track_id, measured in list(self._pending_waveforms.items()): + rel = getattr(self.content(track_id), "AnalysisDataPath", None) + if not rel: + continue # no analysis files: rekordbox draws from its own analysis + dat = self.path.parent / "share" / str(rel).lstrip("/\\") + ext_tags, two_tags = anlz_writer.waveform_tags(measured.frames.bands) + plan = [(dat, anlz_writer.preview_tags(measured.columns.rms, measured.columns.brightness), + ("PPTH", "PVBR", "PQTZ")), + (dat.with_suffix(".EXT"), ext_tags, ("PPTH",)), + (dat.with_suffix(".2EX"), two_tags, ("PPTH",))] + for path, tags, after in plan: + if not path.is_file(): + continue + parsed = anlz_file.parse_file(path) + for data in tags: + parsed.put(data[:4].decode("latin-1"), data, after=after) + partial = path.with_name(f".{path.name}.konduktor-partial") + partial.write_bytes(parsed.to_bytes()) + os.replace(partial, path) + self._pending_waveforms.clear() + def _flush_grids(self) -> None: """Write buffered grids into their ANLZ files. Called by save(). diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 861b7bc..900ce9d 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -162,6 +162,12 @@ class TraktorAdapter: self._refresh(track_id) return self._index.get(track_id) + def audio_changed(self, track_id: str, change) -> Track | None: + with _translate(): + self._store.audio_changed(track_id, change) + 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) diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index 5075475..ea4230e 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -72,6 +72,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: # INFO@COLOR, seven colours (measured, see `track_palette`). colors=list(track_palette.SWATCHES), auto_gain=True, + # Kit G1: a level change never makes Traktor re-analyse (grids are + # safe); its stored gain goes stale, which Normalize rewrites. + normalizable=True, # `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # but only on Windows, and a file added on one OS must play on both. audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"], diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index ecbbf4b..0fc5234 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -587,6 +587,23 @@ class TraktorStore: self._journal.record("track", "set", track_id, "auto_gain", before, after) self.dirty = True + # ---- a level change (Normalize) ------------------------------------------ + def audio_changed(self, track_id: str, change) -> None: + """The file at this entry changed level in place. Traktor keeps only its + size (KB) about it — and was measured (kit G1) to re-analyse nothing on + such a change; its LOUDNESS is rewritten separately (`set_auto_gain`). + Always journalled, so Save runs even if the size is unchanged (MP3).""" + with self._lock: + entry = self._entry_by_key.get(track_id) + if entry is None: + raise PlaylistError(f"Track not found: {track_id}") + if entry.info is None: + entry.info = Infotype() + before = entry.info.filesize + entry.info.filesize = int(round(change.size / 1024)) + self._journal.record("track", "audio", track_id, "level", before, change.gain_db) + self.dirty = True + # ---- adding tracks -------------------------------------------------- def add_entry(self, track, audio_path: Path) -> str: """Append a brand-new ENTRY for `audio_path` and return its track id. diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py index dcd5af3..ad82d2d 100644 --- a/backend/konduktor/app_state.py +++ b/backend/konduktor/app_state.py @@ -177,12 +177,13 @@ class AppState: # A crash may have left converted tracks mid-lifecycle: settle them from # what the SAVED library says, BEFORE the missing-files check — a parked # original is exactly what that check would report as missing. - from .stems.pending import Pending + from .pending import Pending self.pending = Pending(self.library_id) self.recovery = None if self.pending.items: - self.recovery = self.pending.recover(lambda item: adapter.track(item["new_id"]) is not None) + self.recovery = self.pending.recover(lambda item: _committed(adapter, item)) + self._restore_loudness() # Started after the saved mapping is applied, so a volume that mapping # already fixes is not asked about. self.relocation = RelocationCheck(adapter) @@ -191,6 +192,18 @@ class AppState: for hook in self.open_hooks: hook(adapter) + def _restore_loudness(self) -> None: + """A Normalize undone: the original is back, so is its measurement + (its facts are the original's again, so the value reads fresh).""" + entries = [i["loudness_before"] for i in getattr(self.pending, "restored_gain", ()) + if i.get("loudness_before")] + put = getattr(self.loudness, "put_entries", None) + if entries and put is not None: + try: + put(entries) + except Exception: # noqa: BLE001 — bookkeeping must never fail a discard + log.warning("could not restore loudness values", exc_info=True) + def _keep_loudness(self, path, values) -> None: from . import loudness_store @@ -205,6 +218,7 @@ class AppState: # a stem conversion's parked originals go back under their own names. if self.pending is not None and self.pending.items: self.pending.restore() + self._restore_loudness() if previous is not None and hasattr(previous, "close"): try: previous.close() @@ -258,7 +272,19 @@ class AppState: return self._save() def _save(self): - outcome = self.adapter.save() + # Normalize's items: a crash inside the save is the one moment the + # ledger cannot decide alone (see pending.py) — bracket it. + marked = self.pending is not None and bool(self.pending.swapped()) + if marked: + self.pending.begin_save(None) + try: + outcome = self.adapter.save() + except BaseException: + if marked: + self.pending.abort_save() + raise + if marked: + self.pending.mark_saved() commit = self.services.commit_save(self.adapter, outcome) # Konduktor itself just rewrote these files' tags: a loudness value # measured before must not read as stale because of it. (On a remote @@ -291,6 +317,7 @@ class AppState: with self.mutation: if self.pending is not None and self.pending.items: self.pending.restore() + self._restore_loudness() if self.services is not None and self.services.remote: # The server holds the edits; it is what drops them. self.services.discard() @@ -320,3 +347,21 @@ if _env_nml and Path(_env_nml).exists(): STATE.open(Path(_env_nml)) except Exception: # noqa: BLE001 — bad env path shouldn't crash startup pass + + +def _committed(adapter, item: dict) -> bool: + """Recovery's question for an item a crash left mid-save: did the saved + library take it? A stem swap: the library names the stem file. A Normalize: + the library's auto gain is the NEW one and not the old (the end step always + rewrites it); a platform with no auto gain cannot tell, so it is not + (restore — the original audio is never destroyed on a guess).""" + if (item.get("kind") or "stem") == "stem": + return bool(item.get("new_id")) and adapter.track(item["new_id"]) is not None + after, before = item.get("gain_after"), item.get("gain_before") + if after is None: + return False + track = adapter.track(item["track_id"]) + now = getattr(track, "auto_gain_db", None) if track is not None else None + if now is None or abs(now - after) > 0.01: + return False + return before is None or abs(now - before) > 0.01 diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 55026aa..44fbc64 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -185,6 +185,19 @@ class StemSwap: size: int +@dataclass(frozen=True) +class AudioChange: + """A track's audio file changed LEVEL in place (Normalize): same path, the + samples scaled by `gain_db`. `size` is the new file's size; `measured` the + new audio's `core.waveform.Analysis` at the platform's `analysis_lead`, + for a platform that stores drawn waveforms (None: it does not). The + library's own auto gain is a separate command (`set_auto_gain`).""" + + gain_db: float + size: int + measured: object | None = None + + @dataclass class StemSwapResult: #: Old track id -> the id of the entry that now names the stem file. @@ -291,6 +304,12 @@ class LibraryAdapter(Protocol): # every swap is validated before any is applied, so a clash leaves the # library untouched. Gated on `capabilities().tracks.stem_convertible`. # `add_to_playlist` receives the entries "add" mode creates, in order. + # A track's file changed level in place (see `AudioChange`): what the + # library keeps ABOUT the audio follows — its size, its drawn waveforms. + # Always an edit (so Save runs), even where nothing visible changes. + # Gated on `capabilities().tracks.normalizable`. + def audio_changed(self, track_id: str, change: AudioChange) -> Track | None: ... + def apply_stem_swaps(self, swaps: list["StemSwap"], *, add_to_playlist: str | None = None) -> "StemSwapResult": ... diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index 766c56b..8418702 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -127,6 +127,9 @@ class TrackCapabilities(BaseModel): # 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 + # Tracks' files can be normalised in place: the library follows a level + # change (`audio_changed`) and keeps the parked original until Save. + normalizable: bool = False class PlaylistCapabilities(BaseModel): diff --git a/backend/konduktor/core/level_edit.py b/backend/konduktor/core/level_edit.py new file mode 100644 index 0000000..2d46b18 --- /dev/null +++ b/backend/konduktor/core/level_edit.py @@ -0,0 +1,428 @@ +"""Change an audio file's level — losslessly where the format allows, exactly +where it is PCM. Always into a NEW file: the source is never touched. + +Decided 2026-10-19 (the gain-normalisation discussion; `level_plan` decides +the gain): + + * **MP3: the frame-gain edit** (mp3gain's): every granule's 8-bit + `global_gain` in the side info moves by whole steps of 2^(1/4) in + amplitude (1.505 dB). No re-encode, so no quality loss, no change of + encoder delay (cues stay put: `adapters/*/timebase.py`), same size. CRC- + protected frames get their CRC-16 recomputed; the Xing/Info/VBRI header + frame is not audio and is left alone. The undo is recorded as mp3gain + records it — an APEv2 `MP3GAIN_UNDO` tag (+ `MP3GAIN_MINMAX`) — which + Traktor 4.5 was measured to accept (kit G1). Verified exact on real MP3s: + the decode is the original x 2^(n/4) to within 1e-5 of peak. + * **WAV / AIFF: the samples are scaled IN their data chunk** (`data`, + `SSND`), in place in a copy, so the size and every other chunk (ID3, + cue, bext, …) are byte-identical. + * **FLAC: decoded, scaled and re-encoded** at the same bit depth and rate, + every Vorbis comment, picture and application block copied back. + * 16-bit PCM is TPDF-dithered (+-1 LSB triangular) unless the result is + exact; 24-bit and float are rounded without dither. + +`verify` decodes source and result in step and checks result == source x g. +Kit G1 showed Traktor re-analyses nothing when a file's level changes — the +LIBRARY's stored gain goes stale, which the caller rewrites (`set_auto_gain`). +""" + +from __future__ import annotations + +import math +import shutil +import struct +from pathlib import Path + +import numpy as np + +from .level_plan import EXACT, STEP_DB, STEPPED + + +class LevelEditError(Exception): + """A file this module cannot (or will not) change; the message is user-facing.""" + + +def apply(src: Path | str, dst: Path | str, gain_db: float) -> None: + """Write `src` at `gain_db` to `dst`, which must not exist.""" + src, dst = Path(src), Path(dst) + if dst.exists(): + raise LevelEditError(f"{dst.name} already exists") + suffix = src.suffix.lower() + try: + if suffix in STEPPED: + _mp3(src, dst, gain_db) + elif suffix in (".wav", ".wave"): + shutil.copyfile(src, dst) + _scale_chunk(dst, _wav_layout(dst), gain_db) + elif suffix in (".aif", ".aiff"): + shutil.copyfile(src, dst) + _scale_chunk(dst, _aiff_layout(dst), gain_db) + elif suffix == ".flac": + _flac(src, dst, gain_db) + else: + raise LevelEditError(f"Cannot change the level of a {suffix or 'suffix-less'} file") + except BaseException: + dst.unlink(missing_ok=True) + raise + + +# ---- MP3: the frame-gain edit ------------------------------------------------- + +_BITRATE = { + True: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320], + False: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], +} +_RATE = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]} + + +def _get(buf, bit: int, n: int) -> int: + v = 0 + for i in range(n): + v = (v << 1) | ((buf[(bit + i) >> 3] >> (7 - ((bit + i) & 7))) & 1) + return v + + +def _put(buf: bytearray, bit: int, n: int, v: int) -> None: + for i in range(n): + b = (v >> (n - 1 - i)) & 1 + byte, shift = (bit + i) >> 3, 7 - ((bit + i) & 7) + buf[byte] = (buf[byte] & ~(1 << shift) & 0xFF) | (b << shift) + + +def _frame(buf, pos: int) -> dict | None: + """A Layer III frame header at `pos`, or None.""" + if pos + 4 > len(buf) or buf[pos] != 0xFF or (buf[pos + 1] & 0xE0) != 0xE0: + return None + ver, layer = (buf[pos + 1] >> 3) & 3, (buf[pos + 1] >> 1) & 3 + br_i, sr_i = buf[pos + 2] >> 4, (buf[pos + 2] >> 2) & 3 + if ver == 1 or layer != 1 or br_i in (0, 15) or sr_i == 3: + return None + mpeg1 = ver == 3 + nch = 1 if (buf[pos + 3] >> 6) == 3 else 2 + length = (144000 if mpeg1 else 72000) * _BITRATE[mpeg1][br_i] // _RATE[ver][sr_i] + ((buf[pos + 2] >> 1) & 1) + side_len = (17 if nch == 1 else 32) if mpeg1 else (9 if nch == 1 else 17) + return {"mpeg1": mpeg1, "crc": (buf[pos + 1] & 1) == 0, "nch": nch, "len": length, "side_len": side_len} + + +def _gain_bits(h: dict) -> list[int]: + """Bit offsets, from the side info's start, of every granule's global_gain: + MPEG-1 has 2 granules of 59 bits per channel, MPEG-2/2.5 one of 63.""" + nch = h["nch"] + if h["mpeg1"]: + start, block, granules = 9 + (5 if nch == 1 else 3) + 4 * nch, 59, 2 + else: + start, block, granules = 8 + (1 if nch == 1 else 2), 63, 1 + return [start + (g * nch + c) * block + 21 for g in range(granules) for c in range(nch)] + + +def _crc16(data: bytes) -> int: + """CRC-16 as Layer III protects a frame: poly 0x8005, init 0xFFFF, over + header bytes 2-3 and the side info.""" + crc = 0xFFFF + for byte in data: + for i in range(7, -1, -1): + bit = (byte >> i) & 1 + top = (crc >> 15) & 1 + crc = (crc << 1) & 0xFFFF + if top ^ bit: + crc ^= 0x8005 + return crc + + +def _audio_start(buf) -> int: + """Past an ID3v2 tag (and its footer), where the frames begin.""" + if buf[:3] != b"ID3" or len(buf) < 10: + return 0 + size = (buf[6] << 21) | (buf[7] << 14) | (buf[8] << 7) | buf[9] + return 10 + size + (10 if buf[5] & 0x10 else 0) + + +def mp3_steps(gain_db: float) -> int: + steps = round(gain_db / STEP_DB) + if abs(steps * STEP_DB - gain_db) > 1e-3: + raise LevelEditError(f"{gain_db:+.2f} dB is not a whole number of MP3 gain steps") + return steps + + +def _mp3(src: Path, dst: Path, gain_db: float) -> None: + steps = mp3_steps(gain_db) + buf = bytearray(src.read_bytes()) + pos = _audio_start(buf) + frames, first = 0, True + lo, hi = 255, 0 + while (h := _frame(buf, pos)) is not None: + side = pos + 4 + (2 if h["crc"] else 0) + if side + h["side_len"] > len(buf): + break + tag = bytes(buf[side + h["side_len"]: side + h["side_len"] + 4]) + if first and (tag in (b"Xing", b"Info") or bytes(buf[pos + 36: pos + 40]) == b"VBRI"): + pass # the header frame is not audio + else: + for off in _gain_bits(h): + g = _get(buf, side * 8 + off, 8) + steps + if not 0 <= g <= 255: + raise LevelEditError(f"{src.name}: the gain would leave MP3's range (frame {frames})") + _put(buf, side * 8 + off, 8, g) + lo, hi = min(lo, g), max(hi, g) + if h["crc"]: + crc = _crc16(bytes(buf[pos + 2: pos + 4]) + bytes(buf[side: side + h["side_len"]])) + buf[pos + 4: pos + 6] = struct.pack(">H", crc) + frames += 1 + first = False + pos += h["len"] + rest = bytes(buf[pos: pos + 8]) + if frames == 0 or (pos < len(buf) - 128 and not rest.startswith((b"TAG", b"APETAGEX", b"LYRICS"))): + raise LevelEditError(f"{src.name}: not an MP3 this edit can read (lost frame sync at byte {pos})") + dst.write_bytes(buf) + _mp3gain_tag(dst, steps, lo, hi) + + +def _mp3gain_tag(path: Path, steps: int, lo: int, hi: int) -> None: + """mp3gain's own record of the edit, so a later undo (by mp3gain, or by + Konduktor) is exact: MP3GAIN_UNDO = the steps that REVERSE every edit so + far, per channel, and whether any granule wrapped (never: refused).""" + from mutagen.apev2 import APEv2, APENoHeaderError + + try: + tag = APEv2(str(path)) + except APENoHeaderError: + tag = APEv2() + undo = -steps + if "MP3GAIN_UNDO" in tag: + try: + undo += int(str(tag["MP3GAIN_UNDO"]).split(",")[0]) + except ValueError: + pass + tag["MP3GAIN_UNDO"] = f"{undo:+04d},{undo:+04d},N" + tag["MP3GAIN_MINMAX"] = f"{lo:03d},{hi:03d}" + tag.save(str(path)) + + +# ---- WAV / AIFF: the samples scaled in their own chunk ------------------------ + +class _Layout: + def __init__(self, offset: int, size: int, channels: int, bits: int, kind: str, endian: str): + self.offset, self.size, self.channels = offset, size, channels + self.bits, self.kind, self.endian = bits, kind, endian # kind: "int" | "float" + + +def _wav_layout(path: Path) -> _Layout: + with open(path, "rb") as f: + head = f.read(12) + if head[:4] not in (b"RIFF", b"RIFX") or head[8:12] != b"WAVE": + raise LevelEditError(f"{path.name}: not a WAV file") + endian = "<" if head[:4] == b"RIFF" else ">" + fmt = None + while True: + hdr = f.read(8) + if len(hdr) < 8: + break + cid, size = hdr[:4], struct.unpack(endian + "I", hdr[4:])[0] + if cid == b"fmt ": + fmt = f.read(size) + if size % 2: + f.seek(1, 1) + continue + if cid == b"data": + if fmt is None: + raise LevelEditError(f"{path.name}: data before its format") + tag, channels = struct.unpack(endian + "HH", fmt[:4]) + bits = struct.unpack(endian + "H", fmt[14:16])[0] + if tag == 0xFFFE and len(fmt) >= 26: + tag = struct.unpack(endian + "H", fmt[24:26])[0] + kind = {1: "int", 3: "float"}.get(tag) + if kind is None or (kind == "int" and bits not in (16, 24, 32)) or (kind == "float" and bits not in (32, 64)): + raise LevelEditError(f"{path.name}: a WAV encoding this edit does not handle (format {tag}, {bits}-bit)") + return _Layout(f.tell(), size, channels, bits, kind, endian) + f.seek(size + (size % 2), 1) + raise LevelEditError(f"{path.name}: no audio data") + + +def _aiff_layout(path: Path) -> _Layout: + with open(path, "rb") as f: + head = f.read(12) + if head[:4] != b"FORM" or head[8:12] not in (b"AIFF", b"AIFC"): + raise LevelEditError(f"{path.name}: not an AIFF file") + comm = None + while True: + hdr = f.read(8) + if len(hdr) < 8: + break + cid, size = hdr[:4], struct.unpack(">I", hdr[4:])[0] + if cid == b"COMM": + comm = f.read(size) + if size % 2: + f.seek(1, 1) + continue + if cid == b"SSND": + if comm is None: + raise LevelEditError(f"{path.name}: sound data before its format") + channels, _frames, bits = struct.unpack(">hIh", comm[:8]) + compression = comm[18:22] if head[8:12] == b"AIFC" and len(comm) >= 22 else b"NONE" + offset, _block = struct.unpack(">II", f.read(8)) + endian, kind = ">", "int" + if compression == b"sowt": + endian = "<" + elif compression in (b"fl32", b"FL32"): + kind, bits = "float", 32 + elif compression != b"NONE": + raise LevelEditError(f"{path.name}: compressed AIFF ({compression.decode(errors='replace')})") + if kind == "int" and bits not in (16, 24, 32): + raise LevelEditError(f"{path.name}: {bits}-bit AIFF is not handled") + return _Layout(f.tell() + offset, size - 8 - offset, channels, bits, kind, endian) + f.seek(size + (size % 2), 1) + raise LevelEditError(f"{path.name}: no sound data") + + +def _decode_ints(raw: bytes, bits: int, endian: str) -> np.ndarray: + if bits == 24: + b = np.frombuffer(raw, np.uint8).reshape(-1, 3).astype(np.int32) + if endian == "<": + v = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16) + else: + v = b[:, 2] | (b[:, 1] << 8) | (b[:, 0] << 16) + return np.where(v & 0x800000, v - 0x1000000, v).astype(np.int64) + return np.frombuffer(raw, np.dtype(f"{endian}i{bits // 8}")).astype(np.int64) + + +def _encode_ints(v: np.ndarray, bits: int, endian: str) -> bytes: + if bits == 24: + u = (v.astype(np.int64) & 0xFFFFFF).astype(np.uint32) + out = np.empty((u.size, 3), np.uint8) + order = (0, 1, 2) if endian == "<" else (2, 1, 0) + for i, o in enumerate(order): + out[:, i] = (u >> (8 * o)) & 0xFF + return out.tobytes() + return v.astype(np.dtype(f"{endian}i{bits // 8}")).tobytes() + + +def _quantise(x: np.ndarray, bits: int, rng, dither: bool) -> np.ndarray: + """Float samples in integer units -> integers, TPDF-dithered when asked, + clipped to the format's range (a raise is capped below full scale by + `level_plan`, so clipping is only ever the dither's last LSB).""" + if dither: + x = x + rng.random(x.shape) - rng.random(x.shape) + top = 2 ** (bits - 1) + return np.clip(np.rint(x), -top, top - 1).astype(np.int64) + + +def _needs_dither(bits: int, factor: float) -> bool: + # Exact only when scaling up by a whole power of two (an integer factor). + return bits == 16 and not (factor >= 1 and float(factor).is_integer()) + + +def _scale_chunk(path: Path, lay: _Layout, gain_db: float) -> None: + factor = 10.0 ** (gain_db / 20.0) + width = lay.bits // 8 + frame = width * lay.channels + rng = np.random.default_rng(0) # reproducible: a re-run writes the same bytes + dither = lay.kind == "int" and _needs_dither(lay.bits, factor) + usable = lay.size - lay.size % frame + chunk = frame * 65536 + with open(path, "r+b") as f: + done = 0 + while done < usable: + n = min(chunk, usable - done) + f.seek(lay.offset + done) + raw = f.read(n) + if len(raw) < n: + raise LevelEditError(f"{path.name}: the audio data is shorter than its header says") + if lay.kind == "float": + dtype = np.dtype(f"{lay.endian}f{width}") + out = (np.frombuffer(raw, dtype).astype(np.float64) * factor).astype(dtype).tobytes() + else: + out = _encode_ints(_quantise(_decode_ints(raw, lay.bits, lay.endian) * factor, lay.bits, rng, dither), + lay.bits, lay.endian) + f.seek(lay.offset + done) + f.write(out) + done += n + + +# ---- FLAC: decoded, scaled, re-encoded -------------------------------------------- + +def _flac(src: Path, dst: Path, gain_db: float) -> None: + import soundfile as sf + from mutagen.flac import FLAC + + info = sf.info(str(src)) + bits = {"PCM_16": 16, "PCM_24": 24, "PCM_S8": 8, "PCM_U8": 8}.get(info.subtype) + if bits not in (16, 24): + raise LevelEditError(f"{src.name}: {info.subtype} FLAC is not handled") + factor = 10.0 ** (gain_db / 20.0) + rng = np.random.default_rng(0) + dither = _needs_dither(bits, factor) + # int32 reads hold the sample in the TOP bits: shift to the format's units. + shift = 32 - bits + with sf.SoundFile(str(src)) as fin, sf.SoundFile(str(dst), "w", samplerate=info.samplerate, + channels=info.channels, format="FLAC", + subtype=info.subtype) as fout: + for block in fin.blocks(blocksize=65536, dtype="int32", always_2d=True): + v = _quantise((block.astype(np.int64) >> shift) * factor, bits, rng, dither) + fout.write((v << shift).astype(np.int32)) + old, new = FLAC(str(src)), FLAC(str(dst)) + if old.tags: + if new.tags is None: + new.add_tags() + for key, values in old.tags.as_dict().items(): + new.tags[key] = values + for picture in old.pictures: + new.add_picture(picture) + for block in old.metadata_blocks: + if getattr(block, "code", None) == 2: # APPLICATION (e.g. a DJ app's private data) + new.metadata_blocks.append(block) + new.save() + + +# ---- verification --------------------------------------------------------------- + +def _frames(path: Path): + import av + + from . import pyav + + with pyav.open_input(path) as c: + stream = c.streams.audio[0] + rs = av.AudioResampler(format="fltp", layout="stereo" if stream.codec_context.channels > 1 else "mono", + rate=int(stream.codec_context.sample_rate)) + for frame in c.decode(stream): + for out in rs.resample(frame): + yield out.to_ndarray().astype(np.float64) + for out in rs.resample(None): + yield out.to_ndarray().astype(np.float64) + + +def verify(src: Path | str, dst: Path | str, gain_db: float, *, tolerance: float = 1e-3) -> None: + """Decode both and check `dst` == `src` x 10^(g/20), to within `tolerance` + of the source's peak (16-bit dither is ~3e-5). Raises `LevelEditError`.""" + factor = 10.0 ** (gain_db / 20.0) + a_iter, b_iter = _frames(Path(src)), _frames(Path(dst)) + a_buf = b_buf = None + worst = peak = 0.0 + length_a = length_b = 0 + while True: + if a_buf is None or a_buf.shape[1] == 0: + a_buf = next(a_iter, None) + if a_buf is not None: + length_a += a_buf.shape[1] + if b_buf is None or b_buf.shape[1] == 0: + b_buf = next(b_iter, None) + if b_buf is not None: + length_b += b_buf.shape[1] + if a_buf is None or b_buf is None: + break + n = min(a_buf.shape[1], b_buf.shape[1]) + if a_buf.shape[0] != b_buf.shape[0]: + raise LevelEditError(f"{Path(dst).name}: the channel count changed") + a, b = a_buf[:, :n], b_buf[:, :n] + peak = max(peak, float(np.abs(a).max(initial=0.0))) + worst = max(worst, float(np.abs(b - a * factor).max(initial=0.0))) + a_buf, b_buf = a_buf[:, n:], b_buf[:, n:] + for rest in a_iter: + length_a += rest.shape[1] + for rest in b_iter: + length_b += rest.shape[1] + if abs(length_a - length_b) > 0: + raise LevelEditError(f"{Path(dst).name}: the length changed ({length_a} vs {length_b} samples)") + if peak > 0 and worst / peak > tolerance: + raise LevelEditError(f"{Path(dst).name}: the result is not the source at {gain_db:+.2f} dB " + f"(off by {20 * math.log10(max(worst / peak, 1e-12)):.1f} dB of peak)") diff --git a/backend/konduktor/core/level_plan.py b/backend/konduktor/core/level_plan.py new file mode 100644 index 0000000..04ad663 --- /dev/null +++ b/backend/konduktor/core/level_plan.py @@ -0,0 +1,104 @@ +"""What normalising does to ONE file's level, as one pure function. + +Shared by Normalize's preview, its run and (later) the export's "Normalise +audio", as `grid_plan` is shared by Analyze — so the dialog's counts and what +is written cannot disagree. Decided 2026-10-19 (the gain-normalisation +discussion): + + * The level is the user's pick of integrated **LUFS** or loud-section + **RMS** (`core.loudness`), brought to `target`. + * Up AND down, but a raise stops at the TRUE-PEAK `ceiling` (default + -1 dBTP): nothing Konduktor writes ever clips. A track that falls short + is `capped` and says by how much. + * A track whose peak is already over the ceiling and which is at or below + target is left alone (`hot_peak_left`) — normalising is about loudness, + not peak repair. + * Lossy files change only by the LOSSLESS frame-gain edit (`level_edit`): + whole steps of 2^(1/4) in amplitude, 1.505 dB. A lowering rounds to the + nearest step; a raise to the nearest step that stays under the ceiling. + Lossless files take the gain exactly. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Literal + +from .loudness import Loudness + +#: One `global_gain` step: amplitude x 2^(1/4). +STEP_DB = 20.0 * math.log10(2.0 ** 0.25) + +#: Rewritten exactly (PCM scaled, same bit depth). +EXACT = frozenset({".wav", ".wave", ".aif", ".aiff", ".flac"}) +#: Rewritten by the lossless frame-gain edit, in `STEP_DB` steps. +STEPPED = frozenset({".mp3"}) + +#: Closer than this to the target (lossless) is "already there". +_EXACT_TOLERANCE_DB = 0.05 + +Measure = Literal["lufs", "rms"] +Outcome = Literal["apply", "capped", "at_target", "hot_peak_left", "unsupported", "unmeasured"] + + +@dataclass(frozen=True) +class GainStep: + """`gain_db` to apply (0: nothing to write) and why. `short_by` is how far + below target a `capped` track stays.""" + + gain_db: float + outcome: Outcome + short_by: float = 0.0 + + @property + def writes(self) -> bool: + return self.gain_db != 0.0 + + +def supported(suffix: str) -> bool: + return suffix.lower() in EXACT or suffix.lower() in STEPPED + + +def plan_gain(loudness: Loudness | None, suffix: str, *, measure: Measure, + target: float, ceiling: float) -> GainStep: + """The gain for one file. `suffix` decides exact vs stepped (".mp3").""" + suffix = suffix.lower() + if not supported(suffix): + return GainStep(0.0, "unsupported") + if loudness is None: + return GainStep(0.0, "unmeasured") + level = loudness.lufs if measure == "lufs" else loudness.rms + want = target - level + stepped = suffix in STEPPED + tolerance = STEP_DB / 2 if stepped else _EXACT_TOLERANCE_DB + if abs(want) < tolerance: + return GainStep(0.0, "at_target") + if want < 0: # lowering never clips + gain = round(want / STEP_DB) * STEP_DB if stepped else want + return GainStep(_clean(gain), "apply") + headroom = ceiling - loudness.true_peak + if headroom <= 0: + return GainStep(0.0, "hot_peak_left") + gain = min(want, headroom) + if stepped: + n = round(gain / STEP_DB) + if n * STEP_DB > headroom + 1e-9: + n -= 1 + gain = n * STEP_DB + gain = _clean(gain) + if want - gain >= tolerance: + return GainStep(gain if gain > 0 else 0.0, "capped", short_by=_clean(want - gain)) + return GainStep(gain, "apply") + + +def shifted(loudness: Loudness, gain_db: float) -> Loudness: + """A file's loudness after `gain_db`: LUFS, RMS and true peak move by it, + LRA and PLR do not (a gain changes no dynamics). Exact for both edits: + `level_edit` scales the decoded samples by exactly 10^(g/20).""" + return Loudness(lufs=loudness.lufs + gain_db, rms=loudness.rms + gain_db, + true_peak=loudness.true_peak + gain_db, lra=loudness.lra, plr=loudness.plr) + + +def _clean(x: float) -> float: + return round(x, 6) + 0.0 # no -0.0, no float noise in a stored value diff --git a/backend/konduktor/gain/__init__.py b/backend/konduktor/gain/__init__.py new file mode 100644 index 0000000..f2e5968 --- /dev/null +++ b/backend/konduktor/gain/__init__.py @@ -0,0 +1 @@ +"""Gain features on the audio itself: Normalize (`normalize.py`).""" diff --git a/backend/konduktor/gain/normalize.py b/backend/konduktor/gain/normalize.py new file mode 100644 index 0000000..82ceffc --- /dev/null +++ b/backend/konduktor/gain/normalize.py @@ -0,0 +1,267 @@ +"""Normalize: change tracks' audio level in place, as an unsaved change. + +Decided 2026-10-19 (the gain-normalisation discussion). Per track the gain is +`core.level_plan.plan_gain` (the same function the dialog's preview counts +with), the file is rewritten by `core.level_edit` into +`.konduktor-partial` beside it and decode-VERIFIED, and nothing the +library or the user sees changes until ONE short end step under the app's +mutation lock: + + 1. the original is PARKED (`..konduktor-parked`, hidden on Windows) + and the verified file renamed onto the original's own name — the path + never changes, so no playlist, export set or cue needs retargeting; + 2. the library follows the new audio (`audio_changed`: its size, and its + drawn waveforms where it stores them); + 3. the DJ app's auto gain is RECOMPUTED from the new level (decided — the + old value would now double-apply the change; kit G1 measured that Traktor + never re-analyses a file whose level changed); + 4. Konduktor's own loudness value is SHIFTED by the gain (exact: the edit + scales the samples), under the new file's facts. + +From there it is an ordinary unsaved change (`pending.py`, kind "gain"): Save +deletes the parked original — permanent for a lossless file, while an MP3 +keeps an mp3gain undo tag — and Discard puts it back. Measuring first where a +track has no (or a stale) loudness happens inside the run. +""" +from __future__ import annotations + +import logging +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable + +from ..core import level_edit, loudness +from ..core.adapter import AudioChange +from ..core.level_plan import EXACT, GainStep, Measure, plan_gain, shifted +from ..pending import Pending, _replace_no_overwrite, _retrying, parked_name, partial_name, source_facts + +log = logging.getLogger(__name__) + + +class NormalizeError(Exception): + """The batch cannot run; the message is user-facing.""" + + +@dataclass(frozen=True) +class Options: + measure: Measure = "lufs" + target: float = -9.0 + ceiling: float = -1.0 + + +@dataclass +class Row: + """One track's plan: what the preview lists and the run starts from.""" + + track_id: str + title: str + source: Path | None + step: GainStep | None = None + level: float | None = None # the measure now (None: unmeasured) + skip: str | None = None # a reason, when nothing can be done + + def as_dict(self) -> dict: + out = {"track_id": self.track_id, "title": self.title, "level": self.level, "skip": self.skip} + if self.step is not None: + out.update(gain_db=self.step.gain_db, outcome=self.step.outcome, short_by=self.step.short_by, + lossless=self.source is not None and self.source.suffix.lower() in EXACT) + return out + + +@dataclass +class Plan: + rows: list[Row] = field(default_factory=list) + + def as_dict(self) -> dict: + counts: dict[str, int] = {} + lossless = 0 + for r in self.rows: + key = r.skip and "skipped" or (r.step.outcome if r.step else "skipped") + counts[key] = counts.get(key, 0) + 1 + if r.step is not None and r.step.writes and r.source.suffix.lower() in EXACT: + lossless += 1 + writes = sum(1 for r in self.rows if r.step is not None and r.step.writes) + unmeasured = counts.get("unmeasured", 0) + return {"total": len(self.rows), "to_change": writes, "to_measure": unmeasured, + "tracks_to_process": writes + unmeasured, "lossless": lossless, "counts": counts, + "rows": [r.as_dict() for r in self.rows]} + + +def plan(adapter, track_ids, opts: Options, store, pending: Pending | None) -> Plan: + """Per track: the gain `plan_gain` gives from the STORED loudness. A track + with none (or a stale one) is `unmeasured`: the run measures it first.""" + held = pending.holds(track_ids) if pending is not None else set() + out = Plan() + ids = list(dict.fromkeys(track_ids)) + facts = adapter.audio_facts(ids) + entries = store.get([f.key for f in facts.values() if f is not None]) + for tid in ids: + track = adapter.track(tid) + if track is None: + continue + title = track.title or tid + path = adapter.audio_path(tid) + f = facts.get(tid) + if tid in held: + out.rows.append(Row(tid, title, path, skip="has a stem conversion or level change awaiting Save")) + continue + if path is None or f is None or not Path(path).is_file(): + out.rows.append(Row(tid, title, path, skip="audio file not found (is the drive mounted?)")) + continue + entry = entries.get(f.key) + values = entry.values if entry is not None and not entry.stale(f) else None + step = plan_gain(values, Path(path).suffix, measure=opts.measure, target=opts.target, ceiling=opts.ceiling) + level = None if values is None else (values.lufs if opts.measure == "lufs" else values.rms) + out.rows.append(Row(tid, title, Path(path), step=step, level=level)) + return out + + +def run(handle, adapter, track_ids, opts: Options, *, store, pending: Pending, mutation, + still_current: Callable[[], bool]) -> dict: + """The job: measure where needed, rewrite + verify each file, then ONE end + step. Returns the result dict.""" + planned = plan(adapter, track_ids, opts, store, pending) + result = {"normalised": [], "skipped": [], "failed": [], "counts": {}, "cancelled": False} + rows = [r for r in planned.rows] + handle.progress(done=0, total=len(rows), unit="tracks") + finished: list[tuple[Row, dict, object]] = [] + + def skip(row: Row, reason: str) -> None: + result["skipped"].append({"track_id": row.track_id, "title": row.title, "reason": reason}) + + try: + for i, row in enumerate(rows): + if handle.cancelled: + raise _Cancel() + handle.progress(done=i, message=row.title, fraction=0.0, status="") + if row.skip: + skip(row, row.skip) + continue + source = row.source + facts = adapter.audio_facts([row.track_id]).get(row.track_id) + got = store.get([facts.key]).get(facts.key) if facts is not None else None + values = got.values if got is not None and not got.stale(facts) else None + if values is None: + handle.progress(status="measuring") + try: + values = loudness.measure_file(source) + except Exception as ex: # noqa: BLE001 — an undecodable file is one failure + result["failed"].append({"track_id": row.track_id, "title": row.title, + "reason": f"Could not measure: {ex}"}) + continue + if values is None: + skip(row, "nothing to measure (silent or under 3 s)") + continue + store.put(facts, values) + step = plan_gain(values, source.suffix, measure=opts.measure, target=opts.target, ceiling=opts.ceiling) + result["counts"][step.outcome] = result["counts"].get(step.outcome, 0) + 1 + if not step.writes: + skip(row, _WHY[step.outcome]) + continue + partial = partial_name(source) + if partial.exists(): + skip(row, f"{partial.name} is in the way") + continue + track = adapter.track(row.track_id) + before_wire = {"path": facts.key, "size": facts.size, "mtime_ns": facts.mtime_ns, + "version": loudness.VERSION, **values.as_dict()} + pitem = pending.add({ + "kind": "gain", "track_id": row.track_id, "source": str(source), "partial": str(partial), + "parked": str(parked_name(source)), "gain_db": step.gain_db, + "lossless": source.suffix.lower() in EXACT, "state": "writing", + "facts_before": source_facts(source), "loudness_before": before_wire, + "gain_before": getattr(track, "auto_gain_db", None), + }) + handle.progress(status=f"{step.gain_db:+.1f} dB") + try: + level_edit.apply(source, partial, step.gain_db) + handle.progress(fraction=0.5, status="verifying") + level_edit.verify(source, partial, step.gain_db) + except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal + partial.unlink(missing_ok=True) + pending.drop([pitem]) + result["failed"].append({"track_id": row.track_id, "title": row.title, "reason": str(ex)}) + continue + measured = None + lead = getattr(adapter, "analysis_lead", None) + if lead is not None: # the platform draws waveforms from its own files + from ..core import waveform + + handle.progress(fraction=0.8, status="waveform") + measured = waveform.analyse(partial, lead=lead(source)) + pending.update(pitem, state="written", facts_after=source_facts(partial)) + finished.append((row, pitem, (values, step, measured))) + except _Cancel: + for _row, pitem, _ in finished: + Path(pitem["partial"]).unlink(missing_ok=True) + pending.drop([p for _, p, _ in finished]) + result["cancelled"] = True + return result + + handle.progress(done=len(rows), message="Putting the new levels in place…", status="") + with mutation: + if not still_current(): + for _row, pitem, _ in finished: + Path(pitem["partial"]).unlink(missing_ok=True) + pending.drop([p for _, p, _ in finished]) + raise NormalizeError("The library changed while normalizing; nothing was changed") + for row, pitem, (values, step, measured) in finished: + try: + _end_step(adapter, row, pitem, values, step, measured, store, pending) + result["normalised"].append(row.track_id) + except Exception as ex: # noqa: BLE001 — undo that track, keep the rest + log.warning("normalize end step failed for %s", row.track_id, exc_info=True) + pending._undo_gain(pitem) + pending.drop([pitem]) + result["failed"].append({"track_id": row.track_id, "title": row.title, "reason": str(ex)}) + return result + + +def _end_step(adapter, row: Row, pitem: dict, values, step: GainStep, measured, store, pending: Pending) -> None: + source = Path(pitem["source"]) + parked = Path(pitem["parked"]) + _retrying(lambda: _replace_no_overwrite(source, parked)) + _hide(parked) + pending.update(pitem, state="parked") + _retrying(lambda: _replace_no_overwrite(Path(pitem["partial"]), source)) + pending.update(pitem, state="published") + facts = adapter.audio_facts([row.track_id]).get(row.track_id) + after = shifted(values, step.gain_db) + adapter.audio_changed(row.track_id, AudioChange(gain_db=step.gain_db, size=source.stat().st_size, + measured=measured)) + if adapter.capabilities().tracks.auto_gain: + # Recomputed from the NEW level (decided): the old value would now + # double-apply the change. + adapter.set_auto_gain(row.track_id, after) + track = adapter.track(row.track_id) + if facts is not None: + store.put(facts, after) + pending.update(pitem, state="swapped", gain_after=getattr(track, "auto_gain_db", None), + facts_after=source_facts(source)) + + +_WHY = { + "at_target": "already at the target", + "hot_peak_left": "its peak is already over the ceiling", + "capped": "no headroom under the ceiling", + "unsupported": "this format cannot be changed losslessly", + "unmeasured": "not measured", +} + + +class _Cancel(Exception): + pass + + +def _hide(path: Path) -> None: + """Windows ignores dot-names; set the hidden attribute so a parked original + does not show in Explorer (or a naive folder scan).""" + if sys.platform != "win32": + return + try: + import ctypes + + ctypes.windll.kernel32.SetFileAttributesW(str(path), 0x02) + except Exception: # noqa: BLE001 + pass diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index d723184..7ed5e31 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -121,6 +121,7 @@ from .schemas import ( StemEngineInstall, StemSideLoad, StemConvert, + NormalizeRequest, ) log = logging.getLogger(__name__) @@ -409,7 +410,7 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: """Set (or, with blank prefixes, clear) the current collection's remapping. Persists to userprefs AND updates the live store so playback/analysis re-resolve immediately — no reopen needed. Never touches the .nml.""" - _require_no_pending_stems("Changing the path mapping") + _require_no_pending("Changing the path mapping") a = require_adapter() mapping = PathMapping.make(body.from_, body.to) prefs.set_path_mapping( @@ -445,7 +446,7 @@ def remap_paths(body: PathMappingInfo) -> RemapResult: playlist references that join to them) to the `to` prefix, then save (a version-history commit is written). Destructive and OS-specific — the UI warns accordingly.""" - _require_no_pending_stems("Rewriting paths") + _require_no_pending("Rewriting paths") mapping = PathMapping.make(body.from_, body.to) if mapping.empty: raise HTTPException(400, "Both a `from` and `to` prefix are required") @@ -512,7 +513,7 @@ def answer_relocation(body: RelocationApply) -> RelocationApplied: """Answer the check: apply the chosen mappings for THIS SESSION only (no mappings = "Not now"). Nothing is written to the library or to prefs, and a reopen asks again.""" - _require_no_pending_stems("Relocating files") + _require_no_pending("Relocating files") require_adapter() check = STATE.relocation if check is None: @@ -958,9 +959,13 @@ def capabilities() -> Capabilities: @app.get("/api/state", response_model=EditState) def state() -> EditState: stem_job = JOBS.active(STEM_JOB) + normalize_job = JOBS.active(NORMALIZE_JOB) pending = STATE.pending.summary() if STATE.pending is not None else None return EditState(dirty=require_adapter().dirty, library=_library_info(), pending_stems=pending if pending and pending["tracks"] else None, + pending_gain=({"tracks": pending["gain_tracks"], "lossless": pending["gain_lossless"]} + if pending and pending.get("gain_tracks") else None), + normalize_job=normalize_job[0].id if normalize_job else None, stem_job=stem_job[0].id if stem_job else None, stem_recovery=STATE.recovery, remote=STATE.remote.describe() if STATE.remote is not None else None) @@ -1029,14 +1034,19 @@ def install_stem_engine(body: StemEngineInstall) -> JobStatus: return JobStatus(**job.as_dict()) -def _require_no_pending_stems(what: str) -> None: - """Refuse an operation that would SAVE or DROP a stem conversion's swap as a +def _require_no_pending(what: str) -> None: + """Refuse an operation that would SAVE or DROP a pending file change as a side effect — import and remap save pending edits, reload and restore drop - them — while converted tracks await Save/Discard or a conversion runs.""" + them — while converted or normalized tracks await Save/Discard, or a + conversion or Normalize runs. (Remap and relocation would also move the + paths the ledger is keyed by.)""" if JOBS.active(STEM_JOB): raise HTTPException(409, f"{what} is not possible while tracks are being converted to stems") + if JOBS.active(NORMALIZE_JOB): + raise HTTPException(409, f"{what} is not possible while tracks are being normalized") if STATE.pending is not None and STATE.pending.blocking(): - raise HTTPException(409, f"{what} is not possible until the converted tracks are saved or discarded") + raise HTTPException(409, f"{what} is not possible until the converted or normalized tracks " + "are saved or discarded") def _stem_options(body): @@ -1172,7 +1182,7 @@ def discard_changes() -> EditState: @app.post("/api/reload") def reload_collection() -> dict: - _require_no_pending_stems("Reloading") + _require_no_pending("Reloading") if not STATE.loaded: raise HTTPException(409, "No collection loaded") if STATE.remote is not None: @@ -1580,7 +1590,8 @@ class _AnalysisError(Exception): # beats that no longer exist. GRID_JOB = "grid-analysis" CUE_JOB = "auto-hotcues" -BATCH_JOBS = (GRID_JOB, CUE_JOB, STEM_JOB) +NORMALIZE_JOB = "normalize" +BATCH_JOBS = (GRID_JOB, CUE_JOB, STEM_JOB, NORMALIZE_JOB) def _stop_batches() -> None: @@ -1924,6 +1935,56 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: key=False, replace_grid=body.replace_existing)) +# ---- Normalize (the track menu's Mastering ▸ Normalize…) -------------------- +# +# Changes the audio files' level in place (`gain/normalize.py`): parked +# originals until Save, like a stem conversion. The library's own tracks only. + + +def _normalize_target(body: NormalizeRequest): + a = require_adapter() + if STATE.remote is not None: + raise HTTPException(409, "Normalize is not available on a remote library yet") + caps = a.capabilities() + if not (caps.writable and caps.tracks.normalizable): + raise HTTPException(422, "This library's audio files cannot be normalized") + if not -30.0 <= body.target <= 0.0 or not -12.0 <= body.ceiling <= 0.0: + raise HTTPException(400, "Target or ceiling out of range") + from .gain import normalize + + return a, normalize.Options(measure=body.measure, target=body.target, ceiling=body.ceiling) + + +@app.post("/api/tracks/normalize/preview") +def normalize_preview(body: NormalizeRequest) -> dict: + """What Normalize would do per track, from the same `plan_gain` the run uses.""" + from .gain import normalize + + a, opts = _normalize_target(body) + return normalize.plan(a, body.track_ids, opts, STATE.loudness, STATE.pending).as_dict() + + +@app.post("/api/tracks/normalize", response_model=JobStatus) +def normalize_tracks(body: NormalizeRequest) -> JobStatus: + """Normalize as a JOB; the new files land at its end as unsaved changes.""" + from .gain import normalize + + a, opts = _normalize_target(body) + _require_no_batch() + if JOBS.active("import"): + raise HTTPException(409, "Wait for the import to finish") + + def run(handle): + return normalize.run(handle, a, body.track_ids, opts, store=STATE.loudness, pending=STATE.pending, + mutation=STATE.mutation, still_current=lambda: STATE.adapter is a) + + try: + job = JOBS.submit(NORMALIZE_JOB, run, exclusive_with=BATCH_JOBS + ("import",)) + except JobBusy: + raise HTTPException(409, "Another batch or import is running") + return JobStatus(**job.as_dict()) + + # ---- Loudness (the Mastering columns) -------------------------------------- # # Measured by `core/loudness.py` into Konduktor's own store (`loudness_store.py`), @@ -2299,7 +2360,7 @@ def restore_version(commit_id: str) -> CollectionStatus: """Restore the collection to a past version. Writes that version back as a NEW forward save (a fresh commit on top of history — never a rewind), then reloads. The user should close Traktor first (it overwrites on exit).""" - _require_no_pending_stems("Restoring a version") + _require_no_pending("Restoring a version") require_adapter() if not STATE.restore_version(commit_id): raise HTTPException(404, f"Version not found: {commit_id}") @@ -2790,7 +2851,7 @@ def folder_add_preview(body: FolderAddRequest) -> dict: @app.post("/api/folder/add", response_model=JobStatus) def folder_add(body: FolderAddRequest) -> JobStatus: """Add browsed files to the collection. A job, like import: copying can be long.""" - _require_no_pending_stems("Adding files") + _require_no_pending("Adding files") in_place = _is_server_add(body) if in_place: source, dest, plan = _server_add_plan(body) @@ -2880,7 +2941,7 @@ def import_preview(body: ImportRequest) -> dict: @app.post("/api/import", response_model=JobStatus) def start_import(body: ImportRequest) -> JobStatus: """Start an import. Returns immediately; poll the job for progress.""" - _require_no_pending_stems("Importing") + _require_no_pending("Importing") source, dest, destination, plan = _import_plan(body) if not plan.importable: raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)") diff --git a/backend/konduktor/pending.py b/backend/konduktor/pending.py new file mode 100644 index 0000000..adf7994 --- /dev/null +++ b/backend/konduktor/pending.py @@ -0,0 +1,378 @@ +"""Changes to audio FILES that are done on disk but not yet committed by a Save. + +Two kinds of item share this ledger (and every hook into it — Save, Discard, +opening another library, crash recovery, the routes that must refuse while +any are pending): a Convert to Stems swap (`kind` "stem", or no kind — every +ledger written before Normalize) and a Normalize level change (`kind` "gain", +see "Gain items" below). + +A Convert to Stems batch leaves, per track: a stem file, and — in Replace mode — +the original PARKED beside it (`...konduktor-parked`, the same +folder, so the rename is atomic and nothing looks like audio). The collection +swap itself is an ordinary unsaved edit. So the files must follow what happens +to the edits: + + * **Save** commits them: parked originals are deleted (the user chose Replace, + and was told Save deletes them), export sets follow the new ids. + * **Discard** — or opening another library, after its confirm — undoes them: + originals go back under their own names, the stem files are removed. + * **A crash** leaves this ledger on disk. The next open of the library + decides each item from the SAVED collection: if it names the stem file the + swap was committed (finish deleting the original), otherwise it was not + (put the original back). Verified stem files of an uncommitted item are + kept — renamed to their `.konduktor-partial` name, so neither the user nor + Traktor mistakes them for finished files — and a later batch converting the + same source reuses one instead of spending minutes separating it again. + +**Gain items** (Normalize, decided 2026-10-19). The level-changed file is +written beside the source as `.konduktor-partial` and verified; then the +source is PARKED and the partial renamed onto the source's own name, so the +path never changes. States: writing -> written -> parked -> published -> +swapped (the library's gain/waveform edits made) -> saving -> saved. Because +the path does not change, "does the saved library name the new file" cannot +tell a crash's outcome; instead `AppState._save` brackets `adapter.save()` +with `begin_save` / `mark_saved`, so only a crash INSIDE the save (state +"saving") needs the library asked (`is_committed`, which the caller words +per platform). Unsure always means restore: the original audio is never +destroyed on a guess. After Save a lossless file's change is permanent (the +original is deleted); an MP3's stays reversible by its mp3gain undo tag. + +The ledger is Konduktor's own curated state, written atomically +(`paths.write_json`), one file per library id. Every step is taken from what is +actually ON DISK, never from the recorded state alone: a crash can fall between +any two renames. +""" +from __future__ import annotations + +import os +import threading +import time +from pathlib import Path + +from . import paths + +PARTIAL = ".konduktor-partial" +PARKED = ".konduktor-parked" + + +def parked_name(original: Path) -> Path: + return original.with_name(f".{original.name}{PARKED}") + + +def partial_name(stem: Path) -> Path: + return stem.with_name(stem.name + PARTIAL) + + +def source_facts(path: Path) -> dict | None: + try: + st = path.stat() + except OSError: + return None + return {"size": st.st_size, "mtime_ns": st.st_mtime_ns} + + +def _replace_no_overwrite(src: Path, dst: Path) -> None: + """Rename refusing to overwrite: POSIX link+unlink (link fails if dst + exists), Windows rename (which already refuses). A filesystem with no hard + links (FAT / exFAT: a USB stick, which a Normalize can rewrite in place) + falls back to check-then-rename — the only window is another program + creating that exact name in between.""" + if os.name == "nt": + os.rename(src, dst) + return + try: + os.link(src, dst) + except FileExistsError: + raise + except OSError: + if os.path.lexists(dst): + raise FileExistsError(dst) + os.rename(src, dst) + return + os.unlink(src) + + +def _retrying(fn, *, attempts: int = 6, delay: float = 0.25): + """Windows cannot rename a file another process has open (Traktor, the + deck's stream, an antivirus scan of a file just written): retry briefly.""" + for i in range(attempts): + try: + return fn() + except PermissionError: + if os.name != "nt" or i == attempts - 1: + raise + time.sleep(delay * (2 ** i)) + + +class Pending: + """The ledger for ONE library.""" + + def __init__(self, library_id: str | None) -> None: + self.library_id = library_id + #: Gain items the last restore/recover put back, for their loudness. + self.restored_gain: list[dict] = [] + self._lock = threading.RLock() + self._path = (paths.app_data_dir() / "stems" / f"pending-{library_id}.json") if library_id else None + data = paths.read_json(self._path, None) if self._path else None + self.items: list[dict] = (data or {}).get("items", []) + self.leftovers: list[dict] = (data or {}).get("leftovers", []) + + # ---- persistence ---------------------------------------------------------- + def _write(self) -> None: + if self._path is None: + return + if not self.items and not self.leftovers: + self._path.unlink(missing_ok=True) + return + self._path.parent.mkdir(parents=True, exist_ok=True) + paths.write_json(self._path, {"items": self.items, "leftovers": self.leftovers}) + + def add(self, item: dict) -> dict: + with self._lock: + self.items.append(item) + self._write() + return item + + def update(self, item: dict, **fields) -> None: + with self._lock: + item.update(fields) + self._write() + + def drop(self, items: list[dict]) -> None: + with self._lock: + ids = {id(i) for i in items} + self.items = [i for i in self.items if id(i) not in ids] + self._write() + + # ---- what the rest of the app asks ---------------------------------------------- + def swapped(self) -> list[dict]: + """Every item whose library edit is made and awaits Save (both kinds).""" + return [i for i in self.items if i.get("state") in _AWAITING_SAVE.get(_kind(i), ())] + + def blocking(self) -> bool: + """Changes awaiting Save or Discard — while there are any, import, + remap, reload and history restore must refuse: each would save or drop + them as a side effect.""" + return bool(self.swapped()) + + def holds(self, track_ids) -> set[str]: + """The given tracks that have an item of EITHER kind in flight — a + track is converted or normalised once per Save, never both at once.""" + wanted = set(track_ids) + return {i["track_id"] for i in self.items if i.get("track_id") in wanted} + + def summary(self) -> dict: + waiting = self.swapped() + stems = [i for i in waiting if _kind(i) == "stem"] + gains = [i for i in waiting if _kind(i) == "gain"] + parked = [Path(i["parked"]) for i in stems if i.get("parked")] + return {"tracks": len(stems), + "parked": len(parked), + "bytes": sum(p.stat().st_size for p in parked if p.exists()), + # Normalize: files whose level Save makes permanent. + "gain_tracks": len(gains), + "gain_lossless": sum(1 for i in gains if i.get("lossless"))} + + # ---- Save markers (gain items) ------------------------------------------------ + def begin_save(self, library_facts: dict | None) -> None: + """Right before `adapter.save()`: from here a crash's outcome depends + on whether the save landed, which recovery asks the library.""" + with self._lock: + changed = False + for item in self.items: + if _kind(item) == "gain" and item.get("state") == "swapped": + item["state"], item["library_before"] = "saving", library_facts + changed = True + if changed: + self._write() + + def abort_save(self) -> None: + """The save raised: nothing was committed, the items await Save again.""" + self._set_gain_state("saving", "swapped") + + def mark_saved(self) -> None: + """The save returned: the library holds the new gains — commit next.""" + self._set_gain_state("saving", "saved") + + def _set_gain_state(self, frm: str, to: str) -> None: + with self._lock: + changed = False + for item in self.items: + if _kind(item) == "gain" and item.get("state") == frm: + item["state"] = to + changed = True + if changed: + self._write() + + # ---- leftovers (reuse after a crash) ----------------------------------------------- + def find_leftover(self, source: Path) -> dict | None: + facts = source_facts(source) + for lo in self.leftovers: + if lo["source"] == str(source) and lo.get("facts") == facts and Path(lo["partial"]).is_file(): + return lo + return None + + def forget_leftover(self, leftover: dict, *, delete: bool) -> None: + with self._lock: + if delete: + Path(leftover["partial"]).unlink(missing_ok=True) + self.leftovers = [lo for lo in self.leftovers if lo is not leftover] + self._write() + + def _keep_as_leftover(self, item: dict) -> None: + """A verified stem file whose swap was not committed: keep it under its + partial name for reuse (rather than hours of separation lost).""" + stem = Path(item["stem"]) + partial = partial_name(stem) + try: + if _published(item) and stem.is_file() and not partial.exists(): + os.replace(stem, partial) + except OSError: + return + if partial.is_file() and item.get("written"): + self.leftovers.append({"source": item["source"], "facts": item.get("facts"), + "partial": str(partial), "written": item["written"]}) + + # ---- Save / Discard / recovery --------------------------------------------------- + def commit(self) -> dict[str, str]: + """After a successful Save: delete what the swap replaced. Returns the + repoint renames so the caller retargets export sets.""" + renames: dict[str, str] = {} + with self._lock: + for item in self.swapped(): + if _kind(item) == "gain": + if item.get("state") == "saved": + self._commit_gain(item) + continue + if item.get("parked"): + try: + Path(item["parked"]).unlink(missing_ok=True) + except OSError: + pass # a file still open on Windows: recovery tries again + if item.get("mode") == "repoint" and item.get("new_id"): + renames[item["track_id"]] = item["new_id"] + item["state"] = "committed" + self.items = [i for i in self.items if i.get("state") != "committed" + or (i.get("parked") and Path(i["parked"]).exists())] + self._write() + return renames + + def _commit_gain(self, item: dict) -> None: + """The new level is saved: the parked original goes — only if the + normalised file really is in place, never leaving the path empty.""" + parked = Path(item["parked"]) if item.get("parked") else None + if parked is not None and Path(item["source"]).is_file(): + try: + parked.unlink(missing_ok=True) + except OSError: + return # open on Windows: stays "saved", recovery tries again + item["state"] = "committed" + + def restore(self) -> int: + """Undo every uncommitted conversion: originals back, stem files gone. + Returns how many originals were put back.""" + restored = 0 + self.restored_gain = [] + with self._lock: + for item in list(self.items): + if _kind(item) == "gain": + restored += self._undo_gain(item) + else: + restored += self._undo(item, keep_leftover=False) + self.items = [] + self._write() + return restored + + def recover(self, is_committed) -> dict: + """At open, after a crash: decide each leftover item from the SAVED + collection (`is_committed(item)` — does it name the stem file?).""" + report = {"committed": 0, "restored": 0, "kept": 0} + self.restored_gain = [] + with self._lock: + before = len(self.leftovers) + for item in list(self.items): + if _kind(item) == "gain": + state = item.get("state") + if state == "saved" or (state == "saving" and is_committed(item)): + self._commit_gain(item) + report["committed"] += 1 + else: + report["restored"] += self._undo_gain(item) + continue + if item.get("new_id") and is_committed(item): + if item.get("parked"): + Path(item["parked"]).unlink(missing_ok=True) + report["committed"] += 1 + else: + report["restored"] += self._undo(item, keep_leftover=True) + report["kept"] = len(self.leftovers) - before + self.items = [] + self._write() + return report + + def _undo_gain(self, item: dict) -> int: + """Put one Normalize item's file back as it was. Filesystem-driven: + the normalised file at the source's name is removed only when it is + recognisably OURS (its facts, or the state says Save may have touched + its tags); a file someone else put there is kept, with the original + still parked beside it. Records the item in `restored_gain` so the + caller puts its loudness value back.""" + source = Path(item["source"]) + parked = Path(item["parked"]) if item.get("parked") else None + partial = Path(item["partial"]) if item.get("partial") else None + restored = 0 + try: + if partial is not None: + partial.unlink(missing_ok=True) + if parked is not None and parked.exists(): + ours = item.get("state") in ("saving", "saved") or source_facts(source) in (None, item.get("facts_after")) + if source.exists() and ours and item.get("state") in _PUBLISHED_GAIN: + source.unlink() + if not source.exists(): + _retrying(lambda: _replace_no_overwrite(parked, source)) + restored = 1 + except OSError: + return restored + if restored: + self.restored_gain.append(item) + return restored + + def _undo(self, item: dict, *, keep_leftover: bool) -> int: + """Put one item's files back as they were. Filesystem-driven.""" + restored = 0 + original = Path(item["source"]) + parked = Path(item["parked"]) if item.get("parked") else None + if parked is not None and parked.exists() and not original.exists(): + _retrying(lambda: _replace_no_overwrite(parked, original)) + restored = 1 + stem = Path(item["stem"]) + if keep_leftover and item.get("written"): + self._keep_as_leftover(item) + else: + try: + # Only a stem file THIS batch published is ours to delete: before + # that, a file at the target name belongs to someone else. + if _published(item): + stem.unlink(missing_ok=True) + partial_name(stem).unlink(missing_ok=True) # unverified: worthless + except OSError: + pass + return restored + + +def _published(item: dict) -> bool: + return item.get("state") in ("published", "parked", "swapped", "committed") + + +def _kind(item: dict) -> str: + return item.get("kind") or "stem" + + +#: The states in which an item's library edit is made and awaits Save. +_AWAITING_SAVE = {"stem": ("swapped",), "gain": ("swapped", "saving", "saved")} +#: A gain item whose normalised file has been renamed onto the source's name. +_PUBLISHED_GAIN = ("published", "swapped", "saving", "saved") + + +__all__ = ["PARKED", "PARTIAL", "Pending", "parked_name", "partial_name", "source_facts", + "_replace_no_overwrite", "_retrying"] diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index 9a9bf7b..28a6260 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -106,6 +106,7 @@ EXCLUDED: dict[str, str] = { "cover_art": "GET /v1/art — bytes", "set_cover_art": "PUT /v1/art — bytes", "apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)", + "audio_changed": "the server applies a Normalize itself, at its own end step (not yet remote)", "set_path_mapping": "the server's path mapping is its own configuration", "set_session_mappings": "the missing-files check searches THIS computer's drives", "unresolved_path_groups": "the missing-files check searches THIS computer's drives", diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 34c9e3b..6d1301f 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -326,6 +326,11 @@ class EditState(BaseModel): stem_job: str | None = None # What this open's crash recovery did about an interrupted conversion. stem_recovery: dict | None = None + # Normalized tracks awaiting Save/Discard: {tracks, lossless} (lossless = + # files whose change Save makes permanent). + pending_gain: dict | None = None + # A running Normalize's job id, so a reloaded page finds it again. + normalize_job: str | None = None # A remote library's connection: {state, via, machine}. None when local. remote: dict | None = None @@ -701,3 +706,12 @@ class JobStatus(BaseModel): error: str | None = None started_at: float finished_at: float | None = None + + +class NormalizeRequest(BaseModel): + """Normalize's choices (`gain/normalize.py`, `core/level_plan.py`): the + measure brought to `target`, a raise stopping at the true-peak `ceiling`.""" + track_ids: list[str] + measure: Literal["lufs", "rms"] = "lufs" + target: float = -9.0 + ceiling: float = -1.0 diff --git a/backend/konduktor/server/app.py b/backend/konduktor/server/app.py index 3827e6f..4d9d4e3 100644 --- a/backend/konduktor/server/app.py +++ b/backend/konduktor/server/app.py @@ -617,7 +617,7 @@ def create_app(server: Server) -> FastAPI: import hashlib from ..core.loudness import Loudness - from ..stems.pending import partial_name, source_facts + from ..pending import partial_name, source_facts session(token) measured = None @@ -661,7 +661,7 @@ def create_app(server: Server) -> FastAPI: token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict: """A cancelled batch: delete the files it uploaded (a cancel deletes only new files, as on this computer).""" - from ..stems.pending import partial_name + from ..pending import partial_name session(token) pending = server.state.pending @@ -677,7 +677,7 @@ def create_app(server: Server) -> FastAPI: stem file, park originals (Replace), swap every entry at once.""" from ..core import stem_file as sf from ..stems import convert - from ..stems.pending import partial_name + from ..pending import partial_name holder = session(token) opts = stem_options(body.get("options") or {}) diff --git a/backend/konduktor/stems/convert.py b/backend/konduktor/stems/convert.py index 89b14f1..d7d4edd 100644 --- a/backend/konduktor/stems/convert.py +++ b/backend/konduktor/stems/convert.py @@ -159,11 +159,17 @@ def plan(adapter, track_ids: list[str], opts: Options, pending: Pending | None) in_library = {str(p) for t in adapter.tracks if (p := adapter.audio_path(t.id)) is not None} candidates: list[tuple[str, object, Path]] = [] + # A track whose level change (Normalize) awaits Save: converting it would + # build a stem file from audio Discard is about to put back. + held = {i["track_id"] for i in pending.items if i.get("kind") == "gain"} if pending is not None else set() for tid in dict.fromkeys(track_ids): track = adapter.track(tid) src = adapter.audio_path(tid) if track is not None else None if track is None: result.skipped.append({"track_id": tid, "title": tid, "reason": "not in the library"}) + elif tid in held: + result.skipped.append({"track_id": tid, "title": _title(track), + "reason": "its level change awaits Save"}) elif src is None or not Path(src).is_file(): result.skipped.append({"track_id": tid, "title": _title(track), "reason": "the file is missing"}) elif sf.is_stem_file(src): diff --git a/backend/konduktor/stems/pending.py b/backend/konduktor/stems/pending.py index 1597890..4659c88 100644 --- a/backend/konduktor/stems/pending.py +++ b/backend/konduktor/stems/pending.py @@ -1,237 +1,4 @@ -"""Conversions that are done on disk but not yet committed by a Save. - -A Convert to Stems batch leaves, per track: a stem file, and — in Replace mode — -the original PARKED beside it (`...konduktor-parked`, the same -folder, so the rename is atomic and nothing looks like audio). The collection -swap itself is an ordinary unsaved edit. So the files must follow what happens -to the edits: - - * **Save** commits them: parked originals are deleted (the user chose Replace, - and was told Save deletes them), export sets follow the new ids. - * **Discard** — or opening another library, after its confirm — undoes them: - originals go back under their own names, the stem files are removed. - * **A crash** leaves this ledger on disk. The next open of the library - decides each item from the SAVED collection: if it names the stem file the - swap was committed (finish deleting the original), otherwise it was not - (put the original back). Verified stem files of an uncommitted item are - kept — renamed to their `.konduktor-partial` name, so neither the user nor - Traktor mistakes them for finished files — and a later batch converting the - same source reuses one instead of spending minutes separating it again. - -The ledger is Konduktor's own curated state, written atomically -(`paths.write_json`), one file per library id. Every step is taken from what is -actually ON DISK, never from the recorded state alone: a crash can fall between -any two renames. -""" -from __future__ import annotations - -import os -import threading -import time -from pathlib import Path - -from .. import paths - -PARTIAL = ".konduktor-partial" -PARKED = ".konduktor-parked" - - -def parked_name(original: Path) -> Path: - return original.with_name(f".{original.name}{PARKED}") - - -def partial_name(stem: Path) -> Path: - return stem.with_name(stem.name + PARTIAL) - - -def source_facts(path: Path) -> dict | None: - try: - st = path.stat() - except OSError: - return None - return {"size": st.st_size, "mtime_ns": st.st_mtime_ns} - - -def _replace_no_overwrite(src: Path, dst: Path) -> None: - """Rename refusing to overwrite: POSIX link+unlink (link fails if dst - exists), Windows rename (which already refuses).""" - if os.name == "nt": - os.rename(src, dst) - return - os.link(src, dst) - os.unlink(src) - - -def _retrying(fn, *, attempts: int = 6, delay: float = 0.25): - """Windows cannot rename a file another process has open (Traktor, the - deck's stream, an antivirus scan of a file just written): retry briefly.""" - for i in range(attempts): - try: - return fn() - except PermissionError: - if os.name != "nt" or i == attempts - 1: - raise - time.sleep(delay * (2 ** i)) - - -class Pending: - """The ledger for ONE library.""" - - def __init__(self, library_id: str | None) -> None: - self.library_id = library_id - self._lock = threading.RLock() - self._path = (paths.app_data_dir() / "stems" / f"pending-{library_id}.json") if library_id else None - data = paths.read_json(self._path, None) if self._path else None - self.items: list[dict] = (data or {}).get("items", []) - self.leftovers: list[dict] = (data or {}).get("leftovers", []) - - # ---- persistence ---------------------------------------------------------- - def _write(self) -> None: - if self._path is None: - return - if not self.items and not self.leftovers: - self._path.unlink(missing_ok=True) - return - self._path.parent.mkdir(parents=True, exist_ok=True) - paths.write_json(self._path, {"items": self.items, "leftovers": self.leftovers}) - - def add(self, item: dict) -> dict: - with self._lock: - self.items.append(item) - self._write() - return item - - def update(self, item: dict, **fields) -> None: - with self._lock: - item.update(fields) - self._write() - - def drop(self, items: list[dict]) -> None: - with self._lock: - ids = {id(i) for i in items} - self.items = [i for i in self.items if id(i) not in ids] - self._write() - - # ---- what the rest of the app asks ---------------------------------------------- - def swapped(self) -> list[dict]: - return [i for i in self.items if i.get("state") == "swapped"] - - def blocking(self) -> bool: - """Conversions awaiting Save or Discard — while there are any, import, - remap, reload and history restore must refuse: each would save or drop - the swap as a side effect.""" - return bool(self.swapped()) - - def summary(self) -> dict: - parked = [Path(i["parked"]) for i in self.swapped() if i.get("parked")] - return {"tracks": len(self.swapped()), - "parked": len(parked), - "bytes": sum(p.stat().st_size for p in parked if p.exists())} - - # ---- leftovers (reuse after a crash) ----------------------------------------------- - def find_leftover(self, source: Path) -> dict | None: - facts = source_facts(source) - for lo in self.leftovers: - if lo["source"] == str(source) and lo.get("facts") == facts and Path(lo["partial"]).is_file(): - return lo - return None - - def forget_leftover(self, leftover: dict, *, delete: bool) -> None: - with self._lock: - if delete: - Path(leftover["partial"]).unlink(missing_ok=True) - self.leftovers = [lo for lo in self.leftovers if lo is not leftover] - self._write() - - def _keep_as_leftover(self, item: dict) -> None: - """A verified stem file whose swap was not committed: keep it under its - partial name for reuse (rather than hours of separation lost).""" - stem = Path(item["stem"]) - partial = partial_name(stem) - try: - if _published(item) and stem.is_file() and not partial.exists(): - os.replace(stem, partial) - except OSError: - return - if partial.is_file() and item.get("written"): - self.leftovers.append({"source": item["source"], "facts": item.get("facts"), - "partial": str(partial), "written": item["written"]}) - - # ---- Save / Discard / recovery --------------------------------------------------- - def commit(self) -> dict[str, str]: - """After a successful Save: delete what the swap replaced. Returns the - repoint renames so the caller retargets export sets.""" - renames: dict[str, str] = {} - with self._lock: - for item in self.swapped(): - if item.get("parked"): - try: - Path(item["parked"]).unlink(missing_ok=True) - except OSError: - pass # a file still open on Windows: recovery tries again - if item.get("mode") == "repoint" and item.get("new_id"): - renames[item["track_id"]] = item["new_id"] - item["state"] = "committed" - self.items = [i for i in self.items if i.get("state") != "committed" - or (i.get("parked") and Path(i["parked"]).exists())] - self._write() - return renames - - def restore(self) -> int: - """Undo every uncommitted conversion: originals back, stem files gone. - Returns how many originals were put back.""" - restored = 0 - with self._lock: - for item in list(self.items): - restored += self._undo(item, keep_leftover=False) - self.items = [] - self._write() - return restored - - def recover(self, is_committed) -> dict: - """At open, after a crash: decide each leftover item from the SAVED - collection (`is_committed(item)` — does it name the stem file?).""" - report = {"committed": 0, "restored": 0, "kept": 0} - with self._lock: - before = len(self.leftovers) - for item in list(self.items): - if item.get("new_id") and is_committed(item): - if item.get("parked"): - Path(item["parked"]).unlink(missing_ok=True) - report["committed"] += 1 - else: - report["restored"] += self._undo(item, keep_leftover=True) - report["kept"] = len(self.leftovers) - before - self.items = [] - self._write() - return report - - def _undo(self, item: dict, *, keep_leftover: bool) -> int: - """Put one item's files back as they were. Filesystem-driven.""" - restored = 0 - original = Path(item["source"]) - parked = Path(item["parked"]) if item.get("parked") else None - if parked is not None and parked.exists() and not original.exists(): - _retrying(lambda: _replace_no_overwrite(parked, original)) - restored = 1 - stem = Path(item["stem"]) - if keep_leftover and item.get("written"): - self._keep_as_leftover(item) - else: - try: - # Only a stem file THIS batch published is ours to delete: before - # that, a file at the target name belongs to someone else. - if _published(item): - stem.unlink(missing_ok=True) - partial_name(stem).unlink(missing_ok=True) # unverified: worthless - except OSError: - pass - return restored - - -def _published(item: dict) -> bool: - return item.get("state") in ("published", "parked", "swapped", "committed") - - -__all__ = ["PARKED", "PARTIAL", "Pending", "parked_name", "partial_name", "source_facts", - "_replace_no_overwrite", "_retrying"] +"""Moved to `konduktor.pending` (it now holds Normalize's items too); this +module keeps the old import path working.""" +from ..pending import * # noqa: F401,F403 +from ..pending import _published, _replace_no_overwrite, _retrying # noqa: F401 diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 85fde0f..6bf13dd 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_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_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_level_edit.py b/backend/test_level_edit.py new file mode 100644 index 0000000..c4b8eec --- /dev/null +++ b/backend/test_level_edit.py @@ -0,0 +1,201 @@ +"""`core.level_edit` on GENERATED files — every edit decode-checked. + +MP3 is changed by the lossless frame-gain edit, so the proof is that the +decode is the source x 2^(n/4) and the file keeps its size (bar the APE undo +tag); WAV/AIFF are scaled in their data chunk, so every OTHER byte must stay +put; FLAC is re-encoded, so its tags and pictures must come back. The source +is never touched, and a refused edit leaves no file behind. +""" +from __future__ import annotations + +import hashlib +import struct +import tempfile +from pathlib import Path + +import av +import numpy as np +import soundfile as sf + +from konduktor.core import level_edit +from konduktor.core.level_plan import STEP_DB + +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 signal(sr: int, channels: int, seconds: float = 6.0, amp: float = 0.25) -> np.ndarray: + t = np.arange(int(sr * seconds)) / sr + rng = np.random.default_rng(1) + chans = [amp * (0.6 * np.sin(2 * np.pi * (110 + 37 * c) * t) + 0.3 * np.sin(2 * np.pi * 2200 * t) + + 0.1 * rng.standard_normal(t.size)) for c in range(channels)] + return np.vstack(chans).astype(np.float32) + + +def encode_mp3(path: Path, *, sr=44100, channels=2, options=None, container_options=None, bit_rate=192_000): + x = signal(sr, channels) + layout = "stereo" if channels == 2 else "mono" + with av.open(str(path), "w", format="mp3", container_options=container_options or {}) as c: + s = c.add_stream("libmp3lame", rate=sr, layout=layout, options=options or {}) + s.bit_rate = bit_rate + step = 1152 + for i in range(0, x.shape[1], step): + f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, i:i + step]), format="fltp", layout=layout) + f.sample_rate, f.pts = sr, i + for p in s.encode(f): + c.mux(p) + for p in s.encode(None): + c.mux(p) + + +def sha(p: Path) -> str: + return hashlib.sha256(p.read_bytes()).hexdigest() + + +def raises(fn) -> bool: + try: + fn() + except level_edit.LevelEditError: + return True + return False + + +tmp = Path(tempfile.mkdtemp(prefix="konduktor-level-edit-")) + +print("== MP3: the frame-gain edit is exact, lossless and keeps the size ==") +check("CRC-16 is Layer III's (poly 0x8005, init 0xFFFF: '123456789' -> 0xAEE7)", + level_edit._crc16(b"123456789") == 0xAEE7) +variants = { + "cbr-xing": dict(), + "no-xing": dict(container_options={"write_xing": "0"}), + "abr": dict(options={"abr": "1"}), + "mono": dict(channels=1, bit_rate=96_000), + "mpeg2-22k": dict(sr=22050, bit_rate=64_000), +} +for name, kw in variants.items(): + src = tmp / f"{name}.mp3" + encode_mp3(src, **kw) + if name == "cbr-xing": + from mutagen.id3 import APIC, ID3, TIT2 + + tags = ID3() + tags.add(TIT2(encoding=3, text="level")) + tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=b"\xff\xd8" + bytes(5000))) + tags.save(str(src)) + before = sha(src) + for steps in (-2, 1): + dst = tmp / f"{name}.{steps}.mp3" + level_edit.apply(src, dst, steps * STEP_DB) + try: + level_edit.verify(src, dst, steps * STEP_DB) + ok, why = True, "" + except level_edit.LevelEditError as ex: + ok, why = False, str(ex) + check(f"{name} {steps:+d} steps: the decode is the source x 2^({steps}/4)", ok, why) + from mutagen.apev2 import APEv2 + + ape = APEv2(str(dst)) + grown = dst.stat().st_size - src.stat().st_size + check(f"{name} {steps:+d}: same frames, only the APE undo tag added", + 0 < grown < 200 and str(ape["MP3GAIN_UNDO"]) == f"{-steps:+04d},{-steps:+04d},N", f"{grown} {ape}") + check(f"{name}: the source is untouched", sha(src) == before) + +print("== MP3: a second edit accumulates its undo; refusals leave nothing ==") +src, once, twice = tmp / "cbr-xing.mp3", tmp / "once.mp3", tmp / "twice.mp3" +level_edit.apply(src, once, -2 * STEP_DB) +level_edit.apply(once, twice, -1 * STEP_DB) +from mutagen.apev2 import APEv2 # noqa: E402 + +check("undo after -2 then -1 steps reads +3", str(APEv2(str(twice))["MP3GAIN_UNDO"]).startswith("+003"), + str(APEv2(str(twice))["MP3GAIN_UNDO"])) +level_edit.verify(src, twice, -3 * STEP_DB) +check("…and the result is the source at -3 steps", True) +check("a gain that is not a whole number of steps is refused", + raises(lambda: level_edit.apply(src, tmp / "x.mp3", -2.0)) and not (tmp / "x.mp3").exists()) +check("a gain past MP3's range is refused, leaving no file", + raises(lambda: level_edit.apply(src, tmp / "y.mp3", 300 * STEP_DB)) and not (tmp / "y.mp3").exists()) +check("an existing target is never overwritten", raises(lambda: level_edit.apply(src, once, -STEP_DB))) +check("an unsupported format is refused", raises(lambda: level_edit.apply(src, tmp / "z.ogg", -1.0)) + or raises(lambda: level_edit.apply(tmp / "nothing.ogg", tmp / "z2.ogg", -1.0))) + + +def add_chunk_after(path: Path, cid: bytes, body: bytes, *, big_endian: bool) -> None: + """Append an extra chunk (a tag a DJ app might keep) and fix the RIFF/FORM size.""" + data = bytearray(path.read_bytes()) + fmt = ">I" if big_endian else "> 8 + y = sf.read(str(dst), dtype="int32")[0].astype(np.int64) >> 8 + check(f"{suffix} 24-bit is rounded, not dithered", + np.array_equal(y, np.rint(x * 10 ** (-6.0 / 20)))) +src = tmp / "pcm-PCM_16.wav" +d1, d2 = tmp / "dither-a.wav", tmp / "dither-b.wav" +level_edit.apply(src, d1, -3.0) +level_edit.apply(src, d2, -3.0) +check("16-bit is dithered — and reproducibly (the same edit writes the same bytes)", + d1.read_bytes() == d2.read_bytes() + and not np.array_equal(sf.read(str(d1), dtype="int16")[0], + np.rint(sf.read(str(src), dtype="int16")[0] * 10 ** (-3 / 20)).astype(np.int16))) + +print("== FLAC: re-encoded at its depth, tags and pictures carried ==") +from mutagen.flac import FLAC, Picture # noqa: E402 + +for subtype in ("PCM_16", "PCM_24"): + src = tmp / f"tagged-{subtype}.flac" + sf.write(str(src), signal(48000, 2).T, 48000, subtype=subtype) + f = FLAC(str(src)) + f["title"], f["artist"], f["initialkey"] = "Level", "Konduktor", "8A" + pic = Picture() + pic.type, pic.mime, pic.data = 3, "image/jpeg", b"\xff\xd8" + bytes(3000) + f.add_picture(pic) + f.save() + dst = tmp / f"tagged-{subtype}-out.flac" + level_edit.apply(src, dst, -4.2) + try: + level_edit.verify(src, dst, -4.2) + ok, why = True, "" + except level_edit.LevelEditError as ex: + ok, why = False, str(ex) + check(f"FLAC {subtype}: the decode is the source at -4.2 dB", ok, why) + out = FLAC(str(dst)) + check(f"FLAC {subtype}: same depth and rate", sf.info(str(dst)).subtype == subtype + and sf.info(str(dst)).samplerate == 48000) + check(f"FLAC {subtype}: every tag and the picture come back", + dict(out.tags.as_dict()) == dict(FLAC(str(src)).tags.as_dict()) + and [p.data for p in out.pictures] == [pic.data], str(out.tags.as_dict())) + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +raise SystemExit(1 if failed else 0) diff --git a/backend/test_level_plan.py b/backend/test_level_plan.py new file mode 100644 index 0000000..ab00ac7 --- /dev/null +++ b/backend/test_level_plan.py @@ -0,0 +1,77 @@ +"""`core.level_plan.plan_gain` — every outcome, the step rounding, the ceiling. + +Pure: no files, no library. What Normalize's preview counts and what its run +writes both come from this function, so its rules are pinned here once. +""" +from __future__ import annotations + +from konduktor.core.level_plan import STEP_DB, plan_gain, shifted +from konduktor.core.loudness import Loudness + +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 L(lufs, tp, rms=None): + return Loudness(lufs=lufs, rms=rms if rms is not None else lufs + 2, true_peak=tp, lra=6.0, plr=tp - lufs) + + +def plan(loud, suffix=".flac", measure="lufs", target=-9.0, ceiling=-1.0): + return plan_gain(loud, suffix, measure=measure, target=target, ceiling=ceiling) + + +print("== the basics ==") +check("one step is 2^(1/4) in amplitude, 1.505 dB", abs(STEP_DB - 1.50515) < 1e-4, str(STEP_DB)) +s = plan(L(-6.0, 1.0)) +check("a hot lossless track comes down exactly", (s.outcome, s.gain_db) == ("apply", -3.0), str(s)) +s = plan(L(-12.0, -6.0)) +check("a quiet one goes up exactly when the peak allows", (s.outcome, s.gain_db) == ("apply", 3.0), str(s)) +s = plan(L(-9.02, -2.0)) +check("within 0.05 dB is at target (lossless)", s.outcome == "at_target" and not s.writes, str(s)) +check("no measurement: unmeasured", plan(None).outcome == "unmeasured") +check("ALAC / AAC / Ogg: unsupported", all(plan(L(-6, 0), x).outcome == "unsupported" for x in (".m4a", ".ogg", ".opus"))) +check("the suffix is case-blind", plan(L(-6.0, 1.0), ".FLAC").outcome == "apply") + +print("== the ceiling (a raise never clips) ==") +s = plan(L(-14.0, -3.0)) +check("a raise stops at the true-peak ceiling and says how far short", + (s.outcome, s.gain_db, s.short_by) == ("capped", 2.0, 3.0), str(s)) +s = plan(L(-12.0, 0.5)) +check("a peak already over the ceiling at/below target is left alone", (s.outcome, s.gain_db) == ("hot_peak_left", 0.0), str(s)) +s = plan(L(-6.0, 3.0)) +check("…but a HOT track over the ceiling still comes down", (s.outcome, s.gain_db) == ("apply", -3.0), str(s)) + +print("== MP3: lossless steps of 1.505 dB ==") +s = plan(L(-6.0, 1.0), ".mp3") +check("a lowering rounds to the nearest step (-3.0 -> -3.01)", abs(s.gain_db + 2 * STEP_DB) < 1e-6 and s.outcome == "apply", str(s)) +s = plan(L(-8.4, -3.0), ".mp3") +check("under half a step from target is at target", s.outcome == "at_target", str(s)) +s = plan(L(-12.0, -6.0), ".mp3") +check("a raise rounds to the nearest step when the peak allows (+3.0 -> +3.01)", + abs(s.gain_db - 2 * STEP_DB) < 1e-6 and s.outcome == "apply", str(s)) +s = plan(L(-12.0, -3.5), ".mp3") +check("a raise never rounds UP past the ceiling (headroom 2.5 -> one step)", + abs(s.gain_db - STEP_DB) < 1e-6 and s.outcome == "capped", str(s)) +s = plan(L(-12.0, -2.0), ".mp3") +check("headroom under one step: capped at zero, nothing written", s.outcome == "capped" and not s.writes, str(s)) +check("every MP3 gain is a whole number of steps", + all(abs(g / STEP_DB - round(g / STEP_DB)) < 1e-6 + for g in (plan(L(x, x + 5), ".mp3").gain_db for x in (-16, -13.3, -10.1, -7.7, -4.2)))) + +print("== the measure ==") +s = plan(L(-9.0, -6.0, rms=-12.0), measure="rms") +check("RMS measures the loud sections: -12 dB RMS goes up 3", (s.outcome, s.gain_db) == ("apply", 3.0), str(s)) + +print("== the level after ==") +after = shifted(L(-12.0, -6.0), 3.0) +check("LUFS, RMS and true peak move by the gain; LRA and PLR do not", + (after.lufs, after.rms, after.true_peak, after.lra, after.plr) == (-9.0, -7.0, -3.0, 6.0, 6.0), str(after)) + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +raise SystemExit(1 if failed else 0) diff --git a/backend/test_normalize.py b/backend/test_normalize.py new file mode 100644 index 0000000..00c2b0b --- /dev/null +++ b/backend/test_normalize.py @@ -0,0 +1,373 @@ +"""Normalize end to end, through the routes, on temp collections pointed at +GENERATED audio (MP3, FLAC, WAV at known levels). + +What would fail silently or destroy something: + + * the preview's counts are the run's (one `plan_gain`); + * the run leaves the SAVED collection untouched; the new file is the + original x 10^(g/20) under the ORIGINAL's path, the original parked + beside it; the library's auto gain is RECOMPUTED from the new level and + Konduktor's loudness value SHIFTED; operations that would save or drop the + change answer 409; a track awaiting Save is not normalised (or converted) + again; + * Save deletes the parked originals and changes only the touched ENTRYs; + Discard (and opening another library) put the originals back, bytes and + loudness both; + * after a CRASH, the next open restores — or, if the save got through, + finishes — from the ledger plus what the saved library says. +""" +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-normalize-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 paths # 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 +from konduktor.core.level_plan import STEP_DB # noqa: E402 +from konduktor.pending import parked_name # noqa: E402 + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" +ROOT = Path(tempfile.mkdtemp(prefix="konduktor-normalize-")) +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) # a pulse, so it is not a steady tone + 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_mp3(path: Path, amp: float): + x = music(amp=amp) + 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) + + +def make(path: Path, amp: float): + path.parent.mkdir(parents=True, exist_ok=True) + if path.suffix == ".mp3": + make_mp3(path, amp) + else: + sf.write(str(path), music(amp=amp).T, 44100, subtype="PCM_16") + return path + + +FILES = [("hot.mp3", 0.9), ("quiet.flac", 0.03), ("hot.wav", 0.8), ("close.mp3", 0.12)] + + +def library(name: str): + """A temp collection whose first playlisted entries point at FILES.""" + d = ROOT / name + work = d / "collection.nml" + d.mkdir(parents=True) + shutil.copy2(REAL, work) + st = TraktorStore(work) + in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)} + entries = [e for e in st._nml.collection.entry if e.location and st._key_of(e) in in_pl and e.stems is None] + ids, paths_ = [], [] + for (f, amp), e in zip(FILES, entries): + path = make(d / "Music" / f, amp) + old = st._key_of(e) + e.location.volume, e.location.dir, e.location.file = os_path_to_location(path) + new = st._key_of(e) + for n in st._iter_nodes(st._root()): + for pe in (n.playlist.entry if n.playlist else None) or []: + if pe.primarykey and pe.primarykey.key == old: + pe.primarykey.key = new + st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location} + ids.append(new) + paths_.append(path) + st.save() + return work, ids, paths_ + + +def sha(p: Path) -> str: + return hashlib.sha256(p.read_bytes()).hexdigest() + + +def wait(c, jid, timeout=120): + 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") + + +OPTS = {"measure": "lufs", "target": -12.0, "ceiling": -1.0} + + +def normalize(c, ids, **opts): + r = c.post("/api/tracks/normalize", json={"track_ids": ids, **OPTS, **opts}) + assert r.status_code == 200, r.text + return wait(c, r.json()["id"]) + + +def ledger() -> Path: + return paths.app_data_dir() / "stems" / f"pending-{main.STATE.library_id}.json" + + +with TestClient(main.app) as c: + print("== preview: one plan_gain, measured first where needed ==") + work, ids, files = library("run") + r = c.post("/api/library/open", json={"path": str(work)}) + assert r.status_code == 200, r.text + pv = c.post("/api/tracks/normalize/preview", json={"track_ids": ids, **OPTS}).json() + check("unmeasured tracks are counted to be measured first", + pv["to_measure"] == len(ids) and pv["tracks_to_process"] == len(ids), str({k: pv[k] for k in pv if k != "rows"})) + for p in files: + c.post("/api/tracks/loudness", json={"track_id": ids[files.index(p)]}) + before = {p.name: loudness.measure_file(p) for p in files} + pv = c.post("/api/tracks/normalize/preview", json={"track_ids": ids, **OPTS}).json() + rows = {Path(r["title"]).name if False else r["track_id"]: r for r in pv["rows"]} + gains = {files[i].name: rows[t].get("gain_db") for i, t in enumerate(ids)} + check("measured: every track has a plan", + all(rows[t].get("outcome") for t in ids), str(pv["rows"])) + check("an MP3's gain is a whole number of 1.505 dB steps", + abs(gains["hot.mp3"] / STEP_DB - round(gains["hot.mp3"] / STEP_DB)) < 1e-6 and gains["hot.mp3"] < 0, str(gains)) + check("the quiet FLAC is raised, but only to the ceiling", + rows[ids[1]]["outcome"] in ("apply", "capped") and gains["quiet.flac"] > 0 + and before["quiet.flac"].true_peak + gains["quiet.flac"] <= -1.0 + 1e-6, str(rows[ids[1]])) + check("lossless files are counted (Save makes their change permanent)", + pv["lossless"] == sum(1 for i, t in enumerate(ids) if files[i].suffix != ".mp3" and rows[t]["gain_db"]), + str(pv["lossless"])) + + print("== run: new files in place, originals parked, library follows ==") + saved_collection = work.read_bytes() + originals = {p.name: sha(p) for p in files} + job = normalize(c, ids) + res = job["result"] + changed = [files[ids.index(t)] for t in res["normalised"]] + check("the run normalises what the preview planned", + len(res["normalised"]) == pv["to_change"] and not res["failed"], json.dumps(res)[:400]) + check("the SAVED collection is untouched until Save", work.read_bytes() == saved_collection) + for p in changed: + g = gains[p.name] + parked = parked_name(p) + try: + level_edit.verify(parked, p, g) + ok, why = True, "" + except level_edit.LevelEditError as ex: + ok, why = False, str(ex) + check(f"{p.name}: the file at its own path is the original at {g:+.2f} dB", ok, why) + check(f"{p.name}: the original is parked beside it, unchanged", sha(parked) == originals[p.name]) + state = c.get("/api/state").json() + check("Save is due: the library is dirty and the pending change is named", + state["dirty"] and state["pending_gain"]["tracks"] == len(changed) + and state["pending_gain"]["lossless"] == sum(1 for p in changed if p.suffix != ".mp3"), str(state)) + vals = c.post("/api/loudness", json={"track_ids": ids}).json()["values"] + tracks = {t["id"]: t for t in c.get("/api/tracks", params={"limit": 20000}).json()["items"]} + for p in changed: + t = ids[files.index(p)] + want = before[p.name].lufs + gains[p.name] + check(f"{p.name}: Konduktor's loudness value is shifted by the gain, and fresh", + abs(vals[t]["lufs"] - want) < 1e-6 and not vals[t]["stale"], str(vals.get(t))) + check(f"{p.name}: the auto gain is recomputed from the NEW level (-9.2 - LUFS)", + abs(tracks[t]["auto_gain_db"] - (-9.2 - want)) < 1e-4, str(tracks[t]["auto_gain_db"])) + check("measured afresh, the new file agrees with the shifted value", + abs(loudness.measure_file(changed[0]).lufs - (before[changed[0].name].lufs + gains[changed[0].name])) < 0.05) + + print("== while it awaits Save ==") + r = c.post("/api/reload") + check("reload is refused (it would drop the change)", r.status_code == 409, r.text[:200]) + again = c.post("/api/tracks/normalize/preview", json={"track_ids": ids[:1], **OPTS}).json() + check("the same track is not normalised again before Save", + again["rows"][0]["skip"] and "awaiting Save" in again["rows"][0]["skip"], str(again["rows"])) + stems = c.post("/api/tracks/stems/preview", json={"track_ids": ids[:1], "mode": "replace"}).json() + check("…nor converted to stems", any("level change" in s["reason"] for s in stems["skipped"]), str(stems)) + + print("== Save: parked originals deleted, only the touched entries change ==") + r = c.post("/api/save") + check("Save succeeds", r.status_code == 200, r.text[:200]) + check("the parked originals are gone", not any(parked_name(p).exists() for p in changed)) + check("the ledger is empty", not ledger().exists()) + out = work.read_bytes() + for p in changed: + t = ids[files.index(p)] + check(f"{p.name}: the saved LOUDNESS is the new gain", + f'PERCEIVED_DB="{round(-9.2 - (before[p.name].lufs + gains[p.name]), 6):.6f}"'.encode() in out) + check("nothing pending any more", c.get("/api/state").json()["pending_gain"] is None) + + def without_entries(data: bytes, names) -> bytes: + for name in names: + i = data.find(f'FILE="{name}"'.encode()) + start, end = data.rfind(b"", i) + len(b"") + data = data[:start] + data[end:] + return data + + check("outside the normalised tracks' ENTRYs the collection is byte-identical", + without_entries(out, [p.name for p in changed]) == without_entries(saved_collection, [p.name for p in changed])) + + print("== Discard puts the originals back, bytes and loudness ==") + work2, ids2, files2 = library("discard") + c.post("/api/library/open", json={"path": str(work2)}) + for t in ids2: + c.post("/api/tracks/loudness", json={"track_id": t}) + shas = {p.name: sha(p) for p in files2} + vals_before = c.post("/api/loudness", json={"track_ids": ids2}).json()["values"] + res = normalize(c, ids2)["result"] + r = c.post("/api/discard") + check("discard succeeds", r.status_code == 200, r.text[:200]) + check("every file is byte-identical to before", {p.name: sha(p) for p in files2} == shas) + check("no parked file or partial is left", not any(parked_name(p).exists() or Path(str(p) + ".konduktor-partial").exists() + for p in files2)) + vals_after = c.post("/api/loudness", json={"track_ids": ids2}).json()["values"] + check("the loudness values are the originals' again, and fresh", + all(abs(vals_after[t]["lufs"] - vals_before[t]["lufs"]) < 1e-9 and not vals_after[t]["stale"] + for t in res["normalised"]), str(vals_after)) + + print("== a crash: recovery from the ledger + the saved library ==") + work3, ids3, files3 = library("crash") + c.post("/api/library/open", json={"path": str(work3)}) + shas3 = {p.name: sha(p) for p in files3} + res = normalize(c, ids3)["result"] + done = [files3[ids3.index(t)] for t in res["normalised"]] + # Crash 1: the app dies with the change unsaved (state "swapped"). + main.STATE.pending.restore = lambda: 0 # the process never got to restore + main.STATE.pending.items = list(main.STATE.pending.items) + c.post("/api/library/open", json={"path": str(work3)}) + check("an unsaved change is undone at the next open", {p.name: sha(p) for p in files3} == shas3 + and not any(parked_name(p).exists() for p in done)) + check("…and reported", (main.STATE.recovery or {}).get("restored") == len(done), str(main.STATE.recovery)) + # Crash 2: the save got through, the parked originals were never deleted. + res = normalize(c, ids3)["result"] + data = json.loads(ledger().read_text()) + main.STATE.adapter.save() # the library write landed… + for it in data["items"]: + it["state"] = "saving" # …but the app died before mark_saved + ledger().write_text(json.dumps(data)) + main.STATE.pending.restore = lambda: 0 + c.post("/api/library/open", json={"path": str(work3)}) + check("a save that landed is FINISHED: parked originals deleted, new audio kept", + not any(parked_name(p).exists() for p in done) + and all(sha(p) != shas3[p.name] for p in done), str(main.STATE.recovery)) + # Crash 3: died in "saving" BEFORE the library write: restore. + shas3 = {p.name: sha(p) for p in files3} + res = normalize(c, ids3, target=-16.0)["result"] + done3 = [files3[ids3.index(t)] for t in res["normalised"]] + data = json.loads(ledger().read_text()) + for it in data["items"]: + it["state"] = "saving" + ledger().write_text(json.dumps(data)) + main.STATE.pending.restore = lambda: 0 + c.post("/api/library/open", json={"path": str(work3)}) + check("a save that did NOT land is undone (the library still has the old gain)", + done3 and {p.name: sha(p) for p in files3} == shas3, str(main.STATE.recovery)) + +print("== drawn waveforms follow the new audio (rekordbox / OneLibrary ANLZ) ==") +from konduktor.adapters.rekordbox import anlz_file # noqa: E402 +from konduktor.core import waveform # noqa: E402 +from konduktor.core.adapter import AudioChange # noqa: E402 + +measured = waveform.analyse_samples(music(seconds=20, amp=0.5)[0], lead=0.0) +WAVE_TAGS = {".DAT": {"PWAV", "PWV2"}, ".EXT": {"PWV3", "PWV5", "PWV4"}, ".2EX": {"PWV7", "PWV6", "PWVC"}} + + +def tags(path: Path) -> dict: + out = {} + for t in anlz_file.parse_file(path).tags: + out.setdefault(t.type, []).append(t.data) + return out + + +def check_regenerated(label: str, dat: Path, before: dict) -> None: + for ext, wave in WAVE_TAGS.items(): + f = dat.with_suffix(ext) + if not f.is_file(): + continue + now = tags(f) + old = before[ext] + check(f"{label} {ext}: the waveform tags are rewritten", + all(now.get(k) != old.get(k) for k in wave if k in old), str(sorted(now))) + check(f"{label} {ext}: every other tag is byte-identical (cues, grid, phrases)", + {k: v for k, v in now.items() if k not in wave} == {k: v for k, v in old.items() if k not in wave}) + + +from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402 + +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary" +with tempfile.TemporaryDirectory() as d: + drive = Path(d) / "STICK" + shutil.copytree(FIXTURE, drive) + ad = OneLibraryAdapter(drive, read_only=False) + t = next(x for x in ad.tracks) + dat = ad._store.layout.resolve(ad._store.content(t.id).analysisDataFilePath) + before = {ext: tags(dat.with_suffix(ext)) for ext in WAVE_TAGS if dat.with_suffix(ext).is_file()} + db_before = (drive / "PIONEER/rekordbox/exportLibrary.db").read_bytes() + ad.audio_changed(t.id, AudioChange(gain_db=-3.0, size=123456, measured=measured)) + check("OneLibrary: nothing reaches the drive before Save", + {ext: tags(dat.with_suffix(ext)) for ext in before} == before) + check("OneLibrary: a level change is an edit (Save will run)", ad.dirty) + ad.save() + check_regenerated("OneLibrary", dat, before) + check("OneLibrary: the database's fileSize follows", + OneLibraryAdapter(drive, read_only=True)._store.content(t.id).fileSize == 123456) + +from konduktor.adapters.rekordbox import discovery as rb_discovery # noqa: E402 +from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 + +found = rb_discovery.detect_libraries() +if not found: + print(" [SKIP] no Rekordbox library on this machine") +else: + with tempfile.TemporaryDirectory() as d: + src = Path(found[0]["path"]) + work = Path(d) / "master.db" + shutil.copy2(src, work) + shutil.copytree(src.parent / "share", Path(d) / "share", dirs_exist_ok=True) + ad = RekordboxAdapter(work) + t = next((x for x in ad.tracks if getattr(ad._store.content(x.id), "AnalysisDataPath", None) + and (Path(d) / "share" / str(ad._store.content(x.id).AnalysisDataPath).lstrip("/")).is_file()), None) + if t is None: + print(" [SKIP] no track with analysis files") + else: + dat = Path(d) / "share" / str(ad._store.content(t.id).AnalysisDataPath).lstrip("/") + before = {ext: tags(dat.with_suffix(ext)) for ext in WAVE_TAGS if dat.with_suffix(ext).is_file()} + ad.audio_changed(t.id, AudioChange(gain_db=-3.0, size=654321, measured=measured)) + check("rekordbox: nothing reaches the files before Save", + {ext: tags(dat.with_suffix(ext)) for ext in before} == before) + ad.save() + check_regenerated("rekordbox", dat, before) + ad.close() + check("rekordbox: djmdContent.FileSize follows", + RekordboxAdapter(work)._store.content(t.id).FileSize == 654321) + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +raise SystemExit(1 if failed else 0) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c55ab78..9e2c064 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,7 +8,7 @@ import { invalidateTrackLists } from './lib/trackQueries' import { addTracksToPlaylist } from './lib/addTracks' import { isForeign, useDragPayload, useDropTarget, type TracksOrFiles } from './lib/drag' import { useNativeFileDrop } from './lib/fileDrop' -import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' +import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type NormalizeOptions, type NormalizeResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' import { askConfirm } from './lib/confirm' import { @@ -26,6 +26,7 @@ import { CollectionPicker } from './components/CollectionPicker' import { ContextMenu, type MenuItem } from './components/ContextMenu' import { EditTagsDialog } from './components/EditTagsDialog' import { AnalyzeDialog } from './components/AnalyzeDialog' +import { NormalizeDialog } from './components/NormalizeDialog' import { AutoCueDialog } from './components/AutoCueDialog' import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog' import { PathMappingDialog } from './components/PathMappingDialog' @@ -108,7 +109,8 @@ export default function App() { { ids: string[]; origin: TrackOrigin; preset?: 'loudness' | 'gain' } | null >(null) const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null) - const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null) + const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' | 'normalize' } | null>(null) + const [normalizing, setNormalizing] = useState(null) // Convert to Stems: the dialog's selection, a finished run's Details, and a // running engine download (which outlives the dialog — decided). const [stemDialog, setStemDialog] = useState(null) @@ -757,7 +759,7 @@ export default function App() { return } if (job.state === 'failed') { - const what = kind === 'grid' ? 'Analysis' : 'Auto Hotcues' + const what = kind === 'grid' ? 'Analysis' : kind === 'normalize' ? 'Normalize' : 'Auto Hotcues' onError(`${what} failed: ${job.error ?? 'unknown error'}`) return } @@ -770,7 +772,17 @@ export default function App() { let touched: string[] let parts: string[] let failures: CueBatchResult['failed'] - if (kind === 'grid') { + if (kind === 'normalize') { + const r = job.result as unknown as NormalizeResult + touched = r.normalised + failures = r.failed + qc.invalidateQueries({ queryKey: ['state'] }) + parts = [ + `${cancelled ? 'Cancelled — normalized' : 'Normalized'} ${plural(r.normalised.length, 'track')}` + + (r.normalised.length ? ' — Save to keep the new levels, Discard to undo' : ''), + r.skipped.length ? `${r.skipped.length} left as they were` : '', + ] + } else if (kind === 'grid') { const r = job.result as unknown as AnalyzeResult touched = r.analysed failures = r.failed @@ -924,6 +936,11 @@ export default function App() { if (id && !batchJob) setBatchJob({ id, kind: 'stems' }) // eslint-disable-next-line react-hooks/exhaustive-deps }, [editState.data?.stem_job]) + useEffect(() => { + const id = editState.data?.normalize_job + if (id && !batchJob) setBatchJob({ id, kind: 'normalize' }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [editState.data?.normalize_job]) // Tell the user once what crash recovery did about an interrupted conversion. const recovery = editState.data?.stem_recovery const recoveryShown = useRef(null) @@ -1006,6 +1023,14 @@ export default function App() { const canAnalyzeGrid = !!capabilities.data?.grid.editable const canAnalyzeKey = !!capabilities.data?.tracks.key_writable const canAutoGain = !!capabilities.data?.tracks.auto_gain + /** Why Normalize cannot change these tracks' files, if so. */ + const normalizeRefusal = (ids: string[]): string | null => + analyzeRefusal(analyzeOrigin(ids)) ?? + (editState.data?.remote + ? 'Normalize is not available on a remote library yet' + : capabilities.data?.tracks.normalizable + ? null + : "This library's audio files cannot be normalized") const analyzeOrigin = (ids: string[]): TrackOrigin => viewingDevice ? 'device' : viewingFolder && ids.some((id) => !folderFiles[id]) ? 'folder' : 'collection' /** Why BPM / Grid / Key cannot be analysed for these tracks at all, if so. */ @@ -1340,6 +1365,13 @@ export default function App() { { label: 'Mastering', submenu: [ + { + label: 'Normalize…', + hint: batchJob ? 'busy' : undefined, + disabled: !!batchJob || !!normalizeRefusal(menu.ids), + title: normalizeRefusal(menu.ids) ?? undefined, + onClick: () => setNormalizing(menu.ids), + }, { label: 'Auto gain…', hint: batchJob ? 'busy' : undefined, @@ -1455,6 +1487,19 @@ export default function App() { onError={onError} /> )} + {normalizing && ( + { + const job = await api.normalize(normalizing, opts) + setNormalizing(null) + setBatchCancelling(false) + setBatchJob({ id: job.id, kind: 'normalize' }) + }} + onClose={() => setNormalizing(null)} + onError={onError} + /> + )} {stemReport && setStemReport(null)} />} {positioning && ( + rows: NormalizeRow[] +} + +/** What a Normalize run did. */ +export interface NormalizeResult { + normalised: string[] + skipped: { track_id: string; title: string; reason: string }[] + failed: { track_id: string; title: string; reason: string }[] + counts: Record + cancelled: boolean +} + /** What an Analyze run did. */ export interface AnalyzeResult { analysed: string[] @@ -1216,6 +1264,11 @@ export const api = { stemEngineRemove: () => send('DELETE', '/api/stems/engine'), analyzePreview: (trackIds: string[], opts: AnalyzeOptions) => send('POST', '/api/tracks/analyze/preview', { track_ids: trackIds, ...opts }), + normalizePreview: (trackIds: string[], opts: NormalizeOptions) => + send('POST', '/api/tracks/normalize/preview', { track_ids: trackIds, ...opts }), + /** Starts a Normalize job; its `result` is a `NormalizeResult`. */ + normalize: (trackIds: string[], opts: NormalizeOptions) => + send('POST', '/api/tracks/normalize', { track_ids: trackIds, ...opts }), /** Starts an analysis job; its `result` is an `AnalyzeResult`. */ analyze: (trackIds: string[], opts: AnalyzeOptions) => send('POST', '/api/tracks/analyze', { track_ids: trackIds, ...opts }), diff --git a/frontend/src/components/AppSettings.tsx b/frontend/src/components/AppSettings.tsx index 1dbbb60..7d3c4ad 100644 --- a/frontend/src/components/AppSettings.tsx +++ b/frontend/src/components/AppSettings.tsx @@ -16,6 +16,11 @@ export const APP_SETTING_DEFAULTS = { exportRootFolder: false, /** Decimal places on the deck's ELAPSED / REMAIN readouts (0–3). */ timeReadoutDecimals: 1, + /** Normalize's defaults (each run can change them): the measure brought to + * the target, and the true-peak ceiling a raise stops at. */ + levelMeasure: 'lufs' as 'lufs' | 'rms', + levelTarget: -9, + levelCeiling: -1, } type AppSettingKey = keyof typeof APP_SETTING_DEFAULTS @@ -32,6 +37,9 @@ export function AppSettings({ onClose }: { onClose: () => void }) { const expandFolders = useAppSetting('expandPlaylistFolders') const exportRootFolder = useAppSetting('exportRootFolder') const timeDecimals = useAppSetting('timeReadoutDecimals') + const levelMeasure = useAppSetting('levelMeasure') + const levelTarget = useAppSetting('levelTarget') + const levelCeiling = useAppSetting('levelCeiling') const [error, setError] = useState(null) useEffect(() => { @@ -120,6 +128,36 @@ export function AppSettings({ onClose }: { onClose: () => void }) { +
+

Normalize

+ + The defaults Mastering ▸ Normalize… starts from; each run can change them. + + + + +
{error &&
{error}
}
@@ -132,3 +170,31 @@ export function AppSettings({ onClose }: { onClose: () => void }) { document.body, ) } + +/** A dB value typed in place, committed on blur / Enter, clamped to its range. */ +export function LevelInput({ value, unit, min, max, onCommit }: { + value: number; unit: string; min: number; max: number; onCommit: (v: number) => void +}) { + const [text, setText] = useState(String(value)) + useEffect(() => setText(String(value)), [value]) + const commit = () => { + const v = Number(text.replace(',', '.')) + if (!Number.isFinite(v)) return setText(String(value)) + const clamped = Math.min(max, Math.max(min, Math.round(v * 10) / 10)) + setText(String(clamped)) + if (clamped !== value) onCommit(clamped) + } + return ( + + setText(e.target.value)} + onBlur={commit} + onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()} + /> + {unit} + + ) +} diff --git a/frontend/src/components/NormalizeDialog.tsx b/frontend/src/components/NormalizeDialog.tsx new file mode 100644 index 0000000..882eab4 --- /dev/null +++ b/frontend/src/components/NormalizeDialog.tsx @@ -0,0 +1,194 @@ +import { createPortal } from 'react-dom' +import { useEffect, useMemo, useState } from 'react' +import { keepPreviousData, useQuery } from '@tanstack/react-query' +import { api, type NormalizeOptions, type NormalizePreview, type NormalizeRow } from '../api' +import { LevelInput, useAppSetting } from './AppSettings' +import { Icon } from '../lib/icons' + +interface Props { + ids: string[] + onRun: (opts: NormalizeOptions) => Promise + onClose: () => void + onError: (msg: string) => void +} + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}` +const db = (v: number) => `${v > 0 ? '+' : ''}${v.toFixed(1)} dB` + +/** What a row's outcome means, in the dialog's words. */ +function rowNote(r: NormalizeRow): string { + if (r.skip) return r.skip + switch (r.outcome) { + case 'apply': return db(r.gain_db ?? 0) + case 'capped': + return r.gain_db ? `${db(r.gain_db)} — ${r.short_by?.toFixed(1)} dB short (peak ceiling)` : 'no headroom under the ceiling' + case 'at_target': return 'already at the target' + case 'hot_peak_left': return 'peak already over the ceiling — left alone' + case 'unsupported': return 'this format cannot be changed losslessly' + case 'unmeasured': return 'measured first, then levelled' + default: return '' + } +} + +/** + * The track menu's Mastering ▸ Normalize… (decided 2026-10-19): change the + * selected files' audio LEVEL in place, toward a target in the chosen measure, + * a raise stopping at the true-peak ceiling. Every number comes from the + * backend's own plan (`/api/tracks/normalize/preview`). The defaults are the + * app settings; changes here apply to this run only. The originals are parked + * until Save — and Save makes a lossless file's change permanent, which the + * dialog says before it runs. + */ +export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) { + const defaultMeasure = useAppSetting('levelMeasure') + const defaultTarget = useAppSetting('levelTarget') + const defaultCeiling = useAppSetting('levelCeiling') + const [opts, setOpts] = useState(null) + const [busy, setBusy] = useState(false) + useEffect(() => { + if (!opts) setOpts({ measure: defaultMeasure, target: defaultTarget, ceiling: defaultCeiling }) + }, [opts, defaultMeasure, defaultTarget, defaultCeiling]) + + const preview = useQuery({ + queryKey: ['normalize-preview', ids, opts], + queryFn: () => api.normalizePreview(ids, opts!), + enabled: !!opts, + placeholderData: keepPreviousData, + }) + const p: NormalizePreview | undefined = preview.data + const count = p?.tracks_to_process ?? 0 + + useEffect(() => { + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [busy, onClose]) + + const summary = useMemo(() => { + if (!p) return [] + const rows = p.rows + const up = rows.filter((r) => (r.gain_db ?? 0) > 0).length + const down = rows.filter((r) => (r.gain_db ?? 0) < 0).length + const c = p.counts + const lines: string[] = [] + if (up || down) + lines.push(`${plural(up + down, 'track')} change: ${[up && `${up} raised`, down && `${down} lowered`].filter(Boolean).join(', ')}`) + if (p.to_measure) lines.push(`${plural(p.to_measure, 'track')} measured first`) + if (c.capped) lines.push(`${plural(c.capped, 'track')} held short by the peak ceiling`) + if (c.at_target) lines.push(`${c.at_target} already at the target`) + if (c.hot_peak_left) lines.push(`${plural(c.hot_peak_left, 'hot peak')} left alone`) + if (c.unsupported) lines.push(`${plural(c.unsupported, 'file')} in a format that cannot be changed losslessly`) + if (c.skipped) lines.push(`${c.skipped} skipped`) + return lines + }, [p]) + + const run = async () => { + if (!opts || busy || count === 0) return + setBusy(true) + try { + await onRun(opts) + } catch (e) { + onError((e as Error).message) + setBusy(false) + } + } + + const measureUnit = opts?.measure === 'rms' ? 'dB' : 'LUFS' + + return createPortal( +
!busy && onClose()} + > +
e.stopPropagation()}> +
+
Normalize
+
+ {plural(ids.length, 'track')} selected · changes the audio files' level +
+
+ + {opts && ( +
+ + + +
+ )} + +
+
+ {summary.map((line) => ( +
{line}
+ ))} + {p && count === 0 &&
Nothing to change at this target.
} +
+ {p && p.rows.length > 1 && ( +
+ {p.rows.map((r) => ( +
+ + {r.title} + + + {r.level != null && `${r.level.toFixed(1)} ${measureUnit} · `} + {rowNote(r)} + +
+ ))} +
+ )} + {p && p.rows.length === 1 &&
{rowNote(p.rows[0])}
} +
+ + {p && p.lossless > 0 && ( +
+ + + Saving makes the change to {plural(p.lossless, 'lossless file')} permanent: the original + {p.lossless === 1 ? ' is' : 's are'} deleted. MP3s keep an undo tag. Until then, Discard puts + everything back. + +
+ )} + +
+ + +
+
+
, + document.body, + ) +} diff --git a/frontend/src/components/SaveBar.tsx b/frontend/src/components/SaveBar.tsx index bd5c1fe..6981949 100644 --- a/frontend/src/components/SaveBar.tsx +++ b/frontend/src/components/SaveBar.tsx @@ -58,6 +58,7 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) { const exportWarning = exportManagedWarning(caps.save) const dirty = state?.dirty ?? false const pending = state?.pending_stems + const gain = state?.pending_gain const readOnly = readOnlyNotice(caps) // A read-only library has no save to offer, and saying so plainly is the whole @@ -100,6 +101,20 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) {
)} + {/* Normalize: the new levels are files on disk; Save deletes the parked + originals, which makes a lossless file's change permanent. */} + {gain && gain.tracks > 0 && ( +
+ + + Saving keeps the new level of {gain.tracks} file{gain.tracks === 1 ? '' : 's'} + {gain.lossless > 0 + ? ` — permanently for ${gain.lossless} lossless file${gain.lossless === 1 ? '' : 's'}, whose originals are deleted` + : ' (MP3s keep an undo tag)'} + . Discard to put the originals back. + +
+ )}