mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user