Implemented track loudness analysis

This commit is contained in:
patben8 committed 2026-10-19 14:07:54 +02:00
1 parent 5c9387f136
commit d70a7c5de2
28 files changed
+1732 -144

No files matched your search

@@ -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),
)
+3 -2
View File
@@ -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
+12 -2
View File
@@ -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})
+42 -1
View File
@@ -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
+29
View File
@@ -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.
+249
View File
@@ -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()
+192
View File
@@ -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)
+243 -59
View File
@@ -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.
+3 -1
View File
@@ -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
+46 -1
View File
@@ -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):
+37 -3
View File
@@ -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}
+42 -4
View File
@@ -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)."""
+6 -1
View File
@@ -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"])