Implemented basic track normalizing

This commit is contained in:
patben8 committed 2026-10-19 20:45:35 +02:00
1 parent 284a7514fe
commit 64b0396d66
33 files changed
+2584 -262

No files matched your search

@@ -410,6 +410,19 @@ class OneLibraryAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def analysis_lead(self, audio: Path) -> float:
"""rekordbox's clock against the decoded audio (as for the Rekordbox
adapter): what a regenerated waveform is measured at."""
from ..rekordbox import timebase
return timebase.offset(Path(audio))
def audio_changed(self, track_id: str, change) -> Track | None:
self._require_writable("Changing a track's level")
self._store.audio_changed(track_id, change)
self._refresh(track_id)
return self._index.get(track_id)
def set_auto_gain(self, track_id: str, loudness) -> Track | None:
# Measured (kit G2): no stick format carries an auto gain — not the
# database, not export.pdb, not the analysis files. `tracks.auto_gain`
@@ -87,6 +87,9 @@ def capabilities_for(
addable=not read_only,
removable=not read_only,
key_writable=not read_only,
# A stick has no auto gain, so normalising its audio is how it is
# levelled (its drawn waveforms are regenerated).
normalizable=not read_only,
# `content.color_id`, rekordbox's eight; the pdb row follows at Save.
colors=[] if read_only else list(track_palette.SWATCHES),
places_audio=True,
@@ -583,6 +583,41 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
db.session.expire(row)
# ---- writes: a level change (Normalize) -------------------------------------
def audio_changed(self, track_id: str, change) -> None:
"""The file changed level in place: `fileSize` follows (and the pdb's
row with it, at Save), and the drawn waveforms are regenerated into
the track's ANLZ files as edited copies — `.2EX` too — which Save
fingerprints and writes like any cue or grid edit."""
from ..rekordbox import anlz_writer
db = self._require_db()
row = self.content(track_id)
before = row.fileSize
row.fileSize = int(change.size)
measured = change.measured
if measured is not None:
dat, ext = self._editing(track_id)
for data in anlz_writer.preview_tags(measured.columns.rms, measured.columns.brightness):
dat.put(data[:4].decode("latin-1"), data, after=("PPTH", "PVBR", "PQTZ"))
ext_tags, two_tags = anlz_writer.waveform_tags(measured.frames.bands)
for data in ext_tags:
ext.put(data[:4].decode("latin-1"), data, after=("PPTH",))
dat_path, _ext_path = self._anlz_paths(track_id)
two = dat_path.with_suffix(".2EX")
if two in self._pending_anlz or two.is_file():
pending = self._pending_anlz.get(two)
if pending is None:
try:
pending = (anlz_file.parse_file(two), _fingerprint_file(two))
except (OSError, anlz_file.AnlzError) as ex:
raise InvalidCommand(f"Cannot read the analysis file {two.name}: {ex}") from ex
self._pending_anlz[two] = pending
for data in two_tags:
pending[0].put(data[:4].decode("latin-1"), data, after=("PPTH",))
self._journal.record("track", "audio", track_id, "level", before, change.gain_db)
db.flush()
# ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str):
from pyrekordbox.onelibrary import models
@@ -269,6 +269,12 @@ class RekordboxAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def audio_changed(self, track_id: str, change) -> Track | None:
self._require_writable("Changing a track's level")
self._store.audio_changed(track_id, change)
self._refresh(track_id)
return self._index.get(track_id)
def set_auto_gain(self, track_id: str, loudness) -> Track | None:
self._require_writable("Setting the auto gain")
self._store.set_auto_gain(track_id, loudness)
@@ -97,6 +97,7 @@ def capabilities_for(
colors=list(track_palette.SWATCHES),
# djmdMixerParam (measured, see `gain`).
auto_gain=True,
normalizable=True,
artwork=False,
artwork_note=None,
),
@@ -28,6 +28,7 @@ from __future__ import annotations
import json
import logging
import os
import uuid
from contextlib import contextmanager
from datetime import datetime
@@ -124,6 +125,9 @@ class RekordboxStore(ReplaceGridCommands):
# Grid edits buffered until save(): ANLZ files are written to disk, so
# applying them at command time would break the save contract.
self._pending_grids: dict[str, tuple[list, list, list]] = {}
# Normalize: drawn waveforms regenerated from the new audio, written
# into the track's ANLZ files at save (cues, grid, phrases untouched).
self._pending_waveforms: dict[str, object] = {}
# Analysis/artwork files of removed tracks, `share`-relative, deleted
# by save() AFTER the commit — a failed commit must leave them in place.
self._pending_file_removals: set[str] = set()
@@ -163,6 +167,7 @@ class RekordboxStore(ReplaceGridCommands):
self.close()
self._journal = EditJournal()
self._pending_grids.clear()
self._pending_waveforms.clear()
self._pending_file_removals.clear()
self._pending_new_files.clear()
self._load()
@@ -1063,6 +1068,7 @@ class RekordboxStore(ReplaceGridCommands):
# rows after, which hash what was finally written.
written = self._write_new_files()
try:
self._flush_waveforms()
self._flush_grids()
self._add_content_files(written)
self._commit()
@@ -1552,6 +1558,45 @@ class RekordboxStore(ReplaceGridCommands):
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
self._journal.record("grid", "replace" if ordered else "delete", track_id)
def audio_changed(self, track_id: str, change) -> None:
"""The file changed level in place (Normalize): `FileSize` follows, and
the drawn waveforms are regenerated from the new audio at save (they
are drawn from the audio's level; cues, grid and phrases stay)."""
row = self.content(track_id)
before = row.FileSize
row.FileSize = int(change.size)
if change.measured is not None:
self._pending_waveforms[str(track_id)] = change.measured
self._journal.record("track", "audio", track_id, "level", before, change.gain_db)
self._db.flush()
def _flush_waveforms(self) -> None:
"""Write regenerated waveform tags into existing ANLZ files: `.DAT`
PWAV/PWV2, `.EXT` PWV3/PWV5/PWV4, `.2EX` PWV7/PWV6/PWVC — each replaced
in place (`AnlzFile.put`), every other tag kept byte for byte."""
from . import anlz_file, anlz_writer
for track_id, measured in list(self._pending_waveforms.items()):
rel = getattr(self.content(track_id), "AnalysisDataPath", None)
if not rel:
continue # no analysis files: rekordbox draws from its own analysis
dat = self.path.parent / "share" / str(rel).lstrip("/\\")
ext_tags, two_tags = anlz_writer.waveform_tags(measured.frames.bands)
plan = [(dat, anlz_writer.preview_tags(measured.columns.rms, measured.columns.brightness),
("PPTH", "PVBR", "PQTZ")),
(dat.with_suffix(".EXT"), ext_tags, ("PPTH",)),
(dat.with_suffix(".2EX"), two_tags, ("PPTH",))]
for path, tags, after in plan:
if not path.is_file():
continue
parsed = anlz_file.parse_file(path)
for data in tags:
parsed.put(data[:4].decode("latin-1"), data, after=after)
partial = path.with_name(f".{path.name}.konduktor-partial")
partial.write_bytes(parsed.to_bytes())
os.replace(partial, path)
self._pending_waveforms.clear()
def _flush_grids(self) -> None:
"""Write buffered grids into their ANLZ files. Called by save().
@@ -162,6 +162,12 @@ class TraktorAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def audio_changed(self, track_id: str, change) -> Track | None:
with _translate():
self._store.audio_changed(track_id, change)
self._refresh(track_id)
return self._index.get(track_id)
def set_auto_gain(self, track_id: str, loudness) -> Track | None:
with _translate():
self._store.set_auto_gain(track_id, loudness)
@@ -72,6 +72,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
# INFO@COLOR, seven colours (measured, see `track_palette`).
colors=list(track_palette.SWATCHES),
auto_gain=True,
# Kit G1: a level change never makes Traktor re-analyse (grids are
# safe); its stored gain goes stale, which Normalize rewrites.
normalizable=True,
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both.
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
@@ -587,6 +587,23 @@ class TraktorStore:
self._journal.record("track", "set", track_id, "auto_gain", before, after)
self.dirty = True
# ---- a level change (Normalize) ------------------------------------------
def audio_changed(self, track_id: str, change) -> None:
"""The file at this entry changed level in place. Traktor keeps only its
size (KB) about it — and was measured (kit G1) to re-analyse nothing on
such a change; its LOUDNESS is rewritten separately (`set_auto_gain`).
Always journalled, so Save runs even if the size is unchanged (MP3)."""
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
if entry.info is None:
entry.info = Infotype()
before = entry.info.filesize
entry.info.filesize = int(round(change.size / 1024))
self._journal.record("track", "audio", track_id, "level", before, change.gain_db)
self.dirty = True
# ---- adding tracks --------------------------------------------------
def add_entry(self, track, audio_path: Path) -> str:
"""Append a brand-new ENTRY for `audio_path` and return its track id.
+48 -3
View File
@@ -177,12 +177,13 @@ class AppState:
# A crash may have left converted tracks mid-lifecycle: settle them from
# what the SAVED library says, BEFORE the missing-files check — a parked
# original is exactly what that check would report as missing.
from .stems.pending import Pending
from .pending import Pending
self.pending = Pending(self.library_id)
self.recovery = None
if self.pending.items:
self.recovery = self.pending.recover(lambda item: adapter.track(item["new_id"]) is not None)
self.recovery = self.pending.recover(lambda item: _committed(adapter, item))
self._restore_loudness()
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(adapter)
@@ -191,6 +192,18 @@ class AppState:
for hook in self.open_hooks:
hook(adapter)
def _restore_loudness(self) -> None:
"""A Normalize undone: the original is back, so is its measurement
(its facts are the original's again, so the value reads fresh)."""
entries = [i["loudness_before"] for i in getattr(self.pending, "restored_gain", ())
if i.get("loudness_before")]
put = getattr(self.loudness, "put_entries", None)
if entries and put is not None:
try:
put(entries)
except Exception: # noqa: BLE001 — bookkeeping must never fail a discard
log.warning("could not restore loudness values", exc_info=True)
def _keep_loudness(self, path, values) -> None:
from . import loudness_store
@@ -205,6 +218,7 @@ class AppState:
# a stem conversion's parked originals go back under their own names.
if self.pending is not None and self.pending.items:
self.pending.restore()
self._restore_loudness()
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
@@ -258,7 +272,19 @@ class AppState:
return self._save()
def _save(self):
outcome = self.adapter.save()
# Normalize's items: a crash inside the save is the one moment the
# ledger cannot decide alone (see pending.py) — bracket it.
marked = self.pending is not None and bool(self.pending.swapped())
if marked:
self.pending.begin_save(None)
try:
outcome = self.adapter.save()
except BaseException:
if marked:
self.pending.abort_save()
raise
if marked:
self.pending.mark_saved()
commit = self.services.commit_save(self.adapter, outcome)
# Konduktor itself just rewrote these files' tags: a loudness value
# measured before must not read as stale because of it. (On a remote
@@ -291,6 +317,7 @@ class AppState:
with self.mutation:
if self.pending is not None and self.pending.items:
self.pending.restore()
self._restore_loudness()
if self.services is not None and self.services.remote:
# The server holds the edits; it is what drops them.
self.services.discard()
@@ -320,3 +347,21 @@ if _env_nml and Path(_env_nml).exists():
STATE.open(Path(_env_nml))
except Exception: # noqa: BLE001 — bad env path shouldn't crash startup
pass
def _committed(adapter, item: dict) -> bool:
"""Recovery's question for an item a crash left mid-save: did the saved
library take it? A stem swap: the library names the stem file. A Normalize:
the library's auto gain is the NEW one and not the old (the end step always
rewrites it); a platform with no auto gain cannot tell, so it is not
(restore — the original audio is never destroyed on a guess)."""
if (item.get("kind") or "stem") == "stem":
return bool(item.get("new_id")) and adapter.track(item["new_id"]) is not None
after, before = item.get("gain_after"), item.get("gain_before")
if after is None:
return False
track = adapter.track(item["track_id"])
now = getattr(track, "auto_gain_db", None) if track is not None else None
if now is None or abs(now - after) > 0.01:
return False
return before is None or abs(now - before) > 0.01
+19
View File
@@ -185,6 +185,19 @@ class StemSwap:
size: int
@dataclass(frozen=True)
class AudioChange:
"""A track's audio file changed LEVEL in place (Normalize): same path, the
samples scaled by `gain_db`. `size` is the new file's size; `measured` the
new audio's `core.waveform.Analysis` at the platform's `analysis_lead`,
for a platform that stores drawn waveforms (None: it does not). The
library's own auto gain is a separate command (`set_auto_gain`)."""
gain_db: float
size: int
measured: object | None = None
@dataclass
class StemSwapResult:
#: Old track id -> the id of the entry that now names the stem file.
@@ -291,6 +304,12 @@ class LibraryAdapter(Protocol):
# every swap is validated before any is applied, so a clash leaves the
# library untouched. Gated on `capabilities().tracks.stem_convertible`.
# `add_to_playlist` receives the entries "add" mode creates, in order.
# A track's file changed level in place (see `AudioChange`): what the
# library keeps ABOUT the audio follows — its size, its drawn waveforms.
# Always an edit (so Save runs), even where nothing visible changes.
# Gated on `capabilities().tracks.normalizable`.
def audio_changed(self, track_id: str, change: AudioChange) -> Track | None: ...
def apply_stem_swaps(self, swaps: list["StemSwap"], *,
add_to_playlist: str | None = None) -> "StemSwapResult": ...
+3
View File
@@ -127,6 +127,9 @@ class TrackCapabilities(BaseModel):
# The library keeps a per-track auto gain the DJ app applies on load
# (`set_auto_gain`). False on a stick: no stick format has one (measured).
auto_gain: bool = False
# Tracks' files can be normalised in place: the library follows a level
# change (`audio_changed`) and keeps the parked original until Save.
normalizable: bool = False
class PlaylistCapabilities(BaseModel):
+428
View File
@@ -0,0 +1,428 @@
"""Change an audio file's level — losslessly where the format allows, exactly
where it is PCM. Always into a NEW file: the source is never touched.
Decided 2026-10-19 (the gain-normalisation discussion; `level_plan` decides
the gain):
* **MP3: the frame-gain edit** (mp3gain's): every granule's 8-bit
`global_gain` in the side info moves by whole steps of 2^(1/4) in
amplitude (1.505 dB). No re-encode, so no quality loss, no change of
encoder delay (cues stay put: `adapters/*/timebase.py`), same size. CRC-
protected frames get their CRC-16 recomputed; the Xing/Info/VBRI header
frame is not audio and is left alone. The undo is recorded as mp3gain
records it — an APEv2 `MP3GAIN_UNDO` tag (+ `MP3GAIN_MINMAX`) — which
Traktor 4.5 was measured to accept (kit G1). Verified exact on real MP3s:
the decode is the original x 2^(n/4) to within 1e-5 of peak.
* **WAV / AIFF: the samples are scaled IN their data chunk** (`data`,
`SSND`), in place in a copy, so the size and every other chunk (ID3,
cue, bext, …) are byte-identical.
* **FLAC: decoded, scaled and re-encoded** at the same bit depth and rate,
every Vorbis comment, picture and application block copied back.
* 16-bit PCM is TPDF-dithered (+-1 LSB triangular) unless the result is
exact; 24-bit and float are rounded without dither.
`verify` decodes source and result in step and checks result == source x g.
Kit G1 showed Traktor re-analyses nothing when a file's level changes — the
LIBRARY's stored gain goes stale, which the caller rewrites (`set_auto_gain`).
"""
from __future__ import annotations
import math
import shutil
import struct
from pathlib import Path
import numpy as np
from .level_plan import EXACT, STEP_DB, STEPPED
class LevelEditError(Exception):
"""A file this module cannot (or will not) change; the message is user-facing."""
def apply(src: Path | str, dst: Path | str, gain_db: float) -> None:
"""Write `src` at `gain_db` to `dst`, which must not exist."""
src, dst = Path(src), Path(dst)
if dst.exists():
raise LevelEditError(f"{dst.name} already exists")
suffix = src.suffix.lower()
try:
if suffix in STEPPED:
_mp3(src, dst, gain_db)
elif suffix in (".wav", ".wave"):
shutil.copyfile(src, dst)
_scale_chunk(dst, _wav_layout(dst), gain_db)
elif suffix in (".aif", ".aiff"):
shutil.copyfile(src, dst)
_scale_chunk(dst, _aiff_layout(dst), gain_db)
elif suffix == ".flac":
_flac(src, dst, gain_db)
else:
raise LevelEditError(f"Cannot change the level of a {suffix or 'suffix-less'} file")
except BaseException:
dst.unlink(missing_ok=True)
raise
# ---- MP3: the frame-gain edit -------------------------------------------------
_BITRATE = {
True: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
False: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
}
_RATE = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]}
def _get(buf, bit: int, n: int) -> int:
v = 0
for i in range(n):
v = (v << 1) | ((buf[(bit + i) >> 3] >> (7 - ((bit + i) & 7))) & 1)
return v
def _put(buf: bytearray, bit: int, n: int, v: int) -> None:
for i in range(n):
b = (v >> (n - 1 - i)) & 1
byte, shift = (bit + i) >> 3, 7 - ((bit + i) & 7)
buf[byte] = (buf[byte] & ~(1 << shift) & 0xFF) | (b << shift)
def _frame(buf, pos: int) -> dict | None:
"""A Layer III frame header at `pos`, or None."""
if pos + 4 > len(buf) or buf[pos] != 0xFF or (buf[pos + 1] & 0xE0) != 0xE0:
return None
ver, layer = (buf[pos + 1] >> 3) & 3, (buf[pos + 1] >> 1) & 3
br_i, sr_i = buf[pos + 2] >> 4, (buf[pos + 2] >> 2) & 3
if ver == 1 or layer != 1 or br_i in (0, 15) or sr_i == 3:
return None
mpeg1 = ver == 3
nch = 1 if (buf[pos + 3] >> 6) == 3 else 2
length = (144000 if mpeg1 else 72000) * _BITRATE[mpeg1][br_i] // _RATE[ver][sr_i] + ((buf[pos + 2] >> 1) & 1)
side_len = (17 if nch == 1 else 32) if mpeg1 else (9 if nch == 1 else 17)
return {"mpeg1": mpeg1, "crc": (buf[pos + 1] & 1) == 0, "nch": nch, "len": length, "side_len": side_len}
def _gain_bits(h: dict) -> list[int]:
"""Bit offsets, from the side info's start, of every granule's global_gain:
MPEG-1 has 2 granules of 59 bits per channel, MPEG-2/2.5 one of 63."""
nch = h["nch"]
if h["mpeg1"]:
start, block, granules = 9 + (5 if nch == 1 else 3) + 4 * nch, 59, 2
else:
start, block, granules = 8 + (1 if nch == 1 else 2), 63, 1
return [start + (g * nch + c) * block + 21 for g in range(granules) for c in range(nch)]
def _crc16(data: bytes) -> int:
"""CRC-16 as Layer III protects a frame: poly 0x8005, init 0xFFFF, over
header bytes 2-3 and the side info."""
crc = 0xFFFF
for byte in data:
for i in range(7, -1, -1):
bit = (byte >> i) & 1
top = (crc >> 15) & 1
crc = (crc << 1) & 0xFFFF
if top ^ bit:
crc ^= 0x8005
return crc
def _audio_start(buf) -> int:
"""Past an ID3v2 tag (and its footer), where the frames begin."""
if buf[:3] != b"ID3" or len(buf) < 10:
return 0
size = (buf[6] << 21) | (buf[7] << 14) | (buf[8] << 7) | buf[9]
return 10 + size + (10 if buf[5] & 0x10 else 0)
def mp3_steps(gain_db: float) -> int:
steps = round(gain_db / STEP_DB)
if abs(steps * STEP_DB - gain_db) > 1e-3:
raise LevelEditError(f"{gain_db:+.2f} dB is not a whole number of MP3 gain steps")
return steps
def _mp3(src: Path, dst: Path, gain_db: float) -> None:
steps = mp3_steps(gain_db)
buf = bytearray(src.read_bytes())
pos = _audio_start(buf)
frames, first = 0, True
lo, hi = 255, 0
while (h := _frame(buf, pos)) is not None:
side = pos + 4 + (2 if h["crc"] else 0)
if side + h["side_len"] > len(buf):
break
tag = bytes(buf[side + h["side_len"]: side + h["side_len"] + 4])
if first and (tag in (b"Xing", b"Info") or bytes(buf[pos + 36: pos + 40]) == b"VBRI"):
pass # the header frame is not audio
else:
for off in _gain_bits(h):
g = _get(buf, side * 8 + off, 8) + steps
if not 0 <= g <= 255:
raise LevelEditError(f"{src.name}: the gain would leave MP3's range (frame {frames})")
_put(buf, side * 8 + off, 8, g)
lo, hi = min(lo, g), max(hi, g)
if h["crc"]:
crc = _crc16(bytes(buf[pos + 2: pos + 4]) + bytes(buf[side: side + h["side_len"]]))
buf[pos + 4: pos + 6] = struct.pack(">H", crc)
frames += 1
first = False
pos += h["len"]
rest = bytes(buf[pos: pos + 8])
if frames == 0 or (pos < len(buf) - 128 and not rest.startswith((b"TAG", b"APETAGEX", b"LYRICS"))):
raise LevelEditError(f"{src.name}: not an MP3 this edit can read (lost frame sync at byte {pos})")
dst.write_bytes(buf)
_mp3gain_tag(dst, steps, lo, hi)
def _mp3gain_tag(path: Path, steps: int, lo: int, hi: int) -> None:
"""mp3gain's own record of the edit, so a later undo (by mp3gain, or by
Konduktor) is exact: MP3GAIN_UNDO = the steps that REVERSE every edit so
far, per channel, and whether any granule wrapped (never: refused)."""
from mutagen.apev2 import APEv2, APENoHeaderError
try:
tag = APEv2(str(path))
except APENoHeaderError:
tag = APEv2()
undo = -steps
if "MP3GAIN_UNDO" in tag:
try:
undo += int(str(tag["MP3GAIN_UNDO"]).split(",")[0])
except ValueError:
pass
tag["MP3GAIN_UNDO"] = f"{undo:+04d},{undo:+04d},N"
tag["MP3GAIN_MINMAX"] = f"{lo:03d},{hi:03d}"
tag.save(str(path))
# ---- WAV / AIFF: the samples scaled in their own chunk ------------------------
class _Layout:
def __init__(self, offset: int, size: int, channels: int, bits: int, kind: str, endian: str):
self.offset, self.size, self.channels = offset, size, channels
self.bits, self.kind, self.endian = bits, kind, endian # kind: "int" | "float"
def _wav_layout(path: Path) -> _Layout:
with open(path, "rb") as f:
head = f.read(12)
if head[:4] not in (b"RIFF", b"RIFX") or head[8:12] != b"WAVE":
raise LevelEditError(f"{path.name}: not a WAV file")
endian = "<" if head[:4] == b"RIFF" else ">"
fmt = None
while True:
hdr = f.read(8)
if len(hdr) < 8:
break
cid, size = hdr[:4], struct.unpack(endian + "I", hdr[4:])[0]
if cid == b"fmt ":
fmt = f.read(size)
if size % 2:
f.seek(1, 1)
continue
if cid == b"data":
if fmt is None:
raise LevelEditError(f"{path.name}: data before its format")
tag, channels = struct.unpack(endian + "HH", fmt[:4])
bits = struct.unpack(endian + "H", fmt[14:16])[0]
if tag == 0xFFFE and len(fmt) >= 26:
tag = struct.unpack(endian + "H", fmt[24:26])[0]
kind = {1: "int", 3: "float"}.get(tag)
if kind is None or (kind == "int" and bits not in (16, 24, 32)) or (kind == "float" and bits not in (32, 64)):
raise LevelEditError(f"{path.name}: a WAV encoding this edit does not handle (format {tag}, {bits}-bit)")
return _Layout(f.tell(), size, channels, bits, kind, endian)
f.seek(size + (size % 2), 1)
raise LevelEditError(f"{path.name}: no audio data")
def _aiff_layout(path: Path) -> _Layout:
with open(path, "rb") as f:
head = f.read(12)
if head[:4] != b"FORM" or head[8:12] not in (b"AIFF", b"AIFC"):
raise LevelEditError(f"{path.name}: not an AIFF file")
comm = None
while True:
hdr = f.read(8)
if len(hdr) < 8:
break
cid, size = hdr[:4], struct.unpack(">I", hdr[4:])[0]
if cid == b"COMM":
comm = f.read(size)
if size % 2:
f.seek(1, 1)
continue
if cid == b"SSND":
if comm is None:
raise LevelEditError(f"{path.name}: sound data before its format")
channels, _frames, bits = struct.unpack(">hIh", comm[:8])
compression = comm[18:22] if head[8:12] == b"AIFC" and len(comm) >= 22 else b"NONE"
offset, _block = struct.unpack(">II", f.read(8))
endian, kind = ">", "int"
if compression == b"sowt":
endian = "<"
elif compression in (b"fl32", b"FL32"):
kind, bits = "float", 32
elif compression != b"NONE":
raise LevelEditError(f"{path.name}: compressed AIFF ({compression.decode(errors='replace')})")
if kind == "int" and bits not in (16, 24, 32):
raise LevelEditError(f"{path.name}: {bits}-bit AIFF is not handled")
return _Layout(f.tell() + offset, size - 8 - offset, channels, bits, kind, endian)
f.seek(size + (size % 2), 1)
raise LevelEditError(f"{path.name}: no sound data")
def _decode_ints(raw: bytes, bits: int, endian: str) -> np.ndarray:
if bits == 24:
b = np.frombuffer(raw, np.uint8).reshape(-1, 3).astype(np.int32)
if endian == "<":
v = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
else:
v = b[:, 2] | (b[:, 1] << 8) | (b[:, 0] << 16)
return np.where(v & 0x800000, v - 0x1000000, v).astype(np.int64)
return np.frombuffer(raw, np.dtype(f"{endian}i{bits // 8}")).astype(np.int64)
def _encode_ints(v: np.ndarray, bits: int, endian: str) -> bytes:
if bits == 24:
u = (v.astype(np.int64) & 0xFFFFFF).astype(np.uint32)
out = np.empty((u.size, 3), np.uint8)
order = (0, 1, 2) if endian == "<" else (2, 1, 0)
for i, o in enumerate(order):
out[:, i] = (u >> (8 * o)) & 0xFF
return out.tobytes()
return v.astype(np.dtype(f"{endian}i{bits // 8}")).tobytes()
def _quantise(x: np.ndarray, bits: int, rng, dither: bool) -> np.ndarray:
"""Float samples in integer units -> integers, TPDF-dithered when asked,
clipped to the format's range (a raise is capped below full scale by
`level_plan`, so clipping is only ever the dither's last LSB)."""
if dither:
x = x + rng.random(x.shape) - rng.random(x.shape)
top = 2 ** (bits - 1)
return np.clip(np.rint(x), -top, top - 1).astype(np.int64)
def _needs_dither(bits: int, factor: float) -> bool:
# Exact only when scaling up by a whole power of two (an integer factor).
return bits == 16 and not (factor >= 1 and float(factor).is_integer())
def _scale_chunk(path: Path, lay: _Layout, gain_db: float) -> None:
factor = 10.0 ** (gain_db / 20.0)
width = lay.bits // 8
frame = width * lay.channels
rng = np.random.default_rng(0) # reproducible: a re-run writes the same bytes
dither = lay.kind == "int" and _needs_dither(lay.bits, factor)
usable = lay.size - lay.size % frame
chunk = frame * 65536
with open(path, "r+b") as f:
done = 0
while done < usable:
n = min(chunk, usable - done)
f.seek(lay.offset + done)
raw = f.read(n)
if len(raw) < n:
raise LevelEditError(f"{path.name}: the audio data is shorter than its header says")
if lay.kind == "float":
dtype = np.dtype(f"{lay.endian}f{width}")
out = (np.frombuffer(raw, dtype).astype(np.float64) * factor).astype(dtype).tobytes()
else:
out = _encode_ints(_quantise(_decode_ints(raw, lay.bits, lay.endian) * factor, lay.bits, rng, dither),
lay.bits, lay.endian)
f.seek(lay.offset + done)
f.write(out)
done += n
# ---- FLAC: decoded, scaled, re-encoded --------------------------------------------
def _flac(src: Path, dst: Path, gain_db: float) -> None:
import soundfile as sf
from mutagen.flac import FLAC
info = sf.info(str(src))
bits = {"PCM_16": 16, "PCM_24": 24, "PCM_S8": 8, "PCM_U8": 8}.get(info.subtype)
if bits not in (16, 24):
raise LevelEditError(f"{src.name}: {info.subtype} FLAC is not handled")
factor = 10.0 ** (gain_db / 20.0)
rng = np.random.default_rng(0)
dither = _needs_dither(bits, factor)
# int32 reads hold the sample in the TOP bits: shift to the format's units.
shift = 32 - bits
with sf.SoundFile(str(src)) as fin, sf.SoundFile(str(dst), "w", samplerate=info.samplerate,
channels=info.channels, format="FLAC",
subtype=info.subtype) as fout:
for block in fin.blocks(blocksize=65536, dtype="int32", always_2d=True):
v = _quantise((block.astype(np.int64) >> shift) * factor, bits, rng, dither)
fout.write((v << shift).astype(np.int32))
old, new = FLAC(str(src)), FLAC(str(dst))
if old.tags:
if new.tags is None:
new.add_tags()
for key, values in old.tags.as_dict().items():
new.tags[key] = values
for picture in old.pictures:
new.add_picture(picture)
for block in old.metadata_blocks:
if getattr(block, "code", None) == 2: # APPLICATION (e.g. a DJ app's private data)
new.metadata_blocks.append(block)
new.save()
# ---- verification ---------------------------------------------------------------
def _frames(path: Path):
import av
from . import pyav
with pyav.open_input(path) as c:
stream = c.streams.audio[0]
rs = av.AudioResampler(format="fltp", layout="stereo" if stream.codec_context.channels > 1 else "mono",
rate=int(stream.codec_context.sample_rate))
for frame in c.decode(stream):
for out in rs.resample(frame):
yield out.to_ndarray().astype(np.float64)
for out in rs.resample(None):
yield out.to_ndarray().astype(np.float64)
def verify(src: Path | str, dst: Path | str, gain_db: float, *, tolerance: float = 1e-3) -> None:
"""Decode both and check `dst` == `src` x 10^(g/20), to within `tolerance`
of the source's peak (16-bit dither is ~3e-5). Raises `LevelEditError`."""
factor = 10.0 ** (gain_db / 20.0)
a_iter, b_iter = _frames(Path(src)), _frames(Path(dst))
a_buf = b_buf = None
worst = peak = 0.0
length_a = length_b = 0
while True:
if a_buf is None or a_buf.shape[1] == 0:
a_buf = next(a_iter, None)
if a_buf is not None:
length_a += a_buf.shape[1]
if b_buf is None or b_buf.shape[1] == 0:
b_buf = next(b_iter, None)
if b_buf is not None:
length_b += b_buf.shape[1]
if a_buf is None or b_buf is None:
break
n = min(a_buf.shape[1], b_buf.shape[1])
if a_buf.shape[0] != b_buf.shape[0]:
raise LevelEditError(f"{Path(dst).name}: the channel count changed")
a, b = a_buf[:, :n], b_buf[:, :n]
peak = max(peak, float(np.abs(a).max(initial=0.0)))
worst = max(worst, float(np.abs(b - a * factor).max(initial=0.0)))
a_buf, b_buf = a_buf[:, n:], b_buf[:, n:]
for rest in a_iter:
length_a += rest.shape[1]
for rest in b_iter:
length_b += rest.shape[1]
if abs(length_a - length_b) > 0:
raise LevelEditError(f"{Path(dst).name}: the length changed ({length_a} vs {length_b} samples)")
if peak > 0 and worst / peak > tolerance:
raise LevelEditError(f"{Path(dst).name}: the result is not the source at {gain_db:+.2f} dB "
f"(off by {20 * math.log10(max(worst / peak, 1e-12)):.1f} dB of peak)")
+104
View File
@@ -0,0 +1,104 @@
"""What normalising does to ONE file's level, as one pure function.
Shared by Normalize's preview, its run and (later) the export's "Normalise
audio", as `grid_plan` is shared by Analyze — so the dialog's counts and what
is written cannot disagree. Decided 2026-10-19 (the gain-normalisation
discussion):
* The level is the user's pick of integrated **LUFS** or loud-section
**RMS** (`core.loudness`), brought to `target`.
* Up AND down, but a raise stops at the TRUE-PEAK `ceiling` (default
-1 dBTP): nothing Konduktor writes ever clips. A track that falls short
is `capped` and says by how much.
* A track whose peak is already over the ceiling and which is at or below
target is left alone (`hot_peak_left`) — normalising is about loudness,
not peak repair.
* Lossy files change only by the LOSSLESS frame-gain edit (`level_edit`):
whole steps of 2^(1/4) in amplitude, 1.505 dB. A lowering rounds to the
nearest step; a raise to the nearest step that stays under the ceiling.
Lossless files take the gain exactly.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Literal
from .loudness import Loudness
#: One `global_gain` step: amplitude x 2^(1/4).
STEP_DB = 20.0 * math.log10(2.0 ** 0.25)
#: Rewritten exactly (PCM scaled, same bit depth).
EXACT = frozenset({".wav", ".wave", ".aif", ".aiff", ".flac"})
#: Rewritten by the lossless frame-gain edit, in `STEP_DB` steps.
STEPPED = frozenset({".mp3"})
#: Closer than this to the target (lossless) is "already there".
_EXACT_TOLERANCE_DB = 0.05
Measure = Literal["lufs", "rms"]
Outcome = Literal["apply", "capped", "at_target", "hot_peak_left", "unsupported", "unmeasured"]
@dataclass(frozen=True)
class GainStep:
"""`gain_db` to apply (0: nothing to write) and why. `short_by` is how far
below target a `capped` track stays."""
gain_db: float
outcome: Outcome
short_by: float = 0.0
@property
def writes(self) -> bool:
return self.gain_db != 0.0
def supported(suffix: str) -> bool:
return suffix.lower() in EXACT or suffix.lower() in STEPPED
def plan_gain(loudness: Loudness | None, suffix: str, *, measure: Measure,
target: float, ceiling: float) -> GainStep:
"""The gain for one file. `suffix` decides exact vs stepped (".mp3")."""
suffix = suffix.lower()
if not supported(suffix):
return GainStep(0.0, "unsupported")
if loudness is None:
return GainStep(0.0, "unmeasured")
level = loudness.lufs if measure == "lufs" else loudness.rms
want = target - level
stepped = suffix in STEPPED
tolerance = STEP_DB / 2 if stepped else _EXACT_TOLERANCE_DB
if abs(want) < tolerance:
return GainStep(0.0, "at_target")
if want < 0: # lowering never clips
gain = round(want / STEP_DB) * STEP_DB if stepped else want
return GainStep(_clean(gain), "apply")
headroom = ceiling - loudness.true_peak
if headroom <= 0:
return GainStep(0.0, "hot_peak_left")
gain = min(want, headroom)
if stepped:
n = round(gain / STEP_DB)
if n * STEP_DB > headroom + 1e-9:
n -= 1
gain = n * STEP_DB
gain = _clean(gain)
if want - gain >= tolerance:
return GainStep(gain if gain > 0 else 0.0, "capped", short_by=_clean(want - gain))
return GainStep(gain, "apply")
def shifted(loudness: Loudness, gain_db: float) -> Loudness:
"""A file's loudness after `gain_db`: LUFS, RMS and true peak move by it,
LRA and PLR do not (a gain changes no dynamics). Exact for both edits:
`level_edit` scales the decoded samples by exactly 10^(g/20)."""
return Loudness(lufs=loudness.lufs + gain_db, rms=loudness.rms + gain_db,
true_peak=loudness.true_peak + gain_db, lra=loudness.lra, plr=loudness.plr)
def _clean(x: float) -> float:
return round(x, 6) + 0.0 # no -0.0, no float noise in a stored value
+1
View File
@@ -0,0 +1 @@
"""Gain features on the audio itself: Normalize (`normalize.py`)."""
+267
View File
@@ -0,0 +1,267 @@
"""Normalize: change tracks' audio level in place, as an unsaved change.
Decided 2026-10-19 (the gain-normalisation discussion). Per track the gain is
`core.level_plan.plan_gain` (the same function the dialog's preview counts
with), the file is rewritten by `core.level_edit` into
`<name>.konduktor-partial` beside it and decode-VERIFIED, and nothing the
library or the user sees changes until ONE short end step under the app's
mutation lock:
1. the original is PARKED (`.<name>.konduktor-parked`, hidden on Windows)
and the verified file renamed onto the original's own name — the path
never changes, so no playlist, export set or cue needs retargeting;
2. the library follows the new audio (`audio_changed`: its size, and its
drawn waveforms where it stores them);
3. the DJ app's auto gain is RECOMPUTED from the new level (decided — the
old value would now double-apply the change; kit G1 measured that Traktor
never re-analyses a file whose level changed);
4. Konduktor's own loudness value is SHIFTED by the gain (exact: the edit
scales the samples), under the new file's facts.
From there it is an ordinary unsaved change (`pending.py`, kind "gain"): Save
deletes the parked original — permanent for a lossless file, while an MP3
keeps an mp3gain undo tag — and Discard puts it back. Measuring first where a
track has no (or a stale) loudness happens inside the run.
"""
from __future__ import annotations
import logging
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
from ..core import level_edit, loudness
from ..core.adapter import AudioChange
from ..core.level_plan import EXACT, GainStep, Measure, plan_gain, shifted
from ..pending import Pending, _replace_no_overwrite, _retrying, parked_name, partial_name, source_facts
log = logging.getLogger(__name__)
class NormalizeError(Exception):
"""The batch cannot run; the message is user-facing."""
@dataclass(frozen=True)
class Options:
measure: Measure = "lufs"
target: float = -9.0
ceiling: float = -1.0
@dataclass
class Row:
"""One track's plan: what the preview lists and the run starts from."""
track_id: str
title: str
source: Path | None
step: GainStep | None = None
level: float | None = None # the measure now (None: unmeasured)
skip: str | None = None # a reason, when nothing can be done
def as_dict(self) -> dict:
out = {"track_id": self.track_id, "title": self.title, "level": self.level, "skip": self.skip}
if self.step is not None:
out.update(gain_db=self.step.gain_db, outcome=self.step.outcome, short_by=self.step.short_by,
lossless=self.source is not None and self.source.suffix.lower() in EXACT)
return out
@dataclass
class Plan:
rows: list[Row] = field(default_factory=list)
def as_dict(self) -> dict:
counts: dict[str, int] = {}
lossless = 0
for r in self.rows:
key = r.skip and "skipped" or (r.step.outcome if r.step else "skipped")
counts[key] = counts.get(key, 0) + 1
if r.step is not None and r.step.writes and r.source.suffix.lower() in EXACT:
lossless += 1
writes = sum(1 for r in self.rows if r.step is not None and r.step.writes)
unmeasured = counts.get("unmeasured", 0)
return {"total": len(self.rows), "to_change": writes, "to_measure": unmeasured,
"tracks_to_process": writes + unmeasured, "lossless": lossless, "counts": counts,
"rows": [r.as_dict() for r in self.rows]}
def plan(adapter, track_ids, opts: Options, store, pending: Pending | None) -> Plan:
"""Per track: the gain `plan_gain` gives from the STORED loudness. A track
with none (or a stale one) is `unmeasured`: the run measures it first."""
held = pending.holds(track_ids) if pending is not None else set()
out = Plan()
ids = list(dict.fromkeys(track_ids))
facts = adapter.audio_facts(ids)
entries = store.get([f.key for f in facts.values() if f is not None])
for tid in ids:
track = adapter.track(tid)
if track is None:
continue
title = track.title or tid
path = adapter.audio_path(tid)
f = facts.get(tid)
if tid in held:
out.rows.append(Row(tid, title, path, skip="has a stem conversion or level change awaiting Save"))
continue
if path is None or f is None or not Path(path).is_file():
out.rows.append(Row(tid, title, path, skip="audio file not found (is the drive mounted?)"))
continue
entry = entries.get(f.key)
values = entry.values if entry is not None and not entry.stale(f) else None
step = plan_gain(values, Path(path).suffix, measure=opts.measure, target=opts.target, ceiling=opts.ceiling)
level = None if values is None else (values.lufs if opts.measure == "lufs" else values.rms)
out.rows.append(Row(tid, title, Path(path), step=step, level=level))
return out
def run(handle, adapter, track_ids, opts: Options, *, store, pending: Pending, mutation,
still_current: Callable[[], bool]) -> dict:
"""The job: measure where needed, rewrite + verify each file, then ONE end
step. Returns the result dict."""
planned = plan(adapter, track_ids, opts, store, pending)
result = {"normalised": [], "skipped": [], "failed": [], "counts": {}, "cancelled": False}
rows = [r for r in planned.rows]
handle.progress(done=0, total=len(rows), unit="tracks")
finished: list[tuple[Row, dict, object]] = []
def skip(row: Row, reason: str) -> None:
result["skipped"].append({"track_id": row.track_id, "title": row.title, "reason": reason})
try:
for i, row in enumerate(rows):
if handle.cancelled:
raise _Cancel()
handle.progress(done=i, message=row.title, fraction=0.0, status="")
if row.skip:
skip(row, row.skip)
continue
source = row.source
facts = adapter.audio_facts([row.track_id]).get(row.track_id)
got = store.get([facts.key]).get(facts.key) if facts is not None else None
values = got.values if got is not None and not got.stale(facts) else None
if values is None:
handle.progress(status="measuring")
try:
values = loudness.measure_file(source)
except Exception as ex: # noqa: BLE001 — an undecodable file is one failure
result["failed"].append({"track_id": row.track_id, "title": row.title,
"reason": f"Could not measure: {ex}"})
continue
if values is None:
skip(row, "nothing to measure (silent or under 3 s)")
continue
store.put(facts, values)
step = plan_gain(values, source.suffix, measure=opts.measure, target=opts.target, ceiling=opts.ceiling)
result["counts"][step.outcome] = result["counts"].get(step.outcome, 0) + 1
if not step.writes:
skip(row, _WHY[step.outcome])
continue
partial = partial_name(source)
if partial.exists():
skip(row, f"{partial.name} is in the way")
continue
track = adapter.track(row.track_id)
before_wire = {"path": facts.key, "size": facts.size, "mtime_ns": facts.mtime_ns,
"version": loudness.VERSION, **values.as_dict()}
pitem = pending.add({
"kind": "gain", "track_id": row.track_id, "source": str(source), "partial": str(partial),
"parked": str(parked_name(source)), "gain_db": step.gain_db,
"lossless": source.suffix.lower() in EXACT, "state": "writing",
"facts_before": source_facts(source), "loudness_before": before_wire,
"gain_before": getattr(track, "auto_gain_db", None),
})
handle.progress(status=f"{step.gain_db:+.1f} dB")
try:
level_edit.apply(source, partial, step.gain_db)
handle.progress(fraction=0.5, status="verifying")
level_edit.verify(source, partial, step.gain_db)
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
partial.unlink(missing_ok=True)
pending.drop([pitem])
result["failed"].append({"track_id": row.track_id, "title": row.title, "reason": str(ex)})
continue
measured = None
lead = getattr(adapter, "analysis_lead", None)
if lead is not None: # the platform draws waveforms from its own files
from ..core import waveform
handle.progress(fraction=0.8, status="waveform")
measured = waveform.analyse(partial, lead=lead(source))
pending.update(pitem, state="written", facts_after=source_facts(partial))
finished.append((row, pitem, (values, step, measured)))
except _Cancel:
for _row, pitem, _ in finished:
Path(pitem["partial"]).unlink(missing_ok=True)
pending.drop([p for _, p, _ in finished])
result["cancelled"] = True
return result
handle.progress(done=len(rows), message="Putting the new levels in place…", status="")
with mutation:
if not still_current():
for _row, pitem, _ in finished:
Path(pitem["partial"]).unlink(missing_ok=True)
pending.drop([p for _, p, _ in finished])
raise NormalizeError("The library changed while normalizing; nothing was changed")
for row, pitem, (values, step, measured) in finished:
try:
_end_step(adapter, row, pitem, values, step, measured, store, pending)
result["normalised"].append(row.track_id)
except Exception as ex: # noqa: BLE001 — undo that track, keep the rest
log.warning("normalize end step failed for %s", row.track_id, exc_info=True)
pending._undo_gain(pitem)
pending.drop([pitem])
result["failed"].append({"track_id": row.track_id, "title": row.title, "reason": str(ex)})
return result
def _end_step(adapter, row: Row, pitem: dict, values, step: GainStep, measured, store, pending: Pending) -> None:
source = Path(pitem["source"])
parked = Path(pitem["parked"])
_retrying(lambda: _replace_no_overwrite(source, parked))
_hide(parked)
pending.update(pitem, state="parked")
_retrying(lambda: _replace_no_overwrite(Path(pitem["partial"]), source))
pending.update(pitem, state="published")
facts = adapter.audio_facts([row.track_id]).get(row.track_id)
after = shifted(values, step.gain_db)
adapter.audio_changed(row.track_id, AudioChange(gain_db=step.gain_db, size=source.stat().st_size,
measured=measured))
if adapter.capabilities().tracks.auto_gain:
# Recomputed from the NEW level (decided): the old value would now
# double-apply the change.
adapter.set_auto_gain(row.track_id, after)
track = adapter.track(row.track_id)
if facts is not None:
store.put(facts, after)
pending.update(pitem, state="swapped", gain_after=getattr(track, "auto_gain_db", None),
facts_after=source_facts(source))
_WHY = {
"at_target": "already at the target",
"hot_peak_left": "its peak is already over the ceiling",
"capped": "no headroom under the ceiling",
"unsupported": "this format cannot be changed losslessly",
"unmeasured": "not measured",
}
class _Cancel(Exception):
pass
def _hide(path: Path) -> None:
"""Windows ignores dot-names; set the hidden attribute so a parked original
does not show in Explorer (or a naive folder scan)."""
if sys.platform != "win32":
return
try:
import ctypes
ctypes.windll.kernel32.SetFileAttributesW(str(path), 0x02)
except Exception: # noqa: BLE001
pass
+73 -12
View File
@@ -121,6 +121,7 @@ from .schemas import (
StemEngineInstall,
StemSideLoad,
StemConvert,
NormalizeRequest,
)
log = logging.getLogger(__name__)
@@ -409,7 +410,7 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
"""Set (or, with blank prefixes, clear) the current collection's remapping.
Persists to userprefs AND updates the live store so playback/analysis
re-resolve immediately — no reopen needed. Never touches the .nml."""
_require_no_pending_stems("Changing the path mapping")
_require_no_pending("Changing the path mapping")
a = require_adapter()
mapping = PathMapping.make(body.from_, body.to)
prefs.set_path_mapping(
@@ -445,7 +446,7 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
playlist references that join to them) to the `to` prefix, then save (a
version-history commit is written). Destructive and OS-specific — the UI
warns accordingly."""
_require_no_pending_stems("Rewriting paths")
_require_no_pending("Rewriting paths")
mapping = PathMapping.make(body.from_, body.to)
if mapping.empty:
raise HTTPException(400, "Both a `from` and `to` prefix are required")
@@ -512,7 +513,7 @@ def answer_relocation(body: RelocationApply) -> RelocationApplied:
"""Answer the check: apply the chosen mappings for THIS SESSION only (no
mappings = "Not now"). Nothing is written to the library or to prefs, and a
reopen asks again."""
_require_no_pending_stems("Relocating files")
_require_no_pending("Relocating files")
require_adapter()
check = STATE.relocation
if check is None:
@@ -958,9 +959,13 @@ def capabilities() -> Capabilities:
@app.get("/api/state", response_model=EditState)
def state() -> EditState:
stem_job = JOBS.active(STEM_JOB)
normalize_job = JOBS.active(NORMALIZE_JOB)
pending = STATE.pending.summary() if STATE.pending is not None else None
return EditState(dirty=require_adapter().dirty, library=_library_info(),
pending_stems=pending if pending and pending["tracks"] else None,
pending_gain=({"tracks": pending["gain_tracks"], "lossless": pending["gain_lossless"]}
if pending and pending.get("gain_tracks") else None),
normalize_job=normalize_job[0].id if normalize_job else None,
stem_job=stem_job[0].id if stem_job else None,
stem_recovery=STATE.recovery,
remote=STATE.remote.describe() if STATE.remote is not None else None)
@@ -1029,14 +1034,19 @@ def install_stem_engine(body: StemEngineInstall) -> JobStatus:
return JobStatus(**job.as_dict())
def _require_no_pending_stems(what: str) -> None:
"""Refuse an operation that would SAVE or DROP a stem conversion's swap as a
def _require_no_pending(what: str) -> None:
"""Refuse an operation that would SAVE or DROP a pending file change as a
side effect — import and remap save pending edits, reload and restore drop
them — while converted tracks await Save/Discard or a conversion runs."""
them — while converted or normalized tracks await Save/Discard, or a
conversion or Normalize runs. (Remap and relocation would also move the
paths the ledger is keyed by.)"""
if JOBS.active(STEM_JOB):
raise HTTPException(409, f"{what} is not possible while tracks are being converted to stems")
if JOBS.active(NORMALIZE_JOB):
raise HTTPException(409, f"{what} is not possible while tracks are being normalized")
if STATE.pending is not None and STATE.pending.blocking():
raise HTTPException(409, f"{what} is not possible until the converted tracks are saved or discarded")
raise HTTPException(409, f"{what} is not possible until the converted or normalized tracks "
"are saved or discarded")
def _stem_options(body):
@@ -1172,7 +1182,7 @@ def discard_changes() -> EditState:
@app.post("/api/reload")
def reload_collection() -> dict:
_require_no_pending_stems("Reloading")
_require_no_pending("Reloading")
if not STATE.loaded:
raise HTTPException(409, "No collection loaded")
if STATE.remote is not None:
@@ -1580,7 +1590,8 @@ class _AnalysisError(Exception):
# beats that no longer exist.
GRID_JOB = "grid-analysis"
CUE_JOB = "auto-hotcues"
BATCH_JOBS = (GRID_JOB, CUE_JOB, STEM_JOB)
NORMALIZE_JOB = "normalize"
BATCH_JOBS = (GRID_JOB, CUE_JOB, STEM_JOB, NORMALIZE_JOB)
def _stop_batches() -> None:
@@ -1924,6 +1935,56 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
key=False, replace_grid=body.replace_existing))
# ---- Normalize (the track menu's Mastering ▸ Normalize…) --------------------
#
# Changes the audio files' level in place (`gain/normalize.py`): parked
# originals until Save, like a stem conversion. The library's own tracks only.
def _normalize_target(body: NormalizeRequest):
a = require_adapter()
if STATE.remote is not None:
raise HTTPException(409, "Normalize is not available on a remote library yet")
caps = a.capabilities()
if not (caps.writable and caps.tracks.normalizable):
raise HTTPException(422, "This library's audio files cannot be normalized")
if not -30.0 <= body.target <= 0.0 or not -12.0 <= body.ceiling <= 0.0:
raise HTTPException(400, "Target or ceiling out of range")
from .gain import normalize
return a, normalize.Options(measure=body.measure, target=body.target, ceiling=body.ceiling)
@app.post("/api/tracks/normalize/preview")
def normalize_preview(body: NormalizeRequest) -> dict:
"""What Normalize would do per track, from the same `plan_gain` the run uses."""
from .gain import normalize
a, opts = _normalize_target(body)
return normalize.plan(a, body.track_ids, opts, STATE.loudness, STATE.pending).as_dict()
@app.post("/api/tracks/normalize", response_model=JobStatus)
def normalize_tracks(body: NormalizeRequest) -> JobStatus:
"""Normalize as a JOB; the new files land at its end as unsaved changes."""
from .gain import normalize
a, opts = _normalize_target(body)
_require_no_batch()
if JOBS.active("import"):
raise HTTPException(409, "Wait for the import to finish")
def run(handle):
return normalize.run(handle, a, body.track_ids, opts, store=STATE.loudness, pending=STATE.pending,
mutation=STATE.mutation, still_current=lambda: STATE.adapter is a)
try:
job = JOBS.submit(NORMALIZE_JOB, run, exclusive_with=BATCH_JOBS + ("import",))
except JobBusy:
raise HTTPException(409, "Another batch or import is running")
return JobStatus(**job.as_dict())
# ---- Loudness (the Mastering columns) --------------------------------------
#
# Measured by `core/loudness.py` into Konduktor's own store (`loudness_store.py`),
@@ -2299,7 +2360,7 @@ def restore_version(commit_id: str) -> CollectionStatus:
"""Restore the collection to a past version. Writes that version back as a
NEW forward save (a fresh commit on top of history — never a rewind), then
reloads. The user should close Traktor first (it overwrites on exit)."""
_require_no_pending_stems("Restoring a version")
_require_no_pending("Restoring a version")
require_adapter()
if not STATE.restore_version(commit_id):
raise HTTPException(404, f"Version not found: {commit_id}")
@@ -2790,7 +2851,7 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
@app.post("/api/folder/add", response_model=JobStatus)
def folder_add(body: FolderAddRequest) -> JobStatus:
"""Add browsed files to the collection. A job, like import: copying can be long."""
_require_no_pending_stems("Adding files")
_require_no_pending("Adding files")
in_place = _is_server_add(body)
if in_place:
source, dest, plan = _server_add_plan(body)
@@ -2880,7 +2941,7 @@ def import_preview(body: ImportRequest) -> dict:
@app.post("/api/import", response_model=JobStatus)
def start_import(body: ImportRequest) -> JobStatus:
"""Start an import. Returns immediately; poll the job for progress."""
_require_no_pending_stems("Importing")
_require_no_pending("Importing")
source, dest, destination, plan = _import_plan(body)
if not plan.importable:
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
+378
View File
@@ -0,0 +1,378 @@
"""Changes to audio FILES that are done on disk but not yet committed by a Save.
Two kinds of item share this ledger (and every hook into it — Save, Discard,
opening another library, crash recovery, the routes that must refuse while
any are pending): a Convert to Stems swap (`kind` "stem", or no kind — every
ledger written before Normalize) and a Normalize level change (`kind` "gain",
see "Gain items" below).
A Convert to Stems batch leaves, per track: a stem file, and — in Replace mode —
the original PARKED beside it (`.<name>.<ext>.konduktor-parked`, the same
folder, so the rename is atomic and nothing looks like audio). The collection
swap itself is an ordinary unsaved edit. So the files must follow what happens
to the edits:
* **Save** commits them: parked originals are deleted (the user chose Replace,
and was told Save deletes them), export sets follow the new ids.
* **Discard** — or opening another library, after its confirm — undoes them:
originals go back under their own names, the stem files are removed.
* **A crash** leaves this ledger on disk. The next open of the library
decides each item from the SAVED collection: if it names the stem file the
swap was committed (finish deleting the original), otherwise it was not
(put the original back). Verified stem files of an uncommitted item are
kept — renamed to their `.konduktor-partial` name, so neither the user nor
Traktor mistakes them for finished files — and a later batch converting the
same source reuses one instead of spending minutes separating it again.
**Gain items** (Normalize, decided 2026-10-19). The level-changed file is
written beside the source as `<name>.konduktor-partial` and verified; then the
source is PARKED and the partial renamed onto the source's own name, so the
path never changes. States: writing -> written -> parked -> published ->
swapped (the library's gain/waveform edits made) -> saving -> saved. Because
the path does not change, "does the saved library name the new file" cannot
tell a crash's outcome; instead `AppState._save` brackets `adapter.save()`
with `begin_save` / `mark_saved`, so only a crash INSIDE the save (state
"saving") needs the library asked (`is_committed`, which the caller words
per platform). Unsure always means restore: the original audio is never
destroyed on a guess. After Save a lossless file's change is permanent (the
original is deleted); an MP3's stays reversible by its mp3gain undo tag.
The ledger is Konduktor's own curated state, written atomically
(`paths.write_json`), one file per library id. Every step is taken from what is
actually ON DISK, never from the recorded state alone: a crash can fall between
any two renames.
"""
from __future__ import annotations
import os
import threading
import time
from pathlib import Path
from . import paths
PARTIAL = ".konduktor-partial"
PARKED = ".konduktor-parked"
def parked_name(original: Path) -> Path:
return original.with_name(f".{original.name}{PARKED}")
def partial_name(stem: Path) -> Path:
return stem.with_name(stem.name + PARTIAL)
def source_facts(path: Path) -> dict | None:
try:
st = path.stat()
except OSError:
return None
return {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
def _replace_no_overwrite(src: Path, dst: Path) -> None:
"""Rename refusing to overwrite: POSIX link+unlink (link fails if dst
exists), Windows rename (which already refuses). A filesystem with no hard
links (FAT / exFAT: a USB stick, which a Normalize can rewrite in place)
falls back to check-then-rename — the only window is another program
creating that exact name in between."""
if os.name == "nt":
os.rename(src, dst)
return
try:
os.link(src, dst)
except FileExistsError:
raise
except OSError:
if os.path.lexists(dst):
raise FileExistsError(dst)
os.rename(src, dst)
return
os.unlink(src)
def _retrying(fn, *, attempts: int = 6, delay: float = 0.25):
"""Windows cannot rename a file another process has open (Traktor, the
deck's stream, an antivirus scan of a file just written): retry briefly."""
for i in range(attempts):
try:
return fn()
except PermissionError:
if os.name != "nt" or i == attempts - 1:
raise
time.sleep(delay * (2 ** i))
class Pending:
"""The ledger for ONE library."""
def __init__(self, library_id: str | None) -> None:
self.library_id = library_id
#: Gain items the last restore/recover put back, for their loudness.
self.restored_gain: list[dict] = []
self._lock = threading.RLock()
self._path = (paths.app_data_dir() / "stems" / f"pending-{library_id}.json") if library_id else None
data = paths.read_json(self._path, None) if self._path else None
self.items: list[dict] = (data or {}).get("items", [])
self.leftovers: list[dict] = (data or {}).get("leftovers", [])
# ---- persistence ----------------------------------------------------------
def _write(self) -> None:
if self._path is None:
return
if not self.items and not self.leftovers:
self._path.unlink(missing_ok=True)
return
self._path.parent.mkdir(parents=True, exist_ok=True)
paths.write_json(self._path, {"items": self.items, "leftovers": self.leftovers})
def add(self, item: dict) -> dict:
with self._lock:
self.items.append(item)
self._write()
return item
def update(self, item: dict, **fields) -> None:
with self._lock:
item.update(fields)
self._write()
def drop(self, items: list[dict]) -> None:
with self._lock:
ids = {id(i) for i in items}
self.items = [i for i in self.items if id(i) not in ids]
self._write()
# ---- what the rest of the app asks ----------------------------------------------
def swapped(self) -> list[dict]:
"""Every item whose library edit is made and awaits Save (both kinds)."""
return [i for i in self.items if i.get("state") in _AWAITING_SAVE.get(_kind(i), ())]
def blocking(self) -> bool:
"""Changes awaiting Save or Discard — while there are any, import,
remap, reload and history restore must refuse: each would save or drop
them as a side effect."""
return bool(self.swapped())
def holds(self, track_ids) -> set[str]:
"""The given tracks that have an item of EITHER kind in flight — a
track is converted or normalised once per Save, never both at once."""
wanted = set(track_ids)
return {i["track_id"] for i in self.items if i.get("track_id") in wanted}
def summary(self) -> dict:
waiting = self.swapped()
stems = [i for i in waiting if _kind(i) == "stem"]
gains = [i for i in waiting if _kind(i) == "gain"]
parked = [Path(i["parked"]) for i in stems if i.get("parked")]
return {"tracks": len(stems),
"parked": len(parked),
"bytes": sum(p.stat().st_size for p in parked if p.exists()),
# Normalize: files whose level Save makes permanent.
"gain_tracks": len(gains),
"gain_lossless": sum(1 for i in gains if i.get("lossless"))}
# ---- Save markers (gain items) ------------------------------------------------
def begin_save(self, library_facts: dict | None) -> None:
"""Right before `adapter.save()`: from here a crash's outcome depends
on whether the save landed, which recovery asks the library."""
with self._lock:
changed = False
for item in self.items:
if _kind(item) == "gain" and item.get("state") == "swapped":
item["state"], item["library_before"] = "saving", library_facts
changed = True
if changed:
self._write()
def abort_save(self) -> None:
"""The save raised: nothing was committed, the items await Save again."""
self._set_gain_state("saving", "swapped")
def mark_saved(self) -> None:
"""The save returned: the library holds the new gains — commit next."""
self._set_gain_state("saving", "saved")
def _set_gain_state(self, frm: str, to: str) -> None:
with self._lock:
changed = False
for item in self.items:
if _kind(item) == "gain" and item.get("state") == frm:
item["state"] = to
changed = True
if changed:
self._write()
# ---- leftovers (reuse after a crash) -----------------------------------------------
def find_leftover(self, source: Path) -> dict | None:
facts = source_facts(source)
for lo in self.leftovers:
if lo["source"] == str(source) and lo.get("facts") == facts and Path(lo["partial"]).is_file():
return lo
return None
def forget_leftover(self, leftover: dict, *, delete: bool) -> None:
with self._lock:
if delete:
Path(leftover["partial"]).unlink(missing_ok=True)
self.leftovers = [lo for lo in self.leftovers if lo is not leftover]
self._write()
def _keep_as_leftover(self, item: dict) -> None:
"""A verified stem file whose swap was not committed: keep it under its
partial name for reuse (rather than hours of separation lost)."""
stem = Path(item["stem"])
partial = partial_name(stem)
try:
if _published(item) and stem.is_file() and not partial.exists():
os.replace(stem, partial)
except OSError:
return
if partial.is_file() and item.get("written"):
self.leftovers.append({"source": item["source"], "facts": item.get("facts"),
"partial": str(partial), "written": item["written"]})
# ---- Save / Discard / recovery ---------------------------------------------------
def commit(self) -> dict[str, str]:
"""After a successful Save: delete what the swap replaced. Returns the
repoint renames so the caller retargets export sets."""
renames: dict[str, str] = {}
with self._lock:
for item in self.swapped():
if _kind(item) == "gain":
if item.get("state") == "saved":
self._commit_gain(item)
continue
if item.get("parked"):
try:
Path(item["parked"]).unlink(missing_ok=True)
except OSError:
pass # a file still open on Windows: recovery tries again
if item.get("mode") == "repoint" and item.get("new_id"):
renames[item["track_id"]] = item["new_id"]
item["state"] = "committed"
self.items = [i for i in self.items if i.get("state") != "committed"
or (i.get("parked") and Path(i["parked"]).exists())]
self._write()
return renames
def _commit_gain(self, item: dict) -> None:
"""The new level is saved: the parked original goes — only if the
normalised file really is in place, never leaving the path empty."""
parked = Path(item["parked"]) if item.get("parked") else None
if parked is not None and Path(item["source"]).is_file():
try:
parked.unlink(missing_ok=True)
except OSError:
return # open on Windows: stays "saved", recovery tries again
item["state"] = "committed"
def restore(self) -> int:
"""Undo every uncommitted conversion: originals back, stem files gone.
Returns how many originals were put back."""
restored = 0
self.restored_gain = []
with self._lock:
for item in list(self.items):
if _kind(item) == "gain":
restored += self._undo_gain(item)
else:
restored += self._undo(item, keep_leftover=False)
self.items = []
self._write()
return restored
def recover(self, is_committed) -> dict:
"""At open, after a crash: decide each leftover item from the SAVED
collection (`is_committed(item)` — does it name the stem file?)."""
report = {"committed": 0, "restored": 0, "kept": 0}
self.restored_gain = []
with self._lock:
before = len(self.leftovers)
for item in list(self.items):
if _kind(item) == "gain":
state = item.get("state")
if state == "saved" or (state == "saving" and is_committed(item)):
self._commit_gain(item)
report["committed"] += 1
else:
report["restored"] += self._undo_gain(item)
continue
if item.get("new_id") and is_committed(item):
if item.get("parked"):
Path(item["parked"]).unlink(missing_ok=True)
report["committed"] += 1
else:
report["restored"] += self._undo(item, keep_leftover=True)
report["kept"] = len(self.leftovers) - before
self.items = []
self._write()
return report
def _undo_gain(self, item: dict) -> int:
"""Put one Normalize item's file back as it was. Filesystem-driven:
the normalised file at the source's name is removed only when it is
recognisably OURS (its facts, or the state says Save may have touched
its tags); a file someone else put there is kept, with the original
still parked beside it. Records the item in `restored_gain` so the
caller puts its loudness value back."""
source = Path(item["source"])
parked = Path(item["parked"]) if item.get("parked") else None
partial = Path(item["partial"]) if item.get("partial") else None
restored = 0
try:
if partial is not None:
partial.unlink(missing_ok=True)
if parked is not None and parked.exists():
ours = item.get("state") in ("saving", "saved") or source_facts(source) in (None, item.get("facts_after"))
if source.exists() and ours and item.get("state") in _PUBLISHED_GAIN:
source.unlink()
if not source.exists():
_retrying(lambda: _replace_no_overwrite(parked, source))
restored = 1
except OSError:
return restored
if restored:
self.restored_gain.append(item)
return restored
def _undo(self, item: dict, *, keep_leftover: bool) -> int:
"""Put one item's files back as they were. Filesystem-driven."""
restored = 0
original = Path(item["source"])
parked = Path(item["parked"]) if item.get("parked") else None
if parked is not None and parked.exists() and not original.exists():
_retrying(lambda: _replace_no_overwrite(parked, original))
restored = 1
stem = Path(item["stem"])
if keep_leftover and item.get("written"):
self._keep_as_leftover(item)
else:
try:
# Only a stem file THIS batch published is ours to delete: before
# that, a file at the target name belongs to someone else.
if _published(item):
stem.unlink(missing_ok=True)
partial_name(stem).unlink(missing_ok=True) # unverified: worthless
except OSError:
pass
return restored
def _published(item: dict) -> bool:
return item.get("state") in ("published", "parked", "swapped", "committed")
def _kind(item: dict) -> str:
return item.get("kind") or "stem"
#: The states in which an item's library edit is made and awaits Save.
_AWAITING_SAVE = {"stem": ("swapped",), "gain": ("swapped", "saving", "saved")}
#: A gain item whose normalised file has been renamed onto the source's name.
_PUBLISHED_GAIN = ("published", "swapped", "saving", "saved")
__all__ = ["PARKED", "PARTIAL", "Pending", "parked_name", "partial_name", "source_facts",
"_replace_no_overwrite", "_retrying"]
+1
View File
@@ -106,6 +106,7 @@ EXCLUDED: dict[str, str] = {
"cover_art": "GET /v1/art — bytes",
"set_cover_art": "PUT /v1/art — bytes",
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
"audio_changed": "the server applies a Normalize itself, at its own end step (not yet remote)",
"set_path_mapping": "the server's path mapping is its own configuration",
"set_session_mappings": "the missing-files check searches THIS computer's drives",
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
+14
View File
@@ -326,6 +326,11 @@ class EditState(BaseModel):
stem_job: str | None = None
# What this open's crash recovery did about an interrupted conversion.
stem_recovery: dict | None = None
# Normalized tracks awaiting Save/Discard: {tracks, lossless} (lossless =
# files whose change Save makes permanent).
pending_gain: dict | None = None
# A running Normalize's job id, so a reloaded page finds it again.
normalize_job: str | None = None
# A remote library's connection: {state, via, machine}. None when local.
remote: dict | None = None
@@ -701,3 +706,12 @@ class JobStatus(BaseModel):
error: str | None = None
started_at: float
finished_at: float | None = None
class NormalizeRequest(BaseModel):
"""Normalize's choices (`gain/normalize.py`, `core/level_plan.py`): the
measure brought to `target`, a raise stopping at the true-peak `ceiling`."""
track_ids: list[str]
measure: Literal["lufs", "rms"] = "lufs"
target: float = -9.0
ceiling: float = -1.0
+3 -3
View File
@@ -617,7 +617,7 @@ def create_app(server: Server) -> FastAPI:
import hashlib
from ..core.loudness import Loudness
from ..stems.pending import partial_name, source_facts
from ..pending import partial_name, source_facts
session(token)
measured = None
@@ -661,7 +661,7 @@ def create_app(server: Server) -> FastAPI:
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""A cancelled batch: delete the files it uploaded (a cancel deletes
only new files, as on this computer)."""
from ..stems.pending import partial_name
from ..pending import partial_name
session(token)
pending = server.state.pending
@@ -677,7 +677,7 @@ def create_app(server: Server) -> FastAPI:
stem file, park originals (Replace), swap every entry at once."""
from ..core import stem_file as sf
from ..stems import convert
from ..stems.pending import partial_name
from ..pending import partial_name
holder = session(token)
opts = stem_options(body.get("options") or {})
+6
View File
@@ -159,11 +159,17 @@ def plan(adapter, track_ids: list[str], opts: Options, pending: Pending | None)
in_library = {str(p) for t in adapter.tracks if (p := adapter.audio_path(t.id)) is not None}
candidates: list[tuple[str, object, Path]] = []
# A track whose level change (Normalize) awaits Save: converting it would
# build a stem file from audio Discard is about to put back.
held = {i["track_id"] for i in pending.items if i.get("kind") == "gain"} if pending is not None else set()
for tid in dict.fromkeys(track_ids):
track = adapter.track(tid)
src = adapter.audio_path(tid) if track is not None else None
if track is None:
result.skipped.append({"track_id": tid, "title": tid, "reason": "not in the library"})
elif tid in held:
result.skipped.append({"track_id": tid, "title": _title(track),
"reason": "its level change awaits Save"})
elif src is None or not Path(src).is_file():
result.skipped.append({"track_id": tid, "title": _title(track), "reason": "the file is missing"})
elif sf.is_stem_file(src):
+4 -237
View File
@@ -1,237 +1,4 @@
"""Conversions that are done on disk but not yet committed by a Save.
A Convert to Stems batch leaves, per track: a stem file, and — in Replace mode —
the original PARKED beside it (`.<name>.<ext>.konduktor-parked`, the same
folder, so the rename is atomic and nothing looks like audio). The collection
swap itself is an ordinary unsaved edit. So the files must follow what happens
to the edits:
* **Save** commits them: parked originals are deleted (the user chose Replace,
and was told Save deletes them), export sets follow the new ids.
* **Discard** — or opening another library, after its confirm — undoes them:
originals go back under their own names, the stem files are removed.
* **A crash** leaves this ledger on disk. The next open of the library
decides each item from the SAVED collection: if it names the stem file the
swap was committed (finish deleting the original), otherwise it was not
(put the original back). Verified stem files of an uncommitted item are
kept — renamed to their `.konduktor-partial` name, so neither the user nor
Traktor mistakes them for finished files — and a later batch converting the
same source reuses one instead of spending minutes separating it again.
The ledger is Konduktor's own curated state, written atomically
(`paths.write_json`), one file per library id. Every step is taken from what is
actually ON DISK, never from the recorded state alone: a crash can fall between
any two renames.
"""
from __future__ import annotations
import os
import threading
import time
from pathlib import Path
from .. import paths
PARTIAL = ".konduktor-partial"
PARKED = ".konduktor-parked"
def parked_name(original: Path) -> Path:
return original.with_name(f".{original.name}{PARKED}")
def partial_name(stem: Path) -> Path:
return stem.with_name(stem.name + PARTIAL)
def source_facts(path: Path) -> dict | None:
try:
st = path.stat()
except OSError:
return None
return {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
def _replace_no_overwrite(src: Path, dst: Path) -> None:
"""Rename refusing to overwrite: POSIX link+unlink (link fails if dst
exists), Windows rename (which already refuses)."""
if os.name == "nt":
os.rename(src, dst)
return
os.link(src, dst)
os.unlink(src)
def _retrying(fn, *, attempts: int = 6, delay: float = 0.25):
"""Windows cannot rename a file another process has open (Traktor, the
deck's stream, an antivirus scan of a file just written): retry briefly."""
for i in range(attempts):
try:
return fn()
except PermissionError:
if os.name != "nt" or i == attempts - 1:
raise
time.sleep(delay * (2 ** i))
class Pending:
"""The ledger for ONE library."""
def __init__(self, library_id: str | None) -> None:
self.library_id = library_id
self._lock = threading.RLock()
self._path = (paths.app_data_dir() / "stems" / f"pending-{library_id}.json") if library_id else None
data = paths.read_json(self._path, None) if self._path else None
self.items: list[dict] = (data or {}).get("items", [])
self.leftovers: list[dict] = (data or {}).get("leftovers", [])
# ---- persistence ----------------------------------------------------------
def _write(self) -> None:
if self._path is None:
return
if not self.items and not self.leftovers:
self._path.unlink(missing_ok=True)
return
self._path.parent.mkdir(parents=True, exist_ok=True)
paths.write_json(self._path, {"items": self.items, "leftovers": self.leftovers})
def add(self, item: dict) -> dict:
with self._lock:
self.items.append(item)
self._write()
return item
def update(self, item: dict, **fields) -> None:
with self._lock:
item.update(fields)
self._write()
def drop(self, items: list[dict]) -> None:
with self._lock:
ids = {id(i) for i in items}
self.items = [i for i in self.items if id(i) not in ids]
self._write()
# ---- what the rest of the app asks ----------------------------------------------
def swapped(self) -> list[dict]:
return [i for i in self.items if i.get("state") == "swapped"]
def blocking(self) -> bool:
"""Conversions awaiting Save or Discard — while there are any, import,
remap, reload and history restore must refuse: each would save or drop
the swap as a side effect."""
return bool(self.swapped())
def summary(self) -> dict:
parked = [Path(i["parked"]) for i in self.swapped() if i.get("parked")]
return {"tracks": len(self.swapped()),
"parked": len(parked),
"bytes": sum(p.stat().st_size for p in parked if p.exists())}
# ---- leftovers (reuse after a crash) -----------------------------------------------
def find_leftover(self, source: Path) -> dict | None:
facts = source_facts(source)
for lo in self.leftovers:
if lo["source"] == str(source) and lo.get("facts") == facts and Path(lo["partial"]).is_file():
return lo
return None
def forget_leftover(self, leftover: dict, *, delete: bool) -> None:
with self._lock:
if delete:
Path(leftover["partial"]).unlink(missing_ok=True)
self.leftovers = [lo for lo in self.leftovers if lo is not leftover]
self._write()
def _keep_as_leftover(self, item: dict) -> None:
"""A verified stem file whose swap was not committed: keep it under its
partial name for reuse (rather than hours of separation lost)."""
stem = Path(item["stem"])
partial = partial_name(stem)
try:
if _published(item) and stem.is_file() and not partial.exists():
os.replace(stem, partial)
except OSError:
return
if partial.is_file() and item.get("written"):
self.leftovers.append({"source": item["source"], "facts": item.get("facts"),
"partial": str(partial), "written": item["written"]})
# ---- Save / Discard / recovery ---------------------------------------------------
def commit(self) -> dict[str, str]:
"""After a successful Save: delete what the swap replaced. Returns the
repoint renames so the caller retargets export sets."""
renames: dict[str, str] = {}
with self._lock:
for item in self.swapped():
if item.get("parked"):
try:
Path(item["parked"]).unlink(missing_ok=True)
except OSError:
pass # a file still open on Windows: recovery tries again
if item.get("mode") == "repoint" and item.get("new_id"):
renames[item["track_id"]] = item["new_id"]
item["state"] = "committed"
self.items = [i for i in self.items if i.get("state") != "committed"
or (i.get("parked") and Path(i["parked"]).exists())]
self._write()
return renames
def restore(self) -> int:
"""Undo every uncommitted conversion: originals back, stem files gone.
Returns how many originals were put back."""
restored = 0
with self._lock:
for item in list(self.items):
restored += self._undo(item, keep_leftover=False)
self.items = []
self._write()
return restored
def recover(self, is_committed) -> dict:
"""At open, after a crash: decide each leftover item from the SAVED
collection (`is_committed(item)` — does it name the stem file?)."""
report = {"committed": 0, "restored": 0, "kept": 0}
with self._lock:
before = len(self.leftovers)
for item in list(self.items):
if item.get("new_id") and is_committed(item):
if item.get("parked"):
Path(item["parked"]).unlink(missing_ok=True)
report["committed"] += 1
else:
report["restored"] += self._undo(item, keep_leftover=True)
report["kept"] = len(self.leftovers) - before
self.items = []
self._write()
return report
def _undo(self, item: dict, *, keep_leftover: bool) -> int:
"""Put one item's files back as they were. Filesystem-driven."""
restored = 0
original = Path(item["source"])
parked = Path(item["parked"]) if item.get("parked") else None
if parked is not None and parked.exists() and not original.exists():
_retrying(lambda: _replace_no_overwrite(parked, original))
restored = 1
stem = Path(item["stem"])
if keep_leftover and item.get("written"):
self._keep_as_leftover(item)
else:
try:
# Only a stem file THIS batch published is ours to delete: before
# that, a file at the target name belongs to someone else.
if _published(item):
stem.unlink(missing_ok=True)
partial_name(stem).unlink(missing_ok=True) # unverified: worthless
except OSError:
pass
return restored
def _published(item: dict) -> bool:
return item.get("state") in ("published", "parked", "swapped", "committed")
__all__ = ["PARKED", "PARTIAL", "Pending", "parked_name", "partial_name", "source_facts",
"_replace_no_overwrite", "_retrying"]
"""Moved to `konduktor.pending` (it now holds Normalize's items too); this
module keeps the old import path working."""
from ..pending import * # noqa: F401,F403
from ..pending import _published, _replace_no_overwrite, _retrying # noqa: F401