mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Implemented remote side
This commit is contained in:
1 parent
4cb630d0d5
commit
13ba2c721a
14 files changed
+880
-13
No files matched your search
@@ -842,7 +842,22 @@ Two independent apps that talk over HTTP:
|
||||
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
|
||||
converted again. **Remote libraries** (`gain/remote_normalize.py`, the
|
||||
stems-style transfer, decided): the server plans (`/v1/gain/plan`: its
|
||||
`normalize.plan` on its own store and ledger, plus per row the source's
|
||||
size, the platform's `analysis_lead` and `staged`); this computer
|
||||
downloads, measures where the server has none (stored back there),
|
||||
rewrites + VERIFIES, measures the levelled file's drawn waveform where
|
||||
there is a lead, and uploads (`PUT /v1/gain/stage` beside the source as
|
||||
`<name>.konduktor-partial`, sha-256 checked and its gain checked against
|
||||
the server's OWN `plan_gain` — 409 if they differ; `PUT /v1/gain/waveform`
|
||||
the packed analysis); the server keeps each as a "written" ledger item
|
||||
(`pending.staged_gain`; staged items do not `hold` a track), and
|
||||
`/v1/gain/publish` runs the ordinary `normalize._end_step` under its
|
||||
mutation lock. Cancel deletes this run's uploads (`/v1/gain/abandon`); a
|
||||
takeover cannot, and the next plan marks them `staged` and publishes them
|
||||
without rewriting. `RemotePending.blocking` counts `gain_tracks`; protocol
|
||||
1.7. The preview adds `transfer`. 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
|
||||
@@ -1824,6 +1839,18 @@ serialization path.** It enforces:
|
||||
added twice, both into the playlist, analysed here when the server reports
|
||||
a lead). And auto gain: computed here from the SERVER's stored measurement
|
||||
(no new download), written on the server, saved into its collection.
|
||||
- `test_remote_normalize.py` — Normalize on a remote (a real server in a
|
||||
thread, generated audio on it): the server's plan (all to measure first,
|
||||
the transfer, no lead for Traktor); a run measured, rewritten and verified
|
||||
HERE, swapped in ON THE SERVER (the file at its own path = the original at
|
||||
the gain, the original parked, the saved collection untouched, the
|
||||
server's loudness the new level, the mirror's auto gain following it,
|
||||
`pending_gain`, reload 409); Save deletes the parked originals there and
|
||||
writes the new gain; Discard restores the bytes; an upload at a gain the
|
||||
server's plan would not give is refused leaving nothing; Cancel deletes
|
||||
only this run's upload; a takeover keeps the verified upload and the next
|
||||
run publishes it WITHOUT rewriting; a platform with a lead gets the
|
||||
levelled file's waveform measured here and handed to the end step.
|
||||
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
|
||||
the plan's transfer and two-machine space, Replace parks and swaps ON THE
|
||||
SERVER (saved file untouched until Save, which deletes the parked
|
||||
|
||||
@@ -391,6 +391,47 @@ class RemoteAdapter:
|
||||
self._load() # ids changed (repoint) or entries were added
|
||||
return result
|
||||
|
||||
# ---- Normalize (the library side lives on the server) ---------------------------
|
||||
# `gain/remote_normalize.py` drives these: the server plans and swaps, this
|
||||
# computer downloads, rewrites, verifies and uploads.
|
||||
def normalize_plan(self, body: dict) -> dict:
|
||||
return self.client.gain_plan(body)
|
||||
|
||||
def stage_gain(self, track_id: str, local: Path, *, gain_db: float, options: dict,
|
||||
waveform: str | None = None, progress=None) -> dict:
|
||||
import hashlib
|
||||
|
||||
digest = hashlib.sha256()
|
||||
with open(local, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
digest.update(chunk)
|
||||
try:
|
||||
out = self.client.gain_stage(track_id, local, gain_db=gain_db, sha256=digest.hexdigest(),
|
||||
options=options, progress=progress)
|
||||
if waveform is not None:
|
||||
self.client.gain_waveform(track_id, waveform)
|
||||
return out
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
|
||||
def abandon_gain(self, track_ids: list[str]) -> None:
|
||||
self.client.gain_abandon(track_ids)
|
||||
|
||||
def publish_gain(self, track_ids: list[str]) -> dict:
|
||||
try:
|
||||
result = self.client.gain_publish(track_ids)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
# The files changed under the same names: their facts (and so the
|
||||
# cache key and every loudness lookup) are new.
|
||||
with self._lock:
|
||||
for track_id in track_ids:
|
||||
self._facts.pop(track_id, None)
|
||||
self._load()
|
||||
return result
|
||||
|
||||
# ---- metadata / art ------------------------------------------------------------------
|
||||
def set_cover_art(self, track_id, data, mime):
|
||||
try:
|
||||
|
||||
@@ -302,6 +302,35 @@ class RemoteClient:
|
||||
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
|
||||
timeout=None).json()
|
||||
|
||||
# ---- Normalize ------------------------------------------------------------------------
|
||||
def gain_plan(self, body: dict) -> dict:
|
||||
return self.request("POST", "/v1/gain/plan", json=body, timeout=None).json()
|
||||
|
||||
def gain_stage(self, track_id: str, source: Path, *, gain_db: float, sha256: str,
|
||||
options: dict, progress=None) -> dict:
|
||||
def body():
|
||||
with open(source, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
yield chunk
|
||||
|
||||
return self.request(
|
||||
"PUT", "/v1/gain/stage",
|
||||
params={"track_id": track_id, "gain_db": repr(float(gain_db)), "sha256": sha256, **options},
|
||||
content=body(), retry=False, timeout=None,
|
||||
).json()
|
||||
|
||||
def gain_waveform(self, track_id: str, packed: str) -> None:
|
||||
self.request("PUT", "/v1/gain/waveform", params={"track_id": track_id},
|
||||
content=packed.encode("ascii"), retry=False, timeout=None)
|
||||
|
||||
def gain_abandon(self, track_ids: list[str]) -> None:
|
||||
self.request("POST", "/v1/gain/abandon", json={"track_ids": track_ids})
|
||||
|
||||
def gain_publish(self, track_ids: list[str]) -> dict:
|
||||
return self.request("POST", "/v1/gain/publish", json={"track_ids": track_ids}, timeout=None).json()
|
||||
|
||||
def stems_pending(self) -> dict:
|
||||
return self.request("GET", "/v1/stems/pending").json()
|
||||
|
||||
|
||||
@@ -73,7 +73,11 @@ class RemotePending:
|
||||
return {"tracks": 0, "parked": 0, "bytes": 0}
|
||||
|
||||
def blocking(self) -> bool:
|
||||
return bool(self.summary().get("tracks"))
|
||||
summary = self.summary()
|
||||
return bool(summary.get("tracks") or summary.get("gain_tracks"))
|
||||
|
||||
def holds(self, track_ids) -> set:
|
||||
return set() # the server's plan says which tracks it holds
|
||||
|
||||
def swapped(self) -> list:
|
||||
return []
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Normalize on a library held by a Konduktor server (decided 2026-10-19: the
|
||||
same transfer Convert to Stems uses).
|
||||
|
||||
The batch of `normalize.py`, split where the machines split:
|
||||
|
||||
* **The server plans** — from its own loudness store, with its own ledger
|
||||
(a track awaiting Save is skipped there) — and says per track how big the
|
||||
source is, the platform's analysis lead, and whether a verified upload at
|
||||
this very gain is already there (`staged`: a takeover interrupted the
|
||||
run that made it, and this one reuses it).
|
||||
* **This computer rewrites.** The server never decodes audio, so each source
|
||||
is downloaded into the shared cache, measured if the server has no
|
||||
measurement (stored back on the server), rewritten by `core.level_edit`,
|
||||
VERIFIED, measured for its drawn waveform where the platform keeps one,
|
||||
and UPLOADED.
|
||||
* **The server swaps.** One end step there (`/v1/gain/publish`) — park the
|
||||
original, the upload under its name, the library's size / waveforms /
|
||||
auto gain — under its mutation lock, with its own ledger, which its Save
|
||||
commits and its Discard undoes.
|
||||
|
||||
Cancel deletes what this run uploaded; a takeover cannot, so those uploads
|
||||
stay and the next run reuses them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from ..core.adapter import AdapterError
|
||||
from .normalize import _WHY, NormalizeError, Options
|
||||
|
||||
#: Before this computer has measured a download, a conservative LAN speed.
|
||||
DEFAULT_SPEED = 20 * 1024 ** 2 # bytes / s
|
||||
|
||||
|
||||
def options_body(opts: Options) -> dict:
|
||||
return {"measure": opts.measure, "target": opts.target, "ceiling": opts.ceiling}
|
||||
|
||||
|
||||
def plan(adapter, track_ids, opts: Options) -> dict:
|
||||
"""The server's plan, plus what only this computer can answer: how much
|
||||
must cross the network (a source already cached here is not downloaded)."""
|
||||
try:
|
||||
out = adapter.normalize_plan({"track_ids": list(track_ids), **options_body(opts)})
|
||||
except AdapterError as ex:
|
||||
raise NormalizeError(str(ex))
|
||||
work = [r for r in out["rows"] if _needs_work(r) and not r.get("staged")]
|
||||
download = sum(int(r.get("source_size") or 0) for r in work if adapter.cached_audio(r["track_id"]) is None)
|
||||
upload = sum(int(r.get("source_size") or 0) for r in work) # a level change keeps (about) the size
|
||||
speed = adapter.cache.speed()
|
||||
out["transfer"] = {"download": download, "upload": upload, "speed": speed or DEFAULT_SPEED,
|
||||
"measured": speed is not None}
|
||||
return out
|
||||
|
||||
|
||||
def _needs_work(row: dict) -> bool:
|
||||
return not row.get("skip") and (bool(row.get("gain_db")) or row.get("outcome") == "unmeasured")
|
||||
|
||||
|
||||
def run(handle, adapter, track_ids, opts: Options, *, still_current) -> dict:
|
||||
from ..adapters.remote.services import RemoteLoudnessStore
|
||||
from ..core import level_edit, loudness
|
||||
from ..core.adapter import PreparedAnalysis
|
||||
from ..core.level_plan import plan_gain
|
||||
from .. import remote_protocol as rp
|
||||
from ..stems import convert
|
||||
|
||||
planned = plan(adapter, track_ids, opts)
|
||||
result = {"normalised": [], "skipped": [], "failed": [], "counts": dict(planned.get("counts") or {}),
|
||||
"cancelled": False}
|
||||
rows = planned["rows"]
|
||||
store = RemoteLoudnessStore(adapter.client, adapter.session)
|
||||
body = options_body(opts)
|
||||
staged: list[str] = []
|
||||
uploaded: list[str] = [] # what THIS run uploaded (a cancel deletes it)
|
||||
work = convert.work_root() / f"remote-normalize-{id(handle):x}"
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
handle.progress(done=0, total=len(rows), unit="tracks")
|
||||
|
||||
def skip(row: dict, reason: str) -> None:
|
||||
result["skipped"].append({"track_id": row["track_id"], "title": row["title"], "reason": reason})
|
||||
|
||||
def fail(row: dict, reason: str) -> None:
|
||||
result["failed"].append({"track_id": row["track_id"], "title": row["title"], "reason": reason})
|
||||
|
||||
def checkpoint() -> None:
|
||||
if handle.cancelled:
|
||||
raise _Cancel()
|
||||
|
||||
try:
|
||||
for n, row in enumerate(rows):
|
||||
checkpoint()
|
||||
handle.progress(done=n, message=row["title"], fraction=0.0, status="")
|
||||
if row.get("skip"):
|
||||
skip(row, row["skip"])
|
||||
continue
|
||||
if not _needs_work(row):
|
||||
skip(row, _WHY.get(row.get("outcome"), "nothing to change"))
|
||||
continue
|
||||
if row.get("staged"):
|
||||
staged.append(row["track_id"]) # already on the server, verified
|
||||
continue
|
||||
size = max(int(row.get("source_size") or 0), 1)
|
||||
got = 0
|
||||
|
||||
def downloaded(k: int) -> None:
|
||||
nonlocal got
|
||||
got += k
|
||||
checkpoint()
|
||||
f = min(got / size, 1.0) * 0.3
|
||||
handle.progress(fraction=f, status=f"downloading {f / 0.3 * 100:.0f} %")
|
||||
|
||||
local = adapter.audio_path(row["track_id"], progress=downloaded)
|
||||
if local is None:
|
||||
fail(row, "the file is missing on the server")
|
||||
continue
|
||||
gain = float(row.get("gain_db") or 0.0)
|
||||
if row.get("outcome") == "unmeasured":
|
||||
handle.progress(fraction=0.3, status="measuring")
|
||||
try:
|
||||
values = loudness.measure_file(local)
|
||||
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
|
||||
fail(row, f"Could not measure: {ex}")
|
||||
continue
|
||||
if values is None:
|
||||
skip(row, "nothing to measure (silent or under 3 s)")
|
||||
continue
|
||||
facts = adapter.audio_facts([row["track_id"]]).get(row["track_id"])
|
||||
if facts is not None:
|
||||
store.put(facts, values) # the server's store: its stage checks against it
|
||||
step = plan_gain(values, Path(local).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.get(step.outcome, "nothing to change"))
|
||||
continue
|
||||
gain = step.gain_db
|
||||
partial = work / f"{n}{Path(local).suffix}"
|
||||
handle.progress(fraction=0.4, status=f"{gain:+.1f} dB")
|
||||
try:
|
||||
level_edit.apply(local, partial, gain)
|
||||
checkpoint()
|
||||
handle.progress(fraction=0.5, status="verifying")
|
||||
level_edit.verify(local, partial, gain)
|
||||
packed = None
|
||||
if row.get("lead") is not None: # the platform draws waveforms from its own files
|
||||
from ..core import waveform
|
||||
|
||||
handle.progress(fraction=0.7, status="waveform")
|
||||
measured = waveform.analyse(partial, lead=float(row["lead"]))
|
||||
packed = rp.pack_analysis(PreparedAnalysis(measured=measured)) if measured else None
|
||||
sent = 0
|
||||
total = max(partial.stat().st_size, 1)
|
||||
|
||||
def uploading(k: int) -> None:
|
||||
nonlocal sent
|
||||
sent += k
|
||||
checkpoint()
|
||||
f = 0.8 + min(sent / total, 1.0) * 0.2
|
||||
handle.progress(fraction=f, status=f"uploading {(f - 0.8) / 0.2 * 100:.0f} %")
|
||||
|
||||
adapter.stage_gain(row["track_id"], partial, gain_db=gain, options=body, waveform=packed,
|
||||
progress=uploading)
|
||||
except _Cancel:
|
||||
raise
|
||||
except AdapterError:
|
||||
raise
|
||||
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
|
||||
fail(row, str(ex) or type(ex).__name__)
|
||||
continue
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
uploaded.append(row["track_id"])
|
||||
staged.append(row["track_id"])
|
||||
except _Cancel:
|
||||
with contextlib.suppress(AdapterError):
|
||||
if uploaded:
|
||||
adapter.abandon_gain(uploaded)
|
||||
result["cancelled"] = True
|
||||
return result
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
if not staged:
|
||||
return result
|
||||
if not still_current():
|
||||
with contextlib.suppress(AdapterError):
|
||||
adapter.abandon_gain(uploaded)
|
||||
raise NormalizeError("The library changed while normalizing; nothing was changed")
|
||||
handle.progress(done=len(rows), message="Putting the new levels in place on the server…", status="")
|
||||
published = adapter.publish_gain(staged)
|
||||
result["normalised"] = list(published.get("normalised") or [])
|
||||
result["failed"] += published.get("failed") or []
|
||||
return result
|
||||
|
||||
|
||||
class _Cancel(Exception):
|
||||
pass
|
||||
@@ -1977,10 +1977,14 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
|
||||
# originals until Save, like a stem conversion. The library's own tracks only.
|
||||
|
||||
|
||||
def _remote_normalize(adapter) -> bool:
|
||||
"""A library held by a server: it plans and swaps, this computer rewrites
|
||||
(`gain/remote_normalize.py`)."""
|
||||
return hasattr(adapter, "normalize_plan")
|
||||
|
||||
|
||||
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")
|
||||
@@ -1997,6 +2001,13 @@ def normalize_preview(body: NormalizeRequest) -> dict:
|
||||
from .gain import normalize
|
||||
|
||||
a, opts = _normalize_target(body)
|
||||
if _remote_normalize(a):
|
||||
from .gain import remote_normalize
|
||||
|
||||
try:
|
||||
return remote_normalize.plan(a, body.track_ids, opts)
|
||||
except normalize.NormalizeError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
return normalize.plan(a, body.track_ids, opts, STATE.loudness, STATE.pending).as_dict()
|
||||
|
||||
|
||||
@@ -2011,6 +2022,11 @@ def normalize_tracks(body: NormalizeRequest) -> JobStatus:
|
||||
raise HTTPException(409, "Wait for the import to finish")
|
||||
|
||||
def run(handle):
|
||||
if _remote_normalize(a):
|
||||
from .gain import remote_normalize
|
||||
|
||||
return remote_normalize.run(handle, a, body.track_ids, opts,
|
||||
still_current=lambda: STATE.adapter is a)
|
||||
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)
|
||||
|
||||
|
||||
@@ -159,7 +159,13 @@ class Pending:
|
||||
"""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}
|
||||
return {i["track_id"] for i in self.items if i.get("track_id") in wanted and not _staged(i)}
|
||||
|
||||
def staged_gain(self, track_id: str) -> dict | None:
|
||||
"""A Normalize item for `track_id` whose verified file is written but
|
||||
not yet in place — on a server, an UPLOAD a takeover interrupted, which
|
||||
the next run reuses rather than downloading and rewriting again."""
|
||||
return next((i for i in self.items if i.get("track_id") == track_id and _staged(i)), None)
|
||||
|
||||
def summary(self) -> dict:
|
||||
waiting = self.swapped()
|
||||
@@ -364,6 +370,13 @@ def _published(item: dict) -> bool:
|
||||
return item.get("state") in ("published", "parked", "swapped", "committed")
|
||||
|
||||
|
||||
def _staged(item: dict) -> bool:
|
||||
"""A gain item still WRITING its file: not yet a change to the library.
|
||||
Never held across a run on this computer (one batch at a time; a crash's
|
||||
are cleared at the next open); on a server, an upload awaiting publish."""
|
||||
return _kind(item) == "gain" and item.get("state") in ("writing", "written")
|
||||
|
||||
|
||||
def _kind(item: dict) -> str:
|
||||
return item.get("kind") or "stem"
|
||||
|
||||
|
||||
@@ -42,7 +42,9 @@ from .core.model import AutoHotcue, Track, TrackCues
|
||||
#: 1.5 — loudness: `/v1/loudness/get`, `PUT /v1/loudness`, and `loudness` on
|
||||
#: `/v1/stems/stage` (the server keeps a remote library's measurements).
|
||||
#: 1.6 — auto gain: `set_auto_gain`, `Track.auto_gain_db`.
|
||||
API_VERSION: tuple[int, int] = (1, 6)
|
||||
#: 1.7 — Normalize: `/v1/gain/plan|stage|waveform|abandon|publish`, and
|
||||
#: `gain_tracks` / `gain_lossless` in `/v1/stems/pending`.
|
||||
API_VERSION: tuple[int, int] = (1, 7)
|
||||
|
||||
#: 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
|
||||
@@ -106,7 +108,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)",
|
||||
"audio_changed": "the server applies a Normalize itself, at its own end step (POST /v1/gain/publish)",
|
||||
"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",
|
||||
|
||||
@@ -709,6 +709,217 @@ def create_app(server: Server) -> FastAPI:
|
||||
result["rev"] = server.bump()
|
||||
return result
|
||||
|
||||
# ---- Normalize: the library side ---------------------------------------------
|
||||
# Like Convert to Stems: the computer that opened the library downloads,
|
||||
# rewrites + VERIFIES each file and uploads it (the server never decodes
|
||||
# audio); what lives here is the plan, from the server's own loudness store,
|
||||
# the uploads (kept as "written" items in the server's ledger, so a
|
||||
# takeover mid-batch loses nothing — the next run reuses them), and the
|
||||
# end step, under the library's mutation lock.
|
||||
def level_options(body: dict):
|
||||
from ..gain import normalize
|
||||
|
||||
measure = body.get("measure") or "lufs"
|
||||
if measure not in ("lufs", "rms"):
|
||||
raise HTTPException(400, f"Unknown measure {measure!r}")
|
||||
try:
|
||||
return normalize.Options(measure=measure, target=float(body.get("target", -9.0)),
|
||||
ceiling=float(body.get("ceiling", -1.0)))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, "Unreadable target or ceiling")
|
||||
|
||||
def normalizable():
|
||||
caps = server.adapter.capabilities()
|
||||
if not (caps.writable and caps.tracks.normalizable):
|
||||
raise HTTPException(422, "This library's audio files cannot be normalized")
|
||||
|
||||
def gain_source(track_id: str) -> Path:
|
||||
source = server.adapter.audio_path(track_id)
|
||||
if source is None or not Path(source).is_file():
|
||||
raise HTTPException(404, "The track's audio file is missing")
|
||||
return Path(source)
|
||||
|
||||
def waveform_file(track_id: str) -> Path:
|
||||
import hashlib
|
||||
|
||||
from .. import paths
|
||||
|
||||
name = hashlib.sha1(track_id.encode("utf-8")).hexdigest()
|
||||
return paths.app_data_dir() / "gain-waveforms" / f"{name}.npz.b64"
|
||||
|
||||
@app.post("/v1/gain/plan")
|
||||
def gain_plan(body: dict = Body(...)) -> dict:
|
||||
"""Normalize's plan, from the server's stored loudness — with what the
|
||||
client needs per row: the source's size (to download), the platform's
|
||||
analysis lead (None: it draws no waveform), and whether a verified
|
||||
upload at this very gain is already here (`staged`)."""
|
||||
from ..gain import normalize
|
||||
from ..pending import source_facts
|
||||
|
||||
normalizable()
|
||||
opts = level_options(body)
|
||||
adapter = server.adapter
|
||||
planned = normalize.plan(adapter, list(body.get("track_ids") or []), opts,
|
||||
server.state.loudness, server.state.pending)
|
||||
out = planned.as_dict()
|
||||
lead = getattr(adapter, "analysis_lead", None)
|
||||
for row, wire in zip(planned.rows, out["rows"]):
|
||||
source = row.source if row.source is not None and Path(row.source).is_file() else None
|
||||
wire["source_size"] = source.stat().st_size if source else 0
|
||||
wire["lead"] = lead(source) if (lead is not None and source is not None) else None
|
||||
item = server.state.pending.staged_gain(row.track_id)
|
||||
wire["staged"] = bool(
|
||||
item is not None and item.get("state") == "written" and row.step is not None
|
||||
and abs(float(item.get("gain_db") or 0) - row.step.gain_db) < 1e-6
|
||||
and source is not None and item.get("facts_before") == source_facts(source)
|
||||
and Path(item["partial"]).is_file())
|
||||
return out
|
||||
|
||||
@app.put("/v1/gain/stage")
|
||||
async def gain_stage(request: Request, track_id: str, gain_db: float, sha256: str,
|
||||
measure: str = "lufs", target: float = -9.0, ceiling: float = -1.0,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""One verified, levelled file, uploaded beside its source as
|
||||
`<name>.konduktor-partial` and recorded as a "written" item. The gain is
|
||||
checked against this server's own plan (its stored loudness), so a
|
||||
stale plan cannot put a file at the wrong level."""
|
||||
import hashlib
|
||||
|
||||
from ..core.level_plan import EXACT, plan_gain
|
||||
from ..pending import parked_name, partial_name, source_facts
|
||||
|
||||
session(token)
|
||||
normalizable()
|
||||
opts = level_options({"measure": measure, "target": target, "ceiling": ceiling})
|
||||
source = gain_source(track_id)
|
||||
facts = server.adapter.audio_facts([track_id]).get(track_id)
|
||||
entry = server.state.loudness.get([facts.key]).get(facts.key) if facts else None
|
||||
if entry is None or entry.stale(facts):
|
||||
raise HTTPException(409, "The track has no current loudness measurement on the server")
|
||||
step = plan_gain(entry.values, source.suffix, measure=opts.measure, target=opts.target,
|
||||
ceiling=opts.ceiling)
|
||||
if not step.writes or abs(step.gain_db - gain_db) > 1e-6:
|
||||
raise HTTPException(409, "The track's level changed since it was planned; plan again")
|
||||
pending = server.state.pending
|
||||
old = pending.staged_gain(track_id)
|
||||
if old is not None:
|
||||
Path(old["partial"]).unlink(missing_ok=True)
|
||||
pending.drop([old])
|
||||
if pending.holds([track_id]):
|
||||
raise HTTPException(409, "The track has a change awaiting Save")
|
||||
partial = partial_name(source)
|
||||
if partial.exists():
|
||||
raise HTTPException(409, f"{partial.name} is in the way")
|
||||
incoming = source.with_name(f".{source.name}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}")
|
||||
digest = hashlib.sha256()
|
||||
try:
|
||||
with open(incoming, "wb") as out:
|
||||
async for chunk in request.stream():
|
||||
out.write(chunk)
|
||||
digest.update(chunk)
|
||||
if digest.hexdigest() != sha256.lower():
|
||||
raise HTTPException(400, "The file arrived damaged (checksum mismatch)")
|
||||
os.replace(incoming, partial)
|
||||
finally:
|
||||
incoming.unlink(missing_ok=True)
|
||||
track = server.adapter.track(track_id)
|
||||
pending.add({
|
||||
"kind": "gain", "track_id": 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": "written",
|
||||
"facts_before": source_facts(source), "facts_after": source_facts(partial),
|
||||
"loudness_before": entry.wire(facts.key),
|
||||
"gain_before": getattr(track, "auto_gain_db", None),
|
||||
})
|
||||
waveform_file(track_id).unlink(missing_ok=True)
|
||||
return {"partial": str(partial), "gain_db": step.gain_db}
|
||||
|
||||
@app.put("/v1/gain/waveform")
|
||||
async def gain_waveform(request: Request, track_id: str,
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""The levelled file's drawn-waveform measurement (a packed analysis,
|
||||
`remote_protocol.pack_analysis`), measured on the client — kept until
|
||||
the end step regenerates the library's waveform tags from it."""
|
||||
session(token)
|
||||
if server.state.pending.staged_gain(track_id) is None:
|
||||
raise HTTPException(409, "Upload the levelled file first")
|
||||
data = b"".join([chunk async for chunk in request.stream()])
|
||||
if rp.unpack_analysis(data.decode("ascii")) is None:
|
||||
raise HTTPException(400, "Unreadable waveform")
|
||||
dest = waveform_file(track_id)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(data)
|
||||
return {"status": "stored"}
|
||||
|
||||
@app.post("/v1/gain/abandon")
|
||||
def gain_abandon(body: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""A cancelled Normalize: delete the files it uploaded, nothing else."""
|
||||
session(token)
|
||||
pending = server.state.pending
|
||||
for track_id in body.get("track_ids") or []:
|
||||
item = pending.staged_gain(track_id)
|
||||
if item is not None:
|
||||
Path(item["partial"]).unlink(missing_ok=True)
|
||||
pending.drop([item])
|
||||
waveform_file(track_id).unlink(missing_ok=True)
|
||||
return {"status": "abandoned"}
|
||||
|
||||
@app.post("/v1/gain/publish")
|
||||
def gain_publish(body: dict = Body(...),
|
||||
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
|
||||
"""Normalize's END STEP, here where the files are: park each original,
|
||||
put the uploaded file in its place, and let the library follow (size,
|
||||
waveforms, the recomputed auto gain) — an unsaved change, which the
|
||||
server's Save commits and its Discard undoes."""
|
||||
from ..core.level_plan import GainStep
|
||||
from ..core.loudness import Loudness
|
||||
from ..gain import normalize
|
||||
from ..pending import source_facts
|
||||
|
||||
holder = session(token)
|
||||
normalizable()
|
||||
pending = server.state.pending
|
||||
result = {"normalised": [], "failed": []}
|
||||
with server.state.mutation:
|
||||
for track_id in body.get("track_ids") or []:
|
||||
track = server.adapter.track(track_id)
|
||||
title = (track.title if track else None) or track_id
|
||||
item = pending.staged_gain(track_id)
|
||||
if item is None or item.get("state") != "written" or not Path(item["partial"]).is_file():
|
||||
result["failed"].append({"track_id": track_id, "title": title,
|
||||
"reason": "the levelled file never reached the server"})
|
||||
continue
|
||||
source = Path(item["source"])
|
||||
if source_facts(source) != item.get("facts_before"):
|
||||
Path(item["partial"]).unlink(missing_ok=True)
|
||||
pending.drop([item])
|
||||
result["failed"].append({"track_id": track_id, "title": title,
|
||||
"reason": "the file changed on the server meanwhile"})
|
||||
continue
|
||||
wave = waveform_file(track_id)
|
||||
measured = None
|
||||
if wave.is_file():
|
||||
prepared = rp.unpack_analysis(wave.read_text("ascii"))
|
||||
measured = prepared.measured if prepared is not None else None
|
||||
values = Loudness.from_dict(item["loudness_before"])
|
||||
row = normalize.Row(track_id, title, source)
|
||||
try:
|
||||
normalize._end_step(server.adapter, row, item, values,
|
||||
GainStep(float(item["gain_db"]), "apply"), measured,
|
||||
server.state.loudness, pending)
|
||||
result["normalised"].append(track_id)
|
||||
except Exception as ex: # noqa: BLE001 — undo that track, keep the rest
|
||||
log.warning("normalize end step failed for %s", track_id, exc_info=True)
|
||||
pending._undo_gain(item)
|
||||
pending.drop([item])
|
||||
result["failed"].append({"track_id": track_id, "title": title, "reason": str(ex)})
|
||||
finally:
|
||||
wave.unlink(missing_ok=True)
|
||||
server.lock.touch(holder)
|
||||
result["rev"] = server.bump()
|
||||
return result
|
||||
|
||||
@app.get("/v1/stems/pending")
|
||||
def stems_pending() -> dict:
|
||||
pending = server.state.pending
|
||||
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
"""Normalize on a REMOTE library.
|
||||
|
||||
A Konduktor server runs in a thread on a temp copy of the real collection whose
|
||||
entries point at generated audio on "the server"; the app normalises through
|
||||
its own routes. The server never decodes audio, so this pins the split:
|
||||
|
||||
* the server plans from its own loudness store, and this computer reports
|
||||
what must be downloaded and uploaded;
|
||||
* the run downloads, measures where the server has no value (stored back on
|
||||
the server), rewrites + verifies HERE and uploads; the SERVER parks the
|
||||
original, puts the upload under its name and recomputes the auto gain —
|
||||
its saved collection untouched until Save, which deletes the parked
|
||||
original there; Discard puts it back;
|
||||
* the server refuses an upload at a gain its own plan would not give;
|
||||
* Cancel deletes what the run uploaded, and nothing else;
|
||||
* a takeover mid-batch loses nothing: the verified upload stays on the
|
||||
server and the next run publishes it without rewriting;
|
||||
* a platform that draws waveforms gets them measured HERE, from the
|
||||
levelled file, and handed to the end step.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remotenorm-appdata-")
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
import av # noqa: E402
|
||||
import httpx # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
import soundfile as sf # noqa: E402
|
||||
import uvicorn # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor.adapters.remote import config as remote_config # noqa: E402
|
||||
from konduktor.adapters.remote.client import RemoteClient # 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.app_state import AppState # noqa: E402
|
||||
from konduktor.core import level_edit # noqa: E402
|
||||
from konduktor.gain import normalize, remote_normalize # noqa: E402
|
||||
from konduktor.pending import parked_name, partial_name # noqa: E402
|
||||
from konduktor.server.app import Server, create_app # noqa: E402
|
||||
from konduktor.server.config import ServerConfig # noqa: E402
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
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
|
||||
|
||||
|
||||
class MemoryKeychain(dict):
|
||||
def get(self, account): # noqa: D401
|
||||
return dict.get(self, account)
|
||||
|
||||
def set(self, account, password):
|
||||
self[account] = password
|
||||
|
||||
def delete(self, account):
|
||||
self.pop(account, None)
|
||||
|
||||
|
||||
def music(seconds=8.0, amp=0.3, sr=44100, seed=1):
|
||||
t = np.arange(int(sr * seconds)) / sr
|
||||
rng = np.random.default_rng(seed)
|
||||
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
|
||||
x = [amp * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.3 * np.sin(2 * np.pi * (440 + 30 * c) * t)
|
||||
+ 0.2 * rng.standard_normal(t.size)) for c in range(2)]
|
||||
return np.vstack(x).astype(np.float32)
|
||||
|
||||
|
||||
def make(path: Path, amp: float, seed: int) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
x = music(amp=amp, seed=seed)
|
||||
if path.suffix == ".mp3":
|
||||
with av.open(str(path), "w", format="mp3") as c:
|
||||
s = c.add_stream("libmp3lame", rate=44100, layout="stereo")
|
||||
s.bit_rate = 256_000
|
||||
for o in range(0, x.shape[1], 1152):
|
||||
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
|
||||
f.sample_rate, f.pts = 44100, o
|
||||
for p in s.encode(f):
|
||||
c.mux(p)
|
||||
for p in s.encode(None):
|
||||
c.mux(p)
|
||||
else:
|
||||
sf.write(str(path), x.T, 44100, subtype="PCM_16")
|
||||
return path
|
||||
|
||||
|
||||
remote_config.use_password_store(MemoryKeychain())
|
||||
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-remotenorm-"))
|
||||
FILES = ["a.mp3", "b.flac", "c.wav", "d.mp3", "e.wav", "f.mp3"]
|
||||
|
||||
# ---- a server library: entries pointed at generated audio --------------------------------
|
||||
content = (ROOT / "server" / "Music").resolve()
|
||||
work = ROOT / "server" / "collection.nml"
|
||||
work.parent.mkdir(parents=True)
|
||||
shutil.copy2(REAL, work)
|
||||
st = TraktorStore(work)
|
||||
entries = [e for e in st._nml.collection.entry if e.location and e.stems is None][:len(FILES)]
|
||||
ids, files = [], []
|
||||
for n, (name, e) in enumerate(zip(FILES, entries)):
|
||||
path = make(content / name, 0.8, n + 1)
|
||||
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
|
||||
e.cue_v2 = []
|
||||
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||
ids.append(st._key_of(e))
|
||||
files.append(path)
|
||||
st.save()
|
||||
del st
|
||||
originals = {p.name: p.read_bytes() for p in files}
|
||||
keep = ROOT / "originals"
|
||||
keep.mkdir()
|
||||
for p in files:
|
||||
shutil.copy2(p, keep / p.name)
|
||||
|
||||
cfg = ServerConfig(platform="traktor", library=work, content=content, username="dj", password="pw", name="NAS")
|
||||
srv = Server(cfg, state=AppState())
|
||||
srv.open()
|
||||
uv = uvicorn.Server(uvicorn.Config(create_app(srv), host="127.0.0.1", port=0, log_level="warning"))
|
||||
threading.Thread(target=uv.run, daemon=True).start()
|
||||
while not uv.started:
|
||||
time.sleep(0.05)
|
||||
port = uv.servers[0].sockets[0].getsockname()[1]
|
||||
OPTS = {"measure": "lufs", "target": -14.0, "ceiling": -1.0}
|
||||
|
||||
|
||||
def wait(c, jid, timeout=180):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
j = c.get(f"/api/jobs/{jid}").json()
|
||||
if j["state"] != "running":
|
||||
return j
|
||||
time.sleep(0.05)
|
||||
raise AssertionError("job did not finish")
|
||||
|
||||
|
||||
def at_gain(name: str, gain: float) -> bool | str:
|
||||
try:
|
||||
level_edit.verify(keep / name, content / name, gain)
|
||||
return True
|
||||
except level_edit.LevelEditError as ex:
|
||||
return str(ex)
|
||||
|
||||
|
||||
def server_gain_items() -> list[dict]:
|
||||
return [i for i in srv.state.pending.items if i.get("kind") == "gain"]
|
||||
|
||||
|
||||
class Handle:
|
||||
cancelled = False
|
||||
|
||||
def progress(self, **kw):
|
||||
pass
|
||||
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
remote_id = c.post("/api/remotes", json={"name": "NAS", "host": f"127.0.0.1:{port}",
|
||||
"username": "dj", "password": "pw"}).json()["remote"]["id"]
|
||||
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
|
||||
assert r.status_code == 200, r.text
|
||||
server_adapter = srv.state.adapter
|
||||
caps = c.get("/api/capabilities").json()
|
||||
check("a remote Traktor library is normalizable", caps["tracks"]["normalizable"], str(caps["tracks"]))
|
||||
|
||||
print("== the plan: the server's, plus this computer's ==")
|
||||
p = c.post("/api/tracks/normalize/preview", json={"track_ids": ids[:2], **OPTS}).json()
|
||||
check("both tracks are measured first (the server has no value yet)",
|
||||
p.get("to_measure") == 2 and all(r["outcome"] == "unmeasured" for r in p["rows"]), str(p)[:300])
|
||||
check("…and what must cross the network",
|
||||
p["transfer"]["download"] > 0 and p["transfer"]["upload"] > 0, p.get("transfer"))
|
||||
check("Traktor draws no waveform from its own files: no lead", all(r["lead"] is None for r in p["rows"]))
|
||||
|
||||
print("== a run: rewritten here, swapped in on the server ==")
|
||||
saved = work.read_bytes()
|
||||
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": ids[:2], **OPTS}).json()["id"])
|
||||
res = job.get("result") or {}
|
||||
check("the job normalises both", job["state"] == "done" and sorted(res.get("normalised", [])) == sorted(ids[:2]),
|
||||
job.get("error") or res)
|
||||
items = server_gain_items()
|
||||
check("the server's ledger holds both, awaiting Save", len(items) == 2
|
||||
and all(i["state"] == "swapped" for i in items), str([i.get("state") for i in items]))
|
||||
for name in FILES[:2]:
|
||||
g = next(i["gain_db"] for i in items if Path(i["source"]).name == name)
|
||||
check(f"{name}: the file on the server is the original at {g:+.2f} dB", at_gain(name, g) is True,
|
||||
str(at_gain(name, g)))
|
||||
check(f"{name}: the original is parked beside it, unchanged",
|
||||
parked_name(content / name).read_bytes() == originals[name])
|
||||
check("the SAVED collection is untouched until Save", work.read_bytes() == saved)
|
||||
held = httpx.post(f"http://127.0.0.1:{port}/v1/loudness/get", json={"paths": [str(files[0])]},
|
||||
auth=("dj", "pw")).json()["entries"]
|
||||
after_lufs = held[0]["lufs"] if held else None
|
||||
track = main.require_adapter().track(ids[0])
|
||||
check("the server's loudness is the NEW level, and the mirror's auto gain follows it",
|
||||
after_lufs is not None and abs(track.auto_gain_db - (-9.2 - after_lufs)) < 1e-4,
|
||||
f"{after_lufs} {track.auto_gain_db}")
|
||||
st_ = c.get("/api/state").json()
|
||||
check("the state reports the pending change (from the server's ledger)",
|
||||
st_["pending_gain"] and st_["pending_gain"]["tracks"] == 2, st_.get("pending_gain"))
|
||||
check("…and blocks what would save or drop it", c.post("/api/reload").status_code == 409)
|
||||
c.post("/api/save")
|
||||
check("Save deletes the parked originals on the server",
|
||||
not any(parked_name(content / n).exists() for n in FILES[:2]) and not server_gain_items())
|
||||
check("…and the saved collection holds the new gain",
|
||||
f'PERCEIVED_DB="{-9.2 - after_lufs:.6f}"'.encode() in work.read_bytes())
|
||||
|
||||
print("== Discard puts it back ==")
|
||||
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[2]], **OPTS}).json()["id"])
|
||||
check("(setup) a second run", job["state"] == "done" and (job.get("result") or {}).get("normalised"),
|
||||
job.get("error"))
|
||||
c.post("/api/discard")
|
||||
check("Discard restores the original's bytes on the server, nothing parked",
|
||||
(content / FILES[2]).read_bytes() == originals[FILES[2]]
|
||||
and not parked_name(content / FILES[2]).exists() and not server_gain_items())
|
||||
|
||||
print("== the server checks the gain against its own plan ==")
|
||||
adapter = main.require_adapter()
|
||||
local = adapter.audio_path(ids[3])
|
||||
junk = ROOT / "junk.mp3"
|
||||
shutil.copy2(local, junk)
|
||||
c.post("/api/tracks/loudness", json={"track_id": ids[3]})
|
||||
try:
|
||||
adapter.stage_gain(ids[3], junk, gain_db=12.0412, options=OPTS)
|
||||
refused = False
|
||||
except Exception as ex: # noqa: BLE001
|
||||
refused = "planned" in str(ex) or "409" in str(ex)
|
||||
check("an upload at a gain the server would not give is refused", refused)
|
||||
check("…and leaves nothing", not partial_name(content / FILES[3]).exists() and not server_gain_items())
|
||||
|
||||
print("== Cancel deletes what the run uploaded ==")
|
||||
h = Handle()
|
||||
real_stage = adapter.stage_gain
|
||||
|
||||
def stage_then_cancel(*a, **k):
|
||||
out = real_stage(*a, **k)
|
||||
h.cancelled = True
|
||||
return out
|
||||
|
||||
adapter.stage_gain = stage_then_cancel
|
||||
out = remote_normalize.run(h, adapter, [ids[3], ids[4]], normalize.Options(**OPTS), still_current=lambda: True)
|
||||
adapter.stage_gain = real_stage
|
||||
check("a cancel after one upload stops the batch", out["cancelled"])
|
||||
check("…and the uploaded file is deleted on the server",
|
||||
not partial_name(content / FILES[3]).exists() and not server_gain_items(), str(server_gain_items()))
|
||||
check("…nothing else changed", (content / FILES[3]).read_bytes() == originals[FILES[3]]
|
||||
and not server_adapter.dirty)
|
||||
|
||||
print("== a takeover mid-batch loses nothing ==")
|
||||
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "pw")
|
||||
|
||||
def stage_then_takeover(*a, **k):
|
||||
out = real_stage(*a, **k)
|
||||
other.acquire("other", "Studio iMac", takeover=True)
|
||||
other.release()
|
||||
return out
|
||||
|
||||
adapter.stage_gain = stage_then_takeover
|
||||
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[4]], **OPTS}).json()["id"])
|
||||
adapter.stage_gain = real_stage
|
||||
check("(the run cannot publish once taken over)", job["state"] != "done"
|
||||
or not (job.get("result") or {}).get("normalised"), str(job)[:300])
|
||||
check("the verified upload stays on the server",
|
||||
partial_name(content / FILES[4]).is_file() and [i["state"] for i in server_gain_items()] == ["written"])
|
||||
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
|
||||
p = c.post("/api/tracks/normalize/preview", json={"track_ids": [ids[4]], **OPTS}).json()
|
||||
check("the next plan reuses it", p["rows"][0].get("staged") and p["transfer"]["upload"] == 0, str(p)[:300])
|
||||
real_apply = level_edit.apply
|
||||
level_edit.apply = lambda *a, **k: (_ for _ in ()).throw(AssertionError("rewrote a staged file"))
|
||||
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[4]], **OPTS}).json()["id"])
|
||||
level_edit.apply = real_apply
|
||||
check("…and publishes it without rewriting", job["state"] == "done"
|
||||
and (job.get("result") or {}).get("normalised") == [ids[4]], job.get("error") or job.get("result"))
|
||||
c.post("/api/save")
|
||||
g = next((i for i in srv.state.pending.items), None)
|
||||
check("…saved, its original gone", not parked_name(content / FILES[4]).exists() and g is None)
|
||||
|
||||
print("== a platform that draws waveforms gets them measured HERE ==")
|
||||
server_adapter = srv.state.adapter
|
||||
seen = {}
|
||||
server_adapter.analysis_lead = lambda path: 0.0
|
||||
real_changed = server_adapter.audio_changed
|
||||
|
||||
def recording(track_id, change):
|
||||
seen[track_id] = change
|
||||
return real_changed(track_id, change)
|
||||
|
||||
server_adapter.audio_changed = recording
|
||||
p = c.post("/api/tracks/normalize/preview", json={"track_ids": [ids[5]], **OPTS}).json()
|
||||
check("the plan names the platform's lead", p["rows"][0]["lead"] == 0.0, str(p["rows"][0]))
|
||||
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[5]], **OPTS}).json()["id"])
|
||||
change = seen.get(ids[5])
|
||||
check("the end step receives the levelled file's waveform, measured on this computer",
|
||||
job["state"] == "done" and change is not None and change.measured is not None
|
||||
and len(change.measured.frames.bands) > 100, job.get("error"))
|
||||
c.post("/api/discard")
|
||||
uv.should_exit = True
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -1026,11 +1026,7 @@ export default function App() {
|
||||
/** 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")
|
||||
(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. */
|
||||
|
||||
@@ -685,6 +685,8 @@ export interface NormalizeRow {
|
||||
outcome?: 'apply' | 'capped' | 'at_target' | 'hot_peak_left' | 'unsupported' | 'unmeasured'
|
||||
short_by?: number
|
||||
lossless?: boolean
|
||||
/** A remote library: a verified upload at this gain is already on the server. */
|
||||
staged?: boolean
|
||||
}
|
||||
|
||||
export interface NormalizePreview {
|
||||
@@ -696,6 +698,8 @@ export interface NormalizePreview {
|
||||
lossless: number
|
||||
counts: Record<string, number>
|
||||
rows: NormalizeRow[]
|
||||
/** A remote library: what this computer downloads, rewrites and uploads. */
|
||||
transfer?: { download: number; upload: number; speed: number; measured: boolean }
|
||||
}
|
||||
|
||||
/** What a Normalize run did. */
|
||||
|
||||
@@ -79,6 +79,16 @@ export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
|
||||
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`)
|
||||
const t = p.transfer
|
||||
if (t && (t.download || t.upload)) {
|
||||
const mb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.round(b / 1e6))} MB`)
|
||||
const secs = (t.download + t.upload) / Math.max(t.speed, 1)
|
||||
lines.push(
|
||||
`On the server: ${t.download ? `${mb(t.download)} downloaded, ` : ''}${mb(t.upload)} uploaded` +
|
||||
` — about ${secs < 90 ? `${Math.max(1, Math.round(secs))} s` : `${Math.round(secs / 60)} min`}` +
|
||||
(t.measured ? '' : ' (estimated)'),
|
||||
)
|
||||
}
|
||||
return lines
|
||||
}, [p])
|
||||
|
||||
|
||||
Reference in new issue
Block a user