Compare commits

..
Author SHA1 Message Date
patben8 1bd65ea707 Improved scratching engine 2026-11-05 11:57:43 +01:00
patben8 2afba4557c Paused decks now always scratch when jog wheel is moved 2026-11-05 11:33:45 +01:00
patben8 aaa7537d50 Filter FXs are now post-fader 2026-11-05 11:24:57 +01:00
patben8 632d2dc3c4 Master and secondary shift are now configurable 2026-11-03 23:35:44 +01:00
patben8 5d4df2aa52 Encoder direction can now be mapped to separate controls 2026-11-03 23:09:16 +01:00
patben8 8d0817b39e Implemented midi support` 2026-11-03 22:56:19 +01:00
patben8 f55b8f06e4 Autogain is now a toggleable performance setting 2026-11-03 12:18:34 +01:00
patben8 5d1bfcf7f1 Beat jumping can now be done outside of the song range 2026-11-03 11:59:50 +01:00
patben8 2a40106ea5 Added setting for deck focus switching 2026-11-03 11:46:50 +01:00
patben8 4799eaef17 More mixer FX improvements 2026-11-03 10:43:44 +01:00
patben8 717685f621 Improved filter FX 2026-11-03 10:37:53 +01:00
patben8 832dbed341 Changed default crossfader shape` 2026-11-03 10:06:26 +01:00
patben8 352aa3e956 Improve performance mode symmetry 2026-11-03 09:43:18 +01:00
patben8 1b1ed7e2b3 Improved mixer layout 2026-11-03 09:25:04 +01:00
patben8 341f12e275 Moved performance settings to their own panel 2026-11-03 09:14:02 +01:00
patben8 af02b1fc1c Implemented performance mode settings 2026-11-03 08:49:26 +01:00
patben8 fe91a46bae Implemented deck transport controls 2026-11-03 08:40:38 +01:00
patben8 9df73ddcd2 Implemented performance mode 2026-11-02 23:03:58 +01:00
patben8 063463efdd Dj deck is now a reusable component 2026-11-02 22:48:04 +01:00
patben8 2fcf6e7070 Added macos build script 2026-11-02 22:31:57 +01:00
patben8 f5e7202f3f Implemented new audio engine and deck engine 2026-11-02 22:26:19 +01:00
patben8 4fdb2b7ce1 Unified pop-up modals and out-click close behaviour 2026-11-02 13:13:17 +01:00
patben8 65fbc775ce Merge pull request #18 from MrPatben8/dev
Fixed leftover Traktor data blocks from overwriting BPM
2026-10-30 23:34:50 +01:00
patben8 b57dd74445 Bumped version number 2026-10-30 23:33:32 +01:00
patben8 31287bdeb7 Exports now strip Traktor song data blocks that overwrite BPM from collection 2026-10-26 09:42:19 +01:00
patben8 210c1ab135 Merge pull request #17 from MrPatben8/dev
Fixed local export issues & Subtractive playlist edditing
2026-10-22 11:58:34 +02:00
patben8 e211fd180a Bumped version number 2026-10-22 11:56:13 +02:00
patben8 5d059c7604 Improved cue/grid button switch layout and style 2026-10-22 11:48:00 +02:00
patben8 667068c2f1 Mode switch chan now be clicked anywhere to swap options 2026-10-22 11:39:35 +02:00
patben8 75cb0c8138 Added + button next to playlists in sidebar 2026-10-22 10:03:35 +02:00
patben8 068e4da08b Implemented subtractive playlist editing 2026-10-22 09:58:57 +02:00
patben8 1a28ad6102 Local exports are no longer blocked by missing local library 2026-10-21 22:15:45 +02:00
patben8 dd82fa99bb Merge pull request #16 from MrPatben8/dev
Implemented local exports
2026-10-21 19:50:15 +02:00
patben8 fae91e8772 Bumped version number 2026-10-21 19:50:02 +02:00
patben8 68128a123e Update dialog now shows accumulated changes 2026-10-20 11:54:33 +02:00
patben8 23a5cd72f4 Implemented local export system 2026-10-20 11:49:20 +02:00
patben8 17c177e34e Merge pull request #15 from MrPatben8/feature/mastering-tools
Implemented mastering tools
2026-10-20 09:43:58 +02:00
patben8 ee0e055b3f Bumped version number 2026-10-20 09:40:17 +02:00
patben8 21e249ff97 Fixed STEM encoding for consistent conversion 2026-10-19 23:57:28 +02:00
patben8 3e9d5d5528 Implemented AAC normalizing 2026-10-19 22:02:51 +02:00
patben8 13ba2c721a Implemented remote side 2026-10-19 21:39:47 +02:00
patben8 4cb630d0d5 Implemented normalization and auto gain export options 2026-10-19 21:20:57 +02:00
patben8 64b0396d66 Implemented basic track normalizing 2026-10-19 20:45:35 +02:00
patben8 284a7514fe Implemented auto gain analysis 2026-10-19 18:20:13 +02:00
patben8 6eecb2288a Improved loudness calculation 2026-10-19 17:18:05 +02:00
patben8 d70a7c5de2 Implemented track loudness analysis 2026-10-19 14:07:54 +02:00
patben8 5c9387f136 Added quick target location change button in export dialog 2026-10-19 11:33:23 +02:00
patben8 9329236955 Implemented export track grid locking 2026-10-19 10:48:59 +02:00
patben8 2821ba124d Merge pull request #14 from MrPatben8/dev
Improved drag and drop import
2026-10-17 22:55:03 +02:00
patben8 f9ef38d826 Bumped version number 2026-10-17 22:54:08 +02:00
patben8 518542c7bb Improved drag to import dialog 2026-10-17 22:53:37 +02:00
patben8 bf427a628e Fixed drag and drop position accuracy 2026-10-17 22:53:37 +02:00
patben8 4340e948ac Bumped version number 2026-10-17 20:21:28 +02:00
patben8 fe63acc2a2 Merge pull request #13 from MrPatben8/dev
Implemented Cross-Platform Track Color Support
2026-10-17 20:08:02 +02:00
patben8 06361a851f Implemented cross-platform track color support 2026-10-17 19:50:56 +02:00
patben8 0605dbabe6 Improved release description and file names 2026-10-16 18:04:54 +02:00
patben8 6be99e6d7e Merge pull request #12 from MrPatben8/dev
Implemented self-updating
2026-10-16 17:39:28 +02:00
patben8 0eac972173 Implemented self-updating 2026-10-16 17:38:35 +02:00
209 changed files with 25197 additions and 3579 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
"""Lay out one release's assets under user-facing names, plus the updater's
latest.json and the release notes' Download section.
Run by build.yml's release job:
python3 .github/scripts/release_assets.py artifacts release \\
--version 0.6.0 --tag v0.6.0-b42 --repo owner/konduktor
Finds, anywhere under `artifacts`, what `tauri build` produced: the macOS
`*.dmg` and `*.app.tar.gz` (+ `.sig`) and the Windows `*-setup.exe` (+ `.sig`).
Copies them into `release` as
Konduktor-<version>-macOS.dmg (download)
Konduktor-<version>-Windows-Setup.exe (download; the Windows updater runs it too)
Konduktor-<version>-app-updater.tar.gz (the macOS updater's package)
latest.json (the updater's manifest)
and writes `download.md`. Renaming is safe: the signatures cover contents,
not names, and latest.json is written from the final names. `latest.json`
itself keeps its name: the app asks for releases/download/<tag>/latest.json.
Fails if anything is missing: a manifest lacking a platform is refused by the
updater as a whole.
"""
import argparse
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote
def find_one(root: Path, suffix: str) -> Path:
found = [p for p in root.rglob(f"*{suffix}") if p.is_file()]
if len(found) != 1:
sys.exit(f"expected exactly one *{suffix} under {root}, found {len(found)}")
return found[0]
def signature(asset: Path) -> str:
sig = asset.with_name(asset.name + ".sig")
if not sig.is_file():
sys.exit(f"missing signature {sig}")
return sig.read_text(encoding="utf-8").strip()
def lay_out(artifacts: Path, out: Path, version: str, tag: str, repo: str) -> None:
def url(name: str) -> str:
return f"https://github.com/{repo}/releases/download/{quote(tag)}/{quote(name)}"
dmg = find_one(artifacts, ".dmg")
app = find_one(artifacts, ".app.tar.gz")
setup = find_one(artifacts, "-setup.exe")
names = {
dmg: f"Konduktor-{version}-macOS.dmg",
setup: f"Konduktor-{version}-Windows-Setup.exe",
app: f"Konduktor-{version}-app-updater.tar.gz",
}
# Tauri's platform keys -> the file that platform's updater installs.
manifest = {
"version": version,
"pub_date": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
"platforms": {
"darwin-aarch64": {"signature": signature(app), "url": url(names[app])},
"windows-x86_64": {"signature": signature(setup), "url": url(names[setup])},
},
}
out.mkdir(parents=True, exist_ok=True)
for src, name in names.items():
shutil.copy2(src, out / name)
(out / "latest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
(out / "download.md").write_text(
"## Download\n"
f"- **macOS** (Apple Silicon): [{names[dmg]}]({url(names[dmg])})\n"
f"- **Windows**: [{names[setup]}]({url(names[setup])})\n",
encoding="utf-8",
)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("artifacts", type=Path)
ap.add_argument("out", type=Path)
ap.add_argument("--version", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--repo", required=True)
args = ap.parse_args()
lay_out(args.artifacts, args.out, args.version, args.tag, args.repo)
for p in sorted(args.out.iterdir()):
print(p.name)
if __name__ == "__main__":
main()
+37 -7
View File
@@ -86,20 +86,31 @@ jobs:
working-directory: frontend
run: npm ci
# createUpdaterArtifacts also signs the in-app update packages
# (Konduktor.app.tar.gz / the NSIS setup.exe) with the updater key, whose
# public half is plugins.updater.pubkey in tauri.conf.json. Losing the
# private key means installed copies can never update themselves again.
- name: Build Tauri app
working-directory: frontend
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: npx tauri build
# Stage the single installer per OS into a flat folder. Uploading one
# directory (not multiple bundle subpaths) keeps the artifact root at
# ./installer, so the zip holds the bare file — no nested dmg/ or nsis/
# folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows
# (the .msi is intentionally left out).
# (the .msi is intentionally left out), plus what the in-app updater
# installs: the .app.tar.gz on macOS (the setup.exe on Windows) and the
# .sig files the release job folds into latest.json.
- name: Stage installer (macOS)
if: runner.os == 'macOS'
run: |
mkdir -p installer
cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz.sig installer/
- name: Stage installer (Windows)
if: runner.os == 'Windows'
@@ -107,6 +118,7 @@ jobs:
run: |
New-Item -ItemType Directory -Force installer | Out-Null
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe.sig installer/
- name: Upload installer
uses: actions/upload-artifact@v4
@@ -189,11 +201,24 @@ jobs:
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
# The release's files under user-facing names, the in-app updater's
# latest.json (the app reads releases/download/<tag>/latest.json) and the
# notes' Download section. The .sig files are folded into latest.json and
# not uploaded themselves.
- name: Release assets
run: |
python3 .github/scripts/release_assets.py artifacts release \
--version "${{ steps.version.outputs.version }}" \
--tag "v${{ steps.version.outputs.version }}-b${{ github.run_number }}" \
--repo "${{ github.repository }}"
# Release notes from the "Patch notes" section of the PR that merged this
# commit into main (dev → main merges carry many features in one PR, so
# its title alone says little). Written under "What's Changed", the
# heading the app's update dialog reads. No PR (a manual run, a direct
# push) or no such section → GitHub's generated notes, as before.
# push) or no such section → GitHub's generated notes, as before. The
# Download section always comes first (the action puts the body above
# generated notes); the dialog reads only "What's Changed".
- name: Patch notes from the merged PR
id: notes
env:
@@ -218,9 +243,10 @@ jobs:
section.append(line)
notes = "\n".join(section).strip()
found = bool(notes)
if found:
with open("release-notes.md", "w", encoding="utf-8") as f:
f.write("## What's Changed\n\n" + notes + "\n")
with open("release-notes.md", "w", encoding="utf-8") as f:
f.write(open("release/download.md", encoding="utf-8").read())
if found:
f.write("\n## What's Changed\n\n" + notes + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as out:
out.write(f"found={'true' if found else 'false'}\n")
print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.")
@@ -232,7 +258,11 @@ jobs:
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
target_commitish: ${{ github.sha }}
body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }}
body_path: release-notes.md
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
fail_on_unmatched_files: true
files: artifacts/**/*
files: |
release/*.dmg
release/*.exe
release/*.tar.gz
release/latest.json
+3
View File
@@ -51,3 +51,6 @@ backend/dist/
# ---- Stem engine (PyInstaller onedir build) ----
engine/build/
engine/dist/
# ---- Rubber Band build (frontend/rubberband/build.sh downloads + compiles here) ----
frontend/rubberband/upstream/
+8 -3
View File
@@ -88,9 +88,14 @@ cd ..
# 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend
npx tauri build
npx tauri build --config src-tauri/tauri.unsigned.conf.json
```
The `--config` override skips the in-app updater packages, which are signed
with the release key that only CI holds (`TAURI_SIGNING_PRIVATE_KEY`). With
that key set in the environment, plain `npx tauri build` makes them too.
`build.ps1` picks the right one by itself.
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
@@ -117,8 +122,8 @@ folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
## Rebuilding after changes
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build`). Frontend-only changes just need
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
then `npx tauri build` as above). Frontend-only changes just need
`.\build.ps1 -SkipSidecar`.
## Not part of this build: the stem engine
+769 -60
View File
File diff suppressed because it is too large. Load diff
+156
View File
@@ -0,0 +1,156 @@
"""How Traktor's auto-gain relates to Konduktor's loudness measures.
Traktor stores its gain per ENTRY as `<LOUDNESS ANALYZED_DB>` (its own
measurement) and `PERCEIVED_DB` (the gain the deck applies; equal to
ANALYZED after Traktor's own analysis — kit G1, 2026-10-19). If Traktor
levels toward a fixed reference, `ANALYZED_DB = reference − loudness`, so
`ANALYZED_DB + LUFS` is that reference, and its spread is how far Konduktor's
measure is from Traktor's.
python bench_traktor_gain.py FOLDER [--nml collection.nml]
FOLDER's audio must be in the collection and analysed by Traktor (Gain).
A stem file is measured as its four stems SUMMED, as Traktor measures it.
Result (2026-10-19, 80 MP3 + 40 commercial stem files, Traktor 4.5):
ANALYZED_DB = -9.2 - LUFS (free slope 0.99), sd 0.80 dB, |miss| p50 0.56 /
p90 1.35; RMS fits worse (sd 1.17); the miss follows nothing measured here
(LRA, PLR, true peak, bass weight: |r| < 0.2) — it is Traktor's own measure.
Fits LUFS and RMS (slope and fixed-slope), then asks whether what is left
over follows something about the music (LRA, PLR, bass weight, format, genre).
"""
from __future__ import annotations
import argparse
import html
import re
import sys
import unicodedata
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
DEFAULT_NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
def _key(path: str) -> str:
return unicodedata.normalize("NFC", path).casefold()
def traktor_values(nml: Path) -> dict[str, dict]:
"""Absolute path (normalised) -> Traktor's LOUDNESS + genre, for analysed entries."""
out = {}
text = nml.read_text(encoding="utf-8")
for e in re.findall(r"<ENTRY .*?</ENTRY>", text, re.S):
loc = re.search(r'<LOCATION DIR="([^"]*)" FILE="([^"]*)"', e)
loud = re.search(r'<LOUDNESS PEAK_DB="([-\d.]+)" PERCEIVED_DB="([-\d.]+)" ANALYZED_DB="([-\d.]+)"', e)
if not (loc and loud):
continue
path = html.unescape(loc.group(1)).replace("/:", "/") + html.unescape(loc.group(2))
genre = re.search(r'<INFO [^>]*GENRE="([^"]*)"', e)
out[_key(path)] = {
"peak": float(loud.group(1)),
"perceived": float(loud.group(2)),
"analyzed": float(loud.group(3)),
"genre": html.unescape(genre.group(1)) if genre else "",
}
return out
def _measure(path: str):
"""`loudness.measure_file` — which measures a stem file as its four stems
summed, as Traktor does (found by this bench: against the mix stream the
reference was -6.6, sd 1.18; against the sum -9.3, sd 0.68)."""
from konduktor.core import loudness
try:
return path, loudness.measure_file(path)
except Exception as e: # an undecodable file is reported, not fatal
return path, e
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("folder", type=Path)
ap.add_argument("--nml", type=Path, default=DEFAULT_NML)
args = ap.parse_args()
tk = traktor_values(args.nml)
files = sorted(p for p in args.folder.rglob("*") if p.is_file() and not p.name.startswith("."))
held = [p for p in files if _key(str(p)) in tk]
print(f"{len(files)} files, {len(held)} analysed by Traktor")
for p in files:
if _key(str(p)) not in tk:
print(f" not in the collection / not analysed: {p.name}")
rows = []
with ProcessPoolExecutor(4) as pool: # a stem file holds 4 decoded streams
for path, m in pool.map(_measure, [str(p) for p in held]):
if m is None or isinstance(m, Exception):
print(f" not measured: {Path(path).name}: {m}")
continue
t = tk[_key(path)]
rows.append((Path(path), m, t))
name = np.array([r[0].name for r in rows])
lufs = np.array([r[1].lufs for r in rows])
rms = np.array([r[1].rms for r in rows])
tp = np.array([r[1].true_peak for r in rows])
lra = np.array([r[1].lra for r in rows])
plr = np.array([r[1].plr for r in rows])
an = np.array([r[2]["analyzed"] for r in rows])
pc = np.array([r[2]["perceived"] for r in rows])
pk = np.array([r[2]["peak"] for r in rows])
fmt = np.array([r[0].suffix.lower() for r in rows])
genre = np.array([r[2]["genre"] or "(none)" for r in rows])
n = len(rows)
print(f"\n{n} tracks; LUFS {lufs.min():.1f} .. {lufs.max():.1f}, "
f"PERCEIVED == ANALYZED on {int(np.sum(np.isclose(pc, an)))}")
print("\n== reference = ANALYZED_DB + measure (slope fixed at 1)")
for label, v in (("LUFS", lufs), ("RMS", rms)):
ref = an + v
k, b = np.polyfit(-v, an, 1)
free = an - (k * -v + b)
q = np.percentile(np.abs(ref - np.median(ref)), [50, 90])
print(f" {label:4s}: mean {ref.mean():6.2f} median {np.median(ref):6.2f} sd {ref.std():.2f} "
f"|miss| p50 {q[0]:.2f} p90 {q[1]:.2f} (free slope {k:.3f}, sd {free.std():.2f})")
print("\n== PEAK_DB + true peak (Traktor's peak gain vs our true peak)")
d = pk + tp
print(f" mean {d.mean():+.2f} sd {d.std():.2f} min {d.min():+.2f} max {d.max():+.2f}")
ref = an + lufs
resid = ref - ref.mean()
print("\n== does the LUFS miss follow the music? (correlation with the residual)")
bass = rms - lufs # unweighted vs K-weighted: higher = more low end
for label, v in (("LRA", lra), ("PLR", plr), ("true peak", tp), ("bass weight (RMS-LUFS)", bass), ("LUFS", lufs)):
r = np.corrcoef(v, resid)[0, 1]
k = np.polyfit(v, resid, 1)[0]
print(f" {label:24s} r = {r:+.2f} slope {k:+.3f} dB per unit")
X = np.column_stack([bass, lra, np.ones(n)])
coef, *_ = np.linalg.lstsq(X, resid, rcond=None)
print(f" bass + LRA together: sd {resid.std():.2f} -> {(resid - X @ coef).std():.2f}")
print("\n== by format")
for f in sorted(set(fmt)):
s = fmt == f
print(f" {f:5s} n={s.sum():3d} reference mean {ref[s].mean():6.2f} sd {ref[s].std():.2f}")
print("\n== by genre (n >= 3)")
for g in sorted(set(genre), key=lambda g: -np.sum(genre == g)):
s = genre == g
if s.sum() >= 3:
print(f" {g[:24]:24s} n={s.sum():3d} reference mean {ref[s].mean():6.2f} sd {ref[s].std():.2f}")
print("\n== largest misses (LUFS)")
for i in np.argsort(-np.abs(resid))[:8]:
print(f" {resid[i]:+5.2f} LUFS {lufs[i]:6.2f} LRA {lra[i]:4.1f} bass {bass[i]:+5.2f} {genre[i][:14]:14s} {name[i][:50]}")
if __name__ == "__main__":
main()
+321
View File
@@ -0,0 +1,321 @@
"""Kit G1 — what Traktor 4.5 does with gain (dev only, like dev_stems.py).
Answers, by measuring in Traktor itself (see
.claude/discussions/discuss-gain-normalization-2026-10-19.md, "Kit G1"):
1. Does a LEVEL change to a file make Traktor re-analyse it (LOUDNESS,
BPM/grid, AUDIO_ID)? MP3 by lossless frame gain (same size; + an APE undo
tag; + the mtime put back), FLAC re-written exactly, and a control whose
mtime alone changes.
2. Does Traktor KEEP a LOUDNESS Konduktor writes — on an entry it analysed
(AUDIO_ID kept), and on one Konduktor added (AUDIO_ID empty)?
3. Which LOUDNESS attribute drives the deck's auto-gain (the three are set
to values that cannot be confused)?
python dev_gain_kit.py prepare # build the kit folder
# -> in Traktor: import the folder, analyse, quit
python dev_gain_kit.py apply # change the files + write LOUDNESS
# -> in Traktor: load each G1 track, note the gain knob, quit
python dev_gain_kit.py report # what Traktor changed
Traktor must be closed for `apply`. The collection is saved through
TraktorStore (backup-first, byte-exact render).
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
import numpy as np
NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
KITS = Path.home() / "Music/Konduktor Stem Test"
KIT = KITS / "Kit G1"
STEPS = -2 # global_gain steps of 2^(1/4): -2 = -3.01 dB
# name -> (source, what happens at `apply`)
FILES = {
"G1-A0 control touch.mp3": (KITS / "Kit 2/K2 01 All I Need.mp3", "mtime only"),
"G1-A1 mp3 framegain.mp3": (KITS / "Kit 2/K1 01 Abyss of Love - Franky Rizardo Remix.mp3", "frame gain"),
"G1-A2 mp3 framegain ape.mp3": (KITS / "Kit 2/K4 Ragga Bomb with Ragga Twins.mp3", "frame gain + APE undo tag"),
"G1-A3 flac exact.flac": (KITS / "Kit 4/K4-3 flac.flac", "exact gain, re-written"),
"G1-A4 mp3 framegain same mtime.mp3": (KITS / "Kit 4/K4-5 mp3 cbr noxing.mp3", "frame gain, mtime restored"),
"G1-B1 loudness written.mp3": (KITS / "Kit 2/K3 01 Motorola.mp3", "LOUDNESS written, AUDIO_ID kept"),
}
# Added by Konduktor at `apply` (so Traktor never analysed it): AUDIO_ID empty.
B2 = ("G1-B2 konduktor added.mp3", KITS / "Kit 4/K4-4 mp3 cbr xing.mp3")
# Values no real analysis would give, so the deck's knob says which one it read.
B1_LOUDNESS = (2.5, -6.0, 6.0) # PEAK_DB, PERCEIVED_DB, ANALYZED_DB
B2_LOUDNESS = (2.5, -4.0, 4.0)
# ── MP3 frame gain (mp3gain's 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: bytearray, 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 _header(buf: bytearray, pos: int):
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
br, sr = _BITRATE[mpeg1][br_i], _RATE[ver][sr_i]
pad = (buf[pos + 2] >> 1) & 1
length = (144000 if mpeg1 else 72000) * br // sr + pad
return {
"mpeg1": mpeg1,
"crc": (buf[pos + 1] & 1) == 0,
"nch": 1 if (buf[pos + 3] >> 6) == 3 else 2,
"len": length,
}
def _gain_bits(h: dict) -> list[int]:
"""Bit offsets (from the side info's start) of every granule's global_gain."""
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 mp3_frame_gain(path: Path, steps: int) -> int:
"""Add `steps` to every audio granule's global_gain in place; returns frames edited."""
buf = bytearray(path.read_bytes())
pos = 0
if buf[:3] == b"ID3":
size = (buf[6] << 21) | (buf[7] << 14) | (buf[8] << 7) | buf[9]
pos = 10 + size + (10 if buf[5] & 0x10 else 0)
frames = 0
first = True
while (h := _header(buf, pos)) is not None:
side = pos + 4 + (2 if h["crc"] else 0)
if h["crc"]:
raise SystemExit(f"{path.name}: CRC-protected frames are not handled by the kit")
side_len = (17 if h["nch"] == 1 else 32) if h["mpeg1"] else (9 if h["nch"] == 1 else 17)
tag = bytes(buf[side + side_len : side + 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 (Traktor decodes it anyway — leave it as it is)
else:
for off in _gain_bits(h):
g = _get(buf, side * 8 + off, 8) + steps
if not 0 <= g <= 255:
raise SystemExit(f"{path.name}: global_gain would leave 0..255")
_put(buf, side * 8 + off, 8, g)
frames += 1
first = False
pos += h["len"]
rest = bytes(buf[pos : pos + 8])
if pos < len(buf) - 128 and not rest.startswith((b"TAG", b"APETAGEX", b"LYRICS")):
raise SystemExit(f"{path.name}: lost frame sync at {pos} of {len(buf)}")
path.write_bytes(buf)
return frames
def _decode(path: Path) -> np.ndarray:
from konduktor.core import pyav
out = []
with pyav.open_input(path) as c:
for frame in c.decode(audio=0):
a = frame.to_ndarray()
out.append(a if a.ndim == 2 and a.shape[0] <= 2 else a.reshape(1, -1))
return np.concatenate(out, axis=1).astype(np.float64)
def _check_gain(before: np.ndarray, after: Path, db: float, what: str) -> None:
b = before
a = _decode(after)
n = min(b.shape[1], a.shape[1])
want = 10 ** (db / 20)
err = np.max(np.abs(a[:, :n] - b[:, :n] * want)) / max(np.max(np.abs(b)), 1e-9)
print(f" {what}: decoded = original x {want:.4f} ({db:+.2f} dB), max error {err:.1e} of peak")
if err > 1e-3:
raise SystemExit(" gain check FAILED")
def flac_exact_gain(path: Path, db: float) -> None:
import soundfile as sf
from mutagen.flac import FLAC
info = sf.info(str(path))
data, rate = sf.read(str(path), dtype="float64", always_2d=True)
old = FLAC(str(path))
tags, pictures = list(old.tags.items()) if old.tags else [], list(old.pictures)
tmp = path.with_suffix(".tmp.flac")
sf.write(str(tmp), data * 10 ** (db / 20), rate, subtype=info.subtype, format="FLAC")
new = FLAC(str(tmp))
for k, v in tags:
new[k] = v
for p in pictures:
new.add_picture(p)
new.save()
tmp.replace(path)
# ── steps ────────────────────────────────────────────────────────────────────
def _traktor_running() -> bool:
# The executable is "Traktor Pro 4" (an exact "Traktor" never matches).
return subprocess.run(["pgrep", "-f", r"Traktor Pro 4\.app/Contents/MacOS/"], capture_output=True).returncode == 0
def prepare() -> None:
KIT.mkdir(parents=True, exist_ok=True)
for name, (src, what) in FILES.items():
shutil.copy2(src, KIT / name)
print(f" {name:38s} <- {src.name} [{what} at apply]")
print(f"\nKit at {KIT}\n"
"Next, in Traktor 4.5:\n"
" 1. Preferences > Mixer: note the Autogain setting, and turn ON\n"
" 'Set Autogain when Loading Track' (or the nearest wording).\n"
" 2. Import the Kit G1 folder; select its 6 tracks; Analyze (Async) > All.\n"
" 3. Quit Traktor (it writes the collection on exit).\n"
"Then: python dev_gain_kit.py apply")
def _entries(nml_text: str) -> dict[str, str]:
out = {}
for e in re.findall(r"<ENTRY .*?</ENTRY>", nml_text, re.S):
m = re.search(r'<LOCATION [^>]*FILE="(G1-[^"]+)"', e)
if m:
out[m.group(1)] = e
return out
def apply() -> None:
if _traktor_running():
raise SystemExit("Quit Traktor first.")
text = NML.read_text(encoding="utf-8")
have = _entries(text)
missing = [n for n in FILES if n not in have]
if missing:
raise SystemExit(f"Not in the collection yet (import + analyse in Traktor): {missing}")
unanalysed = [n for n in FILES if "<LOUDNESS" not in have[n] or 'AUDIO_ID=""' in have[n] or "AUDIO_ID" not in have[n]]
if unanalysed:
raise SystemExit(f"Not analysed by Traktor yet: {unanalysed}")
shutil.copy2(NML, KIT / "1-after-traktor-analysed.nml")
print("Changing files:")
for name, (_, what) in FILES.items():
p = KIT / name
st = p.stat()
if what == "mtime only":
os.utime(p)
print(f" {name}: mtime touched")
elif what.startswith("frame gain"):
before = _decode(p)
n = mp3_frame_gain(p, STEPS)
print(f" {name}: {n} frames, {STEPS:+d} steps")
_check_gain(before, p, STEPS * 20 * np.log10(2 ** 0.25), "check")
if "APE" in what:
from mutagen.apev2 import APEv2
tag = APEv2()
tag["MP3GAIN_UNDO"] = f"{-STEPS:+04d},{-STEPS:+04d},N"
tag.save(str(p))
print(" + APEv2 MP3GAIN_UNDO tag")
if "restored" in what:
os.utime(p, ns=(st.st_atime_ns, st.st_mtime_ns))
print(f" mtime restored, size {'same' if p.stat().st_size == st.st_size else 'CHANGED'}")
elif what.startswith("exact"):
before = _decode(p)
db = STEPS * 20 * np.log10(2 ** 0.25)
flac_exact_gain(p, db)
print(f" {name}: {db:+.2f} dB, size {st.st_size} -> {p.stat().st_size}")
_check_gain(before, p, db, "check")
from konduktor.adapters.traktor.store import TraktorStore
from konduktor.core import folder
from traktor_nml_utils.models.collection import Loudnesstype
shutil.copy2(B2[1], KIT / B2[0])
store = TraktorStore(NML)
store.add_entry(folder.read_track(KIT / B2[0]), KIT / B2[0])
def set_loudness(file: str, vals) -> None:
for e in store._nml.collection.entry:
if e.location is not None and e.location.file == file:
e.loudness = Loudnesstype(peak_db=vals[0], perceived_db=vals[1], analyzed_db=vals[2])
return
raise SystemExit(f"entry {file} not found")
set_loudness("G1-B1 loudness written.mp3", B1_LOUDNESS)
set_loudness(B2[0], B2_LOUDNESS)
store.save()
shutil.copy2(NML, KIT / "2-after-konduktor-apply.nml")
print(f"\nLOUDNESS written: B1 {B1_LOUDNESS}, B2 (added, AUDIO_ID empty) {B2_LOUDNESS}\n"
"Next, in Traktor 4.5 (do NOT run Analyze):\n"
" 1. Load EACH G1 track into deck A in turn (B1 and B2 first).\n"
" For each, note the GAIN knob's value (hover / the readout) and\n"
" whether Traktor shows it analysing.\n"
" 2. Quit Traktor.\n"
"Then: python dev_gain_kit.py report")
_FIELDS = {
"AUDIO_ID": r'AUDIO_ID="([^"]*)"',
"LOUDNESS": r"<LOUDNESS ([^>]*)>",
"TEMPO": r'<TEMPO BPM="([^"]*)"',
"GRID": r'<CUE_V2 [^>]*TYPE="4"[^>]*START="([^"]*)"',
"MODIFIED": r'MODIFIED_DATE="([^"]*)" MODIFIED_TIME="([^"]*)"',
"FILESIZE": r'FILESIZE="([^"]*)"',
"LAST_PLAYED": r'LAST_PLAYED="([^"]*)"',
}
def report() -> None:
if _traktor_running():
raise SystemExit("Quit Traktor first (it writes the collection on exit).")
shutil.copy2(NML, KIT / "3-after-traktor-load.nml")
stages = [
("analysed", _entries((KIT / "1-after-traktor-analysed.nml").read_text(encoding="utf-8"))),
("applied", _entries((KIT / "2-after-konduktor-apply.nml").read_text(encoding="utf-8"))),
("loaded", _entries(NML.read_text(encoding="utf-8"))),
]
for name in [*FILES, B2[0]]:
print(f"\n== {name} [{FILES.get(name, (None, 'added by Konduktor'))[1]}]")
for field, rx in _FIELDS.items():
vals = []
for _, ents in stages:
e = ents.get(name)
m = re.search(rx, e) if e else None
vals.append(" ".join(m.groups()) if m else ("-" if e else "(no entry)"))
flag = "" if vals[1] == vals[2] else " <-- CHANGED by Traktor"
print(f" {field:11s} analysed: {vals[0][:60]}\n"
f" {'':11s} applied: {vals[1][:60]}\n"
f" {'':11s} loaded: {vals[2][:60]}{flag}")
if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).resolve().parent))
{"prepare": prepare, "apply": apply, "report": report}[sys.argv[1] if len(sys.argv) > 1 else "prepare"]()
+336
View File
@@ -0,0 +1,336 @@
"""Kit G2 — what rekordbox 7 does with auto gain, and whether a stick carries it
(dev only; see .claude/discussions/discuss-gain-normalization-2026-10-19.md).
Already measured without rekordbox open (2026-10-19, 19 local tracks):
`djmdMixerParam.Gain{High,Low}` are the halves of a big-endian float32, LINEAR,
= 10^((-10 - LUFS)/20) to 0.13 dB — rekordbox levels integrated BS.1770
loudness to -10 LUFS. `Peak{High,Low}` = the linear SAMPLE peak.
Every SONG in the local library was added by Konduktor (2026-10-01), whose
rekordbox add writes no MixerParam row — so the fit above is rekordbox's
sample pack only. This kit asks rekordbox itself:
A. A track with NO row: does loading it create one (R2, R3)?
B. After rekordbox analyses the songs: is the gain -10 - LUFS on music too?
C. Is a gain Konduktor writes KEPT (R1 at -20 dB)?
D. Does a USB export carry the gain anywhere a CDJ reads (OneLibrary
exportLibrary.db, export.pdb, the ANLZ files)? R1-R3 are exported twice
with different gains and the two exports diffed.
python dev_gain_kit_g2.py prepare # records state; writes nothing
# A -> rekordbox: Auto Gain on, load R2 + R3, quit
python dev_gain_kit_g2.py status
# B -> rekordbox: Analyze the 7 songs, quit
python dev_gain_kit_g2.py status
python dev_gain_kit_g2.py write # R1 -> -20 dB
# C -> rekordbox: load R1, export R1-R3 to a stick, quit
python dev_gain_kit_g2.py check1 /Volumes/STICK
python dev_gain_kit_g2.py flip
# D -> rekordbox: remove R1-R3 from the stick, export again, quit
python dev_gain_kit_g2.py check2 /Volumes/STICK
python dev_gain_kit_g2.py restore # R1-R3 back to rekordbox's own gains
rekordbox must be closed whenever this script runs. The local master.db is written directly (it is disposable — but `prepare`
records every row it touches and `restore` puts them back).
"""
from __future__ import annotations
import json
import math
import shutil
import sqlite3
import struct
import sys
import uuid
from datetime import datetime
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
KIT = Path.home() / "Music/Konduktor Stem Test/Kit G2"
STATE = KIT / "state.json"
FLIP = {"R1": -8.0, "R2": +6.0, "R3": -14.0} # export 2's gains
def _halves(x: float) -> tuple[int, int]:
bits = struct.unpack(">I", struct.pack(">f", x))[0]
return bits >> 16, bits & 0xFFFF
def _value(hi, lo) -> float | None:
if hi is None or lo is None:
return None
return struct.unpack(">f", struct.pack(">I", ((hi & 0xFFFF) << 16) | (lo & 0xFFFF)))[0]
def _db_str(lin: float | None) -> str:
return "—" if lin is None else ("-inf" if lin <= 0 else f"{20 * math.log10(lin):+.2f} dB")
def _db():
from pyrekordbox import masterdb
from konduktor.adapters.rekordbox.store import rekordbox_probe_suppressed
from pyrekordbox.masterdb import database as rb_database
if rb_database.get_rekordbox_pid():
raise SystemExit("Quit rekordbox first.")
return masterdb.MasterDatabase(), rekordbox_probe_suppressed
def _row(db, content_id):
from pyrekordbox.masterdb import models
return db.query(models.DjmdMixerParam).filter_by(ContentID=content_id).one_or_none()
def _snapshot_row(r) -> dict | None:
if r is None:
return None
return {c: getattr(r, c) for c in ("ID", "ContentID", "GainHigh", "GainLow", "PeakHigh", "PeakLow", "UUID")} | {
"created_at": str(r.created_at), "updated_at": str(r.updated_at)}
def _set_gain(db, content_id: str, db_gain: float) -> None:
r = _row(db, content_id)
r.GainHigh, r.GainLow = _halves(10 ** (db_gain / 20))
SONGS = {"R1": "Faith in You - AC Slater Remix", "R2": "Low Frequency", "R3": "Never Let You Go"} # unlocked: a locked track cannot be analysed
def prepare() -> None:
"""Record the kit's songs, their LUFS and their MixerParam rows. Writes nothing:
every song in this library was added by Konduktor and has NO MixerParam row."""
from konduktor.core import loudness
db, _ = _db()
state = {"tracks": {}, "songs": {}, "created": datetime.now().isoformat()}
KIT.mkdir(parents=True, exist_ok=True)
for c in db.get_content().all():
if (c.Length or 0) < 120 or not Path(c.FolderPath or "").is_file():
continue
m = loudness.measure_file(c.FolderPath)
entry = {"content_id": c.ID, "title": c.Title, "artist": c.Artist.Name if c.Artist else "",
"path": c.FolderPath, "lufs": m.lufs if m else None, "true_peak": m.true_peak if m else None,
"original": _snapshot_row(_row(db, c.ID))}
state["songs"][c.Title] = entry
for name, title in SONGS.items():
if title == c.Title:
state["tracks"][name] = entry
STATE.write_text(json.dumps(state, indent=2))
status()
print("\nNext, in rekordbox 7 (step A — a track with NO MixerParam row):\n"
" 1. Preferences > Controller > Mixer tab > Auto Gain: Enable.\n"
f" 2. PERFORMANCE mode: load '{SONGS['R2']}', open the deck's GRID EDIT panel and\n"
f" note its Auto Gain value (or that it is blank); then '{SONGS['R3']}'.\n"
" (No Performance mode: EXPORT mode, DUAL PLAYER layout, the AUTO GAIN knob.)\n"
" Do NOT run Analyze and do NOT turn the knob (a manual change is saved).\n"
" 3. Quit rekordbox.\n"
"Then: python dev_gain_kit_g2.py status")
def status() -> None:
"""Every song's MixerParam row now, against -10 - LUFS."""
db, _ = _db()
state = json.loads(STATE.read_text())
print("== songs: MixerParam now (expected if rekordbox levels to -10 LUFS)")
for title, t in state["songs"].items():
r = _row(db, t["content_id"])
want = f"{-10 - t['lufs']:+.2f} dB" if t["lufs"] is not None else "?"
if r is None:
print(f" {title[:34]:34s} no row (expect {want})")
else:
g, pk = _value(r.GainHigh, r.GainLow), _value(r.PeakHigh, r.PeakLow)
print(f" {title[:34]:34s} gain {_db_str(g):>10s} peak {_db_str(pk):>10s} (expect {want}; "
f"true peak {t['true_peak']:+.2f}; updated {r.updated_at})")
def write() -> None:
"""Step C: R1's gain set to -20 dB (it must have a row: run after rekordbox analysed it)."""
db, suppressed = _db()
state = json.loads(STATE.read_text())
for name, t in state["tracks"].items():
t["before_write"] = _snapshot_row(_row(db, t["content_id"]))
if state["tracks"]["R1"]["before_write"] is None:
raise SystemExit("R1 has no MixerParam row yet — analyse it in rekordbox first.")
_set_gain(db, state["tracks"]["R1"]["content_id"], -20.0)
with suppressed():
db.commit(autoinc=True)
STATE.write_text(json.dumps(state, indent=2))
print(f"R1 '{SONGS['R1']}' gain written -20.0 dB.\n"
"Next, in rekordbox 7 (step C):\n"
" 1. Load R1 and read GRID EDIT > Auto Gain (or the DUAL PLAYER AUTO GAIN\n"
" knob): -20 dB = kept, ~+4.5 dB = recomputed. Do NOT run Analyze.\n"
f" 2. Export R1, R2, R3 ('{SONGS['R1']}', '{SONGS['R2']}', '{SONGS['R3']}') to a USB stick.\n"
" 3. Quit rekordbox.\n"
"Then: python dev_gain_kit_g2.py check1 /Volumes/<STICK>")
def _rows_now(db, state) -> dict:
return {name: _snapshot_row(_row(db, t["content_id"])) for name, t in state["tracks"].items()}
def _snapshot_stick(stick: Path, dest: Path) -> None:
rb = stick / "PIONEER/rekordbox"
if not rb.is_dir():
raise SystemExit(f"No PIONEER/rekordbox on {stick}")
if dest.exists():
shutil.rmtree(dest)
shutil.copytree(rb, dest / "rekordbox", ignore=shutil.ignore_patterns("*-shm", "*-wal"))
shutil.copytree(stick / "PIONEER/USBANLZ", dest / "USBANLZ")
def _report_rows(label: str, rows: dict, state: dict) -> None:
print(f"\n== master.db MixerParam {label}")
for name, r in rows.items():
t = state["tracks"][name]
orig = t.get("before_write") or t["original"] or {}
if r is None:
print(f" {name}: no row")
continue
g, pk = _value(r["GainHigh"], r["GainLow"]), _value(r["PeakHigh"], r["PeakLow"])
same_id = "same row" if r["ID"] == orig.get("ID") else "NEW row"
print(f" {name}: gain {_db_str(g)}, peak {_db_str(pk)} ({same_id}, updated {r['updated_at']})")
def check1(stick: str) -> None:
db, _ = _db()
state = json.loads(STATE.read_text())
rows = _rows_now(db, state)
state["after_load"] = rows
STATE.write_text(json.dumps(state, indent=2))
_report_rows("after rekordbox loaded + exported (R1 written -20 dB)", rows, state)
_snapshot_stick(Path(stick), KIT / "stick-1")
print(f"\nStick snapshot: {KIT / 'stick-1'}\nThen: python dev_gain_kit_g2.py flip")
def flip() -> None:
db, suppressed = _db()
state = json.loads(STATE.read_text())
for name, g in FLIP.items():
_set_gain(db, state["tracks"][name]["content_id"], g)
with suppressed():
db.commit(autoinc=True)
print("Gains for export 2: " + ", ".join(f"{n} {g:+.1f} dB" for n, g in FLIP.items()) +
"\n"
"Next, in rekordbox 7:\n"
" 1. In the stick's browser, remove R1, R2, R3 from the device.\n"
" 2. Export R1, R2, R3 to the stick again.\n"
" 3. Quit rekordbox.\n"
"Then: python dev_gain_kit_g2.py check2 /Volumes/<STICK>")
def _onelibrary_rows(snap: Path, titles: list[str]) -> dict:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
db = snap / "rekordbox/exportLibrary.db"
if not db.is_file():
return {}
con = sqlcipher.connect(str(db))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
cols = [r[1] for r in con.execute("PRAGMA table_info(content)")]
out = {}
for row in con.execute("SELECT * FROM content"):
d = dict(zip(cols, row))
if d.get("title") in titles:
out[d["title"]] = d
con.close()
return out
def _pdb_rows(snap: Path, titles: list[str]) -> dict:
from konduktor.adapters.rekordbox import pdb
f = snap / "rekordbox/export.pdb"
if not f.is_file():
return {}
buf = f.read_bytes()
out = {}
for row in pdb.table_rows(buf, pdb.TRACKS):
fields, strings = pdb.track_fields(row)
if strings.get("title") in titles:
out[strings["title"]] = (row[: pdb.track_extent(row)], fields, strings)
return out
def _anlz(snap: Path, rel: str | None) -> dict:
from konduktor.adapters.rekordbox import anlz_file
out = {}
if not rel:
return out
base = snap / "USBANLZ" / Path(rel.lstrip("/")).relative_to("PIONEER/USBANLZ")
for ext in (".DAT", ".EXT", ".2EX"):
p = base.with_suffix(ext)
if p.is_file():
tags, seen = {}, {}
for t in anlz_file.parse_file(p).tags: # PCOB / PCO2 come twice (hot, memory)
seen[t.type] = seen.get(t.type, 0) + 1
tags[f"{t.type}#{seen[t.type]}"] = t.data
out[ext] = tags
return out
def check2(stick: str) -> None:
db, _ = _db()
state = json.loads(STATE.read_text())
rows = _rows_now(db, state)
_report_rows("before export 2 (flip), as rekordbox left it", rows, state)
_snapshot_stick(Path(stick), KIT / "stick-2")
titles = [t["title"] for t in state["tracks"].values()]
s1, s2 = KIT / "stick-1", KIT / "stick-2"
print("\n== OneLibrary content rows: columns that differ between export 1 and 2")
a, b = _onelibrary_rows(s1, titles), _onelibrary_rows(s2, titles)
ids = {"content_id", "analysisDataFilePath", "image_id", "path", "dateAdded"}
for title in titles:
if title not in a or title not in b:
print(f" {title}: missing in an export ({title in a}, {title in b})")
continue
diff = {k: (a[title][k], b[title][k]) for k in a[title] if a[title][k] != b[title].get(k)}
print(f" {title[:40]}: {diff or 'identical'}")
print("\n== export.pdb track rows: fields / bytes that differ")
a, b = _pdb_rows(s1, titles), _pdb_rows(s2, titles)
for title in titles:
if title not in a or title not in b:
print(f" {title}: missing in a pdb ({title in a}, {title in b})")
continue
fa, fb = a[title][1], b[title][1]
diff = {k: (fa[k], fb[k]) for k in fa if fa[k] != fb.get(k)}
sdiff = {k: (a[title][2][k], b[title][2][k]) for k in a[title][2] if a[title][2][k] != b[title][2].get(k)}
print(f" {title[:40]}: fields {diff or 'identical'}; strings {sdiff or 'identical'}")
print("\n== ANLZ tags that differ")
oa, ob = _onelibrary_rows(s1, titles), _onelibrary_rows(s2, titles)
for title in titles:
ta = _anlz(s1, (oa.get(title) or {}).get("analysisDataFilePath"))
tb = _anlz(s2, (ob.get(title) or {}).get("analysisDataFilePath"))
changed = [f"{ext}:{k}" for ext in ta for k in ta[ext] if ta[ext][k] != tb.get(ext, {}).get(k)]
missing = [f"{ext}:{k}" for ext in tb for k in tb[ext] if k not in ta.get(ext, {})]
print(f" {title[:40]}: changed {changed or 'none'}; new {missing or 'none'}")
print("\nThen: python dev_gain_kit_g2.py restore")
def restore() -> None:
"""R1 and R3 back to the gain rekordbox computed (their rows before `write`)."""
db, suppressed = _db()
state = json.loads(STATE.read_text())
for name, t in state["tracks"].items():
o, r = t.get("before_write"), _row(db, t["content_id"])
if o and r is not None:
r.GainHigh, r.GainLow, r.PeakHigh, r.PeakLow = o["GainHigh"], o["GainLow"], o["PeakHigh"], o["PeakLow"]
with suppressed():
db.commit(autoinc=True)
print("R1-R3 gains restored to rekordbox's own values.")
if __name__ == "__main__":
cmd = sys.argv[1] if len(sys.argv) > 1 else "prepare"
fn = {"prepare": prepare, "status": status, "write": write, "check1": check1, "flip": flip,
"check2": check2, "restore": restore}[cmd]
fn(*sys.argv[2:])
@@ -404,6 +404,31 @@ class OneLibraryAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
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`
# is False, so nothing offers it.
raise Unsupported("A OneLibrary drive has no auto gain: level a stick by normalising its audio")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -583,3 +608,8 @@ class OneLibraryAdapter:
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
raise Unsupported("OneLibrary has no beatgrid lock")
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
# Only a DJ app's library on this computer is pushed into; a stick is
# filled by an export.
raise Unsupported("A OneLibrary drive is filled by an export, not a push")
@@ -36,7 +36,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import memory_palette, palette
from ..rekordbox import memory_palette, palette, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
@@ -87,6 +87,11 @@ 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,
# `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows
@@ -121,10 +121,10 @@ def rebuild(existing: bytes, session) -> bytes | None:
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
for (cid, title, artist, remixer, album, genre, label, rating, color, bpm, year, released,
comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
"label_id, rating, color_id, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid)
@@ -134,7 +134,8 @@ def rebuild(existing: bytes, session) -> bytes | None:
fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
"rating": max(0, min(5, int(rating or 0))), "color_id": int(color or 0),
"tempo": int(bpm or 0),
"year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""}
@@ -44,7 +44,7 @@ from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, memory_palette, palette, timebase
from ..rekordbox import artwork, memory_palette, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key
@@ -209,13 +209,13 @@ class OneLibraryExporter:
con.execute(
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, color_id, image_id, "
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
"analysisDataUpdateCount, informationUpdateCount) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
content_id, track.title, (track.title or "").lower(),
int(round((track.bpm or 0) * 100)) or None, track.length,
@@ -229,6 +229,7 @@ class OneLibraryExporter:
# where the deck expects "Cm". Rendered from the parsed wheel.
self._lookup(con, "key", lookups["key"],
render_key(track.key_wheel, track.key_mode)),
track_palette.id_for(track.color),
image_id,
track.comment, track.rating or 0, track.release_date,
date.today().isoformat(), rel, item.destination.name, size,
@@ -16,6 +16,7 @@ Field conventions are read off a real rekordbox 7 export rather than guessed:
from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox import track_palette
from ..rekordbox.projection import parse_key
@@ -106,6 +107,8 @@ def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track
grid_locked=False, # OneLibrary has no grid lock
# What the FILE is, as the deck plays it — see the Rekordbox projection.
media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "color_id", None)),
color_hex=track_palette.hex_for(getattr(row, "color_id", None)),
)
+55 -2
View File
@@ -55,7 +55,7 @@ from ...core.grid_edit import ReplaceGridCommands
from ...core.model import CuePoint
from ... import paths
from . import beatgrid, cues as cue_reader, memory_cues
from ..rekordbox import anlz_file, palette, timebase
from ..rekordbox import anlz_file, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox import anlz_writer as W
from ..rekordbox import beatgrid as rb_beatgrid
@@ -566,6 +566,58 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
db.session.expire(row)
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`content.color_id`, a 1-based id into the `color` table (see
`track_palette`); 0 = none, as rekordbox exports an uncoloured track.
Not a file tag; the pdb's track row follows at Save (`device_library`)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
db = self._require_db()
row = self.content(track_id)
before = row.color_id
if int(before or 0) == new:
return
row.color_id = new
self._journal.record("track", "set", track_id, "color", before, new)
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
@@ -1182,7 +1234,7 @@ class OneLibraryStore(ReplaceGridCommands):
"isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, "
"masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, "
"hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, "
":album, :genre, :label, :key, 0, :image, :comment, :rating, :year, :released, "
":album, :genre, :label, :key, :color, :image, :comment, :rating, :year, :released, "
":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, "
"'', 0, :cid, :anlz, :bits, :link, 0)"), {
"cid": cid, "title": getattr(track, "title", None) or final.stem,
@@ -1192,6 +1244,7 @@ class OneLibraryStore(ReplaceGridCommands):
"label": lookup("Label", track.label),
# Rendered from the parsed wheel: a source's "10m" means nothing here.
"key": self._key_id(track.key_wheel, track.key_mode),
"color": track_palette.id_for(getattr(track, "color", None)),
"image": image_id, "comment": track.comment or "",
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
@@ -21,7 +21,7 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
@@ -45,10 +45,12 @@ class RekordboxAdapter:
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
kinds = self._store.cue_kinds()
gains = self._store.mixer_gains()
self._index.rebuild(
[
projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID)))
stem=self._store.is_stem(str(row.ID)),
auto_gain_db=gains.get(str(row.ID)))
for row in self._store.iter_content()
]
)
@@ -71,7 +73,8 @@ class RekordboxAdapter:
kinds = self._store.cue_kinds()
row = self._store.content(track_id)
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID))))
stem=self._store.is_stem(str(row.ID)),
auto_gain_db=self._store.mixer_gain(str(row.ID))))
def close(self) -> None:
"""Release the database connection.
@@ -260,6 +263,24 @@ class RekordboxAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
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)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
@@ -439,6 +460,30 @@ class RekordboxAdapter:
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
"""Clear the track's cues and grid, then place `cues` as `add_tracks`
does (`_place_imported_cues`). Rekordbox has no grid lock, so
`grid_locked` is not carried; a cue on the reserved `Kind=4` (shown,
not editable) is left where it is."""
self._require_writable("Replacing cues")
current = self.track_cues(track_id)
if current is None:
raise NotFound(f"Track not found: {track_id}")
for cue in current.cues:
if not cue.editable:
continue
if cue.role == "hotcue" and cue.slot is not None:
self._store.delete_cue(track_id, cue.slot)
elif cue.id:
self._store.delete_memory_cue(track_id, cue.id)
markers = list(cues.grid_markers or [])
if markers:
self._store.replace_grid(track_id, self._markers_from(markers))
elif current.grid_markers:
self._store.delete_grid(track_id)
self._place_imported_cues(track_id, cues)
return self._refresh_cues(track_id)
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
@@ -539,17 +584,22 @@ class RekordboxAdapter:
else:
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
detect=not markers,
detect_key=item.track.key_wheel is None)
detect_key=item.track.key_wheel is None,
measure_loudness=True)
markers = markers or list(analysed.markers)
measured = analysed.measured
# A file with no key of its own gets one, as it gets a grid
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
track = add_analysis.with_key(item.track, analysed.key)
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
prepared.append((item, track, audio, measured, markers, art[0] if art else None,
getattr(analysed, "loudness", None)))
# The app's loudness store, where one is attached (see `AppState`): a
# measurement made here is worth keeping for the Mastering columns.
on_loudness = getattr(self, "on_loudness", None)
added: list[str] = []
for item, track, audio, measured, markers, art in prepared:
for item, track, audio, measured, markers, art, loud in prepared:
track_id = self._store.add_track(
audio, track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), (),
@@ -558,6 +608,12 @@ class RekordboxAdapter:
self._store.replace_grid(track_id, markers)
if item.cues is not None:
self._place_imported_cues(track_id, item.cues)
if loud is not None:
# rekordbox's own add analyses an auto gain; without a row the
# track plays at 0.0 dB and loading never creates one (kit G2).
self._store.set_auto_gain(track_id, loud)
if on_loudness is not None:
on_loudness(audio, loud)
self._refresh(track_id)
added.append(track_id)
return added
@@ -30,7 +30,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import memory_palette, palette
from . import memory_palette, palette, track_palette
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
@@ -93,6 +93,11 @@ def capabilities_for(
removable=True,
addable=True,
key_writable=True,
# `djmdContent.ColorID`, rekordbox's eight (see `track_palette`).
colors=list(track_palette.SWATCHES),
# djmdMixerParam (measured, see `gain`).
auto_gain=True,
normalizable=True,
artwork=False,
artwork_note=None,
),
@@ -41,7 +41,7 @@ from datetime import date
from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from . import artwork, pdb
from . import artwork, pdb, track_palette
from .projection import render_key
log = logging.getLogger(__name__)
@@ -138,6 +138,7 @@ class RekordboxDeviceExporter:
"id": n, "year": year, "sample_depth": bit_depth or 0,
"duration": min(int(track.length or 0), 0xFFFF),
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
"color_id": track_palette.id_for(track.color),
"u6": _file_type(item.destination), "u7": 3,
},
{
+16 -3
View File
@@ -58,7 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from . import memory_palette, new_content, palette
from . import memory_palette, new_content, palette, track_palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
@@ -109,6 +109,11 @@ class RekordboxExporter:
computer_only = True
library_filename = "master.db"
drive_root = False
#: `djmdContent.Analysed` bit 0x80 — from `TrackCues.grid_locked`.
locks_grids = True
#: `djmdMixerParam` from `ExportTrack.loudness` (without a row a track
#: plays at 0.0 dB in rekordbox; kit G2).
writes_auto_gain = True
def capabilities(self):
"""What a Rekordbox library can hold, with no library to read.
@@ -207,7 +212,12 @@ class RekordboxExporter:
try:
for item in payload.tracks:
track_id = ids.get(item.source_id)
if track_id is None or not item.cues:
if track_id is None:
continue
if item.loudness is not None:
# The same row an Analyze writes (`RekordboxStore.set_auto_gain`).
store.set_auto_gain(track_id, item.loudness)
if not item.cues:
continue
memory = 0
for cue in sorted(item.cues.cues, key=lambda c: c.start):
@@ -313,6 +323,7 @@ class RekordboxExporter:
# export would put "10m" where Rekordbox shows "Cm".
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
content.ContentLink = CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
db.flush()
return content
@@ -331,7 +342,9 @@ class RekordboxExporter:
"""
rel = new_content.anlz_rel(str(content.UUID))
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
content.Analysed = new_content.ANALYSED
if item.cues is not None and item.cues.grid_locked:
content.Analysed |= new_content.ANALYSED_LOCKED
content.AnalysisUpdated = 1
db.flush()
@@ -0,0 +1,32 @@
"""rekordbox's auto gain: one `djmdMixerParam` row per track.
MEASURED (kit G2, 2026-10-19 — `backend/dev_gain_kit_g2.py` and the
gain-normalisation discussion):
* `GainHigh/GainLow` are the two 16-bit halves of a big-endian float32, a
LINEAR gain; pyrekordbox's `DjmdMixerParam.Gain` reads and writes it in dB.
It is what PERFORMANCE mode's GRID EDIT > Auto Gain (and EXPORT mode's
DUAL PLAYER AUTO GAIN knob) shows, with Preferences > Controller > Mixer >
Auto Gain enabled.
* rekordbox's own analysis sets it to `-10 - LUFS` (BS.1770 integrated):
exact on its 19 WAV samples (sd 0.13 dB), +0.24 dB (sd 0.17) on 5 MP3 songs.
* `PeakHigh/PeakLow`: the linear SAMPLE peak, of a CLIPPED decode — never
above 1.0 (a track with a true peak of +3.9 dBTP stored 0.00 dB).
* A row Konduktor writes is kept on load. A track with NO row plays at
Auto Gain 0.0 dB, and loading it creates none — so a track Konduktor adds
gets its row at add time, as rekordbox's own add analyses one.
* No USB export carries it (diffed across two exports with different gains).
"""
from __future__ import annotations
from ...core.loudness import Loudness
#: The level rekordbox's auto gain brings a track to, in LUFS.
REFERENCE_LUFS = -10.0
def values(loudness: Loudness) -> tuple[float, float]:
"""(gain dB, peak dB) for a measured track — the peak clipped at 0 dBFS as
rekordbox's own is."""
return REFERENCE_LUFS - loudness.lufs, min(0.0, loudness.true_peak)
@@ -10,7 +10,10 @@ What a track Rekordbox itself adds looks like was MEASURED (two files dragged
into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a
`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three
JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own
analysis results — key, mixer gain, phrases — which nothing here can produce.
analysis results — key, mixer gain, phrases. Phrases nothing here produces; the
key comes from `key_detect` and the mixer gain from a loudness measurement
(`djmdMixerParam`, written by the adapter's add through `RekordboxStore.
set_auto_gain` — see `gain`).
"""
from __future__ import annotations
@@ -34,6 +37,12 @@ from . import artwork
#: only what is written: 0x2C060E.
CONTENT_LINK = 2885134
#: `djmdContent.Analysed` as a rekordbox-analysed track carries it, and the bit
#: rekordbox 7 sets beside it when the grid is LOCKED (the padlock in Grid Edit):
#: measured 2026-10-19 by locking two tracks — 105 -> 233, nothing else changed.
ANALYSED = 105
ANALYSED_LOCKED = 0x80
def anlz_rel(track_uuid: str) -> str:
"""`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from
@@ -7,7 +7,7 @@ from __future__ import annotations
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, memory_palette, palette, timebase
from . import beatgrid, memory_palette, palette, timebase, track_palette
from .cue_types import cue_type, kind_for, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
@@ -64,7 +64,7 @@ def _name_of(related) -> str | None:
return None
def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
def to_track(row, cue_kinds=(), *, stem: bool = False, auto_gain_db: float | None = None) -> Track:
"""Project one ``DjmdContent`` row.
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
@@ -127,6 +127,10 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
# file's mix, but Konduktor's deck plays its stems, and the Type column
# must not disagree with the deck.
media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "ColorID", None)),
color_hex=track_palette.hex_for(getattr(row, "ColorID", None)),
# From the store's one `djmdMixerParam` query (see `gain`).
auto_gain_db=auto_gain_db,
)
+109 -2
View File
@@ -28,6 +28,7 @@ from __future__ import annotations
import json
import logging
import os
import uuid
from contextlib import contextmanager
from datetime import datetime
@@ -47,7 +48,7 @@ from ...core.adapter import (
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping, stored_form
from . import memory_palette, timebase
from . import gain, memory_palette, timebase, track_palette
from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__)
@@ -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()
@@ -556,6 +561,67 @@ class RekordboxStore(ReplaceGridCommands):
self._db.flush()
self._db.session.expire(row)
# ---- writes: track colour ---------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`djmdContent.ColorID`, a 1-based id into `djmdColor` (see
`track_palette`). Cleared = "0", as on the uncoloured rows of the local
library (a few hold NULL; both read as none)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
row = self.content(track_id)
before = row.ColorID
if track_palette.id_for(track_palette.color_for(before)) == new:
return
row.ColorID = str(new)
self._journal.record("track", "set", track_id, "color", before, row.ColorID)
# A foreign key into djmdColor: flush + expire, as for the others.
self._db.flush()
self._db.session.expire(row)
# ---- auto gain ------------------------------------------------------------
def _mixer_row(self, track_id: str):
return (self._db.query(self._tables.DjmdMixerParam)
.filter(self._tables.DjmdMixerParam.ContentID == str(track_id)).first())
def mixer_gains(self) -> dict[str, float]:
"""``{track_id: auto gain dB}`` for every track with a row — ONE query, so
the projection never lazy-loads a relationship per track."""
t = self._tables.DjmdMixerParam
out = {}
for content_id, low, high in self._db.query(t.ContentID, t.GainLow, t.GainHigh).all():
if content_id is not None and low is not None and high is not None:
out[str(content_id)] = t._get_db(low, high)
return out
def mixer_gain(self, track_id: str) -> float | None:
row = self._mixer_row(track_id)
if row is None or row.GainLow is None or row.GainHigh is None:
return None
return row.Gain
def set_auto_gain(self, track_id: str, loudness) -> None:
"""The track's `djmdMixerParam` row (see `gain`), created as rekordbox
creates its own — `ID` and `UUID` both UUID strings — and through the
ORM, so `commit()` stamps `rb_local_usn`. Writing the halves already
there leaves the library clean."""
self.content(track_id) # NotFound for an unknown track
gain_db, peak_db = gain.values(loudness)
t = self._tables.DjmdMixerParam
g_low, g_high = t._set_db(gain_db)
p_low, p_high = t._set_db(peak_db)
row = self._mixer_row(track_id)
before = None if row is None else (row.GainHigh, row.GainLow, row.PeakHigh, row.PeakLow)
after = (g_high, g_low, p_high, p_low)
if before == after:
return
if row is None:
row = t(ID=str(uuid.uuid4()), ContentID=str(track_id), UUID=str(uuid.uuid4()))
self._db.add(row)
row.GainHigh, row.GainLow, row.PeakHigh, row.PeakLow = after
self._journal.record("track", "set", track_id, "auto_gain", before, after)
self._db.flush()
# ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str):
t = self._tables
@@ -761,6 +827,7 @@ class RekordboxStore(ReplaceGridCommands):
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
content.ContentLink = new_content.CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
if stored != audio:
# pyrekordbox reads the file where it IS; the row names it as the
# library stores every other path (the server's mapping, inverted).
@@ -769,7 +836,7 @@ class RekordboxStore(ReplaceGridCommands):
track_uuid = str(content.UUID)
rel = new_content.anlz_rel(track_uuid)
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
content.Analysed = new_content.ANALYSED
content.AnalysisUpdated = 1
files = new_content.anlz_files(audio, measured, [] if with_grid else None)
for suffix, data in files.items():
@@ -1001,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()
@@ -1490,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().
@@ -0,0 +1,50 @@
"""rekordbox's TRACK colours — the eight a track can be tagged with.
Stored as a 1-based id into the `djmdColor` table (master.db `djmdContent.ColorID`,
a string: "0" = none) and OneLibrary's `color` table (`content.color_id`, an
integer, 0 = none); the stick's legacy `export.pdb` track row has a `color_id`
byte with the same numbering. Both tables list the same eight rows in the same
order: 1 Pink, 2 Red, 3 Orange, 4 Yellow, 5 Green, 6 Aqua, 7 Blue, 8 Purple —
one per generic `TrackColor`, so the mapping is one to one.
Those are the memory-cue palette's names in its order, so the display RGB is
`memory_palette.COLOURS`' (sampled from rekordbox 7's own colour menu). Nothing
stores the RGB — `djmdColor.ColorCode` is NULL in a real library.
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
from . import memory_palette
#: id - 1 -> the generic colour, in rekordbox's menu order.
_NAMES: list[TrackColor] = ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
#: What `capabilities.tracks.colors` offers.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color=name, hex=memory_palette.SWATCHES[i], label=memory_palette.COLOURS[i][0])
for i, name in enumerate(_NAMES)
]
def _id(color_id: int | str | None) -> int:
try:
return int(color_id) if color_id is not None else 0
except (TypeError, ValueError):
return 0
def color_for(color_id: int | str | None) -> TrackColor | None:
"""The generic colour for a stored id; None for 0, NULL or anything unknown."""
n = _id(color_id)
return _NAMES[n - 1] if 1 <= n <= len(_NAMES) else None
def hex_for(color_id: int | str | None) -> str | None:
"""rekordbox's display colour for a stored id; None when uncoloured."""
n = _id(color_id)
return SWATCHES[n - 1].hex if 1 <= n <= len(SWATCHES) else None
def id_for(color: TrackColor | str | None) -> int:
"""The id to store for a generic colour; 0 for none (or an unknown name)."""
return _NAMES.index(color) + 1 if color in _NAMES else 0
@@ -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),
)
+57 -3
View File
@@ -218,6 +218,12 @@ class RemoteAdapter:
def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
def set_track_color(self, track_id, color):
return self._call("set_track_color", track_id=track_id, color=color)
def set_auto_gain(self, track_id, loudness):
return self._call("set_auto_gain", track_id=track_id, loudness=loudness)
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
@@ -274,6 +280,11 @@ class RemoteAdapter:
def set_grid_lock(self, track_id, locked):
return self._call("set_grid_lock", track_id=track_id, locked=locked)
def replace_cues(self, track_id, cues):
# Never travels (`remote_protocol.EXCLUDED`): a push targets a library
# on THIS computer.
raise Unsupported("A library held by a server is not a push target")
# ---- adding tracks ------------------------------------------------------------------
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
"""Send `source` into `folder` on the server; the path it landed at (a
@@ -329,7 +340,8 @@ class RemoteAdapter:
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
has_grid = bool(item.cues and item.cues.grid_markers)
analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid,
detect_key=item.track.key_wheel is None)
detect_key=item.track.key_wheel is None,
measure_loudness=self.capabilities().tracks.auto_gain)
art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \
if item.art else None
wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art,
@@ -357,7 +369,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()
@@ -366,7 +378,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
@@ -383,6 +396,47 @@ class RemoteAdapter:
self._load() # ids changed (repoint) or entries were added
return result
# ---- Normalize (the library side lives on the server) ---------------------------
# `gain/remote_normalize.py` drives these: the server plans and swaps, this
# computer downloads, rewrites, verifies and uploads.
def normalize_plan(self, body: dict) -> dict:
return self.client.gain_plan(body)
def stage_gain(self, track_id: str, local: Path, *, gain_db: float, options: dict,
waveform: str | None = None, progress=None) -> dict:
import hashlib
digest = hashlib.sha256()
with open(local, "rb") as f:
while chunk := f.read(1 << 20):
digest.update(chunk)
try:
out = self.client.gain_stage(track_id, local, gain_db=gain_db, sha256=digest.hexdigest(),
options=options, progress=progress)
if waveform is not None:
self.client.gain_waveform(track_id, waveform)
return out
except SessionLost as ex:
self.session.lost(ex.holder)
raise
def abandon_gain(self, track_ids: list[str]) -> None:
self.client.gain_abandon(track_ids)
def publish_gain(self, track_ids: list[str]) -> dict:
try:
result = self.client.gain_publish(track_ids)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
# The files changed under the same names: their facts (and so the
# cache key and every loudness lookup) are new.
with self._lock:
for track_id in track_ids:
self._facts.pop(track_id, None)
self._load()
return result
# ---- metadata / art ------------------------------------------------------------------
def set_cover_art(self, track_id, data, mime):
try:
+41 -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()
@@ -299,6 +302,35 @@ class RemoteClient:
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
timeout=None).json()
# ---- Normalize ------------------------------------------------------------------------
def gain_plan(self, body: dict) -> dict:
return self.request("POST", "/v1/gain/plan", json=body, timeout=None).json()
def gain_stage(self, track_id: str, source: Path, *, gain_db: float, sha256: str,
options: dict, progress=None) -> dict:
def body():
with open(source, "rb") as f:
while chunk := f.read(1 << 20):
if progress is not None:
progress(len(chunk))
yield chunk
return self.request(
"PUT", "/v1/gain/stage",
params={"track_id": track_id, "gain_db": repr(float(gain_db)), "sha256": sha256, **options},
content=body(), retry=False, timeout=None,
).json()
def gain_waveform(self, track_id: str, packed: str) -> None:
self.request("PUT", "/v1/gain/waveform", params={"track_id": track_id},
content=packed.encode("ascii"), retry=False, timeout=None)
def gain_abandon(self, track_ids: list[str]) -> None:
self.request("POST", "/v1/gain/abandon", json={"track_ids": track_ids})
def gain_publish(self, track_ids: list[str]) -> dict:
return self.request("POST", "/v1/gain/publish", json={"track_ids": track_ids}, timeout=None).json()
def stems_pending(self) -> dict:
return self.request("GET", "/v1/stems/pending").json()
@@ -323,3 +355,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})
+47 -2
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:
@@ -73,7 +73,11 @@ class RemotePending:
return {"tracks": 0, "parked": 0, "bytes": 0}
def blocking(self) -> bool:
return bool(self.summary().get("tracks"))
summary = self.summary()
return bool(summary.get("tracks") or summary.get("gain_tracks"))
def holds(self, track_ids) -> set:
return set() # the server's plan says which tracks it holds
def swapped(self) -> list:
return []
@@ -83,3 +87,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
@@ -156,6 +156,24 @@ class TraktorAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
with _translate():
self._store.set_track_color(track_id, color)
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)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
with _translate():
self._store.set_track_art(track_id, data, mime)
@@ -236,6 +254,10 @@ class TraktorAdapter:
# invent one outside Auto Grid), and it occupies pad A — which
# silently displaced the imported track's own pad A cue.
self.replace_grid(track_id, markers)
if cues.grid_locked:
# The source's lock, or an export's "Lock beatgrids". Unlocked, an
# added entry (no AUDIO_ID) is re-analysed on its first load.
self._store.set_lock(track_id, True)
slots = self.capabilities().cues.hotcue_slots
taken = {c.slot for c in self.track_cues(track_id).cues if c.slot is not None}
@@ -437,6 +459,39 @@ class TraktorAdapter:
self._store.set_lock(track_id, locked)
return self._refresh(track_id)
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
"""Clear the entry's prep, then replay `cues` exactly as `add_tracks`
does (`_apply_imported_cues`), so an updated entry and a new one cannot
differ. `delete_grid` takes the paired companion cues with it."""
current = self.track_cues(track_id)
if current is None:
raise NotFound(f"Track not found: {track_id}")
with _translate():
if current.grid_markers:
self._store.delete_grid(track_id)
# One at a time, re-reading between: a memory cue's id is derived
# from its content and its rank among cues at the same START, so a
# deletion can renumber the next one.
for _ in range(len(self.track_cues(track_id).cues)):
self._refresh(track_id)
left = self.track_cues(track_id).cues
cue = next((c for c in left if c.slot is not None or c.id), None)
if cue is None:
break
if cue.slot is not None:
self._store.delete_hotcue(track_id, cue.slot)
else:
self._store.delete_memory_cue(track_id, cue.id)
if current.grid_locked and not cues.grid_locked:
self._store.set_lock(track_id, False)
self._refresh(track_id)
if current.grid_locked and cues.grid_locked:
# Already locked: `_apply_imported_cues` would lock it again and
# move LOCK_MODIFICATION_TIME for nothing.
cues = cues.model_copy(update={"grid_locked": False})
self._apply_imported_cues(track_id, cues)
return self._refresh(track_id)
# ---- audio / paths ----------------------------------------------------
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
@@ -457,6 +512,15 @@ class TraktorAdapter:
track uploaded there is stored as that computer would have stored it."""
self._store.set_write_stored_paths(enabled)
def prepare_copied_audio(self, path: Path) -> bool:
"""OPTIONAL: ready a file the importer just COPIED for this library —
Traktor's own block removed (`file_block`), which Traktor would
otherwise restore over the entry's grid. Never called for a file
added in place."""
from . import file_block
return file_block.strip(path)
def unresolved_path_groups(self) -> list[PathGroup]:
return self._store.unresolved_path_groups()
@@ -19,6 +19,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import track_palette
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
@@ -68,6 +69,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
addable=True,
stem_convertible=True,
key_writable=True,
# 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"],
+20 -38
View File
@@ -35,8 +35,9 @@ import logging
from pathlib import Path
from ...core.adapter import NewTrack
from ...core.export import ExportPayload, WrittenLibrary
from ...core.export import OTHER_PLAYLIST, ExportPayload, WrittenLibrary, write_playlist_tree
from .adapter import TraktorAdapter
from . import file_block
from .capabilities import capabilities_for
log = logging.getLogger(__name__)
@@ -56,16 +57,23 @@ SKELETON = (
"</INDEXING>\n</NML>\n"
)
#: Loose tracks — added individually rather than through a playlist — would
#: otherwise be reachable only by search in the exported library.
OTHER_PLAYLIST = "Other"
class TraktorExporter:
platform = "traktor"
menu_order = 20
library_filename = "collection.nml"
drive_root = False
#: `LOCK` — honoured from `TrackCues.grid_locked` by `add_tracks`.
locks_grids = True
#: `<LOUDNESS>` from `ExportTrack.loudness` (kit G1: an entry with no
#: AUDIO_ID keeps the PERCEIVED_DB the deck reads through Traktor's first
#: analysis, which overwrites only ANALYZED_DB).
writes_auto_gain = True
@staticmethod
def prepare_copy(path: Path) -> bool:
"""Remove Traktor's own block from a copy (`file_block`): left in, it
is restored over this entry's grid when Traktor opens the collection."""
return file_block.strip(path)
def capabilities(self):
"""What a Traktor library can hold — answered with no library to read.
@@ -99,6 +107,10 @@ class TraktorExporter:
# Source id -> the id it got here. Both are Traktor primary keys derived
# from a LOCATION, and the location changed, so they are never equal.
moved = {t.source_id: new_id for t, new_id in zip(payload.tracks, new_ids)}
# The auto gain, through the same command an Analyze uses.
for t, new_id in zip(payload.tracks, new_ids):
if t.loudness is not None:
adapter.set_auto_gain(new_id, t.loudness)
self._write_playlists(adapter, payload, moved)
adapter.save()
@@ -109,35 +121,5 @@ class TraktorExporter:
"""Recreate the tree — at the top level, or with `payload.root_folder`
under one folder named after the export (None = the top level)."""
root = adapter.create_folder(payload.name) if payload.root_folder else None
folders: dict[tuple[str, ...], str | None] = {(): root}
for playlist in payload.playlists:
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
node_id = adapter.create_playlist(playlist.name, parent)
entries = [moved[t] for t in playlist.track_ids if t in moved]
if entries:
adapter.set_playlist_entries(node_id, entries)
loose = self._loose(payload, moved)
if loose:
node_id = adapter.create_playlist(OTHER_PLAYLIST, root)
adapter.set_playlist_entries(node_id, loose)
@staticmethod
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str | None) -> str | None:
"""Create (once) the folder chain a playlist sits under, and return it."""
for depth in range(1, len(path) + 1):
branch = path[:depth]
if branch not in folders:
folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]])
return folders.get(path, root)
@staticmethod
def _loose(payload: ExportPayload, moved: dict) -> list[str]:
"""Tracks no exported playlist accounts for, in payload order."""
in_playlists = {t for p in payload.playlists for t in p.track_ids}
return [
moved[t.source_id]
for t in payload.tracks
if t.source_id not in in_playlists and t.source_id in moved
]
write_playlist_tree(adapter, payload.playlists, [t.source_id for t in payload.tracks],
moved, root)
@@ -0,0 +1,121 @@
"""Traktor's own block INSIDE an audio file, and removing it from a copy.
Traktor writes a binary block of its analysis into every file it tags — the
same `DMRT` chunk tree in each format, stored where the format allows:
- MP4 (`.m4a`, stem files): the `ilst` atom `NITR`
- ID3 (MP3, AIFF, WAV): a `PRIV` frame owned by `TRAKTOR4`
- Vorbis comments (FLAC, Ogg): the field `traktor4`
It holds a BPM (`HBPM`), the cues (`CUEP`), the audio id, transients, tags.
Measured in Traktor 4.5 (2026-10-24, 2MUCH / Alone (Vip)): on an entry it did
not write itself — no MODIFIED_DATE, as every entry Konduktor creates — Traktor
re-reads the file and takes the block's BPM over the collection's, LOCK or not,
keeping the anchor. A grid fixed after Traktor last wrote the block (in
Konduktor, or in Traktor without a tag write) is reverted on every export.
Giving the entry a MODIFIED_DATE later than the file stops that, but Traktor
then skips the file altogether, cover art included. Giving it the block's
AUDIO_ID changes nothing. Removing the block from the copy does both: Traktor
imports the file as new — art, file facts and analysis from the file; BPM,
grid, lock and cues from the entry — and writes a fresh, correct block itself
when the track is first loaded. A stale `TBPM`/`tmpo` tag is ignored.
Only ever applied to a COPY Konduktor wrote. A file the user's library
references in place is the user's, and is never touched.
"""
from __future__ import annotations
import logging
from pathlib import Path
log = logging.getLogger(__name__)
#: The ID3 PRIV owner and the Vorbis field name Traktor writes the block under.
_PRIV_OWNER = "TRAKTOR4"
_VORBIS_FIELD = "traktor4"
#: The MP4 atom. mutagen keeps it among the atoms it could not parse — or, in
#: some files, parses it into an ordinary key; both are checked.
_MP4_ATOM = "NITR"
def has_block(path: Path) -> bool:
"""Whether the file carries Traktor's block. False for anything unreadable."""
audio = _open(path)
return audio is not None and bool(_remove(audio, dry_run=True))
def strip(path: Path) -> bool:
"""Remove Traktor's block from `path`, in place; True if it held one.
Everything else in the file is kept: other tags, cover, the stem box, the
audio. A file without a block is not rewritten at all. A file that cannot
be read or written is left as it is — a copy that still carries the block
is the old behaviour, never a failed export — and the reason is logged.
"""
audio = _open(path)
if audio is None or not _remove(audio, dry_run=False):
return False
try:
version = getattr(audio.tags, "version", None)
if version is not None and _is_id3(audio):
# Keep the file's own ID3 version: nothing else in it is changing.
audio.save(v2_version=3 if version[1] == 3 else 4)
else:
audio.save()
except Exception as ex: # noqa: BLE001 — see the docstring
log.warning("could not remove Traktor's block from %s: %s", path, ex)
return False
return True
def _open(path: Path):
try:
import mutagen
audio = mutagen.File(path)
except Exception as ex: # noqa: BLE001 — an unreadable file has no block we can see
log.debug("cannot read tags of %s: %s", path, ex)
return None
if audio is None or audio.tags is None:
return None
return audio
def _is_id3(audio) -> bool:
from mutagen.id3 import ID3
return isinstance(audio.tags, ID3)
def _remove(audio, *, dry_run: bool) -> int:
"""How many block entries `audio`'s tags hold, removing them unless
`dry_run`. Never saves."""
from mutagen.mp4 import MP4Tags
tags = audio.tags
found = 0
if isinstance(tags, MP4Tags):
failed = getattr(tags, "_failed_atoms", {})
if _MP4_ATOM in failed:
found += 1
if not dry_run:
del failed[_MP4_ATOM]
if _MP4_ATOM in tags:
found += 1
if not dry_run:
del tags[_MP4_ATOM]
elif _is_id3(audio):
keys = [k for k, frame in tags.items()
if k.startswith("PRIV:") and getattr(frame, "owner", None) == _PRIV_OWNER]
found += len(keys)
if not dry_run:
for k in keys:
del tags[k]
elif hasattr(tags, "keys"): # Vorbis comments: case-insensitive field names
keys = [k for k in tags.keys() if k.lower() == _VORBIS_FIELD]
found += len(keys)
if not dry_run:
for k in keys:
del tags[k]
return found
@@ -0,0 +1,32 @@
"""Traktor's auto gain: `<LOUDNESS PEAK_DB PERCEIVED_DB ANALYZED_DB>` per ENTRY.
MEASURED in Traktor 4.5 (kit G1, 2026-10-19 — `backend/dev_gain_kit.py` and
the gain-normalisation discussion):
* The deck's gain knob reads **PERCEIVED_DB** (an entry written with
PERCEIVED -6 / ANALYZED +6 / PEAK 2.5 loaded at -6.0).
* ANALYZED_DB is Traktor's own measurement. On an entry with an empty
AUDIO_ID, Traktor's first analysis overwrites only ANALYZED_DB and keeps
PERCEIVED_DB and PEAK_DB; its Analyze > Gain overwrites all three.
* Traktor's own value is `-9.2 - LUFS` (BS.1770 integrated; stem files
measured as their stems summed): sd 0.8 dB over 120 tracks
(`backend/bench_traktor_gain.py`), the miss following nothing measurable.
* PEAK_DB is the gain that brings the peak to 0 dBFS (= -peak; Traktor's is
a sample peak, ours a true peak — within ~0.4 dB).
Konduktor writes PERCEIVED and ANALYZED equal, as Traktor's own analysis does.
"""
from __future__ import annotations
from ...core.loudness import Loudness
#: The level Traktor's auto gain brings a track to, in LUFS.
REFERENCE_LUFS = -9.2
def values(loudness: Loudness) -> tuple[float, float, float]:
"""(PEAK_DB, PERCEIVED_DB, ANALYZED_DB) for a measured track, rounded to
Traktor's six decimals so a re-write of the same measurement is a no-op."""
gain = round(REFERENCE_LUFS - loudness.lufs, 6)
return round(-loudness.true_peak, 6), gain, gain
@@ -9,7 +9,7 @@ import re
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase
from . import beatgrid, timebase, track_palette
from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
@@ -172,6 +172,10 @@ def to_track(e) -> Track:
grid_marker_count=len(markers),
grid_locked=bool(e.lock),
media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
color=track_palette.color_for(info.color if info else None),
color_hex=track_palette.hex_for(info.color if info else None),
# The deck's gain knob reads PERCEIVED_DB (kit G1).
auto_gain_db=e.loudness.perceived_db if e.loudness is not None else None,
)
+73 -2
View File
@@ -22,6 +22,7 @@ import copy
import math
import threading
import uuid as uuidlib
from datetime import datetime, timezone
from pathlib import Path
from traktor_nml_utils import (
@@ -37,6 +38,7 @@ from traktor_nml_utils.models.collection import (
Infotype,
MusicalKeytype,
Locationtype,
Loudnesstype,
Nodetype,
Playlisttype,
Primarykeytype,
@@ -53,7 +55,7 @@ from ...core.pathmap import PathMapping, stored_form
from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode
from . import beatgrid, timebase
from . import beatgrid, gain, timebase, track_palette
from .locations import os_path_to_location, resolve_path
from ...core import musical_key
from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
@@ -446,7 +448,9 @@ class TraktorStore:
EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS
# Fields that live only in the collection: Traktor itself writes no file tag
# for "Comment 2" (verified on an m4a it had just edited), so neither do we.
_COLLECTION_ONLY_FIELDS = {"comment2"}
# Nor for the track colour (kit T1: no audio file's mtime moved).
# Nor for its auto gain (LOUDNESS is Traktor's own analysis output).
_COLLECTION_ONLY_FIELDS = {"comment2", "color", "auto_gain"}
def set_track_metadata(self, track_id: str, fields: dict) -> None:
with self._lock:
@@ -544,6 +548,62 @@ class TraktorStore:
self._journal.record("track", "set", track_id, "key", before, entry.info.key)
self.dirty = True
# ---- track colour -----------------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""INFO@COLOR (see `track_palette`). Cleared = the attribute removed, as
every never-coloured entry has it; what Traktor itself leaves after
"None" (absent, or `COLOR="0"`) is not yet measured (kit T1 step 3)."""
code = track_palette.code_for(color)
if color is not None and code is None:
raise InvalidCommand(f"Not a track colour: {color!r}")
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
before = entry.info.color if entry.info is not None else None
if before == code:
return
if entry.info is None:
entry.info = Infotype()
entry.info.color = code
self._journal.record("track", "set", track_id, "color", before, code)
self.dirty = True
# ---- auto gain --------------------------------------------------------
def set_auto_gain(self, track_id: str, loudness) -> None:
"""`<LOUDNESS>` from a measurement (see `gain`). The element is replaced
whole; a write of the values already there leaves the store clean."""
peak, perceived, analyzed = gain.values(loudness)
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
old = entry.loudness
before = None if old is None else (old.peak_db, old.perceived_db, old.analyzed_db)
after = (peak, perceived, analyzed)
if before == after:
return
entry.loudness = Loudnesstype(peak_db=peak, perceived_db=perceived, analyzed_db=analyzed)
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.
@@ -598,6 +658,7 @@ class TraktorStore:
# attribute at all rather than a zero.
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
playtime=getattr(track, "length", None) or None,
color=track_palette.code_for(getattr(track, "color", None)),
)
album = None
if getattr(track, "album", None):
@@ -1187,9 +1248,19 @@ class TraktorStore:
self.dirty = True
def set_lock(self, track_id: str, locked: bool) -> None:
"""Lock or unlock a track's grid.
Locking writes what Traktor 4.5 writes (measured 2026-10-19):
``LOCK="1"`` plus ``LOCK_MODIFICATION_TIME``, an ISO time in UTC to the
second. What Traktor leaves on UNLOCK is unmeasured, so unlocking only
removes ``LOCK``, as it always has.
"""
with self._lock:
entry = self._entry_or_raise(track_id)
entry.lock = 1 if locked else None
if locked:
entry.lock_modification_time = (
datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S"))
self._note("lock", "on" if locked else "off", track_id)
self.dirty = True
@@ -11,8 +11,12 @@ stores — grid markers, cues, loops — sits
samples LATER than the same moment in the decoded audio: ~51.2 ms at 44.1 kHz,
~47.0 ms at 48 kHz. The rule is in SAMPLES. An MP3 WITHOUT a header is decoded
the same way by both sides (nothing to skip, nothing to trim), so its offset is
0 — as is every other format: WAV, AIFF, FLAC and AAC (Traktor honours the MP4
edit list) line up to the sample.
0 — as is every other format: WAV, AIFF, FLAC and AAC line up to the sample.
AAC with a caveat this module cannot fix: Traktor on macOS honours the MP4
edit list, Traktor on WINDOWS skips a fixed 1024 samples instead (2026-10-19:
Apple-encoded files, priming 2112, sat ~25 ms early on a PC; 1024-primed ones
did not). One collection serves both, so the offset stays 0 and Konduktor
writes its own stem files at 1024 (`stem_file.default_encoder`).
Measured 2026-09-30 in Traktor 4.5 ("kit 4", see the stem-conversion discussion
log): hotcues Konduktor wrote on a synthetic kick, blinded, landed on it only
@@ -0,0 +1,59 @@
"""Traktor's TRACK colours — `INFO@COLOR`, an integer.
MEASURED in Traktor 4.5 (kit T1, 2026-10-17,
`.claude/discussions/discuss-track-colour-2026-10-17.md`) by colouring one track
per entry of the browser's Color menu, in its order: 1 Red · 2 Orange ·
3 Yellow · 4 Green · 5 Blue · 6 Violet · 7 Magenta. Traktor keeps it in the
collection only — it does not tag the audio file.
Mapped to the generic colours BY NAME (decided 2026-10-17): Violet is `purple`,
Magenta `pink`, and Blue is `blue` even though it LOOKS like rekordbox's Aqua —
the name is the DJ's category. Traktor has no seventh-and-a-half colour, so
`aqua` arriving from rekordbox is stored as Blue.
The RGB values are DISPLAY colours only — nothing stores them. They were
sampled from the colour dots in Traktor's own browser (a screenshot).
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
#: What `capabilities.tracks.colors` offers; code - 1 -> swatch, menu order.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color="red", hex="#FB413E", label="Red"),
ColorSwatch(color="orange", hex="#F79525", label="Orange"),
ColorSwatch(color="yellow", hex="#F9F918", label="Yellow"),
ColorSwatch(color="green", hex="#52FA52", label="Green"),
ColorSwatch(color="blue", hex="#1ACBFA", label="Blue"),
ColorSwatch(color="purple", hex="#B26CFA", label="Violet"),
ColorSwatch(color="pink", hex="#FA51EB", label="Magenta"),
]
#: Generic colours Traktor has no swatch of its own for.
_FOLDED: dict[str, int] = {"aqua": 5}
def _swatch(code: int | None) -> ColorSwatch | None:
return SWATCHES[code - 1] if isinstance(code, int) and 1 <= code <= len(SWATCHES) else None
def color_for(code: int | None) -> TrackColor | None:
"""The generic colour for a stored code; None for absent, 0 or unknown."""
s = _swatch(code)
return s.color if s else None
def hex_for(code: int | None) -> str | None:
"""Traktor's display colour for a stored code; None when uncoloured."""
s = _swatch(code)
return s.hex if s else None
def code_for(color: TrackColor | str | None) -> int | None:
"""The `INFO@COLOR` to store for a generic colour; None for none."""
if color is None:
return None
for i, s in enumerate(SWATCHES, start=1):
if s.color == color:
return i
return _FOLDED.get(color)
+88 -3
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:
@@ -140,6 +158,9 @@ class AppState:
if saved:
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
self.path, self.adapter = path, adapter
# A measurement the adapter makes while adding a track (rekordbox's add
# writes the auto gain from one) is kept for the Mastering columns.
adapter.on_loudness = self._keep_loudness
caps = adapter.capabilities()
# No sidecar beside a removable library: writing to a user's USB stick to
# satisfy Konduktor's own bookkeeping is not a trade worth making. Those
@@ -156,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)
@@ -170,12 +192,33 @@ 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
try:
self.loudness.put(loudness_store.file_facts(path), values)
except OSError:
log.warning("could not store the loudness of %s", path, exc_info=True)
def _release_previous(self) -> None:
previous = self.adapter
# Leaving a library discards its unsaved edits (the UI has confirmed), so
# 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()
@@ -189,6 +232,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 +255,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
@@ -227,8 +272,29 @@ 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
# 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.
@@ -251,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()
@@ -280,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
+654
View File
@@ -0,0 +1,654 @@
"""Lossless gain for AAC-LC in an MP4 (an `.m4a`, a stem file): aacgain's edit.
Every channel of every AAC frame carries an 8-bit `global_gain`, the start of
its scalefactors: the decoder scales that channel's spectrum by 2^(g/4), so
adding n to every `global_gain` scales the decoded audio by EXACTLY 2^(n/4)
(1.505 dB per step) with no re-encode — like MP3's frame-gain edit
(`level_edit`), and in the same steps. Spectral scalefactors, the noise
energies of PNS and the intensity positions are all coded RELATIVE to it (the
first two from it, intensity as a ratio between channels), so they follow.
Finding the field is the hard part: a channel pair holds the SECOND channel's
`global_gain` after the whole first channel — its section data, scalefactors,
TNS and Huffman-coded spectrum — so each frame is WALKED, never decoded:
codewords are looked up only for their lengths (and, in the unsigned books,
the values that decide sign bits and escapes). `aac_tables` holds the
standard's codebooks. The walk runs in numba (a dependency already, through
librosa): ~10 M codewords for a stereo track.
The walk proves itself on every frame: a raw_data_block must end in its last
byte (an END element, then byte alignment), so a mis-parse is caught, and the
whole file is refused, rather than written. `level_edit.verify` decodes the
result on top. What is refused (`AacGainError`): anything but AAC-LC
(HE-AAC/SBR, PS, LTP, Main, SSR), 960-sample frames, a coupling channel or a
program config element, a scalefactor pushed out of 0..255.
Measured 2026-10-19 on FFmpeg- and Apple-encoded files and commercial stem
files (`test_aac_gain.py`, and the spike numbers in the gain discussion).
"""
from __future__ import annotations
import struct
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from . import aac_tables as T
#: A stem file's streams all share one ladder: one step = 2^(1/4) in amplitude.
STEP_DB = 20.0 * np.log10(2.0 ** 0.25)
class AacGainError(ValueError):
"""A file this edit will not touch; the message is user-facing."""
# ---- the MP4 side: where every AAC frame of every audio track is ------------------
@dataclass
class AacTrack:
"""One audio track: its config and each frame's byte range in the file."""
index: int # the audio stream's order among the file's audio tracks
object_type: int # 2 = AAC-LC
sf_index: int
channels: int
offsets: np.ndarray # int64, each sample's file offset
sizes: np.ndarray # int64
_CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"udta"}
def _boxes(data: bytes, start: int, end: int):
pos = start
while pos + 8 <= end:
size, kind = struct.unpack_from(">I4s", data, pos)
head = 8
if size == 1:
size = struct.unpack_from(">Q", data, pos + 8)[0]
head = 16
elif size == 0:
size = end - pos
if size < head or pos + size > end:
raise AacGainError("not an MP4 file this edit can read (a broken box)")
yield kind, pos + head, pos + size
pos += size
def _find(data: bytes, start: int, end: int, kind: bytes):
for k, s, e in _boxes(data, start, end):
if k == kind:
return s, e
return None
def _descriptor(data: bytes, pos: int) -> tuple[int, int, int]:
"""(tag, body start, body end) of an MPEG-4 descriptor at `pos`."""
tag = data[pos]
pos += 1
size = 0
for _ in range(4):
b = data[pos]
pos += 1
size = (size << 7) | (b & 0x7F)
if not b & 0x80:
break
return tag, pos, pos + size
def _audio_specific_config(data: bytes, s: int, e: int) -> tuple[int, int, int, bool]:
"""(object type, sampling-frequency index, channel config, has SBR) from
an `esds` box body (version/flags first)."""
tag, ds, de = _descriptor(data, s + 4)
if tag != 3:
raise AacGainError("an MP4 audio track without an ES descriptor")
pos = ds + 2
flags = data[pos]
pos += 1
if flags & 0x80:
pos += 2
if flags & 0x40:
pos += 1 + data[pos]
if flags & 0x20:
pos += 2
while pos < de:
tag, bs, be = _descriptor(data, pos)
if tag == 4: # DecoderConfigDescriptor
if data[bs] != 0x40:
raise AacGainError("not an AAC track")
p = bs + 13
while p < be:
t2, s2, e2 = _descriptor(data, p)
if t2 == 5:
return _parse_asc(data[s2:e2])
p = e2
pos = be
raise AacGainError("an AAC track with no AudioSpecificConfig")
def _parse_asc(asc: bytes) -> tuple[int, int, int, bool]:
bits = int.from_bytes(asc, "big")
n = len(asc) * 8
pos = 0
def read(k: int) -> int:
nonlocal pos
v = (bits >> (n - pos - k)) & ((1 << k) - 1)
pos += k
return v
aot = read(5)
if aot == 31:
aot = 32 + read(6)
sfi = read(4)
if sfi == 15:
freq = read(24)
rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]
sfi = min(range(len(rates)), key=lambda i: abs(rates[i] - freq))
channels = read(4)
sbr = aot in (5, 29)
if aot == 2:
frame_length_flag = read(1)
if frame_length_flag:
raise AacGainError("AAC with 960-sample frames is not handled")
if read(1): # dependsOnCoreCoder
read(14)
read(1) # extensionFlag
# Implicit SBR signalling (a sync extension after the GA config) = HE-AAC.
if n - pos >= 16 and read(11) == 0x2B7 and read(5) == 5 and n - pos >= 1 and read(1):
sbr = True
return aot, sfi, channels, sbr
def tracks(path: Path | str) -> list[AacTrack]:
"""Every audio track's AAC frames, in the file's audio-stream order."""
data = Path(path).read_bytes()
moov = _find(data, 0, len(data), b"moov")
if moov is None:
raise AacGainError("not an MP4 file")
out = []
for kind, ts, te in _boxes(data, *moov):
if kind != b"trak":
continue
mdia = _find(data, ts, te, b"mdia")
hdlr = _find(data, *mdia, b"hdlr") if mdia else None
if hdlr is None or data[hdlr[0] + 8:hdlr[0] + 12] != b"soun":
continue
stbl = _find(data, *_find(data, *mdia, b"minf"), b"stbl")
stsd = _find(data, *stbl, b"stsd")
entry = stsd[0] + 8
esize, ekind = struct.unpack_from(">I4s", data, entry)
if ekind != b"mp4a":
raise AacGainError(f"an audio track in {ekind.decode('latin-1')}, not AAC")
esds = _find(data, entry + 36, entry + esize, b"esds")
if esds is None:
raise AacGainError("an AAC track with no esds")
aot, sfi, channels, sbr = _audio_specific_config(data, *esds)
if aot != 2 or sbr:
raise AacGainError("only AAC-LC can be changed losslessly (this is HE-AAC or another profile)")
stsz = _find(data, *stbl, b"stsz")
uniform, count = struct.unpack_from(">II", data, stsz[0] + 4)
sizes = (np.full(count, uniform, np.int64) if uniform else
np.frombuffer(data, ">u4", count, stsz[0] + 12).astype(np.int64))
co = _find(data, *stbl, b"stco")
if co is not None:
n = struct.unpack_from(">I", data, co[0] + 4)[0]
chunks = np.frombuffer(data, ">u4", n, co[0] + 8).astype(np.int64)
else:
co = _find(data, *stbl, b"co64")
n = struct.unpack_from(">I", data, co[0] + 4)[0]
chunks = np.frombuffer(data, ">u8", n, co[0] + 8).astype(np.int64)
stsc = _find(data, *stbl, b"stsc")
m = struct.unpack_from(">I", data, stsc[0] + 4)[0]
runs = np.frombuffer(data, ">u4", m * 3, stsc[0] + 8).reshape(m, 3).astype(np.int64)
offsets = np.empty(count, np.int64)
i = 0
for r in range(m):
first = runs[r, 0] - 1
last = (runs[r + 1, 0] - 1) if r + 1 < m else len(chunks)
per = runs[r, 1]
for c in range(first, last):
pos = chunks[c]
for _ in range(per):
if i >= count:
break
offsets[i] = pos
pos += sizes[i]
i += 1
if i != count:
raise AacGainError("an MP4 sample table this edit cannot follow")
out.append(AacTrack(len(out), aot, sfi, channels, offsets, sizes))
if not out:
raise AacGainError("no AAC audio track")
return out
# ---- the walk ---------------------------------------------------------------------
def _lut(codes, bits, width: int) -> np.ndarray:
"""A lookup on the next `width` bits: (length << 16) | index, 0 = invalid."""
lut = np.zeros(1 << width, np.int32)
for idx, (c, b) in enumerate(zip(codes, bits)):
lo = c << (width - b)
lut[lo:lo + (1 << (width - b))] = (b << 16) | idx
return lut
_SPEC = np.stack([_lut(c, b, 16) for c, b in T.SPECTRAL])
_SF = _lut(T.SF_CODES, T.SF_BITS, 19)
_LONG = np.zeros((13, 64), np.int32)
_SHORT = np.zeros((13, 32), np.int32)
_NLONG = np.zeros(13, np.int32)
_NSHORT = np.zeros(13, np.int32)
for _i in range(13):
_LONG[_i, :len(T.SWB_LONG[_i])] = T.SWB_LONG[_i]
_SHORT[_i, :len(T.SWB_SHORT[_i])] = T.SWB_SHORT[_i]
_NLONG[_i] = len(T.SWB_LONG[_i]) - 1
_NSHORT[_i] = len(T.SWB_SHORT[_i]) - 1
try:
from numba import njit
except ImportError: # pragma: no cover — numba ships with librosa
def njit(*_a, **_k):
return lambda f: f
@njit(cache=True)
def _read(buf, pos, n):
v = 0
for i in range(n):
p = pos + i
v = (v << 1) | ((buf[p >> 3] >> (7 - (p & 7))) & 1)
return v
@njit(cache=True)
def _peek(buf, pos, n, end):
v = 0
for i in range(n):
p = pos + i
bit = 0
if p < end:
bit = (buf[p >> 3] >> (7 - (p & 7))) & 1
v = (v << 1) | bit
return v
@njit(cache=True)
def _walk(buf, offsets, sizes, sfi, spec, sflut, long_swb, short_swb, nlong, nshort):
"""Every frame's global_gain bit positions; out[0] = status (0 ok, else the
failing frame + 1, negated by reason), plus the scalefactor range."""
n_frames = offsets.shape[0]
gpos = np.empty(n_frames * 8, np.int64)
ng = 0
sf_lo = 1 << 30
sf_hi = -(1 << 30)
nz_lo = 1 << 30
nz_hi = -(1 << 30)
sfb_cb = np.zeros((8, 64), np.int32)
group_len = np.zeros(8, np.int32)
status = 0
for f in range(n_frames):
start = offsets[f] * 8
end = start + sizes[f] * 8
pos = start
ok = True
common_ws = 0
common_max_sfb = 0
common_groups = 0
while ok:
if pos + 3 > end:
ok = False
break
elem = _read(buf, pos, 3)
pos += 3
if elem == 7: # END
break
if elem == 0 or elem == 3 or elem == 1: # SCE, LFE, CPE
pos += 4 # element_instance_tag
n_ch = 1
common = 0
if elem == 1:
n_ch = 2
common = _read(buf, pos, 1)
pos += 1
if common:
_r = _read(buf, pos, 1) # reserved
common_ws = _read(buf, pos + 1, 2)
pos += 4
if common_ws == 2:
common_max_sfb = _read(buf, pos, 4)
grouping = _read(buf, pos + 4, 7)
pos += 11
common_groups = 1
group_len[:] = 0
group_len[0] = 1
for b in range(6, -1, -1):
if (grouping >> b) & 1:
group_len[common_groups - 1] += 1
else:
group_len[common_groups] = 1
common_groups += 1
else:
common_max_sfb = _read(buf, pos, 6)
pos += 6
if _read(buf, pos, 1): # predictor data (not LC)
status = -(f + 1)
return gpos[:0], status, 0, 0, 0, 0
pos += 1
common_groups = 1
group_len[0] = 1
ms = _read(buf, pos, 2)
pos += 2
if ms == 1:
pos += common_groups * common_max_sfb
for ch in range(n_ch):
gpos[ng] = pos
ng += 1
gg = _read(buf, pos, 8)
pos += 8
if common:
ws = common_ws
max_sfb = common_max_sfb
groups = common_groups
else:
pos += 1
ws = _read(buf, pos, 2)
pos += 3
if ws == 2:
max_sfb = _read(buf, pos, 4)
grouping = _read(buf, pos + 4, 7)
pos += 11
groups = 1
group_len[:] = 0
group_len[0] = 1
for b in range(6, -1, -1):
if (grouping >> b) & 1:
group_len[groups - 1] += 1
else:
group_len[groups] = 1
groups += 1
else:
max_sfb = _read(buf, pos, 6)
pos += 6
if _read(buf, pos, 1):
status = -(f + 1)
return gpos[:0], status, 0, 0, 0, 0
pos += 1
groups = 1
group_len[0] = 1
short = ws == 2
nswb = nshort[sfi] if short else nlong[sfi]
if max_sfb > nswb:
ok = False
break
# section_data
sbits = 3 if short else 5
esc = (1 << sbits) - 1
for g in range(groups):
k = 0
while k < max_sfb:
cb = _read(buf, pos, 4)
pos += 4
if cb == 12:
ok = False
break
length = 0
while True:
inc = _read(buf, pos, sbits)
pos += sbits
length += inc
if inc != esc:
break
if pos > end:
break
if k + length > max_sfb or pos > end:
ok = False
break
for s in range(k, k + length):
sfb_cb[g, s] = cb
k += length
if not ok:
break
if not ok:
break
# scale_factor_data
sf = gg
noise = gg - 90
noise_first = True
for g in range(groups):
for s in range(max_sfb):
cb = sfb_cb[g, s]
if cb == 0:
continue
if cb == 13 and noise_first:
noise_first = False
noise += _read(buf, pos, 9) - 256
pos += 9
if noise < nz_lo:
nz_lo = noise
if noise > nz_hi:
nz_hi = noise
continue
e = sflut[_peek(buf, pos, 19, end)]
if e == 0:
ok = False
break
pos += e >> 16
delta = (e & 0xFFFF) - 60
if cb == 13:
noise += delta
if noise < nz_lo:
nz_lo = noise
if noise > nz_hi:
nz_hi = noise
elif cb == 14 or cb == 15:
pass # intensity: relative between channels
else:
sf += delta
if sf < sf_lo:
sf_lo = sf
if sf > sf_hi:
sf_hi = sf
if not ok:
break
if not ok:
break
# pulse_data
if _read(buf, pos, 1):
pos += 1
if short:
ok = False
break
npulse = _read(buf, pos, 2)
pos += 8 + (npulse + 1) * 9
else:
pos += 1
# tns_data
if _read(buf, pos, 1):
pos += 1
nwin = 8 if short else 1
for w in range(nwin):
nfilt = _read(buf, pos, 1 if short else 2)
pos += 1 if short else 2
if nfilt:
res = _read(buf, pos, 1)
pos += 1
for _q in range(nfilt):
pos += 4 if short else 6
order = _read(buf, pos, 3 if short else 5)
pos += 3 if short else 5
if order:
pos += 1
compress = _read(buf, pos, 1)
pos += 1
pos += order * (3 + res - compress)
else:
pos += 1
# gain_control_data (SSR only)
if _read(buf, pos, 1):
ok = False
break
pos += 1
# spectral_data
for g in range(groups):
glen = group_len[g]
for s in range(max_sfb):
cb = sfb_cb[g, s]
if cb == 0 or cb >= 13:
continue
if short:
width = short_swb[sfi, s + 1] - short_swb[sfi, s]
else:
width = long_swb[sfi, s + 1] - long_swb[sfi, s]
dim = 4 if cb <= 4 else 2
n_words = glen * width // dim
for _w in range(n_words):
e = spec[cb - 1, _peek(buf, pos, 16, end)]
if e == 0:
ok = False
break
pos += e >> 16
idx = e & 0xFFFF
if cb == 3 or cb == 4:
v0 = idx // 27
v1 = (idx // 9) % 3
v2 = (idx // 3) % 3
v3 = idx % 3
pos += (v0 != 0) + (v1 != 0) + (v2 != 0) + (v3 != 0)
elif cb >= 7:
mod = 8 if cb <= 8 else (13 if cb <= 10 else 17)
y = idx // mod
z = idx % mod
pos += (y != 0) + (z != 0)
if cb == 11:
for v in (y, z):
if v == 16:
nesc = 0
while _read(buf, pos, 1) == 1:
pos += 1
nesc += 1
if nesc > 8:
break
pos += 1
if nesc > 8:
ok = False
break
pos += nesc + 4
if pos > end or not ok:
ok = False
break
if not ok:
break
if not ok:
break
if not ok:
break
if not ok:
break
elif elem == 4: # DSE
pos += 4
align = _read(buf, pos, 1)
pos += 1
count = _read(buf, pos, 8)
pos += 8
if count == 255:
count += _read(buf, pos, 8)
pos += 8
if align:
pos = start + ((pos - start + 7) // 8) * 8
pos += count * 8
elif elem == 6: # FIL
count = _read(buf, pos, 4)
pos += 4
if count == 15:
count += _read(buf, pos, 8) - 1
pos += 8
if count > 0:
ext = _read(buf, pos, 4)
if ext == 13 or ext == 14: # SBR: HE-AAC
status = -(f + 1)
return gpos[:0], status, 0, 0, 0, 0
pos += count * 8
else: # CCE, PCE: not handled
ok = False
break
if pos > end:
ok = False
# The block must end in its last byte: END, then byte alignment.
if not ok or pos > end or end - pos >= 8:
status = f + 1
return gpos[:0], status, 0, 0, 0, 0
return gpos[:ng], 0, sf_lo, sf_hi, nz_lo, nz_hi
@dataclass
class Scan:
"""Where every global_gain is, per audio track, and how far it may move."""
tracks: list[AacTrack]
positions: list[np.ndarray] # bit offsets in the file, per track
min_step: int # the most negative n every track allows
max_step: int
def scan(path: Path | str) -> Scan:
path = Path(path)
found = tracks(path)
buf = np.frombuffer(path.read_bytes(), np.uint8)
positions = []
lo_all, hi_all = -255, 255
for t in found:
if t.sf_index > 12:
raise AacGainError("an AAC sampling rate this edit does not know")
gpos, status, sf_lo, sf_hi, nz_lo, nz_hi = _walk(
buf, t.offsets, t.sizes, t.sf_index, _SPEC, _SF, _LONG, _SHORT, _NLONG, _NSHORT)
if status < 0:
raise AacGainError("only AAC-LC can be changed losslessly (this frame uses another tool)")
if status > 0:
raise AacGainError(f"an AAC frame this edit cannot follow (frame {status - 1} of stream {t.index})")
g = _read_all(buf, gpos)
if gpos.size:
lo_all = max(lo_all, -int(g.min()), -int(sf_lo) if sf_lo < (1 << 29) else -255)
hi_all = min(hi_all, 255 - int(g.max()), 255 - int(sf_hi) if sf_hi > -(1 << 29) else 255)
if nz_lo < (1 << 29):
lo_all = max(lo_all, -155 - int(nz_lo))
hi_all = min(hi_all, 100 - int(nz_hi))
positions.append(gpos)
return Scan(found, positions, lo_all, hi_all)
def _read_all(buf: np.ndarray, gpos: np.ndarray) -> np.ndarray:
"""The 8-bit values at each position (vectorised: a 16-bit window)."""
byte = gpos >> 3
shift = gpos & 7
word = (buf[byte].astype(np.int64) << 8) | buf[np.minimum(byte + 1, buf.size - 1)].astype(np.int64)
return (word >> (8 - shift)) & 0xFF
def apply(src: Path | str, dst: Path | str, steps: int, scanned: Scan | None = None) -> None:
"""Write `src` with every audio track's frames `steps` gain steps louder
(negative: quieter) to `dst`, which must not exist. Same size, every byte
outside the global_gain fields identical."""
src, dst = Path(src), Path(dst)
if dst.exists():
raise AacGainError(f"{dst.name} already exists")
found = scanned or scan(src)
if not found.min_step <= steps <= found.max_step:
raise AacGainError(f"{steps:+d} steps would take the AAC scalefactors out of range")
data = np.frombuffer(src.read_bytes(), np.uint8).copy()
for gpos in found.positions:
values = _read_all(data, gpos) + steps
byte = gpos >> 3
shift = gpos & 7
hi_mask = 0xFF >> shift # the field's bits in the first byte
lo_mask = (0xFF << (8 - shift)) & 0xFF # …and in the second
first = (values >> shift) & 0xFF
second = (values << (8 - shift)) & 0xFF
data[byte] = (data[byte] & ~hi_mask & 0xFF) | (first & hi_mask)
nxt = byte + 1
has = shift > 0
data[nxt[has]] = (data[nxt[has]] & ~lo_mask[has] & 0xFF) | (second[has] & lo_mask[has])
dst.write_bytes(data.tobytes())
+301
View File
@@ -0,0 +1,301 @@
"""The AAC-LC bitstream tables `aac_gain` needs to WALK a raw_data_block
(never to decode audio): the eleven spectral Huffman codebooks and the
scalefactor codebook of ISO/IEC 14496-3 (subpart 4, Annex 4.A), and the
scalefactor-band offsets per sampling-frequency index.
Generated, not hand-typed: extracted from FFmpeg n7.1 `libavcodec/aactab.c`
(LGPL-2.1-or-later; the values are the standard's own) on 2026-10-19, and
checked when generated that every codebook is a complete prefix code (Kraft
sum exactly 1) with no duplicate codewords. Do not edit by hand.
"""
CODES1 = (
2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491,
108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23,
111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484,
107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011,
106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503,
2036,
)
BITS1 = (
11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9,
7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, 7, 5,
7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9,
7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, 11, 9, 11, 10,
7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9,
11,
)
CODES2 = (
499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110,
40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10,
39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100,
30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238,
34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109,
502,
)
BITS2 = (
9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7,
6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, 6, 5,
6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7,
6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, 8, 7, 9, 8,
6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7,
9,
)
CODES3 = (
0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493,
487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117,
1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188,
242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241,
1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089,
32762,
)
BITS3 = (
1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9,
9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, 6, 7,
10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13,
8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, 13, 14, 16, 8,
10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12,
15,
)
CODES4 = (
7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240,
112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4,
229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014,
110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233,
109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013,
2044,
)
BITS4 = (
4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8,
7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, 4, 4,
8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10,
7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, 11, 10, 12, 8,
7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10,
11,
)
CODES5 = (
8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006,
2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8,
25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239,
24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086,
2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091,
8190,
)
BITS5 = (
13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10,
11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, 5, 4,
5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8,
5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, 9, 10, 11, 12,
11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12,
13,
)
CODES6 = (
2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240,
486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4,
6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43,
7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016,
484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019,
2044,
)
BITS6 = (
11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8,
9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, 4, 4,
4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6,
4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, 6, 8, 9, 10,
9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10,
11,
)
CODES7 = (
0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501,
54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018,
243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044,
1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095,
)
BITS7 = (
1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9,
6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, 10, 10,
8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11,
10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, 11, 11, 12, 12,
)
CODES8 = (
14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248,
15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250,
113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020,
504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023,
)
BITS8 = (
5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8,
5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, 8, 8,
7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10,
9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, 9, 9, 9, 10,
)
CODES9 = (
0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53,
114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481,
975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994,
2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071,
8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485,
983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009,
4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059,
8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371,
16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072,
2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063,
8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767,
)
BITS9 = (
1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6,
7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, 8, 9,
10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11,
11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12,
13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9,
10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 11, 10, 10, 11, 11,
12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12,
13, 13, 14, 13, 14, 11, 10, 11, 11, 12, 12, 12, 12, 13, 13, 14,
14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12,
11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 13, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15,
)
CODES10 = (
34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1,
9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40,
91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221,
460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989,
1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94,
90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215,
219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470,
977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022,
2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034,
974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993,
996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095,
)
BITS10 = (
6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4,
5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, 6, 6,
7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8,
9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 10,
10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7,
7, 7, 7, 8, 8, 9, 9, 9, 10, 10, 11, 9, 8, 8, 8, 8,
8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9,
10, 10, 10, 11, 11, 10, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11,
11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11,
10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 11, 10, 10, 10,
10, 10, 10, 11, 11, 12, 12, 12, 12,
)
CODES11 = (
0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094,
910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973,
2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918,
958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929,
913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444,
927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442,
451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431,
447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420,
440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419,
433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429,
435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434,
439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906,
452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917,
925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446,
448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957,
924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093,
988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413,
450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399,
4,
)
BITS11 = (
4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12,
10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, 10, 10,
11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10,
10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10,
10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9,
9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9,
9, 10, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 9, 9,
9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9,
9, 10, 10, 10, 10, 10, 10, 11, 8, 10, 9, 9, 9, 9, 9, 9,
9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9,
9, 10, 10, 10, 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10,
9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9,
9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12,
10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 9,
9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
5,
)
SF_CODES = (
262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279,
524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759,
16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015,
1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27,
57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085,
4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253,
524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256,
524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275,
)
SF_BITS = (
18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, 15, 15,
14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10,
10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, 1, 4, 4, 5,
6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12,
12, 13, 13, 13, 14, 14, 16, 15, 16, 15, 18, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19,
)
SWB_1024_96 = (
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64,
72, 80, 88, 96, 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384,
448, 512, 576, 640, 704, 768, 832, 896, 960, 1024,
)
SWB_1024_64 = (
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64,
72, 80, 88, 100, 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384,
424, 464, 504, 544, 584, 624, 664, 704, 744, 784, 824, 864, 904, 944, 984, 1024,
)
SWB_1024_48 = (
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80,
88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384,
416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896,
928, 1024,
)
SWB_1024_32 = (
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80,
88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384,
416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896,
928, 960, 992, 1024,
)
SWB_1024_24 = (
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76,
84, 92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284,
308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024,
)
SWB_1024_16 = (
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136,
148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424,
456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024,
)
SWB_1024_8 = (
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188,
204, 220, 236, 252, 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544,
580, 620, 664, 712, 764, 820, 880, 944, 1024,
)
SWB_128_96 = (
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
)
SWB_128_48 = (
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
)
SWB_128_24 = (
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
)
SWB_128_16 = (
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
)
SWB_128_8 = (
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
)
SPECTRAL = ((CODES1, BITS1), (CODES2, BITS2), (CODES3, BITS3), (CODES4, BITS4), (CODES5, BITS5), (CODES6, BITS6), (CODES7, BITS7), (CODES8, BITS8), (CODES9, BITS9), (CODES10, BITS10), (CODES11, BITS11))
#: Per sampling-frequency index (0 = 96 kHz … 12 = 7.35 kHz), as FFmpeg's ff_swb_offset_1024/_128.
SWB_LONG = (SWB_1024_96, SWB_1024_96, SWB_1024_64, SWB_1024_48, SWB_1024_48, SWB_1024_32, SWB_1024_24, SWB_1024_24, SWB_1024_16, SWB_1024_16, SWB_1024_16, SWB_1024_8, SWB_1024_8)
SWB_SHORT = (SWB_128_96, SWB_128_96, SWB_128_96, SWB_128_48, SWB_128_48, SWB_128_48, SWB_128_24, SWB_128_24, SWB_128_16, SWB_128_16, SWB_128_16, SWB_128_8, SWB_128_8)
+41 -3
View File
@@ -22,7 +22,8 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol, runtime_checkable
from .capabilities import Capabilities
from .capabilities import Capabilities, TrackColor
from .loudness import Loudness
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping
from .relocate import PathGroup
@@ -110,13 +111,16 @@ class PreparedAnalysis:
its own copy and the result travels with the track. `measured` is a
`core.waveform.Analysis` measured with the file's own time-base lead,
`markers` the detected grid (empty: none found) and `key` the detected
`core.key_detect.KeyResult` (None: not asked for, or none found). Absent,
the adapter decodes as before.
`core.key_detect.KeyResult` (None: not asked for, or none found), and
`loudness` the file's `core.loudness.Loudness` where the platform keeps an
auto gain (None: not asked for, or not measurable). Absent, the adapter
decodes as before.
"""
measured: object
markers: list = field(default_factory=list)
key: object | None = None
loudness: object | None = None
@dataclass
@@ -181,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.
@@ -287,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": ...
@@ -296,6 +319,15 @@ class LibraryAdapter(Protocol):
# analysis writes. Each platform renders it in its own notation (and its own
# analysed-key field, where it has one). Gated on `tracks.key_writable`.
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ...
# The track's colour tag (None clears it), mapped onto the platform's own
# palette by name. Gated on `tracks.colors` being non-empty.
def set_track_color(self, track_id: str, color: TrackColor | None) -> Track | None: ...
# The DJ app's auto gain, computed BY THE ADAPTER from the track's measured
# loudness (the platform's reference level is platform knowledge: Traktor
# levels to -9.2 LUFS, rekordbox to -10, both measured 2026-10-19). Writes
# whatever is there; whether to (fill vs replace) is the caller's call.
# Gated on `tracks.auto_gain`.
def set_auto_gain(self, track_id: str, loudness: Loudness) -> Track | None: ...
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
@@ -317,6 +349,12 @@ class LibraryAdapter(Protocol):
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
# Make a track's prep EXACTLY `cues` — its hot cues, memory cues, grid and
# lock — placed as `add_tracks` would place them on a new entry (a taken or
# out-of-bank pad moves, else becomes a memory cue). What was there goes
# first, grid companions included. A push into a DJ app's library uses it
# to bring a track it added earlier up to date with the source.
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues: ...
# ---- commands: memory cues --------------------------------------------
# Cues on no pad, addressed by `CuePoint.id`. Gated on `cues.memory_cues`.
+13 -3
View File
@@ -18,9 +18,11 @@ from .model import GridMarker
def prepare(path: Path, *, lead: float, detect: bool = True,
detect_key: bool = False) -> PreparedAnalysis:
detect_key: bool = False, measure_loudness: bool = False) -> PreparedAnalysis:
"""Decode `path` once: its waveform at `lead`, and (with `detect`) a grid,
(with `detect_key`) a key."""
(with `detect_key`) a key. `measure_loudness` adds the file's loudness —
a decode of its own, at the file's rate and channels (BS.1770 cannot use
the analysis decode; see `core.loudness`), ~1 s a track."""
from . import grid_detect, waveform
samples = waveform.decode(Path(path))
@@ -40,7 +42,15 @@ def prepare(path: Path, *, lead: float, detect: bool = True,
key = key_detect.detect_key_samples(samples, waveform.SR)
except Exception: # noqa: BLE001 - a missing key is not worth failing an add over
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
return PreparedAnalysis(measured=measured, markers=markers, key=key)
measured_loudness = None
if measure_loudness:
from . import loudness
try:
measured_loudness = loudness.measure_file(path)
except Exception: # noqa: BLE001 - a missing gain is not worth failing an add over
logging.getLogger(__name__).warning("loudness measurement failed", exc_info=True)
return PreparedAnalysis(measured=measured, markers=markers, key=key, loudness=measured_loudness)
def with_key(track, key):
+56
View File
@@ -0,0 +1,56 @@
"""Is a DJ app running on this computer right now?
Asked before a push writes into the app's own library, which must not happen
under a running app: Traktor writes `collection.nml` back when it QUITS, so a
push made while it runs is silently undone, and rekordbox holds `master.db`
open. Answered from the process list (`psutil`), by executable name:
* rekordbox — exactly `rekordbox` (pyrekordbox's own test, minus `.exe`). Its
helpers (`rekordboxAgent`, `rb_http_server`, `edb_streamd`) are other names,
and `rekordboxAgent` runs whenever rekordbox is installed, so a prefix test
would refuse forever.
* Traktor — any name starting with `traktor`: the macOS executable is
`Traktor Pro 4` (read from the 4.5 bundle, 2026-10-20); the Windows one is
not measured, and a prefix covers `Traktor.exe` and `Traktor Pro 4.exe`
alike. Konduktor's own processes start with `konduktor`, not `traktor`.
A process list that cannot be read answers "not running": this is a guard
against a mistake, and refusing every push on a locked-down machine would make
the feature unusable rather than safe.
"""
from __future__ import annotations
import logging
import os
log = logging.getLogger(__name__)
def _names() -> list[str]:
try:
import psutil
except ImportError: # the server image does not ship it, and never pushes
return []
out = []
try:
for proc in psutil.process_iter(["name"]):
name = proc.info.get("name")
if name:
out.append(os.path.splitext(name)[0].lower())
except Exception as ex: # noqa: BLE001 — see the module docstring
log.warning("could not read the process list: %s", ex)
return out
def _matches(platform: str, name: str) -> bool:
if platform == "traktor":
return name.startswith("traktor")
if platform == "rekordbox":
return name == "rekordbox"
return False
def running(platforms: list[str]) -> set[str]:
"""Which of `platforms` (platform ids) have their app running now."""
names = _names()
return {p for p in platforms if any(_matches(p, n) for n in names)}
+23
View File
@@ -36,6 +36,20 @@ CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
MediaKind = Literal["audio", "stem", "video"]
PlaylistKind = Literal["folder", "playlist", "smart"]
# A track's colour tag, as a platform-neutral IDENTITY — what crosses between
# libraries. Each adapter maps its own codes to and from these BY NAME (decided
# 2026-10-17, `.claude/discussions/discuss-track-colour-2026-10-17.md`): eight
# names because rekordbox has eight; Traktor's seven cover all but `aqua`,
# which it receives as its Blue.
TrackColor = Literal["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
class ColorSwatch(BaseModel):
"""One track colour a library offers, in its own menu order."""
color: TrackColor
hex: str # the platform's own display colour
label: str # the platform's own name for it ("Violet" in Traktor)
class CueCapabilities(BaseModel):
@@ -107,6 +121,15 @@ class TrackCapabilities(BaseModel):
# Whether added files can be left where they are ("reference") rather than
# copied. False where the library cannot see this computer's files at all.
reference: bool = True
# The track colours this library can store (`set_track_color`), in its own
# menu order. Empty: the platform has no track colour.
colors: list[ColorSwatch] = []
# 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):
+50
View File
@@ -32,6 +32,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Callable, Protocol, runtime_checkable
from .capabilities import Capabilities
from .loudness import Loudness
from .model import Track, TrackCues
if TYPE_CHECKING:
@@ -58,6 +59,13 @@ class ExportTrack:
#: not decode an unchanged track again. Either may be None.
fingerprint: str | None = None
analysis_cache: "AnalysisCache | None" = field(default=None, repr=False)
#: The COPY's loudness (the source's, moved by `gain_db` when the run
#: normalised it), set only when the run writes the DJ app's auto gain —
#: a writer whose platform keeps one (`writes_auto_gain`) writes it from
#: this; None = write none.
loudness: Loudness | None = None
#: The level change the copy got (0.0: copied as it is).
gain_db: float = 0.0
def waveform(self, *, lead: float = 0.0):
"""`waveform.analyse()` of the copied audio — the call every exporter that
@@ -111,6 +119,40 @@ class ExportPayload:
default=lambda message, step=None, of=None: None, repr=False)
#: The playlist an export's LOOSE tracks (in no exported playlist) land in.
OTHER_PLAYLIST = "Other"
def write_playlist_tree(adapter, playlists: list[ExportPlaylist], track_ids: list[str],
moved: dict[str, str], root: str | None) -> None:
"""Recreate `playlists` under `root` (None = the top level) through the
generic playlist commands: each folder chain once, each playlist with the
entries `moved` maps its SOURCE ids to, and the tracks of `track_ids` no
playlist accounts for in an "Other" playlist. Shared by the Traktor writer
and the push into a DJ app's library, which builds the same tree inside
the set's own folder."""
folders: dict[tuple[str, ...], str | None] = {(): root}
def folder_for(path: tuple[str, ...]) -> str | None:
for depth in range(1, len(path) + 1):
branch = path[:depth]
if branch not in folders:
folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]])
return folders.get(path, root)
for playlist in playlists:
node_id = adapter.create_playlist(playlist.name, folder_for(tuple(playlist.folders)))
entries = [moved[t] for t in playlist.track_ids if t in moved]
if entries:
adapter.set_playlist_entries(node_id, entries)
in_playlists = {t for p in playlists for t in p.track_ids}
loose = [moved[t] for t in track_ids if t not in in_playlists and t in moved]
if loose:
node_id = adapter.create_playlist(OTHER_PLAYLIST, root)
adapter.set_playlist_entries(node_id, loose)
@dataclass
class WrittenLibrary:
"""What an exporter put on disk.
@@ -150,6 +192,14 @@ class LibraryExporter(Protocol):
#: destination, so this is a warning the UI raises, not a refusal: the other
#: targets in the same export are still perfectly valid in any folder.
drive_root: bool = False
#: Optional, and not a protocol member so a target needs nothing to opt
#: out: `prepare_copy(path) -> bool` readies one audio COPY for this
#: library, in place, before its size is recorded or a library refers to
#: it, returning True if it changed the file. Called once per copy and
#: target (the runner records which targets have prepared it, so a kept
#: copy is prepared when a target joins the set). Traktor's removes its
#: own block from the file (`adapters/traktor/file_block.py`). Never
#: called on a file a library references in place.
def capabilities(self) -> Capabilities:
"""What this target can represent — STATIC, with no library to read."""
+461
View File
@@ -0,0 +1,461 @@
"""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 == ".mp3":
_mp3(src, dst, gain_db)
elif suffix in STEPPED:
_aac(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))
# ---- AAC (an .m4a, a stem file): the same edit, in `aac_gain` -----------------
def _aac(src: Path, dst: Path, gain_db: float) -> None:
"""Every audio stream of the MP4 (a stem file's five alike) moved by the
same steps. No undo tag: one would grow `moov` and shift every sample
offset; the edit is exactly reversed by the opposite steps."""
from . import aac_gain
steps = mp3_steps(gain_db)
try:
aac_gain.apply(src, dst, steps)
except aac_gain.AacGainError as ex:
raise LevelEditError(f"{src.name}: {ex}") from ex
# ---- 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 _audio_streams(path: Path) -> int:
from . import pyav
with pyav.open_input(path) as c:
return len(c.streams.audio)
def _frames(path: Path, index: int = 0):
import av
from . import pyav
with pyav.open_input(path) as c:
stream = c.streams.audio[index]
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) — EVERY audio stream (a
stem file's five). Raises `LevelEditError`."""
n_src, n_dst = _audio_streams(Path(src)), _audio_streams(Path(dst))
if n_src != n_dst:
raise LevelEditError(f"{Path(dst).name}: the number of audio streams changed")
for index in range(n_src):
_verify_stream(Path(src), Path(dst), gain_db, tolerance, index)
def _verify_stream(src: Path, dst: Path, gain_db: float, tolerance: float, index: int) -> None:
factor = 10.0 ** (gain_db / 20.0)
a_iter, b_iter = _frames(src, index), _frames(dst, index)
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)")
+106
View File
@@ -0,0 +1,106 @@
"""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 a lossless frame-gain edit, in `STEP_DB` steps: MP3's
#: (`level_edit`) and AAC-LC's (`aac_gain` — an `.m4a`, a stem file; a file
#: that turns out to be HE-AAC is refused when it is rewritten).
STEPPED = frozenset({".mp3", ".m4a", ".mp4"})
#: 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
+305
View File
@@ -0,0 +1,305 @@
"""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 = 2 # 2: a stem file is its four stems summed, not its mix stream
_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.
A stem FILE is measured as its four stems SUMMED — what a stem deck plays
(Traktor's and Konduktor's), and what Traktor's own gain analysis measures
(decided 2026-10-19 after `bench_traktor_gain.py`: commercial stem files'
mix streams are mastered ~2.8 dB, up to 5.3, hotter than their stems sum
to; see the gain-normalisation discussion)."""
from . import stem_file
if stem_file.is_stem_file(path):
return _measure_stem_sum(path)
return _measure_stream(path)
def _measure_stream(path: Path | str) -> Loudness | None:
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()
def _measure_stem_sum(path: Path | str) -> Loudness | None:
"""Streams 1-4 of a stem file, decoded in ONE demux pass and summed as they
arrive, so memory stays at seconds of audio. The stems share their encoder
priming (they were muxed in lockstep), so sample n of each is the same
instant; the sum ends where the shortest stem does."""
import av
from . import pyav
with pyav.open_input(path) as container:
stems = list(container.streams.audio[1:5])
if len(stems) < 4:
raise ValueError(f"{path}: a stem file with {len(stems)} stems")
sr = int(stems[0].codec_context.sample_rate)
resamplers = {s.index: av.AudioResampler(format="fltp", layout="stereo", rate=sr) for s in stems}
queues: dict[int, list[np.ndarray]] = {s.index: [] for s in stems}
meter = _Meter(sr, 2)
def drain(final: bool = False) -> None:
ready = min(sum(a.shape[1] for a in q) for q in queues.values())
if ready == 0 or (not final and ready < sr * 5): # ~5 s per feed
return
total = np.zeros((2, ready), dtype=np.float32)
for idx, q in queues.items():
buf = np.concatenate(q, axis=1)
total += buf[:, :ready]
queues[idx] = [buf[:, ready:]] if buf.shape[1] > ready else []
meter.feed(total)
for packet in container.demux(stems):
idx = packet.stream.index
for frame in packet.decode():
for out in resamplers[idx].resample(frame):
queues[idx].append(out.to_ndarray())
drain()
for idx, rs in resamplers.items():
for out in rs.resample(None):
queues[idx].append(out.to_ndarray())
drain(final=True)
return meter.result()
+16 -1
View File
@@ -13,7 +13,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind, TrackColor
class HotcueChip(BaseModel):
@@ -71,6 +71,15 @@ class Track(BaseModel):
grid_marker_count: int = 0
grid_locked: bool = False
media_kind: MediaKind = "audio"
# The track's colour tag: the neutral identity (what crosses platforms) and
# the platform's own display colour for it, both mapped from the stored
# code by the adapter. None = no colour.
color: TrackColor | None = None
color_hex: str | None = None
# The DJ app's own auto gain for the track in dB (Traktor's deck gain,
# rekordbox's Auto Gain), as the adapter reads it. None = the track has
# none, which is what "fill where missing" looks for.
auto_gain_db: float | None = None
class TrackPage(BaseModel):
@@ -229,6 +238,12 @@ class PlatformOption(BaseModel):
#: As an export TARGET: its library is only ever read on a computer, never
#: from a drive — so it does nothing beside a stick format.
computer_only: bool = False
#: As an export TARGET: its library can store a grid lock, so the export's
#: "Lock beatgrids" option means something there.
locks_grids: bool = False
#: As an export TARGET: its library keeps the DJ app's auto gain, so the
#: export's "Auto gain" option means something there (no stick format does).
writes_auto_gain: bool = False
class RemapSample(BaseModel):
+15 -7
View File
@@ -5,8 +5,10 @@ stem files (see the stem-conversion discussion log): an `ipod` MP4 with FIVE
AAC-LC stereo 44.1 kHz streams — stream 0 the full mix and 1-4 drums / bass /
synths / vox — streams 1-4 not enabled (`disposition` 0, so a player that knows
nothing of stems plays the mix), and a `moov/udta/stem` box holding JSON that
names and colours the stems. Traktor 4.5 loads such a file as stems and honours
the MP4 edit list, so a stem file's time base is the decoded audio's own.
names and colours the stems. Traktor 4.5 loads such a file as stems. On macOS
it honours the MP4 edit list; on Windows it skips a fixed 1024 samples of
priming — so the file must prime exactly 1024 (`default_encoder`), and then its
time base is the decoded audio's own on both.
Platform-independent on purpose: the separation itself is a callback
(`separate`) so this module never imports torch — the stem ENGINE supplies it
@@ -39,7 +41,6 @@ import fractions
import json
import queue
import struct
import sys
import threading
from dataclasses import dataclass
from pathlib import Path
@@ -117,11 +118,18 @@ class Written:
def default_encoder() -> str:
"""Apple's AudioToolbox encoder on macOS (the better AAC encoder there),
FFmpeg's own elsewhere. Both are timing-exact in Traktor (kit 1)."""
import av
"""FFmpeg's own `aac`, on EVERY platform — never Apple's `aac_at`.
return "aac_at" if sys.platform == "darwin" and "aac_at" in av.codecs_available else "aac"
Both are timing-exact in Traktor on macOS (kit 1), which honours the MP4
edit list. Traktor on WINDOWS does not: it skips a fixed 1024 samples of
priming, which is what `aac` (and every commercial stem file measured)
primes — but `aac_at` primes 2112, so its files sat 1088 samples (~25 ms)
early on a PC. Found 2026-10-19: of 148 stem files on one stick, exactly the
9 Konduktor had encoded with `aac_at` were off in Windows Traktor, every one,
and Reset fixed each; a 1024-primed one beside them was not. The cost is
speed: `aac_at` encodes several times faster on a Mac.
"""
return "aac"
def choose_bitrate(source: Source) -> int:
+220 -18
View File
@@ -81,6 +81,7 @@ from . import exports
from .core import registry
from .core.analysis_cache import CACHE_DIR, AnalysisCache, fingerprint
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
from .core.level_plan import Measure, plan_gain, shifted
from .core.pathmap import common_dir_prefix
from .core.places import is_drive_root, is_os_housekeeping
from .importer import SPACE_HEADROOM, copy_file, free_bytes
@@ -116,6 +117,29 @@ class PlannedTrack:
#: kept instead of copied again — possibly a different path from
#: `destination`, in which case it is moved. None means copy.
reuse: Path | None = None
#: The source's stored loudness when fresh (None: not measured, or stale —
#: the run measures it when it needs one).
loudness: object | None = None
#: The level the copy is written at (`level_plan.plan_gain`; 0.0 = copied
#: as it is) and why (None: the run does not normalise).
gain_db: float = 0.0
level_outcome: str | None = None
#: The run needs this source's loudness (it normalises, or writes auto gain).
needs_loudness: bool = False
#: The targets whose `prepare_copy` the copy has been through (sorted
#: platforms; recorded in the manifest, missing = none).
prepared: tuple[str, ...] = ()
@dataclass(frozen=True)
class Level:
"""The run's "Normalise audio": every copy brought to `target` in `measure`,
a raise stopping at the true-peak `ceiling` — Normalize's rules exactly
(`level_plan`), applied to the copy and never to the source."""
measure: Measure = "lufs"
target: float = -9.0
ceiling: float = -1.0
@dataclass
@@ -147,7 +171,17 @@ class ExportPlan:
return sum(1 for t in self.exportable if t.reuse is not None)
def as_dict(self, free: int | None = None) -> dict:
exportable = self.exportable
levels: dict[str, int] = {}
for t in exportable:
if t.level_outcome:
levels[t.level_outcome] = levels.get(t.level_outcome, 0) + 1
return {
# Normalise audio: copies whose level changes, tracks the run
# measures first, and every outcome (`level_plan`) by count.
"normalised": sum(1 for t in exportable if t.gain_db),
"to_measure": sum(1 for t in exportable if t.needs_loudness and t.loudness is None),
"level_counts": levels,
"tracks": len(self.tracks),
"exportable": len(self.exportable),
"unchanged": self.unchanged,
@@ -287,9 +321,46 @@ def _record(planned: PlannedTrack, copy: Path) -> dict:
"mtime_ns": planned.mtime_ns,
"copy_size": st.st_size,
"copy_mtime_ns": st.st_mtime_ns,
# The level the copy was written at: a copy kept by a later export must
# be at the level THAT export wants (missing = 0, every older manifest).
"gain_db": planned.gain_db,
# The targets that have prepared the copy (`prepare_copy`): a kept copy
# is prepared for any target not listed (missing = none, every older
# manifest — which is how existing exports lose Traktor's block).
"prepared": list(planned.prepared),
}
def prepare_copy(path: Path, exporters, done=()) -> tuple[str, ...]:
"""Run each target's optional `prepare_copy` on one copy, in place,
skipping the targets in `done` (already prepared it). Returns every target
that now has — `done` included, so a target leaving the set does not make
a later one prepare the copy twice."""
ready = set(done)
for exporter in exporters:
hook = getattr(exporter, "prepare_copy", None)
if hook is None or exporter.platform in ready:
continue
hook(path)
ready.add(exporter.platform)
return tuple(sorted(ready))
def prepare_kept(path: Path, planned: PlannedTrack, record: dict, exporters) -> dict:
"""Prepare a KEPT copy for any target that has not yet (an export made
before a target's `prepare_copy` existed, or a target new to the set), and
the record that now describes it — the copy's size and mtime as they are
after, so a rollback's manifest still matches the file."""
done = record.get("prepared")
done = tuple(done) if isinstance(done, list) else ()
planned.prepared = prepare_copy(path, exporters, done)
if planned.prepared == tuple(sorted(done)):
return record
st = path.stat()
return {**record, "copy_size": st.st_size, "copy_mtime_ns": st.st_mtime_ns,
"prepared": list(planned.prepared)}
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
"""The last export's copies, by SOURCE path — not by where they sit, since
adding a track from another folder moves the shared root and with it every
@@ -314,6 +385,11 @@ def _reusable(planned: PlannedTrack, previous: dict[str, tuple[Path, dict]]) ->
copy, record = found
if (record.get("size"), record.get("mtime_ns")) != (planned.size, planned.mtime_ns):
return None
try:
if abs(float(record.get("gain_db") or 0.0) - planned.gain_db) > 0.01:
return None # written at another level (Normalise audio changed)
except (TypeError, ValueError):
return None
try:
st = copy.stat()
except OSError:
@@ -328,8 +404,15 @@ def _reusable(planned: PlannedTrack, previous: dict[str, tuple[Path, dict]]) ->
# ---- planning ----------------------------------------------------------------
def plan(adapter, export_set) -> ExportPlan:
"""Resolve the set and work out where every file lands. Reads only."""
def plan(adapter, export_set, *, store=None, level: Level | None = None,
auto_gain: bool = False) -> ExportPlan:
"""Resolve the set and work out where every file lands. Reads only.
With `level` (Normalise audio) each copy's gain comes from the source's
STORED loudness in `store`; with `auto_gain` that loudness is also what the
DJ app's gain is written from. A source with none (or a stale one) is
measured by the run — and its copy decided then, since whether the
previous one can be kept depends on its level."""
destination = Path(export_set.destination).expanduser()
built = ExportPlan(destination=destination)
@@ -357,7 +440,8 @@ def plan(adapter, export_set) -> ExportPlan:
root = common_dir_prefix(present) if present else ""
previous = _previous_copies(destination)
claimed: set[Path] = set()
wants_loudness = store is not None and (level is not None or auto_gain)
entries = store.get([f.key for f in facts.values() if f is not None]) if wants_loudness else {}
for track in tracks:
source = sources.get(track.id)
fact = facts.get(track.id)
@@ -371,15 +455,15 @@ def plan(adapter, export_set) -> ExportPlan:
size=size,
mtime_ns=mtime_ns,
missing=not exists,
needs_loudness=exists and wants_loudness,
)
if exists:
reuse = _reusable(planned, previous)
# One kept copy can serve one planned file: two entries sharing a
# source would otherwise both try to move it.
if reuse is not None and reuse not in claimed:
planned.reuse = reuse
claimed.add(reuse)
if planned.needs_loudness:
entry = entries.get(fact.key)
planned.loudness = entry.values if entry is not None and not entry.stale(fact) else None
if exists and level is not None:
set_level(planned, level)
built.tracks.append(planned)
assign_reuse(built, previous)
names = {p.id: p for p in resolved.playlists}
folders = _folder_paths(adapter)
@@ -404,6 +488,31 @@ def plan(adapter, export_set) -> ExportPlan:
return built
def set_level(planned: PlannedTrack, level: Level) -> None:
"""The copy's gain from the source's loudness (`level_plan.plan_gain`)."""
suffix = planned.source_path.suffix if planned.source_path else ""
step = plan_gain(planned.loudness, suffix, measure=level.measure, target=level.target,
ceiling=level.ceiling)
planned.gain_db, planned.level_outcome = step.gain_db, step.outcome
def assign_reuse(built: ExportPlan, previous: dict[str, tuple[Path, dict]]) -> None:
"""Which planned files keep the previous export's copy. A file whose level
is still undecided (normalising, not yet measured) is copied unless the run
decides otherwise once it has measured it."""
claimed: set[Path] = set()
for planned in built.tracks:
planned.reuse = None
if planned.missing or planned.level_outcome == "unmeasured":
continue
reuse = _reusable(planned, previous)
# One kept copy can serve one planned file: two entries sharing a
# source would otherwise both try to move it.
if reuse is not None and reuse not in claimed:
planned.reuse = reuse
claimed.add(reuse)
def _relative(source: Path, root: str) -> Path:
"""Where `source` sits under the export root, mirroring its own folders."""
text = str(source).replace("\\", "/")
@@ -433,12 +542,35 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
# ---- running -----------------------------------------------------------------
def _locked(cues, lock_grids: bool):
"""The cues as exported: with `lock_grids`, a grid is LOCKED.
The lock rides on the generic `TrackCues.grid_locked`, the same flag a
source's own lock arrives in, so a writer reads one signal and never learns
which of the two set it. Unlocked Traktor re-analyses an exported track on
its first load (it has no AUDIO_ID, which cannot be computed), re-measuring
the BPM — a 174 track can come back as 87 — and drifting the grid; a
locked grid is left alone. A track with no grid is never locked: that
would stop Traktor ever giving it one.
"""
if lock_grids and cues is not None and cues.grid_markers and not cues.grid_locked:
return cues.model_copy(update={"grid_locked": True})
return cues
def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
root_folder: bool = False) -> dict:
root_folder: bool = False, lock_grids: bool = False, store=None,
level: Level | None = None, auto_gain: bool = False) -> dict:
"""Copy what changed, then write every target's library over the audio.
`root_folder` nests the playlists in a folder named after the export (the
"Put exported playlists in a folder" setting); otherwise they sit at the top.
`lock_grids` locks every exported track that HAS a grid (`_locked`); off,
each track keeps the source's own lock. `level` (Normalise audio) writes
each copy at its planned gain (`core.level_edit`, decode-verified); the
source is never touched. `auto_gain` hands every writer the COPY's loudness
for the DJ app's gain. Sources with no stored loudness are measured first,
into `store` — the same measurement the Mastering columns show.
Rolls back EVERYTHING this run wrote on cancel or on any failure —
including the libraries of targets that had already been written when a
@@ -473,6 +605,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
done = 0
try:
destination.mkdir(parents=True, exist_ok=True)
_measure_missing(adapter, built, handle, store=store, level=level)
if is_ours(destination):
handle.progress(message="Replacing the previous export…")
old = _read_manifest(destination).get("audio") or {}
@@ -489,7 +622,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
for planned in items:
planned.reuse = None
reused = [t for t in items if t.reuse is not None]
handle.progress(total=built.total_bytes)
handle.progress(done=0, total=built.total_bytes, unit="bytes")
# Written before anything moves or is copied, listing every path this
# run may leave behind, so even a crash (not a cancel — nothing gets to
# clean up after a crash) leaves a folder the next export can clear.
@@ -503,6 +636,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
if reused:
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
_move_kept(destination, reused, kept)
for planned in reused:
handle.raise_if_cancelled()
path = Path(planned.destination)
kept[path] = prepare_kept(path, planned, kept[path], exporters)
payload_tracks: list[ExportTrack] = []
for planned in items:
@@ -521,19 +658,20 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
done += n
handle.progress(done=done)
# The file to READ: on this machine that is the source itself;
# on a library held by a server, a downloaded copy of it.
local = adapter.audio_path(planned.track_id) or planned.source_path
copy_file(local, partial, handle, advance)
write_copy(adapter, planned, partial, handle, advance)
planned.prepared = prepare_copy(partial, exporters)
os.replace(partial, target)
payload_tracks.append(
ExportTrack(
track=adapter.track(planned.track_id),
destination=target,
cues=adapter.track_cues(planned.track_id),
cues=_locked(adapter.track_cues(planned.track_id), lock_grids),
art=_cover(adapter, planned.track_id),
fingerprint=_fingerprint(planned),
analysis_cache=cache,
loudness=(shifted(planned.loudness, planned.gain_db)
if auto_gain and planned.loudness is not None else None),
gain_db=planned.gain_db,
)
)
@@ -587,6 +725,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
return {
"tracks": len(payload_tracks),
"unchanged": len(reused),
"normalised": sum(1 for t in items if t.gain_db),
"playlists": len(built.playlists),
"skipped": len(built.tracks) - len(items),
"destination": str(destination),
@@ -628,6 +767,33 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
raise
def write_copy(adapter, planned: PlannedTrack, partial: Path, handle: JobHandle, advance) -> None:
"""Write one copy of `planned`'s source to `partial`: at its planned gain
(decode-verified), else byte for byte. A file that cannot be levelled
(HE-AAC in an .m4a — only the file says so) is copied as it is and its
plan says so (`gain_db` 0, outcome "unsupported"); never a failure."""
# The file to READ: on this machine that is the source itself; on a
# library held by a server, a downloaded copy of it.
local = adapter.audio_path(planned.track_id) or planned.source_path
if planned.gain_db:
from .core import level_edit
handle.progress(message=f"Normalising {planned.title} ({planned.gain_db:+.1f} dB)")
try:
level_edit.apply(local, partial, planned.gain_db)
handle.raise_if_cancelled()
# A copy carried to a gig must be the source at the gain, nothing
# else: decode both and compare.
level_edit.verify(local, partial, planned.gain_db)
advance(planned.size)
return
except level_edit.LevelEditError as ex:
log.warning("copying %s unlevelled: %s", planned.title, ex)
partial.unlink(missing_ok=True)
planned.gain_db, planned.level_outcome = 0.0, "unsupported"
copy_file(local, partial, handle, advance)
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
"""Rename each kept copy to where this export puts it — instant on one drive.
@@ -667,7 +833,43 @@ def _rel(path: Path, destination: Path) -> str:
def _fingerprint(planned: PlannedTrack) -> str:
return fingerprint(planned.source_path, planned.size, planned.mtime_ns)
# The waveform cache is keyed by the SOURCE; a copy written at another
# level draws differently, so its gain is part of the key — else a
# normalised stick would be drawn from the un-levelled measurement.
source = planned.source_path if not planned.gain_db else f"{planned.source_path}#gain={planned.gain_db:.4f}"
return fingerprint(source, planned.size, planned.mtime_ns)
def _measure_missing(adapter, built: ExportPlan, handle: JobHandle, *, store, level: Level | None,
previous: dict[str, tuple[Path, dict]] | None = None) -> None:
"""Measure the sources the run needs a loudness for and has none, store
each, then settle their copies' levels and which previous copies can be
kept (`previous`: the copies on record, by source path — by default the
destination's manifest). Before anything at the destination changes, so a
cancel here leaves the previous export as it was."""
todo = [t for t in built.exportable if t.needs_loudness and t.loudness is None]
if not todo or store is None:
return
from .core import loudness
for n, planned in enumerate(todo, start=1):
handle.raise_if_cancelled()
handle.progress(done=n - 1, total=len(todo), unit="tracks",
message=f"Measuring {planned.title} ({n}/{len(todo)})")
local = adapter.audio_path(planned.track_id) or planned.source_path
try:
values = loudness.measure_file(local)
except Exception as ex: # noqa: BLE001 — copied as it is, with no gain
log.warning("could not measure %s: %s", planned.title, ex)
values = None
planned.loudness = values
if values is not None:
fact = adapter.audio_facts([planned.track_id]).get(planned.track_id)
if fact is not None:
store.put(fact, values)
if level is not None:
set_level(planned, level)
assign_reuse(built, previous if previous is not None else _previous_copies(Path(built.destination)))
def _cover(adapter, track_id: str):
+65 -2
View File
@@ -44,6 +44,10 @@ from . import paths
log = logging.getLogger(__name__)
#: A set's `kind` and a "computer" set's `mode` (see `ExportSet`).
KINDS = ("folder", "computer")
MODES = ("merge", "overwrite")
@dataclass
class ExportSet:
@@ -56,12 +60,36 @@ class ExportSet:
id: str
name: str
#: Where the set goes. "folder": a folder or drive the export writes a
#: library into (`destination`). "computer": PUSHED into the DJ apps'
#: own libraries on this computer (`local_push.py`) — `targets` names the
#: apps, `destination` is unused, and which file each app's library is
#: lives in this computer's prefs, not here (a remote library's sets are
#: kept on its server, but the paths belong to whichever laptop pushes).
kind: str = "folder"
#: A "computer" set's push: "merge" adds and updates only what this set
#: put there; "overwrite" replaces the whole library with this set.
mode: str = "merge"
#: Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
#: empty; ordered as the user ticked them, which is the order they are written.
targets: list[str] = field(default_factory=lambda: ["traktor"])
destination: str = "" # OS path of the folder the export is written into
playlist_ids: list[str] = field(default_factory=list)
track_ids: list[str] = field(default_factory=list) # loose tracks only
#: Lock every exported grid, so Traktor does not re-analyse a track on its
#: first load (it re-measures the BPM — 174 can come back as 87 — and the
#: grid drifts). Remembered per set: it is a decision about this stick.
lock_grids: bool = True
#: The run's "Normalise audio": the copies (never the sources) brought to
#: one level. Off by default — it changes the audio on the stick.
normalise: bool = False
#: The run's "Auto gain": the DJ app's gain written from each copy's
#: loudness, where the target keeps one. On by default, like the lock:
#: without it rekordbox plays an exported track at 0.0 dB.
auto_gain: bool = True
#: Normalise's measure / target / ceiling for this set ({"measure",
#: "target", "ceiling"}); None = the app settings at run time.
level: dict | None = None
created: float = 0.0
modified: float = 0.0
@@ -154,6 +182,20 @@ def _write_doc(library_id: str, doc: dict) -> None:
paths.write_json(_store_path(library_id), doc)
def _level(raw) -> dict | None:
"""A stored level, checked: anything malformed reads as None (the app
settings), never as a half-filled one."""
if not isinstance(raw, dict):
return None
try:
measure = raw.get("measure", "lufs")
if measure not in ("lufs", "rms"):
return None
return {"measure": measure, "target": float(raw["target"]), "ceiling": float(raw["ceiling"])}
except (KeyError, TypeError, ValueError):
return None
def _load(library_id: str) -> dict[str, ExportSet]:
data = _read_doc(library_id)
raw = data.get("sets") if isinstance(data, dict) else None
@@ -166,10 +208,16 @@ def _load(library_id: str) -> dict[str, ExportSet]:
out[set_id] = ExportSet(
id=set_id,
name=values.get("name") or "Untitled",
kind=values.get("kind") if values.get("kind") in KINDS else "folder",
mode=values.get("mode") if values.get("mode") in MODES else "merge",
targets=_targets(values),
destination=values.get("destination") or "",
playlist_ids=list(values.get("playlist_ids") or []),
track_ids=list(values.get("track_ids") or []),
lock_grids=bool(values.get("lock_grids", True)),
normalise=bool(values.get("normalise", False)),
auto_gain=bool(values.get("auto_gain", True)),
level=_level(values.get("level")),
created=float(values.get("created") or 0.0),
modified=float(values.get("modified") or 0.0),
)
@@ -219,6 +267,8 @@ def destination_conflict(library_id: str, destination: str, *, ignore: str | Non
if not target:
return None
for existing in _load(library_id).values():
if existing.kind != "folder":
continue # a push has no destination folder to clear
if existing.id != ignore and _normalise(existing.destination) == target:
return existing.name
return None
@@ -234,12 +284,15 @@ def _normalise(destination: str) -> str:
# ---- writing -----------------------------------------------------------------
def create(library_id: str, *, name: str, targets: list[str], destination: str) -> ExportSet:
def create(library_id: str, *, name: str, targets: list[str], destination: str,
kind: str = "folder", mode: str = "merge") -> ExportSet:
sets = _load(library_id)
now = time.time()
created = ExportSet(
id=uuid.uuid4().hex,
name=name.strip() or "Untitled",
kind=kind if kind in KINDS else "folder",
mode=mode if mode in MODES else "merge",
targets=list(dict.fromkeys(targets)),
destination=destination,
created=now,
@@ -251,7 +304,8 @@ def create(library_id: str, *, name: str, targets: list[str], destination: str)
def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
"""Rename, retarget or relocate a set. Unknown fields are ignored."""
"""Rename, retarget or relocate a set, or change its options. Unknown fields
are ignored."""
sets = _load(library_id)
found = sets.get(set_id)
if found is None:
@@ -259,8 +313,17 @@ def update(library_id: str, set_id: str, **fields) -> ExportSet | None:
for key in ("name", "destination"):
if key in fields and fields[key] is not None:
setattr(found, key, fields[key])
if fields.get("kind") in KINDS:
found.kind = fields["kind"]
if fields.get("mode") in MODES:
found.mode = fields["mode"]
if fields.get("targets"):
found.targets = list(dict.fromkeys(fields["targets"]))
for key in ("lock_grids", "normalise", "auto_gain"):
if fields.get(key) is not None:
setattr(found, key, bool(fields[key]))
if fields.get("level") is not None:
found.level = _level(fields["level"])
found.modified = time.time()
_save(library_id, sets)
return found
+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
+199
View File
@@ -0,0 +1,199 @@
"""Normalize on a library held by a Konduktor server (decided 2026-10-19: the
same transfer Convert to Stems uses).
The batch of `normalize.py`, split where the machines split:
* **The server plans** — from its own loudness store, with its own ledger
(a track awaiting Save is skipped there) — and says per track how big the
source is, the platform's analysis lead, and whether a verified upload at
this very gain is already there (`staged`: a takeover interrupted the
run that made it, and this one reuses it).
* **This computer rewrites.** The server never decodes audio, so each source
is downloaded into the shared cache, measured if the server has no
measurement (stored back on the server), rewritten by `core.level_edit`,
VERIFIED, measured for its drawn waveform where the platform keeps one,
and UPLOADED.
* **The server swaps.** One end step there (`/v1/gain/publish`) — park the
original, the upload under its name, the library's size / waveforms /
auto gain — under its mutation lock, with its own ledger, which its Save
commits and its Discard undoes.
Cancel deletes what this run uploaded; a takeover cannot, so those uploads
stay and the next run reuses them.
"""
from __future__ import annotations
import contextlib
import shutil
from pathlib import Path
from ..core.adapter import AdapterError
from .normalize import _WHY, NormalizeError, Options
#: Before this computer has measured a download, a conservative LAN speed.
DEFAULT_SPEED = 20 * 1024 ** 2 # bytes / s
def options_body(opts: Options) -> dict:
return {"measure": opts.measure, "target": opts.target, "ceiling": opts.ceiling}
def plan(adapter, track_ids, opts: Options) -> dict:
"""The server's plan, plus what only this computer can answer: how much
must cross the network (a source already cached here is not downloaded)."""
try:
out = adapter.normalize_plan({"track_ids": list(track_ids), **options_body(opts)})
except AdapterError as ex:
raise NormalizeError(str(ex))
work = [r for r in out["rows"] if _needs_work(r) and not r.get("staged")]
download = sum(int(r.get("source_size") or 0) for r in work if adapter.cached_audio(r["track_id"]) is None)
upload = sum(int(r.get("source_size") or 0) for r in work) # a level change keeps (about) the size
speed = adapter.cache.speed()
out["transfer"] = {"download": download, "upload": upload, "speed": speed or DEFAULT_SPEED,
"measured": speed is not None}
return out
def _needs_work(row: dict) -> bool:
return not row.get("skip") and (bool(row.get("gain_db")) or row.get("outcome") == "unmeasured")
def run(handle, adapter, track_ids, opts: Options, *, still_current) -> dict:
from ..adapters.remote.services import RemoteLoudnessStore
from ..core import level_edit, loudness
from ..core.adapter import PreparedAnalysis
from ..core.level_plan import plan_gain
from .. import remote_protocol as rp
from ..stems import convert
planned = plan(adapter, track_ids, opts)
result = {"normalised": [], "skipped": [], "failed": [], "counts": dict(planned.get("counts") or {}),
"cancelled": False}
rows = planned["rows"]
store = RemoteLoudnessStore(adapter.client, adapter.session)
body = options_body(opts)
staged: list[str] = []
uploaded: list[str] = [] # what THIS run uploaded (a cancel deletes it)
work = convert.work_root() / f"remote-normalize-{id(handle):x}"
work.mkdir(parents=True, exist_ok=True)
handle.progress(done=0, total=len(rows), unit="tracks")
def skip(row: dict, reason: str) -> None:
result["skipped"].append({"track_id": row["track_id"], "title": row["title"], "reason": reason})
def fail(row: dict, reason: str) -> None:
result["failed"].append({"track_id": row["track_id"], "title": row["title"], "reason": reason})
def checkpoint() -> None:
if handle.cancelled:
raise _Cancel()
try:
for n, row in enumerate(rows):
checkpoint()
handle.progress(done=n, message=row["title"], fraction=0.0, status="")
if row.get("skip"):
skip(row, row["skip"])
continue
if not _needs_work(row):
skip(row, _WHY.get(row.get("outcome"), "nothing to change"))
continue
if row.get("staged"):
staged.append(row["track_id"]) # already on the server, verified
continue
size = max(int(row.get("source_size") or 0), 1)
got = 0
def downloaded(k: int) -> None:
nonlocal got
got += k
checkpoint()
f = min(got / size, 1.0) * 0.3
handle.progress(fraction=f, status=f"downloading {f / 0.3 * 100:.0f} %")
local = adapter.audio_path(row["track_id"], progress=downloaded)
if local is None:
fail(row, "the file is missing on the server")
continue
gain = float(row.get("gain_db") or 0.0)
if row.get("outcome") == "unmeasured":
handle.progress(fraction=0.3, status="measuring")
try:
values = loudness.measure_file(local)
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
fail(row, f"Could not measure: {ex}")
continue
if values is None:
skip(row, "nothing to measure (silent or under 3 s)")
continue
facts = adapter.audio_facts([row["track_id"]]).get(row["track_id"])
if facts is not None:
store.put(facts, values) # the server's store: its stage checks against it
step = plan_gain(values, Path(local).suffix, measure=opts.measure, target=opts.target,
ceiling=opts.ceiling)
result["counts"][step.outcome] = result["counts"].get(step.outcome, 0) + 1
if not step.writes:
skip(row, _WHY.get(step.outcome, "nothing to change"))
continue
gain = step.gain_db
partial = work / f"{n}{Path(local).suffix}"
handle.progress(fraction=0.4, status=f"{gain:+.1f} dB")
try:
level_edit.apply(local, partial, gain)
checkpoint()
handle.progress(fraction=0.5, status="verifying")
level_edit.verify(local, partial, gain)
packed = None
if row.get("lead") is not None: # the platform draws waveforms from its own files
from ..core import waveform
handle.progress(fraction=0.7, status="waveform")
measured = waveform.analyse(partial, lead=float(row["lead"]))
packed = rp.pack_analysis(PreparedAnalysis(measured=measured)) if measured else None
sent = 0
total = max(partial.stat().st_size, 1)
def uploading(k: int) -> None:
nonlocal sent
sent += k
checkpoint()
f = 0.8 + min(sent / total, 1.0) * 0.2
handle.progress(fraction=f, status=f"uploading {(f - 0.8) / 0.2 * 100:.0f} %")
adapter.stage_gain(row["track_id"], partial, gain_db=gain, options=body, waveform=packed,
progress=uploading)
except _Cancel:
raise
except AdapterError:
raise
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
fail(row, str(ex) or type(ex).__name__)
continue
finally:
partial.unlink(missing_ok=True)
uploaded.append(row["track_id"])
staged.append(row["track_id"])
except _Cancel:
with contextlib.suppress(AdapterError):
if uploaded:
adapter.abandon_gain(uploaded)
result["cancelled"] = True
return result
finally:
shutil.rmtree(work, ignore_errors=True)
if not staged:
return result
if not still_current():
with contextlib.suppress(AdapterError):
adapter.abandon_gain(uploaded)
raise NormalizeError("The library changed while normalizing; nothing was changed")
handle.progress(done=len(rows), message="Putting the new levels in place on the server…", status="")
published = adapter.publish_gain(staged)
result["normalised"] = list(published.get("normalised") or [])
result["failed"] += published.get("failed") or []
return result
class _Cancel(Exception):
pass
+12 -4
View File
@@ -317,6 +317,7 @@ def run(
folder_name: str | None = None,
reference: bool = False,
into_playlist: str | None = None,
into_playlist_index: int | None = None,
) -> dict:
"""Perform the import. Returns a summary dict for the job result.
@@ -332,7 +333,8 @@ def run(
`reference` adds each file WHERE IT IS instead of copying it, so there is no
destination and nothing to roll back. `into_playlist` appends every planned
track — the new ones and those the destination already held — to one of the
destination's playlists before the save, so both land in one commit.
destination's playlists before the save, so both land in one commit;
`into_playlist_index` inserts them there instead (a drop between rows).
A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary
stick) overrides both: `dest.place_audio` names each copy's target, or says
@@ -345,6 +347,10 @@ def run(
# a folder on the server, instead of copied here. Nothing can be left in
# place — the server cannot see this computer's files.
uploads = not places and uploads_audio(dest)
# The library's optional readying of a file copied FOR it (Traktor: its
# own block removed from the copy). Only copies made here: never a file
# added in place, nor an upload (written on the server).
prepare = getattr(dest, "prepare_copied_audio", None)
if uploads and reference and not getattr(source, "on_library_host", False):
raise ValueError("A remote library cannot reference files on this computer")
if not reference and not places and not uploads:
@@ -402,6 +408,8 @@ def run(
handle.progress(message=f"Copying {planned.title}")
created.append(target) # registered BEFORE the write, so a cancel
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
if prepare is not None:
prepare(target)
copied.append((planned, target))
handle.raise_if_cancelled()
@@ -446,9 +454,9 @@ def run(
handle.progress(message="Adding to the playlist…")
current = dest.playlist_entries(into_playlist) or []
have = set(current)
dest.set_playlist_entries(
into_playlist, current + [i for i in all_ids if i not in have]
)
fresh = [i for i in all_ids if i not in have]
at = len(current) if into_playlist_index is None else max(0, min(len(current), into_playlist_index))
dest.set_playlist_entries(into_playlist, current[:at] + fresh + current[at:])
playlists_made = _rebuild_playlists(
source, dest, plan, by_source, folder_name, handle
+979
View File
@@ -0,0 +1,979 @@
"""Pushing an export set into the DJ apps' own libraries on THIS computer.
An export set of kind "computer" is not written into a folder: its tracks and
playlists go straight into the Traktor collection and/or rekordbox library this
computer's DJ apps use — the collection a DJ keeps on a server, prepared there,
and pushed to the laptop that plays the gig. Decided 2026-10-20
(`.claude/discussions/discuss-export-to-local-library-2026-10-20.md`).
## Two modes, chosen on the set
**Merge** (the default) adds and updates ONLY what this set put there: the
user's own tracks and playlists are never touched, and several sets can push
into one library side by side. Each push brings the set's tracks up to date
from the source (the source wins: a cue added on the laptop to a pushed track
is replaced), rebuilds the set's playlists inside ONE folder named after the
set, and removes from the library what left the set — unless another set still
holds it, or rekordbox refuses (a track in its History, Sampler, …), in which
case it stays, is reported, and the next push tries again.
**Overwrite** replaces the whole library with this set: the export writers
build a fresh one in app-data and it is swapped in, as a user would swap an
exported `collection.nml` / `master.db` by hand. Every other set that had been
pushed into that library is gone from it afterwards.
## One shared audio folder
Every pushed file lives under one folder (default `~/Music/Konduktor`), at its
SOURCE path minus the anchor — stable across sets and pushes, so a track in
two sets is one file and one entry in the DJ app. (`common_dir_prefix`, which
an export mirrors from, moves whenever a set changes; in a shared folder that
would leave the same track at two paths.) Being shared, the files can have only
one level, so Normalise lives with the folder in the app's settings, not on a
set. A file is deleted when no set in any library still holds it.
## What Konduktor remembers
A ledger in app-data (`local_push/ledger.json`, Konduktor's own data, never
written into a library): per library (by `library_id`) and set, which local
track each source track became, the copy it uses, a hash of the prep last
pushed (an unchanged track costs nothing on a re-push), and the set's folder;
per audio folder, the facts of each copy (the export manifest's record), so an
unchanged file is never copied again.
## Safety
A push refuses while the DJ app runs (Traktor writes its collection back on
quit, undoing the push; rekordbox holds its database open), checked again
just before each save. It never writes the library open in Konduktor itself,
nor a cloud-synced rekordbox library. Before writing, a Traktor collection
gets a version-history baseline and each push is committed to it (restored by
opening that collection in Konduktor); a rekordbox library is copied to
app-data, the last 10 kept. Audio is copied FIRST and the library written
LAST: a cancel before any save leaves every library untouched and removes the
files this run placed. A copy that REPLACES a file a library already plays
waits under a temporary name until a library has been saved.
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import shutil
import tempfile
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from . import __version__, exports, history, library_id, paths, prefs
from .core import apps_running, registry
from .core import export as core_export
from .core.adapter import AudioChange, NewTrack, Unsupported
from .core.analysis_cache import AnalysisCache
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, write_playlist_tree
from .core.level_plan import shifted
from .exporter import (
PARTIAL_SUFFIX,
ExportPlan,
Level,
PlannedTrack,
_cover,
_fingerprint,
_folder_paths,
_locked,
_measure_missing,
_record,
assign_reuse,
prepare_copy,
prepare_kept,
set_level,
write_copy,
)
from .importer import SPACE_HEADROOM, _existing_files, _key, free_bytes
from .jobs import JobHandle
log = logging.getLogger(__name__)
#: The DJ apps a set can be pushed into, in the order they are offered.
PLATFORMS = ("traktor", "rekordbox")
JOB_KIND = "local-push"
_BACKUPS_KEPT = 10
#: Why a library cannot be pushed into. Facts; the UI words them.
NOT_FOUND = "not_found"
OPEN_IN_KONDUKTOR = "open_in_konduktor"
CLOUD_SYNCED = "cloud_synced"
UNREADABLE = "unreadable"
#: Why a push cannot run.
BLOCKED_NO_TARGET = "no_target"
#: Every library the set names is missing on THIS computer.
BLOCKED_NONE_HERE = "no_library_here"
BLOCKED_EMPTY = "nothing_to_push"
BLOCKED_UNAVAILABLE = "target_unavailable"
BLOCKED_RUNNING = "app_running"
_LOCK = threading.RLock()
class PushRefused(Exception):
"""A push that must not go ahead (a DJ app started, a library became
unwritable). The message is for the user."""
# ---- where things are ---------------------------------------------------------
def _local_dir() -> Path:
return paths.app_data_dir() / "local_push"
def audio_root() -> Path:
"""The shared folder pushed audio lives in: the setting, else the user's
Music folder (platformdirs — hardcoding `~/Music` is wrong somewhere on
every OS) + `Konduktor`."""
raw = prefs.load_prefs().get("localAudioRoot")
if isinstance(raw, str) and raw.strip():
return Path(raw).expanduser()
import platformdirs
return Path(platformdirs.user_music_dir()) / "Konduktor"
def level() -> Level | None:
"""The shared folder's Normalise level, or None when it is off. The
measure / target / ceiling default to Normalize's app settings."""
p = prefs.load_prefs()
if not p.get("localNormalise"):
return None
raw = p.get("localLevel") if isinstance(p.get("localLevel"), dict) else {}
try:
measure = raw.get("measure", p.get("levelMeasure", "lufs"))
return Level(measure=measure if measure in ("lufs", "rms") else "lufs",
target=float(raw.get("target", p.get("levelTarget", -9.0))),
ceiling=float(raw.get("ceiling", p.get("levelCeiling", -1.0))))
except (TypeError, ValueError):
return Level()
def _override(platform: str) -> Path | None:
raw = prefs.load_prefs().get("localLibraries")
value = raw.get(platform) if isinstance(raw, dict) else None
return Path(value).expanduser() if isinstance(value, str) and value.strip() else None
def library_path(platform: str) -> tuple[Path | None, bool]:
"""(the library a push into `platform` writes, whether it was DETECTED).
The setting wins; else the platform's own detection, best first (Traktor:
the newest `Traktor x.y` folder)."""
chosen = _override(platform)
if chosen is not None:
return chosen, False
for found in registry.detect_for(platform):
raw = found.get("path") if isinstance(found, dict) else getattr(found, "path", None)
if raw and Path(raw).is_file():
return Path(raw), True
return None, True
def _same(a: Path | None, b: Path | None) -> bool:
if a is None or b is None:
return False
try:
return Path(a).resolve() == Path(b).resolve()
except OSError:
return str(a) == str(b)
# Opening a library to ask whether it can be written costs a parse; the answer
# only changes with the file, so it is kept per path + mtime. Only a platform
# whose library can be read-only is opened for it: rekordbox (cloud sync). A
# Traktor collection is always writable, and parsing 8,000 entries to hear so
# would hold up the dialog that asks.
_MAY_BE_READ_ONLY = {"rekordbox"}
_WRITABLE: dict[tuple[str, int], str | None] = {}
def _unwritable(path: Path, platform: str) -> str | None:
"""Why `platform`'s library at `path` cannot be written, or None."""
try:
stamp = (str(path), path.stat().st_mtime_ns)
except OSError:
return NOT_FOUND
if stamp in _WRITABLE:
return _WRITABLE[stamp]
reason: str | None
adapter = None
try:
driver = registry.driver_for(path) # the cheap probe: is it that format at all?
if driver.platform != platform:
reason = UNREADABLE # e.g. a master.db chosen as the Traktor collection
elif driver.platform not in _MAY_BE_READ_ONLY:
reason = None
else:
adapter = driver.open(path)
caps = adapter.capabilities()
if caps.writable:
reason = None
else:
reason = CLOUD_SYNCED if caps.readonly_cause == "cloud_synced" else UNREADABLE
except Exception as ex: # noqa: BLE001 — anything that will not open is not a target
log.warning("cannot open %s to push into: %s", path, ex)
reason = UNREADABLE
finally:
_close(adapter)
_WRITABLE[stamp] = reason
return reason
def _close(adapter) -> None:
close = getattr(adapter, "close", None)
if close is not None:
try:
close()
except Exception: # noqa: BLE001
log.warning("closing a pushed-into library failed", exc_info=True)
def _display_name(platform: str) -> str:
try:
return registry.driver_by_platform(platform).display_name
except registry.LibraryNotSupported:
return platform
@dataclass
class LocalLibrary:
"""One DJ app's library on this computer, as a push target."""
platform: str
name: str
path: str | None
detected: bool
#: Why it cannot be pushed into (`NOT_FOUND`, `OPEN_IN_KONDUKTOR`,
#: `CLOUD_SYNCED`, `UNREADABLE`), or None.
blocked: str | None = None
running: bool = False
def as_dict(self) -> dict:
return dict(self.__dict__)
def local_libraries(open_path: Path | None, platforms=PLATFORMS) -> list[LocalLibrary]:
"""The push targets this computer has, each with why it cannot be used."""
running = apps_running.running(list(platforms))
out = []
for platform in platforms:
path, detected = library_path(platform)
lib = LocalLibrary(platform=platform, name=_display_name(platform),
path=str(path) if path else None, detected=detected,
running=platform in running)
if path is None or not path.is_file():
lib.blocked = NOT_FOUND
elif _same(path, open_path):
# Its edits are the open session's; a push would race them.
lib.blocked = OPEN_IN_KONDUKTOR
else:
lib.blocked = _unwritable(path, platform)
out.append(lib)
return out
# ---- the ledger ----------------------------------------------------------------
def _ledger_path() -> Path:
return _local_dir() / "ledger.json"
def _read_ledger() -> dict:
data = paths.read_json(_ledger_path(), {})
if not isinstance(data, dict):
data = {}
data.setdefault("libraries", {})
data.setdefault("audio", {})
return data
def _write_ledger(doc: dict) -> None:
paths.write_json(_ledger_path(), doc)
def _rel_for(source: Path) -> str:
"""Where `source` sits under the shared folder: its whole path minus the
anchor (`/Volumes/Music/a.mp3` -> `Volumes/Music/a.mp3`, `D:\\x.mp3` ->
`D/x.mp3`). Never collides, and never moves when a set changes."""
text = str(source).replace("\\", "/")
if len(text) >= 2 and text[1] == ":":
text = text[0] + text[2:]
return text.lstrip("/")
def _owned(doc: dict) -> set[str]:
"""Every copy (by `rel`) some set in some library still holds."""
out = set()
for lib in doc["libraries"].values():
for entry in (lib.get("sets") or {}).values():
for rec in (entry.get("tracks") or {}).values():
if rec.get("rel"):
out.add(rec["rel"])
return out
# ---- planning -------------------------------------------------------------------
@dataclass
class TargetPlan:
platform: str
name: str
path: str | None
blocked: str | None = None
running: bool = False
#: Tracks this set has not pushed into this library before.
add: int = 0
#: Tracks it has: kept as they are, or brought up to date where changed.
already: int = 0
#: Tracks that left the set since the last push (removed from the library
#: unless another set holds them, or rekordbox refuses).
remove: int = 0
#: Overwrite: the other sets pushed into this library, which it removes.
wipes_sets: list[str] = field(default_factory=list)
@property
def skipped(self) -> bool:
"""Not on this computer, so passed over rather than blocking: a set's
targets are shared by every computer that opens the library (a
remote's sets live on its server), and one with only Traktor must
still push a Traktor + rekordbox set."""
return self.blocked == NOT_FOUND
def as_dict(self) -> dict:
return {**self.__dict__, "skipped": self.skipped}
@dataclass
class PushPlan:
#: The audio, planned as an export into the shared folder: one
#: `PlannedTrack` per track, `destination` = its copy there, `reuse` set
#: where the copy on record is still good.
audio: ExportPlan
playlists: list[ExportPlaylist]
targets: list[TargetPlan]
mode: str = "merge"
blocked: str | None = None
#: The copies on record before this push, by source path (for `reuse`).
previous: dict = field(default_factory=dict)
@property
def tracks(self) -> list[PlannedTrack]:
return self.audio.tracks
@property
def active(self) -> list[TargetPlan]:
"""The targets this push writes: every one found on this computer."""
return [t for t in self.targets if not t.skipped]
def as_dict(self) -> dict:
audio = self.audio
free = free_bytes(audio.destination) if audio.destination else None
need = audio.total_bytes
counts: dict[str, int] = {}
for t in audio.exportable:
if t.level_outcome:
counts[t.level_outcome] = counts.get(t.level_outcome, 0) + 1
return {
"mode": self.mode,
"tracks": len(audio.tracks),
"pushable": len(audio.exportable),
"unchanged": audio.unchanged,
"missing": [t.title for t in audio.tracks if t.missing],
"playlists": [p.name for p in self.playlists],
"total_bytes": need,
"audio_root": str(audio.destination),
"free_bytes": free,
"enough_space": None if free is None else free >= need + SPACE_HEADROOM,
"normalised": sum(1 for t in audio.exportable if t.gain_db),
"level_counts": counts,
"to_measure": sum(1 for t in audio.exportable if t.needs_loudness and t.loudness is None),
"targets": [t.as_dict() for t in self.targets],
"blocked": self.blocked,
}
def plan(adapter, export_set, *, store=None, level: Level | None = None,
auto_gain: bool = False, open_path: Path | None = None) -> PushPlan:
"""What a push of `export_set` would do now. Reads only — neither the
target libraries (their state is the ledger's, checked again by the run)
nor any audio file."""
root = audio_root()
built = ExportPlan(destination=root)
doc = _read_ledger()
records = doc["audio"].get(str(root)) or {}
previous = {r["source"]: (root / rel, r) for rel, r in records.items()
if isinstance(r, dict) and isinstance(r.get("source"), str)}
resolved = exports.resolve(adapter, export_set)
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
facts = adapter.audio_facts([t.id for t in tracks])
wants_loudness = store is not None and (level is not None or auto_gain)
entries = store.get([f.key for f in facts.values() if f is not None]) if wants_loudness else {}
for track in tracks:
fact = facts.get(track.id)
source = Path(fact.key) if fact is not None else None
planned = PlannedTrack(
track_id=track.id,
title=track.title or (source.name if source else track.id),
source_path=source,
destination=(root / _rel_for(source)) if source else None,
size=fact.size if fact else 0,
mtime_ns=fact.mtime_ns if fact else 0,
missing=fact is None,
needs_loudness=fact is not None and wants_loudness,
)
if planned.needs_loudness:
entry = entries.get(fact.key)
planned.loudness = entry.values if entry is not None and not entry.stale(fact) else None
if fact is not None and level is not None:
set_level(planned, level)
built.tracks.append(planned)
assign_reuse(built, previous)
folders = _folder_paths(adapter)
playlists = [ExportPlaylist(name=p.name, track_ids=list(p.track_ids), folders=folders.get(p.id, []))
for p in resolved.playlists if not p.missing and p.track_ids]
pushable = {t.track_id for t in built.exportable}
targets = []
known = {lib.platform: lib for lib in local_libraries(open_path, [
t for t in export_set.targets if t in PLATFORMS])}
for platform in export_set.targets:
lib = known.get(platform)
if lib is None:
targets.append(TargetPlan(platform=platform, name=_display_name(platform), path=None,
blocked=NOT_FOUND))
continue
target = TargetPlan(platform=platform, name=lib.name, path=lib.path,
blocked=lib.blocked, running=lib.running)
lid = library_id.read_sidecar(Path(lib.path)) if lib.path else None
sets = (doc["libraries"].get(lid) or {}).get("sets") or {} if lid else {}
mine = (sets.get(export_set.id) or {}).get("tracks") or {}
target.add = sum(1 for t in pushable if t not in mine)
target.already = sum(1 for t in pushable if t in mine)
target.remove = sum(1 for t in mine if t not in pushable)
if export_set.mode == "overwrite":
target.wipes_sets = sorted(s.get("name") or "Untitled"
for sid, s in sets.items() if sid != export_set.id)
targets.append(target)
out = PushPlan(audio=built, playlists=playlists, targets=targets, mode=export_set.mode,
previous=previous)
if not targets:
out.blocked = BLOCKED_NO_TARGET
elif not out.active:
out.blocked = BLOCKED_NONE_HERE
elif not built.exportable:
out.blocked = BLOCKED_EMPTY
elif any(t.blocked for t in out.active):
out.blocked = BLOCKED_UNAVAILABLE
elif any(t.running for t in out.active):
out.blocked = BLOCKED_RUNNING
return out
# ---- running --------------------------------------------------------------------
def _partial(target: Path) -> Path:
return target.with_name(target.name + PARTIAL_SUFFIX)
def _jsonable(value):
if value is None:
return None
dump = getattr(value, "model_dump", None)
if dump is not None:
return dump()
if hasattr(value, "__dict__"):
return dict(value.__dict__)
return value
_PREP_FIELDS = ("title", "artist", "album", "genre", "label", "remixer", "producer", "mix",
"comment", "comment2", "release_date", "rating", "key_wheel", "key_mode", "color")
_METADATA_FIELDS = ("title", "artist", "album", "genre", "label", "remixer", "producer", "mix",
"comment", "comment2", "release_date", "rating")
def _prep_hash(item: ExportTrack) -> str:
"""What a re-push compares: the track's own fields, its cues and grid
(lock included) and the auto gain it would get — not the file, whose
copy is checked by its own facts."""
blob = {
"track": {k: getattr(item.track, k, None) for k in _PREP_FIELDS},
"cues": _jsonable(item.cues),
"loudness": _jsonable(item.loudness),
"gain_db": round(item.gain_db, 4),
}
return hashlib.sha256(json.dumps(blob, sort_keys=True, default=str).encode()).hexdigest()[:24]
def _checkpoint(handle: JobHandle):
def checkpoint(message: str, step: int | None = None, of: int | None = None) -> None:
handle.raise_if_cancelled()
if step is not None and of:
handle.progress(done=step - 1, total=of, unit="tracks", message=message)
else:
handle.progress(message=message)
return checkpoint
def _refuse_if_running(platform: str) -> None:
if apps_running.running([platform]):
raise PushRefused(f"{_display_name(platform)} is running — quit it, then push again")
def run(adapter, export_set, built: PushPlan, handle: JobHandle, *, lock_grids: bool = True,
store=None, level: Level | None = None, auto_gain: bool = False) -> dict:
"""Copy what changed into the shared folder, then push into each target.
See the module docstring for the order and what a cancel leaves."""
if built.blocked:
raise PushRefused(f"This push cannot run: {built.blocked}")
for target in built.active:
_refuse_if_running(target.platform)
root = Path(built.audio.destination)
created: list[Path] = [] # new files this run placed (rolled back)
waiting: list[tuple[Path, Path]] = [] # (partial, file) replacing a file in use
written: set[str] = set() # source ids whose copy this run wrote
saved = False
done = 0
try:
_measure_missing(adapter, built.audio, handle, store=store, level=level,
previous=built.previous)
items = built.audio.exportable
# The targets' writers, for `prepare_copy` (Traktor's removes its own
# block from the file, which it would restore over the pushed grid).
writers = [w for w in (core_export.for_platform(t.platform) for t in built.active) if w]
handle.progress(done=0, total=built.audio.total_bytes, unit="bytes", message="Copying…")
for planned in items:
handle.raise_if_cancelled()
if planned.reuse is not None:
# Kept: prepared for any target that has not yet. In place —
# no target app is running (refused above), and a library
# already holding the file re-reads its tags on its own.
old = built.previous.get(str(planned.source_path))
prepare_kept(planned.reuse, planned, old[1] if old else {}, writers)
continue
target = Path(planned.destination)
target.parent.mkdir(parents=True, exist_ok=True)
partial = _partial(target)
created.append(partial)
def advance(n: int) -> None:
nonlocal done
done += n
handle.progress(done=done)
handle.progress(message=f"Copying {planned.title}")
write_copy(adapter, planned, partial, handle, advance)
planned.prepared = prepare_copy(partial, writers)
written.add(planned.track_id)
if target.exists():
# A library may be playing this file: it is replaced only
# once a library has been saved to match.
waiting.append((partial, target))
else:
os.replace(partial, target)
created.remove(partial)
created.append(target)
cache = AnalysisCache(_local_dir() / "analysis")
payload_tracks = []
for planned in items:
handle.raise_if_cancelled()
payload_tracks.append(ExportTrack(
track=adapter.track(planned.track_id),
destination=Path(planned.destination),
cues=_locked(adapter.track_cues(planned.track_id), lock_grids),
art=_cover(adapter, planned.track_id),
fingerprint=_fingerprint(planned),
analysis_cache=cache,
loudness=(shifted(planned.loudness, planned.gain_db)
if auto_gain and planned.loudness is not None else None),
gain_db=planned.gain_db,
))
payload = ExportPayload(name=export_set.name, root_folder=True, tracks=payload_tracks,
playlists=built.playlists, checkpoint=_checkpoint(handle))
results = []
for target in built.active:
handle.raise_if_cancelled()
handle.progress(done=0, total=0, unit="tracks",
message=f"Pushing into {target.name}…")
push = _overwrite if export_set.mode == "overwrite" else _merge
results.append(push(target, export_set, payload, handle,
planned={t.track_id: t for t in items}, written=written,
waiting=waiting, previous=built.previous))
saved = True
# The library now plays the new files: the waiting ones go in.
for partial, final in waiting:
os.replace(partial, final)
waiting.clear()
with _LOCK:
doc = _read_ledger()
records = doc["audio"].setdefault(str(root), {})
for planned in items:
records[_rel_for(planned.source_path)] = _record(planned, Path(planned.destination))
removed = _prune_audio(doc, root)
_write_ledger(doc)
return {
"tracks": len(items),
"copied": len(written),
"unchanged": built.audio.unchanged,
"normalised": sum(1 for t in items if t.gain_db),
"skipped": len(built.audio.tracks) - len(items),
"deleted_files": removed,
"audio_root": str(root),
"targets": results,
"skipped_targets": [t.name for t in built.targets if t.skipped],
}
except BaseException:
for partial, _final in waiting:
partial.unlink(missing_ok=True)
if not saved:
# No library refers to anything this run placed.
for path in created:
path.unlink(missing_ok=True)
raise
def _prune_audio(doc: dict, root: Path) -> int:
"""Delete the shared folder's copies no set holds any more."""
records = doc["audio"].get(str(root)) or {}
owned = _owned(doc)
gone = [rel for rel in records if rel not in owned]
for rel in gone:
path = root / rel
try:
path.unlink(missing_ok=True)
except OSError as ex:
log.warning("could not delete %s: %s", path, ex)
continue
records.pop(rel, None)
_prune_empty(path.parent, root)
return len(gone)
def _prune_empty(folder: Path, root: Path) -> None:
while folder != root and root in folder.parents:
try:
folder.rmdir()
except OSError:
return
folder = folder.parent
# ---- one library: merge ------------------------------------------------------------
def _backup(platform: str, path: Path) -> None:
"""Before a push writes `path`. Traktor: a version-history baseline (the
push itself is committed after). rekordbox, which Konduktor does not
version (a library is more than one file): the database, its WAL and the
playlist XML copied to app-data, the last 10 kept."""
if platform == "traktor":
history.ensure_baseline(path)
return
base = _local_dir() / "backups" / platform
dest = base / time.strftime("%Y%m%d-%H%M%S")
n = 1
while dest.exists():
n += 1
dest = base / f"{time.strftime('%Y%m%d-%H%M%S')}-{n}"
dest.mkdir(parents=True)
for p in (path, path.with_name(path.name + "-wal"), path.with_name("masterPlaylists6.xml")):
if p.is_file():
shutil.copy2(p, dest / p.name)
for old in sorted(d for d in base.iterdir() if d.is_dir())[:-_BACKUPS_KEPT]:
shutil.rmtree(old, ignore_errors=True)
def _commit(platform: str, path: Path, data: bytes | None, summary: str) -> None:
if platform == "traktor" and data is not None:
history.commit(path, data, summary, __version__)
def _folder_name(adapter, wanted: str, own: str | None) -> str:
"""The set's folder name: `wanted`, unless a top-level node the user owns
already has it — Traktor's `create_folder` would hand back THEIR folder,
and the next push would delete it."""
taken = {n.name for n in adapter.playlist_tree() if n.id != own}
name, n = wanted, 1
while name in taken:
name = f"{wanted} (Konduktor)" if n == 1 else f"{wanted} (Konduktor {n})"
n += 1
return name
def _tree_hash(name: str, payload: ExportPayload, moved: dict[str, str]) -> str:
blob = [name, [[p.name, p.folders, [moved.get(t) for t in p.track_ids]] for p in payload.playlists],
[moved.get(t.source_id) for t in payload.tracks]]
return hashlib.sha256(json.dumps(blob).encode()).hexdigest()[:24]
def _node_ids(nodes) -> set[str]:
out = set()
for n in nodes or []:
out.add(n.id)
out |= _node_ids(getattr(n, "children", None))
return out
def _update(target, local_id: str, item: ExportTrack, *, audio_change: AudioChange | None) -> None:
"""Bring a track this set pushed earlier up to date with the source."""
caps = target.capabilities().tracks
now = target.track(local_id)
fields = {}
for k in _METADATA_FIELDS:
if k in caps.editable_fields:
value = getattr(item.track, k, None)
if (getattr(now, k, None) or None) != (value or None):
fields[k] = value if value is not None else ("" if k != "rating" else 0)
if fields:
target.set_track_metadata(local_id, fields)
if caps.key_writable and item.track.key_wheel and item.track.key_mode and (
(now.key_wheel, now.key_mode) != (item.track.key_wheel, item.track.key_mode)):
target.set_key(local_id, item.track.key_wheel, item.track.key_mode)
if caps.colors and now.color != item.track.color:
target.set_track_color(local_id, item.track.color)
if audio_change is not None and caps.normalizable:
target.audio_changed(local_id, audio_change)
if item.loudness is not None and caps.auto_gain:
target.set_auto_gain(local_id, item.loudness)
if item.cues is not None:
target.replace_cues(local_id, item.cues)
def _audio_change(target, item: ExportTrack, planned: PlannedTrack, previous: dict,
waiting: list) -> AudioChange:
"""What a copy written this run means to a library already playing it:
its size, the level change, and — for a platform that draws waveforms
from the file (rekordbox) — the new audio measured at its time base."""
final = item.destination
path = next((p for p, f in waiting if f == final), final)
old = previous.get(str(planned.source_path))
before = float((old[1] if old else {}).get("gain_db") or 0.0)
measured = None
lead = getattr(target, "analysis_lead", None)
if lead is not None:
from .core import waveform
try:
measured = waveform.analyse(path, lead=lead(final))
except Exception as ex: # noqa: BLE001 — the old waveform stays drawn
log.warning("could not measure %s for its waveform: %s", path, ex)
return AudioChange(gain_db=item.gain_db - before, size=path.stat().st_size, measured=measured)
def _merge(tp: TargetPlan, export_set, payload: ExportPayload, handle: JobHandle, *,
planned: dict[str, PlannedTrack], written: set[str], waiting: list,
previous: dict) -> dict:
path = Path(tp.path)
lid = library_id.for_path(path, platform=tp.platform, label=tp.name)
with _LOCK:
doc = _read_ledger()
lib = doc["libraries"].get(lid) or {}
sets = lib.get("sets") or {}
mine = sets.get(export_set.id) or {}
tracks: dict[str, dict] = dict(mine.get("tracks") or {})
others = {rec.get("local_id") for sid, s in sets.items() if sid != export_set.id
for rec in (s.get("tracks") or {}).values()}
_backup(tp.platform, path)
target = registry.open_library(path)
try:
caps = target.capabilities()
if not caps.writable:
raise PushRefused(f"{tp.name} cannot be written: {caps.readonly_cause}")
held = _existing_files(target)
moved: dict[str, str] = {}
new_items: list[ExportTrack] = []
updates: list[tuple[ExportTrack, str]] = []
for item in payload.tracks:
sid = item.source_id
rec = tracks.get(sid)
local = rec.get("local_id") if rec and rec.get("local_id") else None
if local is not None and target.track(local) is None:
local = None # removed in the DJ app since: add it again
if local is None:
# Already in the library at that path (another set's, or a
# ledger that was lost): the same file is the same track — a
# second entry would be a corrupt Traktor collection.
local = held.get(_key(item.destination))
if local is None:
new_items.append(item)
continue
moved[sid] = local
if rec is None or rec.get("prep") != _prep_hash(item) or sid in written:
updates.append((item, local))
added = target.add_tracks(
[NewTrack(track=i.track, audio_path=i.destination, cues=i.cues, art=i.art)
for i in new_items], checkpoint=payload.checkpoint) if new_items else []
for item, local in zip(new_items, added):
moved[item.source_id] = local
if item.loudness is not None and caps.tracks.auto_gain:
target.set_auto_gain(local, item.loudness)
for n, (item, local) in enumerate(updates, start=1):
payload.checkpoint(f"Updating {item.track.title or item.destination.name}", step=n,
of=len(updates))
change = (_audio_change(target, item, planned[item.source_id], previous, waiting)
if item.source_id in written else None)
_update(target, local, item, audio_change=change)
# What left the set.
present = {i.source_id for i in payload.tracks}
kept: list[str] = []
removed = 0
for sid in [s for s in tracks if s not in present]:
rec = tracks[sid]
local = rec.get("local_id")
if not local or local in others or target.track(local) is None:
tracks.pop(sid)
continue
title = target.track(local).title or local
try:
target.remove_tracks([local])
removed += 1
tracks.pop(sid)
except Unsupported as ex:
# rekordbox: a track in its History, Sampler, … — kept, and
# the next push tries again.
kept.append(title)
rec["kept"] = str(ex)
for item in payload.tracks:
local = moved.get(item.source_id)
if local is not None:
tracks[item.source_id] = {
"local_id": local, "rel": _rel_for(planned[item.source_id].source_path),
"prep": _prep_hash(item)}
# The set's folder, rebuilt when anything in it would change.
existing = _node_ids(target.playlist_tree())
folder = mine.get("folder_id") if mine.get("folder_id") in existing else None
tree = _tree_hash(export_set.name, payload, moved)
if folder is None or mine.get("tree") != tree or mine.get("folder_name") != export_set.name:
if folder is not None:
target.delete_playlist(folder)
name = _folder_name(target, export_set.name, None)
folder = target.create_folder(name)
write_playlist_tree(target, payload.playlists, [t.source_id for t in payload.tracks],
moved, folder)
folder_name = export_set.name
else:
folder_name = mine.get("folder_name")
if target.dirty:
_refuse_if_running(tp.platform)
handle.progress(message=f"Saving {tp.name}…")
outcome = target.save()
_commit(tp.platform, path, getattr(outcome, "snapshot", None),
f"Pushed “{export_set.name}” from Konduktor")
with _LOCK:
doc = _read_ledger()
lib = doc["libraries"].setdefault(lid, {})
lib.update({"platform": tp.platform, "path": str(path)})
lib.setdefault("sets", {})[export_set.id] = {
"name": export_set.name, "folder_id": folder, "folder_name": folder_name,
"tree": tree, "tracks": tracks, "pushed": time.time(),
}
_write_ledger(doc)
return {"platform": tp.platform, "name": tp.name, "added": len(new_items),
"updated": len(updates), "removed": removed, "kept": kept}
finally:
_close(target)
# ---- one library: overwrite ----------------------------------------------------------
def _replace_file(source: Path, final: Path) -> None:
"""Put `source` at `final` atomically: copied beside it, then renamed."""
partial = final.with_name(final.name + PARTIAL_SUFFIX)
shutil.copy2(source, partial)
os.replace(partial, final)
def _overwrite(tp: TargetPlan, export_set, payload: ExportPayload, handle: JobHandle, *,
planned: dict[str, PlannedTrack], written: set[str], waiting: list,
previous: dict) -> dict:
"""Replace the library with this set: the platform's export writer builds
a fresh one in app-data (the playlists in a folder named after the set,
as a merge puts them), and its files are swapped in."""
path = Path(tp.path)
lid = library_id.for_path(path, platform=tp.platform, label=tp.name)
writer = core_export.for_platform(tp.platform)
if writer is None:
raise PushRefused(f"Konduktor cannot write a {tp.name} library")
# The old library goes, so nothing still plays the files being replaced —
# and the writer measures and sizes each file as it now is.
for partial, final in waiting:
os.replace(partial, final)
waiting.clear()
work_root = _local_dir() / "work"
work_root.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(dir=work_root))
try:
result = writer.write(payload, work)
handle.raise_if_cancelled()
_refuse_if_running(tp.platform)
handle.progress(message=f"Replacing the {tp.name} library…")
_backup(tp.platform, path)
if tp.platform == "traktor":
_replace_file(result.library, path)
_commit(tp.platform, path, path.read_bytes(), f"Replaced by “{export_set.name}” from Konduktor")
else:
# rekordbox: the database, its playlist XML and the analysis files
# under `share/` beside it (new UUID paths, so nothing collides).
# A WAL left by the old database would be replayed into the new one.
for suffix in ("-wal", "-shm"):
path.with_name(path.name + suffix).unlink(missing_ok=True)
_replace_file(result.library, path)
xml = work / "masterPlaylists6.xml"
if xml.is_file():
_replace_file(xml, path.with_name(xml.name))
share = work / "share"
if share.is_dir():
shutil.copytree(share, path.parent / "share", dirs_exist_ok=True)
finally:
shutil.rmtree(work, ignore_errors=True)
# Record what the new library holds, so a later merge push of this set
# finds its tracks and folder.
target = registry.open_library(path)
try:
held = _existing_files(target)
tracks = {}
for item in payload.tracks:
local = held.get(_key(item.destination))
if local is not None:
tracks[item.source_id] = {"local_id": local,
"rel": _rel_for(planned[item.source_id].source_path),
"prep": _prep_hash(item)}
folder = next((n.id for n in target.playlist_tree() if n.name == export_set.name), None)
moved = {sid: rec["local_id"] for sid, rec in tracks.items()}
finally:
_close(target)
with _LOCK:
doc = _read_ledger()
doc["libraries"][lid] = {"platform": tp.platform, "path": str(path), "sets": {
export_set.id: {"name": export_set.name, "folder_id": folder,
"folder_name": export_set.name,
"tree": _tree_hash(export_set.name, payload, moved),
"tracks": tracks, "pushed": time.time()}}}
_write_ledger(doc)
return {"platform": tp.platform, "name": tp.name, "added": len(tracks), "updated": 0,
"removed": 0, "kept": [], "replaced": True, "wiped_sets": tp.wipes_sets}
+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)
+634 -96
View File
File diff suppressed because it is too large. Load diff
+391
View File
@@ -0,0 +1,391 @@
"""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 and not _staged(i)}
def staged_gain(self, track_id: str) -> dict | None:
"""A Normalize item for `track_id` whose verified file is written but
not yet in place — on a server, an UPLOAD a takeover interrupted, which
the next run reuses rather than downloading and rewriting again."""
return next((i for i in self.items if i.get("track_id") == track_id and _staged(i)), None)
def summary(self) -> dict:
waiting = self.swapped()
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 _staged(item: dict) -> bool:
"""A gain item still WRITING its file: not yet a change to the library.
Never held across a run on this computer (one batch at a time; a crash's
are cleared at the next open); on a server, an upload awaiting publish."""
return _kind(item) == "gain" and item.get("state") in ("writing", "written")
def _kind(item: dict) -> str:
return item.get("kind") or "stem"
#: 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"]
+21 -3
View File
@@ -38,7 +38,13 @@ from .core.model import AutoHotcue, Track, TrackCues
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
#: 1.3 — memory cues: `add_memory_cue`, `rename_memory_cue`,
#: `set_memory_cue_type`, `set_memory_cue_color`, `delete_memory_cue`.
API_VERSION: tuple[int, int] = (1, 3)
#: 1.4 — track colour: `set_track_color`, `Track.color` / `color_hex`.
#: 1.5 — loudness: `/v1/loudness/get`, `PUT /v1/loudness`, and `loudness` on
#: `/v1/stems/stage` (the server keeps a remote library's measurements).
#: 1.6 — auto gain: `set_auto_gain`, `Track.auto_gain_db`.
#: 1.7 — Normalize: `/v1/gain/plan|stage|waveform|abandon|publish`, and
#: `gain_tracks` / `gain_lossless` in `/v1/stems/pending`.
API_VERSION: tuple[int, int] = (1, 7)
#: How long a session survives without a heartbeat, and how often the holder
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
@@ -77,7 +83,8 @@ _READ = (
)
_MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key",
"set_track_color", "set_auto_gain", "set_cue",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_memory_cue",
"rename_memory_cue", "set_memory_cue_type", "set_memory_cue_color", "delete_memory_cue", "add_grid_marker",
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
@@ -101,6 +108,8 @@ 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 (POST /v1/gain/publish)",
"replace_cues": "a push targets a DJ app's library on THIS computer, never one a server holds",
"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",
@@ -244,6 +253,9 @@ def pack_analysis(prepared) -> str | None:
**({} if prepared.key is None else {
"key": np.array([prepared.key.pitch_class, prepared.key.wheel,
prepared.key.mode == "minor", prepared.key.confidence], dtype=np.float64)}),
**({} if getattr(prepared, "loudness", None) is None else {
"loudness": np.array([prepared.loudness.lufs, prepared.loudness.rms, prepared.loudness.true_peak,
prepared.loudness.lra, prepared.loudness.plr], dtype=np.float64)}),
)
return base64.b64encode(buf.getvalue()).decode("ascii")
@@ -272,4 +284,10 @@ def unpack_analysis(text: str | None):
pitch, wheel, minor, confidence = z["key"]
key = KeyResult(pitch_class=int(pitch), mode="minor" if minor else "major",
wheel=int(wheel), confidence=float(confidence))
return PreparedAnalysis(measured=measured, markers=markers, key=key)
loud = None
if "loudness" in z:
from .core.loudness import Loudness
lufs, rms, tp, lra, plr = (float(v) for v in z["loudness"])
loud = Loudness(lufs=lufs, rms=rms, true_peak=tp, lra=lra, plr=plr)
return PreparedAnalysis(measured=measured, markers=markers, key=key, loudness=loud)
+202 -3
View File
@@ -5,7 +5,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType
from .core.capabilities import CueRole, CueType, TrackColor
class CreatePlaylist(BaseModel):
@@ -27,6 +27,15 @@ class AddEntries(BaseModel):
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and
# report how many, so the UI can ask and send again with skip/add.
duplicates: Literal["skip", "add", "ask"] = "skip"
# Insert at this position among the playlist's CURRENT entries (a drop
# between rows); None appends. Clamped to the list.
index: int | None = None
class RemoveEntries(BaseModel):
track_ids: list[str]
# Count what would go and change nothing — the confirm dialog's numbers.
dry_run: bool = False
class MovePlaylist(BaseModel):
@@ -40,6 +49,13 @@ class EditTrack(BaseModel):
fields: dict[str, str | int | None]
class SetTrackColor(BaseModel):
"""The context menu's Colour ▸: one colour (None = No Color) for a selection."""
track_ids: list[str]
color: TrackColor | None = None
class FileTagOutcome(BaseModel):
track_id: str
file: str
@@ -147,17 +163,34 @@ 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. `gain` writes the DJ app's own auto gain from the
track's loudness (measured first where it has none, or a stale one) —
only where the track has none, unless `replace_gain`."""
track_ids: list[str]
bpm: bool = True
grid: bool = True
key: bool = False
loudness: bool = False
gain: bool = False
replace_grid: bool = False
replace_key: bool = False
replace_loudness: bool = False
replace_gain: bool = False
origin: LoudnessOrigin = "collection"
class AnalyzePreview(BaseModel):
@@ -179,6 +212,43 @@ 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)
# Auto gain (the DJ app's own field): a track that has one is skipped
# unless Replace is ticked.
gain_set: int = 0
gain_existing: int = 0 # skipped: has an auto gain, Replace not ticked
with_gain: int = 0 # tracks that have one (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):
@@ -262,6 +332,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
@@ -333,24 +408,56 @@ class CollectionOptions(BaseModel):
class ExportSetOut(BaseModel):
id: str
name: str
#: "folder": exported into `destination`; "computer": pushed into the DJ
#: apps' own libraries on this computer (`local_push.py`), `mode` saying how.
kind: Literal["folder", "computer"] = "folder"
mode: Literal["merge", "overwrite"] = "merge"
targets: list[str] # platform ids of the export TARGETS, never empty
destination: str
playlist_ids: list[str] = []
track_ids: list[str] = [] # loose tracks only
lock_grids: bool = True
normalise: bool = False
auto_gain: bool = True
level: dict | None = None
created: float = 0.0
modified: float = 0.0
class CreateExportSet(BaseModel):
name: str
kind: Literal["folder", "computer"] = "folder"
mode: Literal["merge", "overwrite"] = "merge"
targets: list[str] = ["traktor"]
destination: str
destination: str = "" # a "computer" set has none
class ExportLevel(BaseModel):
"""Normalise audio's measure / target / ceiling (see `exporter.Level`)."""
measure: Literal["lufs", "rms"] = "lufs"
target: float = Field(-9.0, ge=-30.0, le=0.0)
ceiling: float = Field(-1.0, ge=-12.0, le=0.0)
class UpdateExportSet(BaseModel):
name: str | None = None
mode: Literal["merge", "overwrite"] | None = None
targets: list[str] | None = None
destination: str | None = None
lock_grids: bool | None = None
normalise: bool | None = None
auto_gain: bool | None = None
level: ExportLevel | None = None
class RunExport(BaseModel):
#: The run dialog's options — each remembered on the set. None keeps the
#: set's own answer. The preview takes the same body, so its counts are
#: for the options as ticked.
lock_grids: bool | None = None
normalise: bool | None = None
auto_gain: bool | None = None
level: ExportLevel | None = None
class ExportSetMembers(BaseModel):
@@ -384,6 +491,8 @@ class ExportPreview(BaseModel):
tracks: int = 0
exportable: int = 0
#: Copies from the last export kept rather than copied again.
unchanged: int = 0
missing: list[str] = []
playlists: list[str] = []
total_bytes: int = 0
@@ -398,6 +507,77 @@ class ExportPreview(BaseModel):
#: Targets whose library is only found at a drive's root, when the
#: destination is not one. A warning — the export can still run.
not_drive_root: list[str] = []
#: Normalise audio: copies whose level changes, and every `level_plan`
#: outcome by count. `to_measure`: sources the run measures first (no
#: stored loudness), for Normalise or Auto gain.
normalised: int = 0
to_measure: int = 0
level_counts: dict[str, int] = {}
# ---- pushing into this computer's DJ apps (`local_push.py`) -------------------
class LocalLibraryOut(BaseModel):
"""One DJ app's library on this computer, as a push target."""
platform: str
name: str
path: str | None = None
#: Found by the platform's own detection (False: the user's setting).
detected: bool = True
#: A FACT: `not_found`, `open_in_konduktor`, `cloud_synced`, `unreadable`.
blocked: str | None = None
running: bool = False
class LocalLibrariesOut(BaseModel):
libraries: list[LocalLibraryOut] = []
#: The shared folder pushed audio lives in, and where it is by default.
audio_root: str
audio_root_default: str
#: The shared folder's Normalise level (None: off).
level: ExportLevel | None = None
class PushTargetOut(BaseModel):
platform: str
name: str
path: str | None = None
blocked: str | None = None
#: Not on this computer (`blocked` = not_found): passed over by the push
#: instead of blocking it.
skipped: bool = False
running: bool = False
add: int = 0
already: int = 0
remove: int = 0
#: Overwrite: the other sets pushed into this library, which it removes.
wipes_sets: list[str] = []
class PushPreview(BaseModel):
"""What a push would do now. Computed fresh; never stored."""
mode: Literal["merge", "overwrite"] = "merge"
tracks: int = 0
pushable: int = 0
#: Copies in the shared folder kept rather than copied again.
unchanged: int = 0
missing: list[str] = []
playlists: list[str] = []
total_bytes: int = 0
audio_root: str
free_bytes: int | None = None
enough_space: bool | None = None
normalised: int = 0
to_measure: int = 0
level_counts: dict[str, int] = {}
targets: list[PushTargetOut] = []
#: A FACT: `no_target`, `no_library_here` (none of the set's libraries
#: is on this computer), `nothing_to_push`, `target_unavailable`,
#: `app_running`, or null when it can run.
blocked: str | None = None
class FsPlace(BaseModel):
@@ -538,6 +718,7 @@ class ImportRequest(BaseModel):
# drop): every imported track — and every one the collection already
# holds — goes into it, as folder add does.
into_playlist: str | None = None
into_playlist_index: int | None = None # where in it (see AddEntries.index)
export_id: str | None = None
@@ -606,6 +787,7 @@ class FolderAddRequest(BaseModel):
mode: Literal["copy", "reference"]
destination: str | None = None # required for `copy`
playlist_id: str | None = None
playlist_index: int | None = None # where in it (see AddEntries.index)
export_id: str | None = None
@@ -627,3 +809,20 @@ 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
class MidiExportRequest(BaseModel):
"""A controller mapping written to a file (`/api/midi/export`). Its shape
is the UI's (`lib/midi/mapping.ts`); only the version is checked here."""
dir: str
name: str
mapping: dict
+251 -6
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 ..stems.pending import partial_name, source_facts
from ..core.loudness import Loudness
from ..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}
@@ -627,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
@@ -643,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 {})
@@ -675,6 +709,217 @@ def create_app(server: Server) -> FastAPI:
result["rev"] = server.bump()
return result
# ---- Normalize: the library side ---------------------------------------------
# Like Convert to Stems: the computer that opened the library downloads,
# rewrites + VERIFIES each file and uploads it (the server never decodes
# audio); what lives here is the plan, from the server's own loudness store,
# the uploads (kept as "written" items in the server's ledger, so a
# takeover mid-batch loses nothing — the next run reuses them), and the
# end step, under the library's mutation lock.
def level_options(body: dict):
from ..gain import normalize
measure = body.get("measure") or "lufs"
if measure not in ("lufs", "rms"):
raise HTTPException(400, f"Unknown measure {measure!r}")
try:
return normalize.Options(measure=measure, target=float(body.get("target", -9.0)),
ceiling=float(body.get("ceiling", -1.0)))
except (TypeError, ValueError):
raise HTTPException(400, "Unreadable target or ceiling")
def normalizable():
caps = server.adapter.capabilities()
if not (caps.writable and caps.tracks.normalizable):
raise HTTPException(422, "This library's audio files cannot be normalized")
def gain_source(track_id: str) -> Path:
source = server.adapter.audio_path(track_id)
if source is None or not Path(source).is_file():
raise HTTPException(404, "The track's audio file is missing")
return Path(source)
def waveform_file(track_id: str) -> Path:
import hashlib
from .. import paths
name = hashlib.sha1(track_id.encode("utf-8")).hexdigest()
return paths.app_data_dir() / "gain-waveforms" / f"{name}.npz.b64"
@app.post("/v1/gain/plan")
def gain_plan(body: dict = Body(...)) -> dict:
"""Normalize's plan, from the server's stored loudness — with what the
client needs per row: the source's size (to download), the platform's
analysis lead (None: it draws no waveform), and whether a verified
upload at this very gain is already here (`staged`)."""
from ..gain import normalize
from ..pending import source_facts
normalizable()
opts = level_options(body)
adapter = server.adapter
planned = normalize.plan(adapter, list(body.get("track_ids") or []), opts,
server.state.loudness, server.state.pending)
out = planned.as_dict()
lead = getattr(adapter, "analysis_lead", None)
for row, wire in zip(planned.rows, out["rows"]):
source = row.source if row.source is not None and Path(row.source).is_file() else None
wire["source_size"] = source.stat().st_size if source else 0
wire["lead"] = lead(source) if (lead is not None and source is not None) else None
item = server.state.pending.staged_gain(row.track_id)
wire["staged"] = bool(
item is not None and item.get("state") == "written" and row.step is not None
and abs(float(item.get("gain_db") or 0) - row.step.gain_db) < 1e-6
and source is not None and item.get("facts_before") == source_facts(source)
and Path(item["partial"]).is_file())
return out
@app.put("/v1/gain/stage")
async def gain_stage(request: Request, track_id: str, gain_db: float, sha256: str,
measure: str = "lufs", target: float = -9.0, ceiling: float = -1.0,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""One verified, levelled file, uploaded beside its source as
`<name>.konduktor-partial` and recorded as a "written" item. The gain is
checked against this server's own plan (its stored loudness), so a
stale plan cannot put a file at the wrong level."""
import hashlib
from ..core.level_plan import EXACT, plan_gain
from ..pending import parked_name, partial_name, source_facts
session(token)
normalizable()
opts = level_options({"measure": measure, "target": target, "ceiling": ceiling})
source = gain_source(track_id)
facts = server.adapter.audio_facts([track_id]).get(track_id)
entry = server.state.loudness.get([facts.key]).get(facts.key) if facts else None
if entry is None or entry.stale(facts):
raise HTTPException(409, "The track has no current loudness measurement on the server")
step = plan_gain(entry.values, source.suffix, measure=opts.measure, target=opts.target,
ceiling=opts.ceiling)
if not step.writes or abs(step.gain_db - gain_db) > 1e-6:
raise HTTPException(409, "The track's level changed since it was planned; plan again")
pending = server.state.pending
old = pending.staged_gain(track_id)
if old is not None:
Path(old["partial"]).unlink(missing_ok=True)
pending.drop([old])
if pending.holds([track_id]):
raise HTTPException(409, "The track has a change awaiting Save")
partial = partial_name(source)
if partial.exists():
raise HTTPException(409, f"{partial.name} is in the way")
incoming = source.with_name(f".{source.name}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}")
digest = hashlib.sha256()
try:
with open(incoming, "wb") as out:
async for chunk in request.stream():
out.write(chunk)
digest.update(chunk)
if digest.hexdigest() != sha256.lower():
raise HTTPException(400, "The file arrived damaged (checksum mismatch)")
os.replace(incoming, partial)
finally:
incoming.unlink(missing_ok=True)
track = server.adapter.track(track_id)
pending.add({
"kind": "gain", "track_id": track_id, "source": str(source), "partial": str(partial),
"parked": str(parked_name(source)), "gain_db": step.gain_db,
"lossless": source.suffix.lower() in EXACT, "state": "written",
"facts_before": source_facts(source), "facts_after": source_facts(partial),
"loudness_before": entry.wire(facts.key),
"gain_before": getattr(track, "auto_gain_db", None),
})
waveform_file(track_id).unlink(missing_ok=True)
return {"partial": str(partial), "gain_db": step.gain_db}
@app.put("/v1/gain/waveform")
async def gain_waveform(request: Request, track_id: str,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""The levelled file's drawn-waveform measurement (a packed analysis,
`remote_protocol.pack_analysis`), measured on the client — kept until
the end step regenerates the library's waveform tags from it."""
session(token)
if server.state.pending.staged_gain(track_id) is None:
raise HTTPException(409, "Upload the levelled file first")
data = b"".join([chunk async for chunk in request.stream()])
if rp.unpack_analysis(data.decode("ascii")) is None:
raise HTTPException(400, "Unreadable waveform")
dest = waveform_file(track_id)
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(data)
return {"status": "stored"}
@app.post("/v1/gain/abandon")
def gain_abandon(body: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""A cancelled Normalize: delete the files it uploaded, nothing else."""
session(token)
pending = server.state.pending
for track_id in body.get("track_ids") or []:
item = pending.staged_gain(track_id)
if item is not None:
Path(item["partial"]).unlink(missing_ok=True)
pending.drop([item])
waveform_file(track_id).unlink(missing_ok=True)
return {"status": "abandoned"}
@app.post("/v1/gain/publish")
def gain_publish(body: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""Normalize's END STEP, here where the files are: park each original,
put the uploaded file in its place, and let the library follow (size,
waveforms, the recomputed auto gain) — an unsaved change, which the
server's Save commits and its Discard undoes."""
from ..core.level_plan import GainStep
from ..core.loudness import Loudness
from ..gain import normalize
from ..pending import source_facts
holder = session(token)
normalizable()
pending = server.state.pending
result = {"normalised": [], "failed": []}
with server.state.mutation:
for track_id in body.get("track_ids") or []:
track = server.adapter.track(track_id)
title = (track.title if track else None) or track_id
item = pending.staged_gain(track_id)
if item is None or item.get("state") != "written" or not Path(item["partial"]).is_file():
result["failed"].append({"track_id": track_id, "title": title,
"reason": "the levelled file never reached the server"})
continue
source = Path(item["source"])
if source_facts(source) != item.get("facts_before"):
Path(item["partial"]).unlink(missing_ok=True)
pending.drop([item])
result["failed"].append({"track_id": track_id, "title": title,
"reason": "the file changed on the server meanwhile"})
continue
wave = waveform_file(track_id)
measured = None
if wave.is_file():
prepared = rp.unpack_analysis(wave.read_text("ascii"))
measured = prepared.measured if prepared is not None else None
values = Loudness.from_dict(item["loudness_before"])
row = normalize.Row(track_id, title, source)
try:
normalize._end_step(server.adapter, row, item, values,
GainStep(float(item["gain_db"]), "apply"), measured,
server.state.loudness, pending)
result["normalised"].append(track_id)
except Exception as ex: # noqa: BLE001 — undo that track, keep the rest
log.warning("normalize end step failed for %s", track_id, exc_info=True)
pending._undo_gain(item)
pending.drop([item])
result["failed"].append({"track_id": track_id, "title": title, "reason": str(ex)})
finally:
wave.unlink(missing_ok=True)
server.lock.touch(holder)
result["rev"] = server.bump()
return result
@app.get("/v1/stems/pending")
def stems_pending() -> dict:
pending = server.state.pending
+48 -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}
@@ -155,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):
@@ -259,9 +269,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 +313,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 +391,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)."""
+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
+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"])
+6
View File
@@ -12,10 +12,16 @@ python-multipart>=0.0.9 # multipart form parsing for cover-art upload
# app-data dir. Both bundle cleanly into the frozen sidecar.
dulwich>=0.22
platformdirs>=4.0
# Is Traktor / rekordbox running? (core/apps_running.py — a push refuses while
# one is). Came only through pyrekordbox before; imported directly now.
psutil>=5.9
# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
librosa>=0.11
scikit-learn>=1.5
# Imported directly (not only through librosa): loudness K-weighting and
# true-peak oversampling (core/loudness.py), grid detection, structure.
scipy>=1.11
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
#
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_midi_mappings.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_local_push.py test_traktor_file_block.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+218
View File
@@ -0,0 +1,218 @@
"""AAC-LC's lossless gain edit (`core/aac_gain.py`) on GENERATED files, plus the
user's real ones when present (kits 4 and 5, Kit Bulk's commercial stems).
What would fail silently: a mis-walked frame writing a "global_gain" that is
really spectral data (the walk must end in each frame's last byte, and the
decode of EVERY stream must be the source x 2^(n/4)); a byte changed that is
not a global_gain; a stem file's streams levelled unevenly; HE-AAC (whose SBR
part this edit does not scale) or a non-AAC MP4 treated as AAC-LC.
"""
from __future__ import annotations
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
import av # noqa: E402
import numpy as np # noqa: E402
from konduktor.core import aac_gain, level_edit, pyav # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
from stem_test_support import make_mp3 # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def signal(sr, ch, seconds=5, seed=1):
t = np.arange(int(sr * seconds)) / sr
rng = np.random.default_rng(seed)
beat = np.sin(2 * np.pi * 2 * t) > 0.6
x = [0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.3 * np.sin(2 * np.pi * (440 + 30 * c) * t)
+ 0.2 * rng.standard_normal(t.size)) for c in range(ch)]
if ch == 2:
x[1] = 0.8 * x[0] + 0.2 * x[1] # correlated: invites M/S and intensity stereo
return np.vstack(x).astype(np.float32)
def encode(path: Path, codec: str, sr: int, ch: int, bit_rate: int, options=None, profile=None) -> Path | None:
layout = "stereo" if ch == 2 else "mono"
x = signal(sr, ch)
try:
with av.open(str(path), "w", format="ipod") as c:
s = c.add_stream(codec, rate=sr, layout=layout)
s.bit_rate = bit_rate
if options:
s.options = options
if profile:
s.codec_context.profile = profile
for o in range(0, x.shape[1], 1024):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1024]), format="fltp", layout=layout)
f.sample_rate, f.pts = sr, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
except Exception: # noqa: BLE001 — an encoder this machine lacks (aac_at off macOS)
path.unlink(missing_ok=True)
return None
return path
def decode(path: Path, index: int) -> np.ndarray:
with pyav.open_input(path) as c:
s = c.streams.audio[index]
rs = av.AudioResampler(format="fltp", layout="stereo" if s.codec_context.channels > 1 else "mono",
rate=int(s.codec_context.sample_rate))
out = [o.to_ndarray() for fr in c.decode(s) for o in rs.resample(fr)]
out += [o.to_ndarray() for o in rs.resample(None)]
return np.concatenate(out, axis=1).astype(np.float64)
def exact(src: Path, dst: Path, steps: int, streams: int) -> tuple[bool, str]:
worst = 0.0
for i in range(streams):
a, b = decode(src, i), decode(dst, i)
if a.shape != b.shape:
return False, f"stream {i}: {a.shape} vs {b.shape}"
worst = max(worst, float(np.abs(b - a * 2 ** (steps / 4)).max() / max(np.abs(a).max(), 1e-12)))
return worst < 1e-5, f"{worst:.1e}"
def only_global_gains(src: Path, dst: Path, scanned) -> bool:
a = np.frombuffer(src.read_bytes(), np.uint8)
b = np.frombuffer(dst.read_bytes(), np.uint8)
allowed = set()
for gpos in scanned.positions:
allowed.update((gpos >> 3).tolist())
allowed.update(((gpos >> 3) + 1).tolist())
return a.size == b.size and set(np.nonzero(a != b)[0].tolist()) <= allowed
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-aacgain-"))
CASES = [
("FFmpeg stereo 44.1 kHz", "aac", 44100, 2, 192000, None),
("FFmpeg mono", "aac", 44100, 1, 96000, None),
("FFmpeg 48 kHz", "aac", 48000, 2, 160000, None),
("FFmpeg 22.05 kHz", "aac", 22050, 2, 64000, None),
("FFmpeg 48 kb/s, PNS + intensity + M/S", "aac", 44100, 2, 48000, {"aac_pns": "1", "aac_is": "1", "aac_ms": "1"}),
("FFmpeg with TNS", "aac", 44100, 2, 128000, {"aac_tns": "1"}),
("Apple (aac_at) 128 kb/s", "aac_at", 44100, 2, 128000, None),
("Apple (aac_at) mono 64 kb/s", "aac_at", 44100, 1, 64000, None),
]
print("== generated AAC-LC: the decode is the source x 2^(n/4), only global_gain bytes change ==")
for label, codec, sr, ch, br, opts in CASES:
src = encode(ROOT / f"{len(list(ROOT.iterdir()))}.m4a", codec, sr, ch, br, opts)
if src is None:
print(f" [SKIP] {label}: no {codec} encoder here")
continue
scanned = aac_gain.scan(src)
check(f"{label}: every frame walked", len(scanned.positions[0]) == len(scanned.tracks[0].sizes) * ch,
f"{len(scanned.positions[0])} for {len(scanned.tracks[0].sizes)} frames")
for steps in (-2, 3):
dst = ROOT / f"{src.stem}{steps:+d}.m4a"
aac_gain.apply(src, dst, steps, scanned)
ok, detail = exact(src, dst, steps, 1)
check(f"{label} {steps:+d}: exact", ok, detail)
check(f"{label} {steps:+d}: same size, only global_gain bytes differ", only_global_gains(src, dst, scanned))
print("== a stem file: all five streams by the same steps ==")
source = make_mp3(ROOT / "stem-source.mp3", seconds=5)
stem = ROOT / "track.stem.m4a"
sf.build(source, stem, lambda pcm: [pcm * g for g in (0.5, 0.25, -0.2, 0.1)])
scanned = aac_gain.scan(stem)
check("five AAC streams found", len(scanned.tracks) == 5, str(len(scanned.tracks)))
out = ROOT / "track-2.stem.m4a"
aac_gain.apply(stem, out, -2, scanned)
ok, detail = exact(stem, out, -2, 5)
check("every stream decodes at exactly -2 steps", ok, detail)
check("…the stem box and every other byte untouched", only_global_gains(stem, out, scanned)
and sf.is_stem_file(out))
back = ROOT / "track-back.stem.m4a"
aac_gain.apply(out, back, 2)
check("the opposite steps give the original back, byte for byte", back.read_bytes() == stem.read_bytes())
print("== through level_edit: the generic path ==")
dst = ROOT / "via-level-edit.stem.m4a"
level_edit.apply(stem, dst, -2 * aac_gain.STEP_DB)
try:
level_edit.verify(stem, dst, -2 * aac_gain.STEP_DB)
ok = True
except level_edit.LevelEditError as ex:
ok = str(ex)
check("level_edit applies and verifies an .m4a (all five streams)", ok is True, str(ok))
# One stream levelled unlike the others must fail verification.
part = ROOT / "part.stem.m4a"
one = aac_gain.Scan(scanned.tracks, [p if i == 2 else p[:0] for i, p in enumerate(scanned.positions)],
scanned.min_step, scanned.max_step)
aac_gain.apply(dst, part, 2, one) # stream 2 back up: now it differs from the rest
try:
level_edit.verify(stem, part, -2 * aac_gain.STEP_DB)
caught = False
except level_edit.LevelEditError:
caught = True
check("…and a stem file with one stream at another level fails verification", caught)
try:
level_edit.apply(stem, ROOT / "half.stem.m4a", -2.0)
refused = False
except level_edit.LevelEditError:
refused = True
check("a gain that is not a whole number of steps is refused", refused and not (ROOT / "half.stem.m4a").exists())
print("== refusals leave nothing ==")
he = encode(ROOT / "he.m4a", "aac_at", 44100, 2, 64000, profile="HE-AAC")
if he is None:
print(" [SKIP] no HE-AAC encoder here")
else:
try:
aac_gain.scan(he)
check("HE-AAC is refused (its SBR part is not scaled by global_gain)", False)
except aac_gain.AacGainError:
check("HE-AAC is refused (its SBR part is not scaled by global_gain)", True)
alac = encode(ROOT / "alac.m4a", "alac", 44100, 2, 0)
if alac is not None:
try:
aac_gain.scan(alac)
check("ALAC in an .m4a is refused", False)
except aac_gain.AacGainError:
check("ALAC in an .m4a is refused", True)
try:
aac_gain.apply(stem, ROOT / "far.m4a", scanned.max_step + 1, scanned)
refused = False
except aac_gain.AacGainError:
refused = True
check("steps that would push a scalefactor out of range are refused, leaving no file",
refused and not (ROOT / "far.m4a").exists())
try:
aac_gain.apply(stem, out, -1)
refused = False
except aac_gain.AacGainError:
refused = True
check("an existing target is never overwritten", refused)
print("== real files on this machine (skipped when absent) ==")
kits = Path.home() / "Music" / "Konduktor Stem Test"
real = [kits / "Kit 4" / "K4-8 aac ffmpeg.m4a", kits / "Kit 4" / "K4-9 aac apple.m4a",
*sorted((kits / "Kit 5").glob("*.stem.m4a"))[:2], *sorted((kits / "Kit Bulk").glob("*.stem.m4a"))[:3]]
for f in real:
if not f.is_file():
continue
s = aac_gain.scan(f)
dst = ROOT / f"real-{f.name}"
aac_gain.apply(f, dst, -2, s)
ok, detail = exact(f, dst, -2, len(s.tracks))
check(f"{f.name}: every stream exact at -2 steps", ok, detail)
dst.unlink()
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+4 -1
View File
@@ -153,7 +153,8 @@ for i, (title, artist, key) in enumerate((("One", "Artist A", (8, "minor")), ("T
png = __import__("io").BytesIO()
Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG")
t = Track(id=f"src{i}", title=title, artist=artist, album="LP", genre="House", bpm=125.0,
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio))
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio),
color=("purple", None, "aqua")[i])
tracks.append(ExportTrack(track=t, destination=audio, art=(png.getvalue(), "image/png"),
cues=TrackCues(track_id=t.id, grid_markers=[GridMarker(start=0.0, bpm=125.0)],
cues=[CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0)])))
@@ -174,6 +175,8 @@ check("a track with no key has key 0", lib.tracks[1]["key_id"] == 0)
check("bpm x100, rating, file type, bitmask as rekordbox writes them",
all(t["tempo"] == 12500 and t["u6"] == 11 and t["bitmask"] == 0xC0700 and t["u5"] == 0x29 for t in lib.tracks)
and [t["rating"] for t in lib.tracks] == [1, 2, 3])
check("the track colour is the 1-based id (Purple 8, none 0, Aqua 6)",
[t["color_id"] for t in lib.tracks] == [8, 0, 6], str([t["color_id"] for t in lib.tracks]))
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
tree = {p["name"]: p for p in lib.playlists}
+53 -5
View File
@@ -66,11 +66,14 @@ chosen = [flexible, cued, plain]
dest = Path(tempfile.mkdtemp()) / "GIG"
dest.mkdir(parents=True)
items = []
# Colours by generic name: `aqua` is rekordbox's, which Traktor stores as Blue.
COLOURS = {flexible.id: "aqua", cued.id: "pink", plain.id: None}
for track in chosen:
audio = dest / "Music" / "Library" / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 64)
items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
items.append(ExportTrack(track=track.model_copy(update={"color": COLOURS[track.id]}),
destination=audio, cues=src.track_cues(track.id)))
payload = ExportPayload(
name="GIG",
@@ -126,6 +129,11 @@ check("artist survived", by_title[plain.title].artist == plain.artist)
if plain.key:
check("key notation is copied, not converted", by_title[plain.title].key == plain.key)
check("track colours cross by name: aqua -> Blue (5), pink -> Magenta (7), none -> no COLOR",
[by_title[t.title].color for t in chosen] == ["blue", "pink", None]
and 'COLOR="5"' in text and 'COLOR="7"' in text and text.count(' COLOR="') == 2,
str([by_title[t.title].color for t in chosen]))
print("== the playlist tree ==")
tree = {}
@@ -166,10 +174,14 @@ check("with its tempo changes",
check("and its marker positions",
[round(m.start, 3) for m in out_grid.grid_markers]
== [round(m.start, 3) for m in src_grid.grid_markers])
# Ben's decision: exported grids are NOT locked, so they stay editable like any
# other track. If Traktor turns out to re-analyse and flatten them, this is what
# makes that visible rather than hidden behind a lock.
check("grids are not locked", not by_title[flexible.title].grid_locked)
# A grid crosses with the lock it had: unlocked at the source, unlocked here.
# Locking every grid is the run's "Lock beatgrids" option (below), because
# Traktor DID turn out to re-analyse an unlocked exported track on first load.
check("each track keeps its source's lock",
[by_title[t.title].grid_locked for t in chosen] == [t.grid_locked for t in chosen],
str([(t.title, t.grid_locked, by_title[t.title].grid_locked) for t in chosen]))
check("and only a locked one has LOCK written",
text.count(' LOCK="1"') == sum(1 for t in chosen if t.grid_locked))
src_cues = src.track_cues(cued.id)
out_cues = back.track_cues(by_title[cued.title].id)
@@ -270,6 +282,42 @@ check("the audio is really there",
check("the result re-opens as a library",
len(TraktorDriver().open(dest / "collection.nml").tracks) == len(built.exportable))
print("== Lock beatgrids ==")
check("a new export set locks by default", exports.get(LIB, eset.id).lock_grids is True)
check("and remembers being told not to",
exports.update(LIB, eset.id, lock_grids=False).lock_grids is False
and exports.get(LIB, eset.id).lock_grids is False)
exports.update(LIB, eset.id, lock_grids=True)
gridded = src.track_cues(flexible.id).model_copy(update={"grid_locked": False})
bare = gridded.model_copy(update={"grid_markers": []})
check("on: a grid is locked", exporter._locked(gridded, True).grid_locked)
check("on: a track with no grid is not (Traktor would never give it one)",
not exporter._locked(bare, True).grid_locked)
check("off: the source's own lock is kept",
exporter._locked(gridded.model_copy(update={"grid_locked": True}), False).grid_locked
and not exporter._locked(gridded, False).grid_locked)
lock_dest = Path(tempfile.mkdtemp()) / "LOCKED"
lset = exports.create(LIB, name="LOCKED", targets=["traktor"], destination=str(lock_dest))
exports.add(LIB, lset.id, playlist_ids=[source_pl.id], track_ids=[ad.tracks[3].id])
lset = exports.get(LIB, lset.id)
ljob = JOBS.submit("export", lambda h: exporter.run(
ad, lset, exporter.plan(ad, lset), h, lock_grids=True))
while not ljob.finished:
time.sleep(0.02)
check("a locked export finishes", ljob.state == "done", f"{ljob.state}: {ljob.error}")
ltext = (lock_dest / "collection.nml").read_text(encoding="utf-8")
lback = TraktorDriver().open(lock_dest / "collection.nml")
with_grid = [t for t in lback.tracks if t.grid_marker_count]
check("every exported track with a grid is locked",
with_grid and all(t.grid_locked for t in with_grid),
str([(t.title, t.grid_locked) for t in lback.tracks]))
check("none without one is",
not any(t.grid_locked for t in lback.tracks if not t.grid_marker_count))
# Measured in Traktor 4.5: LOCK="1" then LOCK_MODIFICATION_TIME, ISO, UTC.
check("written as Traktor writes it: LOCK then an ISO LOCK_MODIFICATION_TIME",
len(re.findall(r' LOCK="1" LOCK_MODIFICATION_TIME="\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d"',
ltext)) == len(with_grid))
print("== Konduktor only ever deletes what Konduktor wrote ==")
mine = dest / "MY OWN NOTES.txt"
mine.write_text("do not delete")
+268
View File
@@ -0,0 +1,268 @@
"""Export with "Normalise audio" and "Auto gain", through the routes, on a temp
collection pointed at GENERATED audio, exported to Traktor + Rekordbox Library
+ OneLibrary at once.
What would fail silently, and matter at a gig:
* a normalised COPY is its source at exactly the planned gain, the source is
never touched, and a copy that needs no change is byte-identical;
* the DJ app's gain is written from the COPY's level (Traktor -9.2 - LUFS,
rekordbox -10 - LUFS), and only where the target keeps one;
* sources with no loudness are measured once, into the store;
* the set remembers its options; a re-export at the same level copies
nothing, one at another level re-copies only the copies whose level
changes, and turning Normalise off puts the source's own bytes back;
* the waveform cache is keyed by the level too (else a stick is drawn from
the un-levelled measurement).
"""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-export-level-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
import av # noqa: E402
import numpy as np # noqa: E402
import soundfile as sf # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor import exporter, loudness_store # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.core import level_edit, loudness # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-export-level-"))
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def music(seconds=8.0, amp=0.3, sr=44100, seed=1):
t = np.arange(int(sr * seconds)) / sr
rng = np.random.default_rng(seed)
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
x = [amp * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.3 * np.sin(2 * np.pi * (440 + 30 * c) * t)
+ 0.2 * rng.standard_normal(t.size)) for c in range(2)]
return np.vstack(x).astype(np.float32)
def make(path: Path, amp: float, spike: bool = False) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
x = music(amp=amp)
if spike:
x[:, 44100] = 0.99 # a quiet track with one peak over the ceiling
if path.suffix == ".mp3":
with av.open(str(path), "w", format="mp3") as c:
s = c.add_stream("libmp3lame", rate=44100, layout="stereo")
s.bit_rate = 256_000
for o in range(0, x.shape[1], 1152):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
f.sample_rate, f.pts = 44100, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
else:
sf.write(str(path), x.T, 44100, subtype="PCM_16")
return path
FILES = [("hot.mp3", 0.9, False), ("quiet.flac", 0.05, False), ("hot.wav", 0.8, False),
("spike.wav", 0.02, True)]
def library():
d = ROOT / "lib"
work = d / "collection.nml"
d.mkdir(parents=True)
shutil.copy2(REAL, work)
st = TraktorStore(work)
entries = [e for e in st._nml.collection.entry if e.location and e.stems is None]
ids, files = [], []
for (f, amp, spike), e in zip(FILES, entries):
path = make(d / "Music" / f, amp, spike)
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
e.cue_v2 = [] # the real track's cues mean nothing on 8 s of generated audio
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
ids.append(st._key_of(e))
files.append(path)
st.save()
return work, ids, files
def sha(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def wait(c, jid, timeout=300):
end = time.time() + timeout
while time.time() < end:
j = c.get(f"/api/jobs/{jid}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
raise AssertionError("job did not finish")
def manifest_gains(dest: Path) -> dict[str, float]:
audio = json.loads((dest / exporter.MANIFEST_NAME).read_text())["audio"]
return {Path(rel).name: float(r.get("gain_db") or 0.0) for rel, r in audio.items()}
def traktor_gains(dest: Path) -> dict[str, float | None]:
st = TraktorStore(dest / "collection.nml")
return {e.location.file: (e.loudness.perceived_db if e.loudness is not None else None)
for e in st._nml.collection.entry}
def rekordbox_gains(dest: Path) -> dict[str, float | None]:
ad = RekordboxAdapter(dest / "master.db")
try:
return {Path(t.filepath).name: t.auto_gain_db for t in ad.tracks}
finally:
ad.close()
LEVEL = {"measure": "lufs", "target": -9.0, "ceiling": -1.0}
work, ids, sources = library()
before = {p.name: sha(p) for p in sources}
dest = ROOT / "STICK"
dest.mkdir()
with TestClient(main.app) as c:
r = c.post("/api/library/open", json={"path": str(work)})
assert r.status_code == 200, r.text
s = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor", "rekordbox", "onelibrary"],
"destination": str(dest)}).json()
c.post(f"/api/exports/{s['id']}/add", json={"track_ids": ids})
check("a new set: Normalise off, Auto gain on", (s["normalise"], s["auto_gain"]) == (False, True), str(s))
targets = {o["platform"]: o for o in c.get("/api/export-targets").json()}
check("Auto gain is offered for Traktor and the Rekordbox Library, not for a stick",
targets["traktor"]["writes_auto_gain"] and targets["rekordbox"]["writes_auto_gain"]
and not targets["onelibrary"]["writes_auto_gain"]
and not targets["rekordbox_export"]["writes_auto_gain"])
print("== the first export: every source measured, the copies levelled ==")
body = {"normalise": True, "auto_gain": True, "level": LEVEL}
pv = c.post(f"/api/exports/{s['id']}/preview", json=body).json()
check("the preview counts the sources the run measures first",
pv["to_measure"] == len(ids) and pv["level_counts"].get("unmeasured") == len(ids), str(pv))
j = wait(c, c.post(f"/api/exports/{s['id']}/run", json=body).json()["id"])
check("the export runs", j["state"] == "done", str(j.get("error")))
store = loudness_store.local()
entries = store.get([str(p) for p in sources])
check("every source was measured into the store", len(entries) == len(sources), str(list(entries)))
check("the sources are byte-identical", {p.name: sha(p) for p in sources} == before)
gains = manifest_gains(dest)
check("the manifest records each copy's level", set(gains) == {p.name for p in sources}, str(gains))
check("three copies change level, the spike's does not (hot peak left alone)",
sum(1 for g in gains.values() if g) == 3 and gains["spike.wav"] == 0.0 and j["result"]["normalised"] == 3,
str(gains))
for p in sources:
copy = dest / "Contents" / p.name
g = gains[p.name]
if g:
try:
level_edit.verify(p, copy, g)
ok = True
except level_edit.LevelEditError as ex:
ok = str(ex)
check(f"{p.name}: the copy is the source at {g:+.2f} dB", ok is True, str(ok))
else:
check(f"{p.name}: an unchanged level is a byte-identical copy", sha(copy) == before[p.name])
after = {p.name: shifted for p in sources
if (shifted := entries[str(p)].values.lufs + gains[p.name]) is not None}
tk, rb = traktor_gains(dest), rekordbox_gains(dest)
check("Traktor's gain is -9.2 - the COPY's LUFS",
all(abs(tk[n] - (-9.2 - lufs)) < 1e-3 for n, lufs in after.items()), str(tk))
check("the Rekordbox Library's gain is -10 - the COPY's LUFS",
all(abs(rb[n] - (-10.0 - lufs)) < 1e-3 for n, lufs in after.items()), str(rb))
saved = c.get("/api/exports").json()
mine = next(x for x in saved if x["id"] == s["id"])
check("the set remembers Normalise, Auto gain and the level",
(mine["normalise"], mine["auto_gain"], mine["level"]) == (True, True, LEVEL), str(mine))
print("== a re-export at the same level copies nothing ==")
inodes = {p.name: (dest / "Contents" / p.name).stat().st_ino for p in sources}
pv = c.post(f"/api/exports/{s['id']}/preview", json={}).json()
check("nothing left to measure", pv["to_measure"] == 0, str(pv))
j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={}).json()["id"])
check("every copy kept", j["state"] == "done" and j["result"]["unchanged"] == len(sources), str(j.get("result")))
check("…the very same files", {p.name: (dest / "Contents" / p.name).stat().st_ino for p in sources} == inodes)
print("== another target re-copies only the copies whose level changes ==")
j = wait(c, c.post(f"/api/exports/{s['id']}/run",
json={"level": {**LEVEL, "target": -10.0}}).json()["id"])
new_gains = manifest_gains(dest)
# At -10 the MP3's nearest step and the ceiling-capped FLAC keep their
# gain; the WAV's changes; the spike stays at 0.
changed = {n for n in gains if abs(new_gains[n] - gains[n]) > 0.01}
kept = set(gains) - changed
check("a copy whose level changes is written again — and only that one",
j["state"] == "done" and changed == {"hot.wav"}
and j["result"]["unchanged"] == len(kept), f"{changed} {j.get('result')}")
check("…the others are the very same files",
all((dest / "Contents" / n).stat().st_ino == inodes[n] for n in kept))
try:
level_edit.verify(sources[2], dest / "Contents" / "hot.wav", new_gains["hot.wav"])
ok = True
except level_edit.LevelEditError as ex:
ok = str(ex)
check("…and the re-written one is at the new level", ok is True, str(ok))
print("== Normalise off: the source's own bytes, the gain from the source's level ==")
j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={"normalise": False}).json()["id"])
check("every copy is byte-identical to its source",
j["state"] == "done" and all(sha(dest / "Contents" / p.name) == before[p.name] for p in sources))
tk = traktor_gains(dest)
check("Traktor's gain follows the SOURCE's LUFS",
all(abs(tk[p.name] - (-9.2 - entries[str(p)].values.lufs)) < 1e-3 for p in sources), str(tk))
print("== Auto gain off: none written ==")
j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={"auto_gain": False}).json()["id"])
check("no LOUDNESS in the exported collection", all(v is None for v in traktor_gains(dest).values()))
check("no auto gain in the Rekordbox Library", all(v is None for v in rekordbox_gains(dest).values()))
print("== a file only the file says cannot be levelled (HE-AAC) is copied as it is ==")
real_apply = level_edit.apply
def refuse(src, dst, gain_db):
raise level_edit.LevelEditError(f"{Path(src).name}: only AAC-LC can be changed losslessly")
level_edit.apply = refuse
j = wait(c, c.post(f"/api/exports/{s['id']}/run", json={"normalise": True, "auto_gain": True}).json()["id"])
level_edit.apply = real_apply
check("the export still completes", j["state"] == "done" and j["result"]["normalised"] == 0, str(j.get("error")))
check("…every copy byte-identical to its source, recorded at no gain",
all(sha(dest / "Contents" / p.name) == before[p.name] for p in sources)
and all(g == 0.0 for g in manifest_gains(dest).values()))
check("…and the auto gain from the SOURCE's level",
all(abs(traktor_gains(dest)[p.name] - (-9.2 - entries[str(p)].values.lufs)) < 1e-3 for p in sources))
print("== the waveform cache is keyed by the level ==")
p = exporter.PlannedTrack(track_id="t", title="t", source_path=Path("/x.mp3"), destination=None,
size=10, mtime_ns=1)
plain = exporter._fingerprint(p)
p.gain_db = -3.01
check("a levelled copy gets its own waveform-cache key", exporter._fingerprint(p) != plain)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
raise SystemExit(1 if failed else 0)
+21 -1
View File
@@ -58,13 +58,19 @@ cued = next(t for t in src.tracks
chosen = [flexible, cued]
COLOURS = ["purple", "aqua"]
def build(root: Path) -> ExportPayload:
items = []
for i, track in enumerate(chosen):
audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 4096)
items.append(ExportTrack(track=track, destination=audio,
# A colour each, as the generic name crosses (Traktor's Violet is
# `purple`; `aqua` is rekordbox's own, with no Traktor swatch).
coloured = track.model_copy(update={"color": COLOURS[i % len(COLOURS)]})
items.append(ExportTrack(track=coloured, destination=audio,
cues=src.track_cues(track.id)))
return ExportPayload(
name="GIG", tracks=items,
@@ -136,6 +142,20 @@ for platform, reopen in (
all(abs((by_title[t.title].bpm or 0) - (t.bpm or 0)) < 0.02
for t in chosen if t.bpm))
check("the track colour crossed by name",
[by_title[t.title].color for t in chosen] == COLOURS[:len(chosen)],
str([by_title[t.title].color for t in chosen]))
if platform == "rekordbox":
# Measured 2026-10-19: rekordbox 7's grid padlock sets bit 0x80 of
# `djmdContent.Analysed` (105 -> 233) and nothing else.
analysed = {c.Title: c.Analysed for c in back._store._db.get_content()}
check("a locked grid is Analysed 233, an unlocked one 105",
[analysed[t.title] for t in chosen]
== [233 if src.track_cues(t.id).grid_locked else 105 for t in chosen]
and any(src.track_cues(t.id).grid_locked for t in chosen),
str([(t.title, analysed[t.title]) for t in chosen]))
print(f"-- {platform}: the key was CONVERTED, not copied")
for track in chosen:
if not track.key:
+14
View File
@@ -150,6 +150,20 @@ check("paths are compared normalised, not as strings",
exports.destination_conflict(LIB, str(work / "out") + "/./", ignore=s3.id) == "Ibiza")
exports.delete(LIB, s3.id)
print("== a set pushed into this computer's DJ apps ==")
check("a set saved before kinds existed loads as a folder export, merge",
(exports.get(LIB, s1.id).kind, exports.get(LIB, s1.id).mode) == ("folder", "merge"))
s4 = exports.create(LIB, name="Laptop", targets=["traktor"], destination="", kind="computer",
mode="overwrite")
check("kind and mode persist", (exports.get(LIB, s4.id).kind, exports.get(LIB, s4.id).mode)
== ("computer", "overwrite"))
exports.update(LIB, s4.id, mode="merge", kind="nonsense")
check("mode changes; an unknown kind is ignored",
(exports.get(LIB, s4.id).kind, exports.get(LIB, s4.id).mode) == ("computer", "merge"))
check("a computer set has no destination to clash over",
exports.destination_conflict(LIB, "", ignore=s1.id) is None)
exports.delete(LIB, s4.id)
print("== following track ids that change under a path remap ==")
exports.retarget(LIB, {all_tracks[0]: "Macintosh HD/:Moved/:one.mp3"})
check("a renamed id is followed",
+5 -1
View File
@@ -181,7 +181,9 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
three_dir = music / "Deeper"
c.get("/api/folder/tracks", params={"path": str(three_dir)})
dest = Path(tempfile.mkdtemp()) / "Imported"
req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest)}
# Dropped between the playlist's rows: inserted there, not appended.
req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest),
"playlist_id": playlist, "playlist_index": 1}
p = c.post("/api/folder/add/preview", json=req).json()
check("the preview sizes the copy", p["total_bytes"] > 0, str(p))
job = wait(c, c.post("/api/folder/add", json=req).json())
@@ -191,6 +193,8 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac",
str(a.audio_path(copied_id)))
check("the original is untouched", (three_dir / "three.flac").is_file())
check("it went into the playlist AT the index", a.playlist_entries(playlist) == [added, copied_id, new],
str(a.playlist_entries(playlist)))
check("copy without a destination is refused",
c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400)
check("an unscanned file cannot be added",
+43
View File
@@ -20,6 +20,9 @@ from types import SimpleNamespace
import numpy as np
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
# Loudness (and its store) is measured by these routes too: keep it out of the
# real app-data. Set before konduktor is imported.
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-grid-batch-appdata-")
failed = False
@@ -338,6 +341,46 @@ with tempfile.TemporaryDirectory() as d:
main.key_detect.detect_key_samples = lambda y, sr: (_ for _ in ()).throw(RuntimeError("boom"))
r = c.post("/api/tracks/grid/auto", json={"track_id": bare[1]})
check("…and a failing key never fails the grid", r.status_code == 200, r.text[:200])
# Gain: the DJ app's auto gain from the stored loudness — measured
# first where there is none, skipped where the track has a gain unless
# Replace. Traktor's value is -9.2 - LUFS (kit G1).
from konduktor.core.loudness import Loudness
measured: list[str] = []
main.loudness.measure_file = lambda p: (measured.append(str(p))
or Loudness(lufs=-12.0, rms=-10.0, true_peak=-1.0, lra=5.0, plr=11.0))
has = [t.id for t in a.tracks if t.auto_gain_db is not None][:2]
lacks = [t.id for t in a.tracks if t.auto_gain_db is None][:2]
# A file of its own per track: the store is keyed by the FILE.
files = {}
for n, tid in enumerate(has + lacks):
files[tid] = Path(d) / f"gain-{n}.bin"
files[tid].write_bytes(b"x" * (100 + n))
a.audio_path = lambda tid: files.get(tid, Path(__file__))
gain_only = {"bpm": False, "grid": False, "key": False, "gain": True}
pv = c.post("/api/tracks/analyze/preview", json={"track_ids": has + lacks, **gain_only}).json()
check("preview: Gain fills the tracks without one, skips the rest",
(pv["gain_set"], pv["gain_existing"], pv["with_gain"], pv["tracks_to_analyze"])
== (len(lacks), len(has), len(has), len(lacks)), str(pv))
before_has = {t: a.track(t).auto_gain_db for t in has}
res = run(track_ids=has + lacks, **gain_only)
check("the run's counts match the preview",
(res["gain"]["set"], res["gain"]["existing"]) == (len(lacks), len(has)), str(res["gain"]))
check("…a missing gain is written as -9.2 - LUFS",
all(abs(a.track(t).auto_gain_db - 2.8) < 1e-6 for t in lacks),
str([a.track(t).auto_gain_db for t in lacks]))
check("…measuring each track first (it had no loudness)", len(measured) == len(lacks), str(measured))
check("…and an existing gain is left alone", {t: a.track(t).auto_gain_db for t in has} == before_has)
measured.clear()
res = run(track_ids=has, replace_gain=True, **gain_only)
check("Replace gain overwrites them", res["gain"]["set"] == len(has)
and all(abs(a.track(t).auto_gain_db - 2.8) < 1e-6 for t in has), str(res["gain"]))
check("…measuring the tracks that had no loudness", len(measured) == len(has), str(measured))
measured.clear()
res = run(track_ids=lacks, replace_gain=True, **gain_only)
check("a fresh measurement is reused, not decoded again",
res["gain"]["set"] == len(lacks) and measured == [], str(measured))
check("nothing reached disk", work.read_bytes() == REAL.read_bytes())
print("== BPM alone / Grid alone write through the hand-edit commands ==")
+201
View File
@@ -0,0 +1,201 @@
"""`core.level_edit` on GENERATED files — every edit decode-checked.
MP3 is changed by the lossless frame-gain edit, so the proof is that the
decode is the source x 2^(n/4) and the file keeps its size (bar the APE undo
tag); WAV/AIFF are scaled in their data chunk, so every OTHER byte must stay
put; FLAC is re-encoded, so its tags and pictures must come back. The source
is never touched, and a refused edit leaves no file behind.
"""
from __future__ import annotations
import hashlib
import struct
import tempfile
from pathlib import Path
import av
import numpy as np
import soundfile as sf
from konduktor.core import level_edit
from konduktor.core.level_plan import STEP_DB
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def signal(sr: int, channels: int, seconds: float = 6.0, amp: float = 0.25) -> np.ndarray:
t = np.arange(int(sr * seconds)) / sr
rng = np.random.default_rng(1)
chans = [amp * (0.6 * np.sin(2 * np.pi * (110 + 37 * c) * t) + 0.3 * np.sin(2 * np.pi * 2200 * t)
+ 0.1 * rng.standard_normal(t.size)) for c in range(channels)]
return np.vstack(chans).astype(np.float32)
def encode_mp3(path: Path, *, sr=44100, channels=2, options=None, container_options=None, bit_rate=192_000):
x = signal(sr, channels)
layout = "stereo" if channels == 2 else "mono"
with av.open(str(path), "w", format="mp3", container_options=container_options or {}) as c:
s = c.add_stream("libmp3lame", rate=sr, layout=layout, options=options or {})
s.bit_rate = bit_rate
step = 1152
for i in range(0, x.shape[1], step):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, i:i + step]), format="fltp", layout=layout)
f.sample_rate, f.pts = sr, i
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
def sha(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def raises(fn) -> bool:
try:
fn()
except level_edit.LevelEditError:
return True
return False
tmp = Path(tempfile.mkdtemp(prefix="konduktor-level-edit-"))
print("== MP3: the frame-gain edit is exact, lossless and keeps the size ==")
check("CRC-16 is Layer III's (poly 0x8005, init 0xFFFF: '123456789' -> 0xAEE7)",
level_edit._crc16(b"123456789") == 0xAEE7)
variants = {
"cbr-xing": dict(),
"no-xing": dict(container_options={"write_xing": "0"}),
"abr": dict(options={"abr": "1"}),
"mono": dict(channels=1, bit_rate=96_000),
"mpeg2-22k": dict(sr=22050, bit_rate=64_000),
}
for name, kw in variants.items():
src = tmp / f"{name}.mp3"
encode_mp3(src, **kw)
if name == "cbr-xing":
from mutagen.id3 import APIC, ID3, TIT2
tags = ID3()
tags.add(TIT2(encoding=3, text="level"))
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=b"\xff\xd8" + bytes(5000)))
tags.save(str(src))
before = sha(src)
for steps in (-2, 1):
dst = tmp / f"{name}.{steps}.mp3"
level_edit.apply(src, dst, steps * STEP_DB)
try:
level_edit.verify(src, dst, steps * STEP_DB)
ok, why = True, ""
except level_edit.LevelEditError as ex:
ok, why = False, str(ex)
check(f"{name} {steps:+d} steps: the decode is the source x 2^({steps}/4)", ok, why)
from mutagen.apev2 import APEv2
ape = APEv2(str(dst))
grown = dst.stat().st_size - src.stat().st_size
check(f"{name} {steps:+d}: same frames, only the APE undo tag added",
0 < grown < 200 and str(ape["MP3GAIN_UNDO"]) == f"{-steps:+04d},{-steps:+04d},N", f"{grown} {ape}")
check(f"{name}: the source is untouched", sha(src) == before)
print("== MP3: a second edit accumulates its undo; refusals leave nothing ==")
src, once, twice = tmp / "cbr-xing.mp3", tmp / "once.mp3", tmp / "twice.mp3"
level_edit.apply(src, once, -2 * STEP_DB)
level_edit.apply(once, twice, -1 * STEP_DB)
from mutagen.apev2 import APEv2 # noqa: E402
check("undo after -2 then -1 steps reads +3", str(APEv2(str(twice))["MP3GAIN_UNDO"]).startswith("+003"),
str(APEv2(str(twice))["MP3GAIN_UNDO"]))
level_edit.verify(src, twice, -3 * STEP_DB)
check("…and the result is the source at -3 steps", True)
check("a gain that is not a whole number of steps is refused",
raises(lambda: level_edit.apply(src, tmp / "x.mp3", -2.0)) and not (tmp / "x.mp3").exists())
check("a gain past MP3's range is refused, leaving no file",
raises(lambda: level_edit.apply(src, tmp / "y.mp3", 300 * STEP_DB)) and not (tmp / "y.mp3").exists())
check("an existing target is never overwritten", raises(lambda: level_edit.apply(src, once, -STEP_DB)))
check("an unsupported format is refused", raises(lambda: level_edit.apply(src, tmp / "z.ogg", -1.0))
or raises(lambda: level_edit.apply(tmp / "nothing.ogg", tmp / "z2.ogg", -1.0)))
def add_chunk_after(path: Path, cid: bytes, body: bytes, *, big_endian: bool) -> None:
"""Append an extra chunk (a tag a DJ app might keep) and fix the RIFF/FORM size."""
data = bytearray(path.read_bytes())
fmt = ">I" if big_endian else "<I"
data += cid + struct.pack(fmt, len(body)) + body + (b"\0" if len(body) % 2 else b"")
data[4:8] = struct.pack(fmt, len(data) - 8)
path.write_bytes(data)
print("== WAV / AIFF: scaled inside the data chunk, every other byte untouched ==")
for suffix, subtype, big in ((".wav", "PCM_16", False), (".wav", "PCM_24", False), (".wav", "FLOAT", False),
(".aiff", "PCM_16", True), (".aiff", "PCM_24", True)):
src = tmp / f"pcm-{subtype}{suffix}"
sf.write(str(src), signal(44100, 2).T, 44100, subtype=subtype)
add_chunk_after(src, b"id3 " if not big else b"ID3 ", b"ID3\x03\x00\x00\x00\x00\x00\x05TAGS!", big_endian=big)
lay = (level_edit._wav_layout if suffix == ".wav" else level_edit._aiff_layout)(src)
for gain in (-3.7, 2.5):
dst = tmp / f"pcm-{subtype}-{gain}{suffix}"
level_edit.apply(src, dst, gain)
a, b = src.read_bytes(), dst.read_bytes()
outside = a[:lay.offset] + a[lay.offset + lay.size:] == b[:lay.offset] + b[lay.offset + lay.size:]
try:
level_edit.verify(src, dst, gain)
ok, why = True, ""
except level_edit.LevelEditError as ex:
ok, why = False, str(ex)
check(f"{suffix} {subtype} {gain:+.1f} dB: same size, every other chunk byte-identical",
len(a) == len(b) and outside)
check(f"{suffix} {subtype} {gain:+.1f} dB: the decode is the source at the gain", ok, why)
if subtype == "PCM_24":
dst = tmp / f"exact-{subtype}{suffix}"
level_edit.apply(src, dst, -6.0)
x = sf.read(str(src), dtype="int32")[0].astype(np.int64) >> 8
y = sf.read(str(dst), dtype="int32")[0].astype(np.int64) >> 8
check(f"{suffix} 24-bit is rounded, not dithered",
np.array_equal(y, np.rint(x * 10 ** (-6.0 / 20))))
src = tmp / "pcm-PCM_16.wav"
d1, d2 = tmp / "dither-a.wav", tmp / "dither-b.wav"
level_edit.apply(src, d1, -3.0)
level_edit.apply(src, d2, -3.0)
check("16-bit is dithered — and reproducibly (the same edit writes the same bytes)",
d1.read_bytes() == d2.read_bytes()
and not np.array_equal(sf.read(str(d1), dtype="int16")[0],
np.rint(sf.read(str(src), dtype="int16")[0] * 10 ** (-3 / 20)).astype(np.int16)))
print("== FLAC: re-encoded at its depth, tags and pictures carried ==")
from mutagen.flac import FLAC, Picture # noqa: E402
for subtype in ("PCM_16", "PCM_24"):
src = tmp / f"tagged-{subtype}.flac"
sf.write(str(src), signal(48000, 2).T, 48000, subtype=subtype)
f = FLAC(str(src))
f["title"], f["artist"], f["initialkey"] = "Level", "Konduktor", "8A"
pic = Picture()
pic.type, pic.mime, pic.data = 3, "image/jpeg", b"\xff\xd8" + bytes(3000)
f.add_picture(pic)
f.save()
dst = tmp / f"tagged-{subtype}-out.flac"
level_edit.apply(src, dst, -4.2)
try:
level_edit.verify(src, dst, -4.2)
ok, why = True, ""
except level_edit.LevelEditError as ex:
ok, why = False, str(ex)
check(f"FLAC {subtype}: the decode is the source at -4.2 dB", ok, why)
out = FLAC(str(dst))
check(f"FLAC {subtype}: same depth and rate", sf.info(str(dst)).subtype == subtype
and sf.info(str(dst)).samplerate == 48000)
check(f"FLAC {subtype}: every tag and the picture come back",
dict(out.tags.as_dict()) == dict(FLAC(str(src)).tags.as_dict())
and [p.data for p in out.pictures] == [pic.data], str(out.tags.as_dict()))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
raise SystemExit(1 if failed else 0)
+81
View File
@@ -0,0 +1,81 @@
"""`core.level_plan.plan_gain` — every outcome, the step rounding, the ceiling.
Pure: no files, no library. What Normalize's preview counts and what its run
writes both come from this function, so its rules are pinned here once.
"""
from __future__ import annotations
from konduktor.core.level_plan import STEP_DB, plan_gain, shifted
from konduktor.core.loudness import Loudness
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def L(lufs, tp, rms=None):
return Loudness(lufs=lufs, rms=rms if rms is not None else lufs + 2, true_peak=tp, lra=6.0, plr=tp - lufs)
def plan(loud, suffix=".flac", measure="lufs", target=-9.0, ceiling=-1.0):
return plan_gain(loud, suffix, measure=measure, target=target, ceiling=ceiling)
print("== the basics ==")
check("one step is 2^(1/4) in amplitude, 1.505 dB", abs(STEP_DB - 1.50515) < 1e-4, str(STEP_DB))
s = plan(L(-6.0, 1.0))
check("a hot lossless track comes down exactly", (s.outcome, s.gain_db) == ("apply", -3.0), str(s))
s = plan(L(-12.0, -6.0))
check("a quiet one goes up exactly when the peak allows", (s.outcome, s.gain_db) == ("apply", 3.0), str(s))
s = plan(L(-9.02, -2.0))
check("within 0.05 dB is at target (lossless)", s.outcome == "at_target" and not s.writes, str(s))
check("no measurement: unmeasured", plan(None).outcome == "unmeasured")
check("Ogg / Opus / WMA: unsupported", all(plan(L(-6, 0), x).outcome == "unsupported" for x in (".ogg", ".opus", ".wma")))
s = plan(L(-6.0, -3.0), ".m4a")
check("AAC (.m4a, a stem file) is planned in whole steps, like MP3 (aac_gain)",
s.outcome == "apply" and abs(s.gain_db / STEP_DB - round(s.gain_db / STEP_DB)) < 1e-6
and plan(L(-6.0, -3.0), ".mp4").gain_db == s.gain_db, str(s))
check("the suffix is case-blind", plan(L(-6.0, 1.0), ".FLAC").outcome == "apply")
print("== the ceiling (a raise never clips) ==")
s = plan(L(-14.0, -3.0))
check("a raise stops at the true-peak ceiling and says how far short",
(s.outcome, s.gain_db, s.short_by) == ("capped", 2.0, 3.0), str(s))
s = plan(L(-12.0, 0.5))
check("a peak already over the ceiling at/below target is left alone", (s.outcome, s.gain_db) == ("hot_peak_left", 0.0), str(s))
s = plan(L(-6.0, 3.0))
check("…but a HOT track over the ceiling still comes down", (s.outcome, s.gain_db) == ("apply", -3.0), str(s))
print("== MP3: lossless steps of 1.505 dB ==")
s = plan(L(-6.0, 1.0), ".mp3")
check("a lowering rounds to the nearest step (-3.0 -> -3.01)", abs(s.gain_db + 2 * STEP_DB) < 1e-6 and s.outcome == "apply", str(s))
s = plan(L(-8.4, -3.0), ".mp3")
check("under half a step from target is at target", s.outcome == "at_target", str(s))
s = plan(L(-12.0, -6.0), ".mp3")
check("a raise rounds to the nearest step when the peak allows (+3.0 -> +3.01)",
abs(s.gain_db - 2 * STEP_DB) < 1e-6 and s.outcome == "apply", str(s))
s = plan(L(-12.0, -3.5), ".mp3")
check("a raise never rounds UP past the ceiling (headroom 2.5 -> one step)",
abs(s.gain_db - STEP_DB) < 1e-6 and s.outcome == "capped", str(s))
s = plan(L(-12.0, -2.0), ".mp3")
check("headroom under one step: capped at zero, nothing written", s.outcome == "capped" and not s.writes, str(s))
check("every MP3 gain is a whole number of steps",
all(abs(g / STEP_DB - round(g / STEP_DB)) < 1e-6
for g in (plan(L(x, x + 5), ".mp3").gain_db for x in (-16, -13.3, -10.1, -7.7, -4.2))))
print("== the measure ==")
s = plan(L(-9.0, -6.0, rms=-12.0), measure="rms")
check("RMS measures the loud sections: -12 dB RMS goes up 3", (s.outcome, s.gain_db) == ("apply", 3.0), str(s))
print("== the level after ==")
after = shifted(L(-12.0, -6.0), 3.0)
check("LUFS, RMS and true peak move by the gain; LRA and PLR do not",
(after.lufs, after.rms, after.true_peak, after.lra, after.plr) == (-9.0, -7.0, -3.0, 6.0, 6.0), str(after))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
raise SystemExit(1 if failed else 0)
+437
View File
@@ -0,0 +1,437 @@
"""Pushing an export set into this computer's Traktor / rekordbox library
(`local_push.py`), through the routes.
The source library is a temp copy of the real collection pointed at GENERATED
audio; the "local" Traktor collection pushed into is ANOTHER temp copy of the
real one — the user's own 8,485 entries — and the shared audio folder is a temp
folder. Prefs and app-data are redirected, and whether a DJ app is running is
faked (a real Traktor may be open on the machine running this).
What would fail SILENTLY, and matter at a gig:
* a merge touches nothing of the user's own: existing entries and playlists
render byte-identically, only new ENTRYs and the set's folder appear;
* a re-push of an unchanged set copies and writes nothing;
* the source wins: an edited cue or title reaches the pushed entry, and a
re-levelled copy is swapped in with the entry's size following;
* removal follows the set, but never takes a track another set holds, and a
rekordbox refusal keeps the track and reports it;
* the set's folder never takes over a folder of the user's with its name;
* overwrite leaves only this set, deleting the other sets' files;
* a running DJ app, the open library, and a failure mid-copy all leave the
library as it was.
"""
from __future__ import annotations
import difflib
import hashlib
import os
import shutil
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-push-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
import av # noqa: E402
import numpy as np # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor import history, local_push, paths, prefs # noqa: E402
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.core import apps_running # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-push-"))
AUDIO = ROOT / "Music" / "Konduktor"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def make_mp3(path: Path, seed: int) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
sr = 44100
t = np.arange(sr * 8) / sr
rng = np.random.default_rng(seed)
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
x = np.vstack([0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.2 * rng.standard_normal(t.size))
for _ in range(2)]).astype(np.float32)
with av.open(str(path), "w", format="mp3") as c:
s = c.add_stream("libmp3lame", rate=sr, layout="stereo")
s.bit_rate = 192_000
for o in range(0, x.shape[1], 1152):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
f.sample_rate, f.pts = sr, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
return path
def source_library(n=5):
d = ROOT / "source"
d.mkdir(parents=True)
work = d / "collection.nml"
shutil.copy2(REAL, work)
st = TraktorStore(work)
entries = [e for e in st._nml.collection.entry if e.location and e.stems is None]
ids, files = [], []
for i, e in enumerate(entries[:n]):
path = make_mp3(d / "Music" / f"track{i}.mp3", seed=i)
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
e.cue_v2 = []
e.title = f"Track {i}"
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
ids.append(st._key_of(e))
files.append(path)
st.save()
return work, ids, files
def sha(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def wait(c, jid, timeout=300):
end = time.time() + timeout
while time.time() < end:
j = c.get(f"/api/jobs/{jid}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
raise AssertionError("job did not finish")
def copy_of(source: Path) -> Path:
return AUDIO / local_push._rel_for(source)
def pushed(target: Path) -> dict[str, object]:
"""The target's entries that live in the shared audio folder, by file name."""
st = TraktorStore(target)
out = {}
for e in st._nml.collection.entry:
path = st.audio_path(st._key_of(e)) if e.location else None
if path and AUDIO in Path(path).parents:
out[Path(path).name] = e
return out
def top_level(target: Path) -> dict[str, object]:
ad = TraktorAdapter(target)
return {n.name: n for n in ad.playlist_tree()}
def removed_lines(before: str, after: str) -> list[str]:
return [l for l in difflib.unified_diff(before.splitlines(), after.splitlines(), lineterm="", n=0)
if l.startswith("-") and not l.startswith("---")]
src, ids, files = source_library()
target = ROOT / "laptop" / "Traktor 4.5.0" / "collection.nml"
target.parent.mkdir(parents=True)
shutil.copy2(REAL, target)
RUNNING: set[str] = set()
apps_running.running = lambda platforms: {p for p in platforms if p in RUNNING}
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(ROOT / "none" / "master.db")},
"localAudioRoot": str(AUDIO), "localNormalise": False})
with TestClient(main.app) as c:
r = c.post("/api/library/open", json={"path": str(src)})
assert r.status_code == 200, r.text
adapter = main.STATE.adapter
print("== the local libraries ==")
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
check("Traktor is the configured collection, usable", libs["traktor"]["path"] == str(target)
and libs["traktor"]["blocked"] is None and not libs["traktor"]["detected"], str(libs["traktor"]))
check("a rekordbox library that is not there is not_found", libs["rekordbox"]["blocked"] == "not_found")
print("== a computer set ==")
r = c.post("/api/exports", json={"name": "Gig", "kind": "computer", "targets": ["onelibrary"]})
check("a stick format is not a push target", r.status_code == 422, r.text)
gig = c.post("/api/exports", json={"name": "Gig", "kind": "computer", "targets": ["traktor"]}).json()
check("created with no destination, mode merge", gig["kind"] == "computer" and gig["mode"] == "merge"
and gig["destination"] == "", str(gig))
pl = c.post("/api/playlists", json={"name": "Peak"}).json()["id"]
c.put(f"/api/playlists/{pl}/entries", json={"track_ids": ids[:2]})
c.post(f"/api/exports/{gig['id']}/add", json={"playlist_ids": [pl], "track_ids": [ids[2]]})
adapter.set_cue(ids[0], slot=0, start_sec=1.0, cue_type="cue", name="Drop")
adapter.replace_grid(ids[0], [(0.5, 120.0)])
check("an export route refuses a computer set",
c.post(f"/api/exports/{gig['id']}/preview", json={}).status_code == 400)
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
t = pv["targets"][0]
check("the preview: three to add, nothing blocked", pv["blocked"] is None and pv["pushable"] == 3
and (t["add"], t["already"], t["remove"]) == (3, 0, 0), str(pv))
print("== the first push merges ==")
before = target.read_text()
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
check("the push runs", j["state"] == "done", str(j.get("error")))
check("each copy is its source, byte for byte",
all(copy_of(f).is_file() and sha(copy_of(f)) == sha(f) for f in files[:3]))
after = target.read_text()
gone = removed_lines(before, after)
check("nothing of the user's changed: only the entry count and the root folder's count",
all("<COLLECTION ENTRIES=" in l or "SUBNODES COUNT=" in l for l in gone), "\n".join(gone[:5]))
entries = pushed(target)
check("three entries in the shared folder", set(entries) == {"track0.mp3", "track1.mp3", "track2.mp3"},
str(list(entries)))
tree = top_level(target)
folder = tree.get("Gig")
names = {n.name for n in folder.children} if folder else set()
check("the set's folder holds its playlist and Other", names == {"Peak", "Other"}, str(names))
tk = TraktorAdapter(target)
tid = next(t.id for t in tk.tracks if t.title == "Track 0")
cues = tk.track_cues(tid)
check("the cue and grid crossed, the grid locked",
any(c_.slot == 0 and c_.name == "Drop" for c_ in cues.cues) and len(cues.grid_markers) == 1
and cues.grid_locked, str(cues))
check("the push is in the collection's version history",
len(history.list_history(target)) >= 2, str(history.list_history(target)))
print("== an unchanged re-push writes nothing ==")
stamp = target.stat().st_mtime_ns
inodes = {f.name: copy_of(f).stat().st_ino for f in files[:3]}
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
check("the preview: three already there", (pv["targets"][0]["add"], pv["targets"][0]["already"]) == (0, 3)
and pv["unchanged"] == 3, str(pv))
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
check("nothing copied", j["state"] == "done" and j["result"]["copied"] == 0, str(j.get("result")))
check("…the same files, and the collection not saved",
{f.name: copy_of(f).stat().st_ino for f in files[:3]} == inodes and target.stat().st_mtime_ns == stamp)
print("== the source wins ==")
adapter.set_cue(ids[0], slot=1, start_sec=2.0, cue_type="cue", name="Break")
adapter.set_track_metadata(ids[1], {"title": "Track 1 (edit)"})
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
tk = TraktorAdapter(target)
cues = tk.track_cues(tid)
check("the new cue reached the pushed entry, the old one kept, no duplicates",
j["state"] == "done" and sorted((c_.slot, c_.name) for c_ in cues.cues if c_.slot is not None)
== [(0, "Drop"), (1, "Break")], str(cues.cues))
check("the new title too", any(t.title == "Track 1 (edit)" for t in tk.tracks))
check("…and only those two were updated", j["result"]["targets"][0]["updated"] == 2, str(j["result"]))
print("== a re-levelled copy is swapped in ==")
prefs.update_prefs({"localNormalise": True, "localLevel": {"measure": "lufs", "target": -6.0, "ceiling": -0.5}})
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
check("the push runs", j["state"] == "done", str(j.get("error")))
changed = [f for f in files[:3] if sha(copy_of(f)) != sha(f)]
check("the copies changed level", j["result"]["normalised"] > 0 and changed, str(j.get("result")))
entries = pushed(target)
check("each entry's FILESIZE follows its new copy",
all(entries[f.name].info.filesize == round(copy_of(f).stat().st_size / 1024) for f in files[:3]))
check("no temporary file left", not list(AUDIO.rglob("*.konduktor-partial")))
prefs.update_prefs({"localNormalise": False})
wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
check("Normalise off: the source's own bytes back", all(sha(copy_of(f)) == sha(f) for f in files[:3]))
print("== a second set, sharing a track ==")
warm = c.post("/api/exports", json={"name": "Warmup", "kind": "computer", "targets": ["traktor"]}).json()
c.post(f"/api/exports/{warm['id']}/add", json={"track_ids": [ids[2], ids[3]]})
tk = TraktorAdapter(target)
tk.create_folder("Warmup") # the user's own folder, with the set's name
tk.save()
j = wait(c, c.post(f"/api/exports/{warm['id']}/push", json={}).json()["id"])
tree = top_level(target)
check("a user's folder with the set's name is left alone; the set's is suffixed",
j["state"] == "done" and "Warmup" in tree and "Warmup (Konduktor)" in tree
and not tree["Warmup"].children, str(list(tree)))
check("the shared track is one entry", sum(1 for n in pushed(target) if n == "track2.mp3") == 1
and len(pushed(target)) == 4, str(list(pushed(target))))
print("== removal follows the set ==")
c.post(f"/api/exports/{gig['id']}/remove", json={"track_ids": [ids[2]]})
c.put(f"/api/playlists/{pl}/entries", json={"track_ids": ids[:1]})
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
check("the preview counts two to remove", pv["targets"][0]["remove"] == 2, str(pv["targets"]))
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
names = set(pushed(target))
check("track1 left the collection, track2 stays (Warmup holds it)",
j["state"] == "done" and "track1.mp3" not in names and "track2.mp3" in names, str(names))
check("track1's copy deleted, track2's kept",
not copy_of(files[1]).exists() and copy_of(files[2]).exists())
check("one removal reported", j["result"]["targets"][0]["removed"] == 1, str(j["result"]))
print("== a library missing on this computer is skipped, not a block ==")
# The set's targets are shared by every computer opening the library;
# this one has no rekordbox (its pref points at nothing).
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["traktor", "rekordbox"]})
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
by = {t["platform"]: t for t in pv["targets"]}
check("the preview runs, rekordbox skipped", pv["blocked"] is None and by["rekordbox"]["skipped"]
and by["rekordbox"]["blocked"] == "not_found" and not by["traktor"]["skipped"], str(pv))
RUNNING.add("rekordbox")
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
check("a skipped library's app running blocks nothing", pv["blocked"] is None, str(pv))
RUNNING.clear()
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
check("the push runs into Traktor alone and names the skipped one", j["state"] == "done"
and [t["name"] for t in j["result"]["targets"]] == ["Traktor"]
and j["result"]["skipped_targets"] == ["Rekordbox"], str(j.get("error") or j["result"]))
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["rekordbox"]})
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
check("none of its libraries here blocks it", pv["blocked"] == "no_library_here", str(pv))
check("…and the run is refused", c.post(f"/api/exports/{gig['id']}/push", json={}).status_code == 409)
c.patch(f"/api/exports/{gig['id']}", json={"targets": ["traktor"]})
print("== refusals ==")
RUNNING.add("traktor")
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
check("Traktor running blocks the push", pv["blocked"] == "app_running" and pv["targets"][0]["running"], str(pv))
check("…and the run is refused", c.post(f"/api/exports/{gig['id']}/push", json={}).status_code == 409)
RUNNING.clear()
prefs.update_prefs({"localLibraries": {"traktor": str(src)}})
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
check("the library open in Konduktor is never a target", libs["traktor"]["blocked"] == "open_in_konduktor",
str(libs["traktor"]))
wrong = ROOT / "not-a-collection.nml"
wrong.write_text("hello")
prefs.update_prefs({"localLibraries": {"traktor": str(wrong)}})
libs = {l["platform"]: l for l in c.get("/api/local-libraries").json()["libraries"]}
check("a file that is not a Traktor collection is unreadable", libs["traktor"]["blocked"] == "unreadable",
str(libs["traktor"]))
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(ROOT / "none" / "master.db")}})
print("== a failure mid-copy leaves the library and the folder as they were ==")
c.post(f"/api/exports/{gig['id']}/add", json={"track_ids": [ids[4]]})
real_write = local_push.write_copy
def broken(adapter_, planned, partial, handle, advance):
partial.write_bytes(b"half")
raise OSError("disk unplugged")
local_push.write_copy = broken
before = target.read_bytes()
j = wait(c, c.post(f"/api/exports/{gig['id']}/push", json={}).json()["id"])
local_push.write_copy = real_write
check("the push fails", j["state"] == "failed", str(j))
check("…the collection untouched, no file placed",
target.read_bytes() == before and not copy_of(files[4]).exists()
and not list(AUDIO.rglob("*.konduktor-partial")))
print("== overwrite ==")
c.patch(f"/api/exports/{warm['id']}", json={"mode": "overwrite"})
pv = c.post(f"/api/exports/{warm['id']}/push/preview", json={}).json()
check("the preview names the set it removes", pv["targets"][0]["wipes_sets"] == ["Gig"], str(pv["targets"]))
j = wait(c, c.post(f"/api/exports/{warm['id']}/push", json={}).json()["id"])
check("the overwrite runs", j["state"] == "done", str(j.get("error")))
st = TraktorStore(target)
check("the collection holds only Warmup's two tracks", len(st._nml.collection.entry) == 2
and set(pushed(target)) == {"track2.mp3", "track3.mp3"}, str(len(st._nml.collection.entry)))
tree = top_level(target)
check("…in its folder", set(tree) == {"Warmup"}, str(list(tree)))
check("Gig's own file is deleted, Warmup's kept",
not copy_of(files[0]).exists() and copy_of(files[2]).exists() and copy_of(files[3]).exists())
check("the replaced collection is in the version history",
len(history.list_history(target)) >= 3)
pv = c.post(f"/api/exports/{gig['id']}/push/preview", json={}).json()
check("Gig is forgotten there: every track to add again",
pv["targets"][0]["already"] == 0 and pv["targets"][0]["add"] == pv["pushable"], str(pv["targets"]))
c.patch(f"/api/exports/{warm['id']}", json={"mode": "merge"})
pv = c.post(f"/api/exports/{warm['id']}/push/preview", json={}).json()
check("a merge after the overwrite finds Warmup's tracks", pv["targets"][0]["already"] == 2, str(pv["targets"]))
# ---- rekordbox, when installed --------------------------------------------------
from konduktor.adapters.rekordbox import discovery as rb_discovery
found = rb_discovery.detect_libraries()
if not found:
print("== rekordbox: not installed here, skipped ==")
else:
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter
from konduktor.core.adapter import Unsupported
print("== rekordbox: merge ==")
rb_dir = ROOT / "rekordbox"
rb_dir.mkdir()
real_db = Path(found[0]["path"])
for name in ("master.db", "masterPlaylists6.xml"):
if (real_db.parent / name).is_file():
shutil.copy2(real_db.parent / name, rb_dir / name)
rb = rb_dir / "master.db"
probe = RekordboxAdapter(rb)
synced, count = probe.capabilities().readonly_cause == "cloud_synced", len(probe.tracks)
probe.close()
if synced:
print(" (the local rekordbox library is cloud-synced: checking it is refused)")
prefs.update_prefs({"localLibraries": {"traktor": str(target), "rekordbox": str(rb)}})
rbset = c.post("/api/exports", json={"name": "RB Gig", "kind": "computer", "targets": ["rekordbox"]}).json()
c.post(f"/api/exports/{rbset['id']}/add", json={"track_ids": ids[:2]})
pv = c.post(f"/api/exports/{rbset['id']}/push/preview", json={}).json()
if synced:
check("a cloud-synced library is refused", pv["blocked"] == "target_unavailable"
and pv["targets"][0]["blocked"] == "cloud_synced", str(pv))
else:
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
check("the push runs", j["state"] == "done", str(j.get("error")))
ad = RekordboxAdapter(rb)
mine = [t for t in ad.tracks if t.filepath and str(AUDIO) in t.filepath]
tree = {n.name: n for n in ad.playlist_tree()}
tid = next((t.id for t in mine if t.title == "Track 0"), None)
cues = ad.track_cues(tid) if tid else None
ad.close()
check("two tracks added beside the user's", len(mine) == 2, str([t.title for t in mine]))
check("the set's folder", "RB Gig" in tree, str(list(tree)))
check("the cues crossed", cues is not None and any(c_.slot == 0 for c_ in cues.cues), str(cues))
backups = list((paths.app_data_dir() / "local_push" / "backups" / "rekordbox").iterdir())
check("the library was backed up first", backups and (backups[0] / "master.db").is_file())
print("== rekordbox: a track it will not remove is kept and reported ==")
real_remove = RekordboxAdapter.remove_tracks
def refuse(self, track_ids):
raise Unsupported("“Track 1” is in a History list in Rekordbox")
RekordboxAdapter.remove_tracks = refuse
c.post(f"/api/exports/{rbset['id']}/remove", json={"track_ids": [ids[1]]})
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
RekordboxAdapter.remove_tracks = real_remove
res = j.get("result") or {}
check("the push still completes, reporting the kept track",
j["state"] == "done" and res["targets"][0]["kept"], str(j.get("error") or res))
check("…whose file stays", copy_of(files[1]).exists())
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
ad = RekordboxAdapter(rb)
left = [t for t in ad.tracks if t.filepath and str(AUDIO) in t.filepath]
ad.close()
check("the next push removes it", j["state"] == "done" and len(left) == 1, str([t.title for t in left]))
print("== rekordbox: overwrite ==")
(rb_dir / "master.db-wal").write_bytes(b"stale")
c.patch(f"/api/exports/{rbset['id']}", json={"mode": "overwrite"})
j = wait(c, c.post(f"/api/exports/{rbset['id']}/push", json={}).json()["id"])
check("the overwrite runs", j["state"] == "done", str(j.get("error")))
ad = RekordboxAdapter(rb)
titles = [t.title for t in ad.tracks]
tree = [n.name for n in ad.playlist_tree()]
ad.close()
check("the library holds only the set", titles == ["Track 0"], f"{count} -> {titles}")
check("…in its folder", tree == ["RB Gig"], str(tree))
check("the stale WAL is gone", not (rb_dir / "master.db-wal").exists())
print("== the ledger and sets survive as plain data ==")
sets = {s["name"]: s for s in c.get("/api/exports").json()}
check("kind and mode persist", sets["Warmup"]["kind"] == "computer" and sets["Warmup"]["mode"] == "merge")
shutil.rmtree(ROOT, ignore_errors=True)
print()
print("RESULT:", "SOME FAILED" if failed else "ALL PASSED")
raise SystemExit(1 if failed else 0)
+191
View File
@@ -0,0 +1,191 @@
"""Loudness measurement (`core/loudness.py`) on GENERATED signals.
Integrated loudness, LRA and true peak are checked against FFmpeg's own
`ebur128` filter, run through the PyAV wheel the app already ships — a
reference meter nothing has to be installed for. True peak is also checked
against the exact answer on an inter-sample peak, where FFmpeg's cheaper
interpolator overshoots. RMS has no reference meter here, so its definition is
pinned on signals whose answer is known: a full-scale sine reads 0 dB (AES17),
a square +3 dB, and a long quiet intro moves it not at all (it is the loudest
fifth of the 3 s blocks).
"""
from __future__ import annotations
import math
import tempfile
from pathlib import Path
import av
import numpy as np
import soundfile as sf
from konduktor.core import loudness
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def ebur128(pcm: np.ndarray, sr: int) -> dict:
"""FFmpeg's measurement of `pcm` (channels, n): the last frame's metadata."""
from av.filter import Graph
pcm = np.ascontiguousarray(np.atleast_2d(pcm).astype(np.float32))
layout = "mono" if pcm.shape[0] == 1 else "stereo"
graph = Graph()
src = graph.add_abuffer(format="fltp", sample_rate=sr, layout=layout)
meter = graph.add("ebur128", "peak=true:metadata=1")
sink = graph.add("abuffersink")
src.link_to(meter)
meter.link_to(sink)
graph.configure()
last = None
def drain():
nonlocal last
while True:
try:
last = sink.pull()
except (av.BlockingIOError, av.EOFError):
return
pts = 0
for start in range(0, pcm.shape[1], 4096):
block = pcm[:, start:start + 4096]
frame = av.AudioFrame.from_ndarray(np.ascontiguousarray(block), format="fltp", layout=layout)
frame.sample_rate, frame.pts = sr, pts
pts += block.shape[1]
src.push(frame)
drain()
try:
src.push(None)
except Exception: # noqa: BLE001 — some builds raise at EOF; the frames are out
pass
drain()
m = last.metadata
return {"lufs": float(m["lavfi.r128.I"]), "lra": float(m["lavfi.r128.LRA"]),
"true_peak": 20 * math.log10(float(m["lavfi.r128.true_peak"]))}
rng = np.random.default_rng(7)
def tone(freq, seconds, sr, amp=0.5, phase=0.0):
t = np.arange(int(sr * seconds)) / sr
return amp * np.sin(2 * np.pi * freq * t + phase)
def signals(sr):
t = np.arange(sr * 30) / sr
loud_quiet = np.where((t % 10) < 5, 1.0, 0.05)
kick = np.exp(-(t % 0.5) * 20) * np.sin(2 * np.pi * 55 * t)
return {
"1 kHz sine": np.vstack([tone(1000, 30, sr, 0.1)] * 2),
"noise": 0.2 * rng.standard_normal((2, t.size)),
"loud/quiet sections": np.vstack([loud_quiet * tone(220, 30, sr, 0.3), loud_quiet * tone(330, 30, sr, 0.3)]),
"kick + noise": np.vstack([0.9 * kick + 0.05 * rng.standard_normal(t.size)] * 2),
"mono noise": (0.2 * rng.standard_normal(t.size))[None],
}
print("== against FFmpeg's ebur128 ==")
for sr in (44100, 48000):
for name, x in signals(sr).items():
ours = loudness.measure(x.astype(np.float32), sr)
ref = ebur128(x, sr)
check(f"{sr} {name}: integrated within 0.1 LU ({ours.lufs:.2f} vs {ref['lufs']:.2f})",
abs(ours.lufs - ref["lufs"]) <= 0.1)
check(f"{sr} {name}: LRA within 0.3 LU ({ours.lra:.2f} vs {ref['lra']:.2f})",
abs(ours.lra - ref["lra"]) <= 0.3)
check(f"{sr} {name}: true peak within 0.2 dB ({ours.true_peak:.2f} vs {ref['true_peak']:.2f})",
abs(ours.true_peak - ref["true_peak"]) <= 0.2)
print("== the standard's anchors ==")
sr = 48000
r = loudness.measure(np.vstack([tone(1000, 20, sr, 10 ** (-23 / 20))] * 2), sr)
check("a stereo 1 kHz sine at -23 dBFS is -23.0 LUFS", abs(r.lufs + 23.0) <= 0.1, f"{r.lufs:.2f}")
# A sine at a quarter of the rate, 45 degrees off the samples: every sample is
# 0.707 of the peak, which only oversampling can see. Exact: -6.02 dBTP.
r = loudness.measure(np.vstack([tone(sr / 4, 20, sr, 0.5, math.pi / 4)] * 2), sr)
check("an inter-sample peak is found (exact -6.02 dBTP)", abs(r.true_peak + 6.02) <= 0.2, f"{r.true_peak:.2f}")
check("…well above the sample peak (-9.03 dB)", r.true_peak > -8.0)
check("PLR is true peak minus integrated", abs(r.plr - (r.true_peak - r.lufs)) < 1e-9)
steps = signals(sr)["loud/quiet sections"]
r = loudness.measure(steps, sr)
check("alternating loud and quiet sections have a wide LRA", r.lra > 5, f"{r.lra:.2f}")
print("== RMS: AES17, loudest fifth of 3 s blocks ==")
r = loudness.measure(np.vstack([tone(997, 30, sr, 1.0)] * 2), sr)
check("a full-scale sine reads 0.0 dB", abs(r.rms) <= 0.05, f"{r.rms:.3f}")
square = np.sign(tone(997, 30, sr, 1.0))
r = loudness.measure(np.vstack([square] * 2), sr)
check("a full-scale square reads +3.01 dB", abs(r.rms - 3.01) <= 0.05, f"{r.rms:.3f}")
body = np.vstack([tone(440, 60, sr, 0.5)] * 2)
intro = np.vstack([tone(440, 120, sr, 0.02)] * 2)
plain = loudness.measure(body, sr)
long_intro = loudness.measure(np.concatenate([intro, body], axis=1), sr)
check("a long quiet intro leaves RMS where it was", abs(plain.rms - long_intro.rms) <= 0.05,
f"{plain.rms:.2f} vs {long_intro.rms:.2f}")
check("…and RMS is the loud part's: a -6 dBFS sine reads -6 dB", abs(plain.rms + 6.02) <= 0.05, f"{plain.rms:.2f}")
print("== nothing to measure ==")
check("silence is None", loudness.measure(np.zeros((2, sr * 10), dtype=np.float32), sr) is None)
check("under 3 s is None", loudness.measure(np.vstack([tone(440, 2.5, sr)] * 2), sr) is None)
check("a mono (n,) array is accepted", loudness.measure(tone(440, 10, sr), sr) is not None)
print("== streaming: chunked feeding equals one pass ==")
x = signals(44100)["kick + noise"].astype(np.float32)
whole = loudness.measure(x, 44100)
meter = loudness._Meter(44100, 2)
for start in range(0, x.shape[1], 1153): # odd, frame-like chunks
meter.feed(x[:, start:start + 1153])
chunked = meter.result()
check("identical to the last digit that matters",
all(abs(getattr(whole, k) - getattr(chunked, k)) < 1e-6 for k in ("lufs", "rms", "true_peak", "lra")),
f"{whole} vs {chunked}")
print("== measure_file: the file's own rate and channels ==")
with tempfile.TemporaryDirectory() as d:
for sr_, suffix in ((44100, "flac"), (48000, "wav")):
x = np.vstack([tone(1000, 10, sr_, 0.1), tone(1000, 10, sr_, 0.1)]).T
path = Path(d) / f"t.{suffix}"
sf.write(path, x, sr_)
r = loudness.measure_file(path)
check(f"a {sr_} Hz {suffix} reads as its samples do", r is not None and abs(r.lufs + 20.0) <= 0.1,
str(r))
mono = Path(d) / "mono.flac"
sf.write(mono, tone(1000, 10, 44100, 0.1), 44100)
r = loudness.measure_file(mono)
check("a mono file is measured as ONE channel (3 dB under its stereo twin)",
r is not None and abs(r.lufs + 23.0) <= 0.1, str(r))
# A stem file is its four stems SUMMED (what a stem deck plays, and what
# Traktor measures), not its mix stream — commercial mixes are mastered
# hotter than their stems. Here each stem is an eighth of the mix, so the
# sum is the mix at half amplitude: -6.02 dB.
from konduktor.core import stem_file
src = Path(d) / "src.flac"
sf.write(src, np.vstack([tone(1000, 10, 44100, 0.5)] * 2).T, 44100)
stem = Path(d) / "s.stem.m4a"
stem_file.build(src, stem, lambda pcm: [pcm * 0.125] * 4)
mix = loudness._measure_stream(stem)
summed = loudness.measure_file(stem)
check("a stem file measures its stem SUM (6.02 dB under its mix stream)",
summed is not None and mix is not None and abs((mix.lufs - summed.lufs) - 6.02) <= 0.1,
f"mix {mix and mix.lufs:.2f}, sum {summed and summed.lufs:.2f}")
try:
loudness.measure_file(Path(d) / "missing.flac")
check("a missing file raises", False)
except Exception: # noqa: BLE001
check("a missing file raises", True)
print()
if failed:
print("FAILED")
raise SystemExit(1)
print("All loudness checks passed.")
+250
View File
@@ -0,0 +1,250 @@
"""Where loudness lives (`loudness_store.py`) and the routes that fill and read it.
Runs on a temp app-data dir, a temp copy of the real collection and FLACs
generated here. Pins the decisions that would otherwise fail silently:
* values are keyed by PATH; a changed file keeps its value but reads STALE
(dimmed, still sorted on) — never silently dropped, never silently trusted;
* Konduktor's OWN tag write at Save does not stale a value;
* a measurement is not an edit: the library stays clean and Discard keeps it;
* loudness works where nothing can be written (a Files folder, a device),
while BPM / Grid / Key for those are refused;
* a path remap carries values to the files' new paths;
* Analyze skips a measured track unless Replace is ticked, and the preview's
counts match what the run does.
"""
from __future__ import annotations
import os
import shutil
import tempfile
import threading
import time
from pathlib import Path
import numpy as np
import soundfile as sf
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
_DATA = tempfile.TemporaryDirectory()
os.environ["KONDUKTOR_DATA_DIR"] = _DATA.name
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
from konduktor import loudness_store # noqa: E402
from konduktor.core.adapter import AudioFacts # noqa: E402
from konduktor.core.loudness import VERSION, Loudness # noqa: E402
from konduktor.core.pathmap import PathMapping # noqa: E402
V = Loudness(lufs=-8.0, rms=-7.5, true_peak=0.3, lra=5.0, plr=8.3)
print("== the store ==")
store = loudness_store.LocalLoudnessStore(Path(tempfile.mkdtemp()) / "l.sqlite3")
f = AudioFacts(key="/music/a.mp3", size=100, mtime_ns=5)
store.put(f, V)
got = store.get(["/music/a.mp3", "/music/none.mp3"])
check("a measured path answers, an unmeasured one does not", list(got) == ["/music/a.mp3"], str(got))
e = got["/music/a.mp3"]
check("values round-trip", e.values == V and e.version == VERSION)
check("fresh while the facts match", not e.stale(f))
check("stale once the size or mtime moves", e.stale(AudioFacts(f.key, 100, 6)) and e.stale(AudioFacts(f.key, 101, 5)))
check("an older measurement version is stale", loudness_store.Entry(V, 100, 5, VERSION - 1).stale(f))
check("keyed as asked, normalised underneath", "/music//a.mp3" in store.get(["/music//a.mp3"]))
n = store.remap(PathMapping.make("/music", "/Volumes/SSD/music"))
check("a remap moves values under the old prefix", n == 1 and "/Volumes/SSD/music/a.mp3" in store.get(
["/Volumes/SSD/music/a.mp3"]) and not store.get(["/music/a.mp3"]))
store.put(AudioFacts("/x/b.mp3", 1, 1), V)
store.put(AudioFacts("/y/b.mp3", 2, 2), V)
store.remap(PathMapping.make("/x", "/y"))
check("…a value already at the new path wins", store.get(["/y/b.mp3"])["/y/b.mp3"].size == 2
and not store.get(["/x/b.mp3"]))
check("…and only under the prefix, segment-aware",
store.remap(PathMapping.make("/Volumes/SS", "/elsewhere")) == 0)
errors = []
def burst(k):
try:
for i in range(50):
store.put(AudioFacts(f"/t/{k}/{i}.mp3", i, i), V)
except Exception as ex: # noqa: BLE001
errors.append(ex)
threads = [threading.Thread(target=burst, args=(k,)) for k in range(8)]
[t.start() for t in threads]
[t.join() for t in threads]
check("concurrent writers lose nothing", not errors and len(store.get(
[f"/t/{k}/{i}.mp3" for k in range(8) for i in range(50)])) == 400, str(errors[:1]))
# ---- generated audio ------------------------------------------------------
def tone_flac(path: Path, amp: float, seconds: float = 8.0, **tags) -> Path:
from mutagen.flac import FLAC
path.parent.mkdir(parents=True, exist_ok=True)
t = np.arange(int(44100 * seconds)) / 44100
x = (amp * np.sin(2 * np.pi * 440 * t)).astype("float32")
sf.write(path, np.stack([x, x], axis=1), 44100, format="FLAC")
audio = FLAC(path)
for k, v in tags.items():
audio[k] = str(v)
audio.save()
return path
root = Path(tempfile.mkdtemp())
music = root / "Loose"
loud = tone_flac(music / "loud.flac", 0.5, title="Loud One")
quiet = tone_flac(music / "quiet.flac", 0.05, title="Quiet One")
short = tone_flac(music / "short.flac", 0.5, seconds=2.0, title="Too Short")
work = Path(tempfile.mkdtemp()) / "collection.nml"
shutil.copy2(REAL, work)
os.environ["KONDUKTOR_NML"] = str(work)
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor.app_state import STATE # noqa: E402
def wait(c, job):
while job["state"] == "running":
time.sleep(0.05)
job = c.get(f"/api/jobs/{job['id']}").json()
return job
with TestClient(main.app, raise_server_exceptions=False) as c:
a = main.require_adapter()
files = [str(loud), str(quiet), str(short)]
c.get("/api/folder/tracks", params={"path": str(music)})
print("== a Files folder: loudness only ==")
check("nothing is measured yet",
c.post("/api/loudness", json={"origin": "folder", "track_ids": files}).json()["values"] == {})
p = c.post("/api/tracks/analyze/preview", json={
"origin": "folder", "track_ids": files, "bpm": False, "grid": False, "loudness": True}).json()
check("the preview counts three to measure", (p["total"], p["loudness_measure"], p["tracks_to_analyze"])
== (3, 3, 3), str(p))
r = c.post("/api/tracks/analyze", json={"origin": "folder", "track_ids": files, "bpm": True, "grid": False})
check("BPM for a folder's files is refused", r.status_code == 400, r.text)
r = c.post("/api/tracks/analyze", json={"origin": "folder", "track_ids": files, "bpm": False,
"grid": False, "loudness": False})
check("nothing ticked is refused", r.status_code == 400)
job = wait(c, c.post("/api/tracks/analyze", json={
"origin": "folder", "track_ids": files, "bpm": False, "grid": False, "loudness": True}).json())
res = job["result"]
check("the job finishes", job["state"] == "done", str(job))
check("two measured, the 2-second file has nothing to measure",
res["loudness"] == {"measured": 2, "existing": 0, "none": 1}, str(res))
vals = c.post("/api/loudness", json={"origin": "folder", "track_ids": files}).json()["values"]
check("the table reads both", set(vals) == {str(loud), str(quiet)}, str(vals))
check("the louder file reads 20 dB louder",
abs((vals[str(loud)]["lufs"] - vals[str(quiet)]["lufs"]) - 20.0) < 0.1, str(vals))
check("a -6 dBFS sine's RMS is -6 dB", abs(vals[str(loud)]["rms"] + 6.02) < 0.05, str(vals[str(loud)]))
check("fresh", not vals[str(loud)]["stale"])
check("the library is not dirty: a measurement is not an edit", not c.get("/api/state").json()["dirty"])
print("== skip measured, unless Replace ==")
body = {"origin": "folder", "track_ids": files, "bpm": False, "grid": False, "loudness": True}
p = c.post("/api/tracks/analyze/preview", json=body).json()
check("measured tracks are skipped", (p["loudness_existing"], p["with_loudness"], p["loudness_measure"])
== (2, 2, 1), str(p))
job = wait(c, c.post("/api/tracks/analyze", json=body).json())
check("…and the run agrees", job["result"]["loudness"] == {"measured": 0, "existing": 2, "none": 1},
str(job["result"]))
p = c.post("/api/tracks/analyze/preview", json={**body, "replace_loudness": True}).json()
check("Replace measures them again", (p["loudness_existing"], p["loudness_measure"]) == (0, 3), str(p))
print("== a changed file reads stale, and is offered again ==")
was = vals[str(quiet)]["lufs"]
st = os.stat(quiet)
os.utime(quiet, ns=(st.st_atime_ns, st.st_mtime_ns + 10_000_000_000))
vals = c.post("/api/loudness", json={"origin": "folder", "track_ids": files}).json()["values"]
check("stale, value kept", vals[str(quiet)]["stale"] and vals[str(quiet)]["lufs"] == was,
str(vals[str(quiet)]))
p = c.post("/api/tracks/analyze/preview", json=body).json()
check("the preview offers it again", p["loudness_measure"] == 2, str(p))
print("== the deck's Analyze where nothing can be written ==")
r = c.post("/api/tracks/loudness", json={"origin": "folder", "track_id": str(quiet)})
check("measures and answers the values", r.status_code == 200 and not r.json()["stale"], r.text)
vals = c.post("/api/loudness", json={"origin": "folder", "track_ids": [str(quiet)]}).json()["values"]
check("…and the value is fresh again", not vals[str(quiet)]["stale"])
r = c.post("/api/tracks/loudness", json={"origin": "folder", "track_id": str(short)})
check("too short to measure is a 400 with a reason", r.status_code == 400 and "3 seconds" in r.text, r.text)
r = c.post("/api/tracks/loudness", json={"origin": "folder", "track_id": "/etc/passwd"})
check("a file no scan found is a 404", r.status_code == 404)
print("== in the collection: the same file, the same value ==")
job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(loud)], "mode": "reference"}).json())
tid = job["result"]["track_ids"][0]
vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [tid]}).json()["values"]
check("the collection track shows the folder's measurement", tid in vals and not vals[tid]["stale"], str(vals))
held = c.post("/api/loudness", json={"origin": "folder", "track_ids": [tid]}).json()["values"]
check("a folder view's held row (a collection id) resolves too", tid in held, str(held))
print("== Konduktor's own tag write does not stale it ==")
r = c.patch("/api/tracks", json={"track_id": tid, "fields": {"title": "Loud Renamed"}})
check("edit accepted", r.status_code == 200, r.text)
before = os.stat(loud).st_mtime_ns
r = c.post("/api/save")
check("saved", r.status_code == 200, r.text)
check("the save wrote the file's tags", os.stat(loud).st_mtime_ns != before)
vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [tid]}).json()["values"]
check("…and the value is still fresh", tid in vals and not vals[tid]["stale"], str(vals))
print("== Discard keeps measurements ==")
c.patch("/api/tracks", json={"track_id": tid, "fields": {"comment": "dirty"}})
r = c.post("/api/tracks/loudness", json={"origin": "collection", "track_id": tid})
check("measured while dirty", r.status_code == 200, r.text)
check("discarded", c.post("/api/discard").status_code == 200)
vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [tid]}).json()["values"]
check("the value survived", tid in vals, str(vals))
print("== the collection's Analyze measures alongside the grid ==")
p = c.post("/api/tracks/analyze/preview", json={
"track_ids": [tid], "bpm": False, "grid": False, "key": False, "loudness": True,
"replace_loudness": True}).json()
check("collection preview counts it", p["loudness_measure"] == 1 and p["with_loudness"] == 1, str(p))
print("== a path remap carries values to the new paths ==")
moved = root / "Moved"
shutil.move(str(music), str(moved))
r = c.post("/api/library/remap-paths", json={"from": str(music), "to": str(moved)})
check("remapped", r.status_code == 200 and r.json()["rewritten"] >= 1, r.text)
new_id = next(t.id for t in a.tracks if a.audio_path(t.id) == moved / "loud.flac")
vals = c.post("/api/loudness", json={"origin": "collection", "track_ids": [new_id]}).json()["values"]
check("the moved file keeps its value, fresh (a move keeps size and mtime)",
new_id in vals and not vals[new_id]["stale"], str(vals))
print("== a device: loudness only, failures reported per track ==")
fixture = Path(tempfile.mkdtemp()) / "onelibrary"
shutil.copytree(FIXTURE, fixture)
check("the stick opens as a source", c.post("/api/source/open", json={"path": str(fixture)}).status_code == 200)
ids = [t["id"] for t in c.get("/api/source/tracks", params={"limit": 3}).json()["items"]]
r = c.post("/api/tracks/analyze", json={"origin": "device", "track_ids": ids, "bpm": False,
"grid": False, "key": True})
check("a key for a device's tracks is refused", r.status_code == 400, r.text)
job = wait(c, c.post("/api/tracks/analyze", json={"origin": "device", "track_ids": ids, "bpm": False,
"grid": False, "loudness": True}).json())
# The fixture's demo MP3s are 12-byte stubs: each is one reported failure.
check("the job finishes, each undecodable stub reported, not fatal",
job["state"] == "done" and len(job["result"]["failed"]) == len(ids), str(job)[:300])
print()
if failed:
print("FAILED")
raise SystemExit(1)
print("All loudness store checks passed.")
+80
View File
@@ -0,0 +1,80 @@
"""MIDI controller mappings moved to and from FILES (`/api/midi/export`,
`/api/midi/import`) — the only backend part of controller support; the
mapping itself lives in userprefs and is validated by the UI.
Pins what would hurt silently: an export never overwrites a file (a shared
mapping saved twice must not replace the first), the name cannot steer the
file outside the chosen folder, and import refuses anything that is not a
small version-1 JSON object rather than handing the UI garbage. The file
browser's `suffix` filter lists the mapping files.
"""
import json
import sys
import tempfile
from pathlib import Path
from fastapi import HTTPException
from konduktor import prefs
_TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
from konduktor.main import fs_list, midi_export, midi_import # noqa: E402
from konduktor.schemas import MidiExportRequest # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def refused(fn, status):
try:
fn()
except HTTPException as e:
return e.status_code == status
return False
folder = Path(_TMP.name) / "maps"
folder.mkdir()
mapping = {"version": 1, "shift": "note:1:63", "bindings": {"note:1:11": {"encoding": "button", "normal": "deck.A.play"}}}
print("export")
first = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping=mapping))["path"])
check("written as <name>.konduktor-midi.json", first.name == "DDJ-400.konduktor-midi.json")
check("holds the mapping", json.loads(first.read_text()) == mapping)
second = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping={"version": 1}))["path"])
check("never overwrites: a second export is -2", second.name == "DDJ-400-2.konduktor-midi.json")
check("the first file is untouched", json.loads(first.read_text()) == mapping)
sneaky = Path(midi_export(MidiExportRequest(dir=str(folder), name="../../escape", mapping=mapping))["path"])
check("a name cannot leave the folder", sneaky.parent == folder, str(sneaky))
check("a missing folder is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder / "nope"), name="x", mapping=mapping)), 400))
check("a non-mapping is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder), name="x", mapping={"version": 9})), 400))
print("import")
check("reads back what was exported", midi_import(str(first))["mapping"] == mapping)
bad = folder / "bad.konduktor-midi.json"
bad.write_text("{not json")
check("invalid JSON refused", refused(lambda: midi_import(str(bad)), 400))
bad.write_text(json.dumps([1, 2]))
check("not an object refused", refused(lambda: midi_import(str(bad)), 400))
bad.write_text(json.dumps({"version": 2}))
check("wrong version refused", refused(lambda: midi_import(str(bad)), 400))
big = folder / "big.konduktor-midi.json"
big.write_text(json.dumps({"version": 1, "pad": "x" * 1_100_000}))
check("an oversized file refused", refused(lambda: midi_import(str(big)), 400))
check("a missing file is 404", refused(lambda: midi_import(str(folder / "absent.json")), 404))
print("file browser")
(folder / "notes.json").write_text("{}")
listed = {f.name for f in fs_list(path=str(folder), suffix=".konduktor-midi.json").files}
check("the suffix lists mapping files only", "notes.json" not in listed and first.name in listed, str(listed))
sys.exit(1 if failed else 0)
+392
View File
@@ -0,0 +1,392 @@
"""Normalize end to end, through the routes, on temp collections pointed at
GENERATED audio (MP3, FLAC, WAV at known levels).
What would fail silently or destroy something:
* the preview's counts are the run's (one `plan_gain`);
* the run leaves the SAVED collection untouched; the new file is the
original x 10^(g/20) under the ORIGINAL's path, the original parked
beside it; the library's auto gain is RECOMPUTED from the new level and
Konduktor's loudness value SHIFTED; operations that would save or drop the
change answer 409; a track awaiting Save is not normalised (or converted)
again;
* Save deletes the parked originals and changes only the touched ENTRYs;
Discard (and opening another library) put the originals back, bytes and
loudness both;
* after a CRASH, the next open restores — or, if the save got through,
finishes — from the ledger plus what the saved library says.
"""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-normalize-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
import av # noqa: E402
import numpy as np # noqa: E402
import soundfile as sf # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor import paths # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.core import level_edit, loudness # noqa: E402
from konduktor.core.level_plan import STEP_DB # noqa: E402
from konduktor.pending import parked_name # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-normalize-"))
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def music(seconds=8.0, amp=0.3, sr=44100, seed=1):
t = np.arange(int(sr * seconds)) / sr
rng = np.random.default_rng(seed)
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float) # a pulse, so it is not a steady tone
x = [amp * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.3 * np.sin(2 * np.pi * (440 + 30 * c) * t)
+ 0.2 * rng.standard_normal(t.size)) for c in range(2)]
return np.vstack(x).astype(np.float32)
def make_mp3(path: Path, amp: float):
x = music(amp=amp)
with av.open(str(path), "w", format="mp3") as c:
s = c.add_stream("libmp3lame", rate=44100, layout="stereo")
s.bit_rate = 256_000
for o in range(0, x.shape[1], 1152):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
f.sample_rate, f.pts = 44100, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
def make_m4a(path: Path, amp: float):
x = music(amp=amp)
with av.open(str(path), "w", format="ipod") as c:
s = c.add_stream("aac", rate=44100, layout="stereo")
s.bit_rate = 192_000
for o in range(0, x.shape[1], 1024):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1024]), format="fltp", layout="stereo")
f.sample_rate, f.pts = 44100, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
def make(path: Path, amp: float):
path.parent.mkdir(parents=True, exist_ok=True)
if path.suffix == ".mp3":
make_mp3(path, amp)
elif path.suffix == ".m4a":
make_m4a(path, amp)
else:
sf.write(str(path), music(amp=amp).T, 44100, subtype="PCM_16")
return path
FILES = [("hot.mp3", 0.9), ("quiet.flac", 0.03), ("hot.wav", 0.8), ("close.mp3", 0.12), ("hot.m4a", 0.8)]
LOSSLESS = {".flac", ".wav"}
def library(name: str):
"""A temp collection whose first playlisted entries point at FILES."""
d = ROOT / name
work = d / "collection.nml"
d.mkdir(parents=True)
shutil.copy2(REAL, work)
st = TraktorStore(work)
in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)}
entries = [e for e in st._nml.collection.entry if e.location and st._key_of(e) in in_pl and e.stems is None]
ids, paths_ = [], []
for (f, amp), e in zip(FILES, entries):
path = make(d / "Music" / f, amp)
old = st._key_of(e)
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
new = st._key_of(e)
for n in st._iter_nodes(st._root()):
for pe in (n.playlist.entry if n.playlist else None) or []:
if pe.primarykey and pe.primarykey.key == old:
pe.primarykey.key = new
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
ids.append(new)
paths_.append(path)
st.save()
return work, ids, paths_
def sha(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def wait(c, jid, timeout=120):
end = time.time() + timeout
while time.time() < end:
j = c.get(f"/api/jobs/{jid}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
raise AssertionError("job did not finish")
OPTS = {"measure": "lufs", "target": -12.0, "ceiling": -1.0}
def normalize(c, ids, **opts):
r = c.post("/api/tracks/normalize", json={"track_ids": ids, **OPTS, **opts})
assert r.status_code == 200, r.text
return wait(c, r.json()["id"])
def ledger() -> Path:
return paths.app_data_dir() / "stems" / f"pending-{main.STATE.library_id}.json"
with TestClient(main.app) as c:
print("== preview: one plan_gain, measured first where needed ==")
work, ids, files = library("run")
r = c.post("/api/library/open", json={"path": str(work)})
assert r.status_code == 200, r.text
pv = c.post("/api/tracks/normalize/preview", json={"track_ids": ids, **OPTS}).json()
check("unmeasured tracks are counted to be measured first",
pv["to_measure"] == len(ids) and pv["tracks_to_process"] == len(ids), str({k: pv[k] for k in pv if k != "rows"}))
for p in files:
c.post("/api/tracks/loudness", json={"track_id": ids[files.index(p)]})
before = {p.name: loudness.measure_file(p) for p in files}
pv = c.post("/api/tracks/normalize/preview", json={"track_ids": ids, **OPTS}).json()
rows = {Path(r["title"]).name if False else r["track_id"]: r for r in pv["rows"]}
gains = {files[i].name: rows[t].get("gain_db") for i, t in enumerate(ids)}
check("measured: every track has a plan",
all(rows[t].get("outcome") for t in ids), str(pv["rows"]))
check("an AAC file (.m4a) is levelled in the same whole steps (aac_gain)",
abs(gains["hot.m4a"] / STEP_DB - round(gains["hot.m4a"] / STEP_DB)) < 1e-6 and gains["hot.m4a"] < 0, str(gains))
check("an MP3's gain is a whole number of 1.505 dB steps",
abs(gains["hot.mp3"] / STEP_DB - round(gains["hot.mp3"] / STEP_DB)) < 1e-6 and gains["hot.mp3"] < 0, str(gains))
check("the quiet FLAC is raised, but only to the ceiling",
rows[ids[1]]["outcome"] in ("apply", "capped") and gains["quiet.flac"] > 0
and before["quiet.flac"].true_peak + gains["quiet.flac"] <= -1.0 + 1e-6, str(rows[ids[1]]))
check("lossless files are counted (Save makes their change permanent)",
pv["lossless"] == sum(1 for i, t in enumerate(ids) if files[i].suffix in LOSSLESS and rows[t]["gain_db"]),
str(pv["lossless"]))
print("== run: new files in place, originals parked, library follows ==")
saved_collection = work.read_bytes()
originals = {p.name: sha(p) for p in files}
job = normalize(c, ids)
res = job["result"]
changed = [files[ids.index(t)] for t in res["normalised"]]
check("the run normalises what the preview planned",
len(res["normalised"]) == pv["to_change"] and not res["failed"], json.dumps(res)[:400])
check("the SAVED collection is untouched until Save", work.read_bytes() == saved_collection)
for p in changed:
g = gains[p.name]
parked = parked_name(p)
try:
level_edit.verify(parked, p, g)
ok, why = True, ""
except level_edit.LevelEditError as ex:
ok, why = False, str(ex)
check(f"{p.name}: the file at its own path is the original at {g:+.2f} dB", ok, why)
check(f"{p.name}: the original is parked beside it, unchanged", sha(parked) == originals[p.name])
state = c.get("/api/state").json()
check("Save is due: the library is dirty and the pending change is named",
state["dirty"] and state["pending_gain"]["tracks"] == len(changed)
and state["pending_gain"]["lossless"] == sum(1 for p in changed if p.suffix in LOSSLESS), str(state))
vals = c.post("/api/loudness", json={"track_ids": ids}).json()["values"]
tracks = {t["id"]: t for t in c.get("/api/tracks", params={"limit": 20000}).json()["items"]}
for p in changed:
t = ids[files.index(p)]
want = before[p.name].lufs + gains[p.name]
check(f"{p.name}: Konduktor's loudness value is shifted by the gain, and fresh",
abs(vals[t]["lufs"] - want) < 1e-6 and not vals[t]["stale"], str(vals.get(t)))
check(f"{p.name}: the auto gain is recomputed from the NEW level (-9.2 - LUFS)",
abs(tracks[t]["auto_gain_db"] - (-9.2 - want)) < 1e-4, str(tracks[t]["auto_gain_db"]))
check("measured afresh, the new file agrees with the shifted value",
abs(loudness.measure_file(changed[0]).lufs - (before[changed[0].name].lufs + gains[changed[0].name])) < 0.05)
print("== while it awaits Save ==")
r = c.post("/api/reload")
check("reload is refused (it would drop the change)", r.status_code == 409, r.text[:200])
again = c.post("/api/tracks/normalize/preview", json={"track_ids": ids[:1], **OPTS}).json()
check("the same track is not normalised again before Save",
again["rows"][0]["skip"] and "awaiting Save" in again["rows"][0]["skip"], str(again["rows"]))
stems = c.post("/api/tracks/stems/preview", json={"track_ids": ids[:1], "mode": "replace"}).json()
check("…nor converted to stems", any("level change" in s["reason"] for s in stems["skipped"]), str(stems))
print("== Save: parked originals deleted, only the touched entries change ==")
r = c.post("/api/save")
check("Save succeeds", r.status_code == 200, r.text[:200])
check("the parked originals are gone", not any(parked_name(p).exists() for p in changed))
check("the ledger is empty", not ledger().exists())
out = work.read_bytes()
for p in changed:
t = ids[files.index(p)]
check(f"{p.name}: the saved LOUDNESS is the new gain",
f'PERCEIVED_DB="{round(-9.2 - (before[p.name].lufs + gains[p.name]), 6):.6f}"'.encode() in out)
check("nothing pending any more", c.get("/api/state").json()["pending_gain"] is None)
def without_entries(data: bytes, names) -> bytes:
for name in names:
i = data.find(f'FILE="{name}"'.encode())
start, end = data.rfind(b"<ENTRY ", 0, i), data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
data = data[:start] + data[end:]
return data
check("outside the normalised tracks' ENTRYs the collection is byte-identical",
without_entries(out, [p.name for p in changed]) == without_entries(saved_collection, [p.name for p in changed]))
print("== Discard puts the originals back, bytes and loudness ==")
work2, ids2, files2 = library("discard")
c.post("/api/library/open", json={"path": str(work2)})
for t in ids2:
c.post("/api/tracks/loudness", json={"track_id": t})
shas = {p.name: sha(p) for p in files2}
vals_before = c.post("/api/loudness", json={"track_ids": ids2}).json()["values"]
res = normalize(c, ids2)["result"]
r = c.post("/api/discard")
check("discard succeeds", r.status_code == 200, r.text[:200])
check("every file is byte-identical to before", {p.name: sha(p) for p in files2} == shas)
check("no parked file or partial is left", not any(parked_name(p).exists() or Path(str(p) + ".konduktor-partial").exists()
for p in files2))
vals_after = c.post("/api/loudness", json={"track_ids": ids2}).json()["values"]
check("the loudness values are the originals' again, and fresh",
all(abs(vals_after[t]["lufs"] - vals_before[t]["lufs"]) < 1e-9 and not vals_after[t]["stale"]
for t in res["normalised"]), str(vals_after))
print("== a crash: recovery from the ledger + the saved library ==")
work3, ids3, files3 = library("crash")
c.post("/api/library/open", json={"path": str(work3)})
shas3 = {p.name: sha(p) for p in files3}
res = normalize(c, ids3)["result"]
done = [files3[ids3.index(t)] for t in res["normalised"]]
# Crash 1: the app dies with the change unsaved (state "swapped").
main.STATE.pending.restore = lambda: 0 # the process never got to restore
main.STATE.pending.items = list(main.STATE.pending.items)
c.post("/api/library/open", json={"path": str(work3)})
check("an unsaved change is undone at the next open", {p.name: sha(p) for p in files3} == shas3
and not any(parked_name(p).exists() for p in done))
check("…and reported", (main.STATE.recovery or {}).get("restored") == len(done), str(main.STATE.recovery))
# Crash 2: the save got through, the parked originals were never deleted.
res = normalize(c, ids3)["result"]
data = json.loads(ledger().read_text())
main.STATE.adapter.save() # the library write landed…
for it in data["items"]:
it["state"] = "saving" # …but the app died before mark_saved
ledger().write_text(json.dumps(data))
main.STATE.pending.restore = lambda: 0
c.post("/api/library/open", json={"path": str(work3)})
check("a save that landed is FINISHED: parked originals deleted, new audio kept",
not any(parked_name(p).exists() for p in done)
and all(sha(p) != shas3[p.name] for p in done), str(main.STATE.recovery))
# Crash 3: died in "saving" BEFORE the library write: restore.
shas3 = {p.name: sha(p) for p in files3}
res = normalize(c, ids3, target=-16.0)["result"]
done3 = [files3[ids3.index(t)] for t in res["normalised"]]
data = json.loads(ledger().read_text())
for it in data["items"]:
it["state"] = "saving"
ledger().write_text(json.dumps(data))
main.STATE.pending.restore = lambda: 0
c.post("/api/library/open", json={"path": str(work3)})
check("a save that did NOT land is undone (the library still has the old gain)",
done3 and {p.name: sha(p) for p in files3} == shas3, str(main.STATE.recovery))
print("== drawn waveforms follow the new audio (rekordbox / OneLibrary ANLZ) ==")
from konduktor.adapters.rekordbox import anlz_file # noqa: E402
from konduktor.core import waveform # noqa: E402
from konduktor.core.adapter import AudioChange # noqa: E402
measured = waveform.analyse_samples(music(seconds=20, amp=0.5)[0], lead=0.0)
WAVE_TAGS = {".DAT": {"PWAV", "PWV2"}, ".EXT": {"PWV3", "PWV5", "PWV4"}, ".2EX": {"PWV7", "PWV6", "PWVC"}}
def tags(path: Path) -> dict:
out = {}
for t in anlz_file.parse_file(path).tags:
out.setdefault(t.type, []).append(t.data)
return out
def check_regenerated(label: str, dat: Path, before: dict) -> None:
for ext, wave in WAVE_TAGS.items():
f = dat.with_suffix(ext)
if not f.is_file():
continue
now = tags(f)
old = before[ext]
check(f"{label} {ext}: the waveform tags are rewritten",
all(now.get(k) != old.get(k) for k in wave if k in old), str(sorted(now)))
check(f"{label} {ext}: every other tag is byte-identical (cues, grid, phrases)",
{k: v for k, v in now.items() if k not in wave} == {k: v for k, v in old.items() if k not in wave})
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
with tempfile.TemporaryDirectory() as d:
drive = Path(d) / "STICK"
shutil.copytree(FIXTURE, drive)
ad = OneLibraryAdapter(drive, read_only=False)
t = next(x for x in ad.tracks)
dat = ad._store.layout.resolve(ad._store.content(t.id).analysisDataFilePath)
before = {ext: tags(dat.with_suffix(ext)) for ext in WAVE_TAGS if dat.with_suffix(ext).is_file()}
db_before = (drive / "PIONEER/rekordbox/exportLibrary.db").read_bytes()
ad.audio_changed(t.id, AudioChange(gain_db=-3.0, size=123456, measured=measured))
check("OneLibrary: nothing reaches the drive before Save",
{ext: tags(dat.with_suffix(ext)) for ext in before} == before)
check("OneLibrary: a level change is an edit (Save will run)", ad.dirty)
ad.save()
check_regenerated("OneLibrary", dat, before)
check("OneLibrary: the database's fileSize follows",
OneLibraryAdapter(drive, read_only=True)._store.content(t.id).fileSize == 123456)
from konduktor.adapters.rekordbox import discovery as rb_discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
found = rb_discovery.detect_libraries()
if not found:
print(" [SKIP] no Rekordbox library on this machine")
else:
with tempfile.TemporaryDirectory() as d:
src = Path(found[0]["path"])
work = Path(d) / "master.db"
shutil.copy2(src, work)
shutil.copytree(src.parent / "share", Path(d) / "share", dirs_exist_ok=True)
ad = RekordboxAdapter(work)
t = next((x for x in ad.tracks if getattr(ad._store.content(x.id), "AnalysisDataPath", None)
and (Path(d) / "share" / str(ad._store.content(x.id).AnalysisDataPath).lstrip("/")).is_file()), None)
if t is None:
print(" [SKIP] no track with analysis files")
else:
dat = Path(d) / "share" / str(ad._store.content(t.id).AnalysisDataPath).lstrip("/")
before = {ext: tags(dat.with_suffix(ext)) for ext in WAVE_TAGS if dat.with_suffix(ext).is_file()}
ad.audio_changed(t.id, AudioChange(gain_db=-3.0, size=654321, measured=measured))
check("rekordbox: nothing reaches the files before Save",
{ext: tags(dat.with_suffix(ext)) for ext in before} == before)
ad.save()
check_regenerated("rekordbox", dat, before)
ad.close()
check("rekordbox: djmdContent.FileSize follows",
RekordboxAdapter(work)._store.content(t.id).FileSize == 654321)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
raise SystemExit(1 if failed else 0)
+19
View File
@@ -438,6 +438,25 @@ check("refusing leaves nothing dirty", adapter.dirty is False)
check("an unknown track is a NotFound, not an Unsupported",
_raises(lambda: adapter.audio_path("no-such-track"), NotFound))
print("== track colour ==")
# Goober (`fixtures/onelibrary-goober`) is a stick coloured in rekordbox:
# `content.color_id` 1-based into the `color` table (1 Pink, 2 Red, 5 Green).
from konduktor.adapters.rekordbox import track_palette # noqa: E402
_gdir = Path(tempfile.mkdtemp(prefix="konduktor-ol-colour-")) / "goober"
shutil.copytree(FIXTURE.parent / "onelibrary-goober", _gdir)
_goober = OneLibraryAdapter(_gdir)
_colours = {t.title: (t.color, t.color_hex) for t in _goober.tracks}
check("rekordbox's track colours project by name + display RGB",
_colours.get("Nemean - Doomed") == ("red", "#E13121")
and _colours.get("Sleepnet - Lapse") == ("green", "#65DB41")
and _colours.get("Life Is A Loop - Grand Prix") == ("pink", "#E577EF"), str(_colours))
check("an uncoloured track has none", _colours.get("Demo Track 2") == (None, None))
_goober.close()
check("the palette maps ids both ways",
[track_palette.id_for(track_palette.color_for(i)) for i in range(9)] == list(range(9))
and track_palette.color_for("0") is None and track_palette.color_for(9) is None)
print("== reads that answer rather than refuse ==")
check("cover art is absent, not an error", adapter.cover_art(one.id) is None)
# A drive stores everything relative to its own root, so it cannot have stale
+43
View File
@@ -442,6 +442,49 @@ check("setting 12A reuses the stick's '12A' row instead of adding 'Dbm'",
if r2["title"] == target.title))["key_id"]) == names["12A"])
g.close()
print("== track colour ==")
# `content.color_id` (1 Pink .. 8 Purple, 0 none); the pdb track row's
# `color_id` byte uses the same ids, and Goober's two agree on every track.
from konduktor.adapters.rekordbox import pdb # noqa: E402
goober = Path(tempfile.mkdtemp(prefix="konduktor-olfid-colour-")) / "Goober"
shutil.copytree(FIXTURE.parent / "onelibrary-goober", goober, ignore=shutil.ignore_patterns("after"))
pdb_path = goober / "PIONEER" / "rekordbox" / "export.pdb"
def pdb_colours() -> dict:
return {pdb.row_id(pdb.TRACKS, r): pdb.track_fields(r)[0]["color_id"]
for r in pdb.table_rows(pdb_path.read_bytes(), pdb.TRACKS)}
before = dump(db_of(goober))
check("rekordbox's own pdb carries the same colour ids as the database",
pdb_colours() == {int(r["content_id"]): int(r["color_id"] or 0) for r in before["content"].values()},
str(pdb_colours()))
g = OneLibraryAdapter(goober)
check("an editable stick offers rekordbox's eight colours",
[s.color for s in g.capabilities().tracks.colors]
== ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"])
check("a browsed one offers none",
OneLibraryAdapter(goober, read_only=True).capabilities().tracks.colors == [])
g.set_track_color(next(x for x in g.tracks if x.color == "green").id, "green")
check("setting the colour it has is not an edit", g.dirty is False)
red = next(t for t in g.tracks if t.color == "red")
t = g.set_track_color(red.id, "blue")
check("the projection shows it at once", (t.color, t.color_hex) == ("blue", "#1F4EED"), str(t))
g.save()
changes = diff(before, dump(db_of(goober)))
check("exactly content.color_id changes (2 = Red -> 7 = Blue)",
len(changes) == 1 and changes[0][3] == {"color_id": (2, 7)}, describe(changes))
cid = int(changes[0][1]) if changes else None
check("and the pdb's track row follows", pdb_colours().get(cid) == 7, str(pdb_colours()))
g.set_track_color(red.id, None)
g.save()
check("No Color stores 0, in both",
dump(db_of(goober))["content"][changes[0][1]]["color_id"] == 0 and pdb_colours().get(cid) == 0)
check("an unknown colour is refused", _raises(lambda: g.set_track_color(red.id, "teal"), Exception))
g.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+29
View File
@@ -191,9 +191,38 @@ check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 an
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json()
check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1)
more = [t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"]
if t["id"] not in track_ids][:2]
before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
r = client.post(f"/api/playlists/{target}/add", json={"track_ids": more[:1], "index": 1}).json()
after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
check("an index inserts there (a drop between rows)",
r["added"] == 1 and after == before[:1] + more[:1] + before[1:])
client.post(f"/api/playlists/{target}/add", json={"track_ids": more[1:2], "index": 999})
after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
check("an index past the end appends", after[-1] == more[1])
check("capabilities say Traktor holds duplicates",
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
outsider = next(t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"]
if t["id"] not in before)
picked = [first[0], rest[0], outsider] # first[0] is in there twice
r = client.post(f"/api/playlists/{target}/remove",
json={"track_ids": picked, "dry_run": True}).json()
check("a dry-run remove counts tracks held and entries (both copies) and changes nothing",
r["tracks"] == 2 and r["removed"] == 3
and [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] == before)
r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": picked}).json()
after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
check("remove drops every copy and keeps the rest in order",
r["removed"] == 3 and r["count"] == len(before) - 3
and after == [t for t in before if t not in picked])
r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": [outsider]}).json()
check("removing tracks it does not hold changes nothing", r["removed"] == 0 and r["count"] == len(after))
check("remove from an unknown playlist is a 404",
client.post("/api/playlists/nope/remove", json={"track_ids": picked}).status_code == 404)
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
+4 -1
View File
@@ -511,7 +511,10 @@ with tempfile.TemporaryDirectory() as d:
_raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound))
print("== beatgrid edits ==")
grid_track = next((t for t in adapter.tracks if t.bpm), None)
# Long enough for a marker at 60 s: a grid is stored per beat, only up to
# the track's end, and the library's first BPM track became a 1 s Sampler
# WAV ("House 1"), where a marker at 60 s simply vanished.
grid_track = next((t for t in adapter.tracks if t.bpm and (t.length or 0) >= 90), None)
if grid_track:
check("a gridded track starts with at least one marker",
len(adapter.track_cues(grid_track.id).grid_markers) >= 1)
+83 -1
View File
@@ -833,8 +833,14 @@ with tempfile.TemporaryDirectory() as d:
== {("agentRegistry", "UPDATE")}, describe(changes))
check("into the tables Rekordbox writes for a new track",
new_rows <= {"djmdContent", "djmdCue", "contentCue", "contentFile",
"djmdArtist", "djmdKey"}, str(sorted(new_rows)))
"djmdArtist", "djmdKey", "djmdMixerParam"}, str(sorted(new_rows)))
after = dump(work)
# rekordbox's own add analyses an auto gain; without a row a track plays at
# 0.0 dB and loading never creates one (kit G2). The generated kick tracks
# are measurable, so each gets its row.
gains = {r["ContentID"] for r in after["djmdMixerParam"].values()}
check("every added track arrives with an auto gain (a djmdMixerParam row)",
all(i in gains for i in ids), str(sorted(set(ids) - gains)))
rows = {i: after["djmdContent"][i] for i in ids}
plain_row, prepped_row = rows[ids[0]], rows[ids[1]]
check("the row is filled from the file",
@@ -952,5 +958,81 @@ with tempfile.TemporaryDirectory() as d:
len(dump(work)["djmdKey"]) == len(after["djmdKey"]))
adapter.close()
print("== L: track colour is djmdContent.ColorID, one row + the counter ==")
clean_copy(REAL, work)
before = dump(work)
adapter = RekordboxAdapter(work)
t1 = adapter.tracks[0]
got = adapter.set_track_color(t1.id, "aqua")
check("the projection updates immediately", (got.color, got.color_hex) == ("aqua", "#55BBF1"), str(got))
adapter.save()
changes = diff(before, dump(work))
content = [c for c in changes if c[0] == "djmdContent"]
check("exactly the track row and the counter change",
{t for t, _, _, _ in changes} == {"djmdContent", "agentRegistry"} and len(changes) == 2,
describe(changes))
check("ColorID '6' (Aqua, 1-based into djmdColor)",
content and content[0][3].get("ColorID", (None, None))[1] == "6", str(content and content[0][3]))
before = dump(work)
adapter.set_track_color(t1.id, None)
adapter.save()
changes = diff(before, dump(work))
check("No Color writes '0'",
[c[3].get("ColorID", (None, None))[1] for c in changes if c[0] == "djmdContent"] == ["0"],
describe(changes))
adapter.close()
print("== M: auto gain is one djmdMixerParam row (+ the counter), as rekordbox writes it ==")
# Measured (kit G2): Gain = 10^((-10 - LUFS)/20) as float32 halves; Peak =
# the clipped sample peak; a track with no row plays at 0.0 dB.
import struct as _struct
from konduktor.core.loudness import Loudness
def _lin(hi, lo):
return _struct.unpack(">f", _struct.pack(">I", ((hi & 0xFFFF) << 16) | (lo & 0xFFFF)))[0]
clean_copy(REAL, work)
before = dump(work)
adapter = RekordboxAdapter(work)
bare = next((t for t in adapter.tracks if t.auto_gain_db is None), None)
if bare is None:
print(" [SKIP] every track already has a MixerParam row")
else:
measured = Loudness(lufs=-13.0, rms=-11.0, true_peak=2.5, lra=6.0, plr=15.5)
got = adapter.set_auto_gain(bare.id, measured)
check("the projection updates immediately", got is not None and abs(got.auto_gain_db - 3.0) < 1e-4,
str(got and got.auto_gain_db))
adapter.save()
after = dump(work)
changes = diff(before, after)
check("exactly one MixerParam INSERT and the counter",
{t for t, _, _, _ in changes} == {"djmdMixerParam", "agentRegistry"} and len(changes) == 2,
describe(changes))
new = [c for c in changes if c[0] == "djmdMixerParam"]
if new:
row = new[0][3]
check("ContentID, UUID-string ID and UUID, stamped with a USN",
row["ContentID"] == bare.id and len(row["ID"]) == 36 and len(row["UUID"]) == 36
and row["rb_local_usn"] is not None, str(row))
check("Gain = 10^((-10 - LUFS)/20) as float32 halves",
abs(_lin(row["GainHigh"], row["GainLow"]) - 10 ** (3.0 / 20)) < 1e-6, str(row))
check("Peak clipped at 0 dBFS (1.0) as rekordbox's own is",
abs(_lin(row["PeakHigh"], row["PeakLow"]) - 1.0) < 1e-6, str(row))
before = after
adapter.set_auto_gain(bare.id, measured)
check("writing the same gain again is not an edit", not adapter.dirty)
adapter.set_auto_gain(bare.id, Loudness(lufs=-8.0, rms=-6.0, true_peak=-1.0, lra=4.0, plr=7.0))
adapter.save()
changes = diff(before, dump(work))
check("a new value UPDATES that row only (+ the counter)",
sorted((t, k) for t, _, k, _ in changes) == [("agentRegistry", "UPDATE"), ("djmdMixerParam", "UPDATE")],
describe(changes))
reopened = RekordboxAdapter(work)
check("the gain projects after a reopen (-2.0 dB)",
abs((reopened.track(bare.id).auto_gain_db or 0) + 2.0) < 1e-4)
reopened.close()
adapter.close()
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+43
View File
@@ -241,6 +241,47 @@ with tempfile.TemporaryDirectory() as d:
check("…with no second download", downloads == [target], downloads)
c.post("/api/save")
print("== loudness: measured here, kept on the server ==")
import httpx
puts = []
real_put = adapter.client.loudness_put
adapter.client.loudness_put = lambda entries: (puts.append(entries), real_put(entries))[1]
r = c.post("/api/tracks/loudness", json={"track_id": target})
check("the deck's loudness runs here, on the cached copy", r.status_code == 200 and downloads == [target],
r.text[:200])
server_path = str(mapped / file_name)
check("…and is sent to the server, keyed by the SERVER's path",
puts and puts[-1][0]["path"] == server_path, str(puts)[:300])
vals = c.post("/api/loudness", json={"track_ids": [target]}).json()["values"]
check("the table reads it back through the server", target in vals and not vals[target]["stale"], str(vals))
direct = httpx.post(f"http://127.0.0.1:{port}/v1/loudness/get", json={"paths": [server_path]},
auth=("dj", "secret")).json()
check("…the server holds it", [e["path"] for e in direct["entries"]] == [server_path], str(direct))
r = httpx.put(f"http://127.0.0.1:{port}/v1/loudness", json={"entries": direct["entries"]},
auth=("dj", "secret"))
check("storing without the session is refused (423)", r.status_code == 423, r.text[:200])
check("…and a measurement leaves nothing unsaved", not c.get("/api/state").json()["dirty"])
print("== auto gain: computed here from the server's measurement, written on the server ==")
r = c.post("/api/tracks/analyze", json={"track_ids": [target], "bpm": False, "grid": False,
"gain": True, "replace_gain": True})
job = r.json()
for _ in range(200):
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
break
time.sleep(0.05)
lufs = vals[target]["lufs"]
got = c.get("/api/tracks", params={"limit": 20000}).json()
row = next((t for t in got["items"] if t["id"] == target), None)
check("the gain is -9.2 - LUFS, from the stored measurement (no new download)",
j["state"] == "done" and j["result"]["gain"]["set"] == 1 and row is not None
and abs(row["auto_gain_db"] - (-9.2 - lufs)) < 1e-4 and downloads == [target], str(j)[:300])
c.post("/api/save")
check("…and Save writes it into the server's collection",
b'PERCEIVED_DB="%.6f"' % round(-9.2 - lufs, 6) in work.read_bytes())
print("== export, from the server's library ==")
dest = root / "stick"
r = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"], "destination": str(dest)})
@@ -399,6 +440,8 @@ with tempfile.TemporaryDirectory() as d:
and st["remote"]["machine"] == "Studio iMac")
caps = c.get("/api/capabilities").json()
check("…through its capabilities", not caps["writable"] and caps["readonly_cause"] == "taken_over")
r = c.post("/api/tracks/loudness", json={"track_id": target})
check("…and a measurement can no longer be stored", r.status_code == 503, r.text[:200])
check("the server still has the genre this computer saved", server_adapter.track(target).genre == "Remote Edit")
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
check("reopening says who holds it", r.status_code == 409
+315
View File
@@ -0,0 +1,315 @@
"""Normalize on a REMOTE library.
A Konduktor server runs in a thread on a temp copy of the real collection whose
entries point at generated audio on "the server"; the app normalises through
its own routes. The server never decodes audio, so this pins the split:
* the server plans from its own loudness store, and this computer reports
what must be downloaded and uploaded;
* the run downloads, measures where the server has no value (stored back on
the server), rewrites + verifies HERE and uploads; the SERVER parks the
original, puts the upload under its name and recomputes the auto gain —
its saved collection untouched until Save, which deletes the parked
original there; Discard puts it back;
* the server refuses an upload at a gain its own plan would not give;
* Cancel deletes what the run uploaded, and nothing else;
* a takeover mid-batch loses nothing: the verified upload stays on the
server and the next run publishes it without rewriting;
* a platform that draws waveforms gets them measured HERE, from the
levelled file, and handed to the end step.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import threading
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remotenorm-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
import av # noqa: E402
import httpx # noqa: E402
import numpy as np # noqa: E402
import soundfile as sf # noqa: E402
import uvicorn # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor.adapters.remote import config as remote_config # noqa: E402
from konduktor.adapters.remote.client import RemoteClient # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.app_state import AppState # noqa: E402
from konduktor.core import level_edit # noqa: E402
from konduktor.gain import normalize, remote_normalize # noqa: E402
from konduktor.pending import parked_name, partial_name # noqa: E402
from konduktor.server.app import Server, create_app # noqa: E402
from konduktor.server.config import ServerConfig # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
class MemoryKeychain(dict):
def get(self, account): # noqa: D401
return dict.get(self, account)
def set(self, account, password):
self[account] = password
def delete(self, account):
self.pop(account, None)
def music(seconds=8.0, amp=0.3, sr=44100, seed=1):
t = np.arange(int(sr * seconds)) / sr
rng = np.random.default_rng(seed)
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
x = [amp * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.3 * np.sin(2 * np.pi * (440 + 30 * c) * t)
+ 0.2 * rng.standard_normal(t.size)) for c in range(2)]
return np.vstack(x).astype(np.float32)
def make(path: Path, amp: float, seed: int) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
x = music(amp=amp, seed=seed)
if path.suffix == ".mp3":
with av.open(str(path), "w", format="mp3") as c:
s = c.add_stream("libmp3lame", rate=44100, layout="stereo")
s.bit_rate = 256_000
for o in range(0, x.shape[1], 1152):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
f.sample_rate, f.pts = 44100, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
else:
sf.write(str(path), x.T, 44100, subtype="PCM_16")
return path
remote_config.use_password_store(MemoryKeychain())
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-remotenorm-"))
FILES = ["a.mp3", "b.flac", "c.wav", "d.mp3", "e.wav", "f.mp3"]
# ---- a server library: entries pointed at generated audio --------------------------------
content = (ROOT / "server" / "Music").resolve()
work = ROOT / "server" / "collection.nml"
work.parent.mkdir(parents=True)
shutil.copy2(REAL, work)
st = TraktorStore(work)
entries = [e for e in st._nml.collection.entry if e.location and e.stems is None][:len(FILES)]
ids, files = [], []
for n, (name, e) in enumerate(zip(FILES, entries)):
path = make(content / name, 0.8, n + 1)
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
e.cue_v2 = []
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
ids.append(st._key_of(e))
files.append(path)
st.save()
del st
originals = {p.name: p.read_bytes() for p in files}
keep = ROOT / "originals"
keep.mkdir()
for p in files:
shutil.copy2(p, keep / p.name)
cfg = ServerConfig(platform="traktor", library=work, content=content, username="dj", password="pw", name="NAS")
srv = Server(cfg, state=AppState())
srv.open()
uv = uvicorn.Server(uvicorn.Config(create_app(srv), host="127.0.0.1", port=0, log_level="warning"))
threading.Thread(target=uv.run, daemon=True).start()
while not uv.started:
time.sleep(0.05)
port = uv.servers[0].sockets[0].getsockname()[1]
OPTS = {"measure": "lufs", "target": -14.0, "ceiling": -1.0}
def wait(c, jid, timeout=180):
end = time.time() + timeout
while time.time() < end:
j = c.get(f"/api/jobs/{jid}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
raise AssertionError("job did not finish")
def at_gain(name: str, gain: float) -> bool | str:
try:
level_edit.verify(keep / name, content / name, gain)
return True
except level_edit.LevelEditError as ex:
return str(ex)
def server_gain_items() -> list[dict]:
return [i for i in srv.state.pending.items if i.get("kind") == "gain"]
class Handle:
cancelled = False
def progress(self, **kw):
pass
with TestClient(main.app) as c:
remote_id = c.post("/api/remotes", json={"name": "NAS", "host": f"127.0.0.1:{port}",
"username": "dj", "password": "pw"}).json()["remote"]["id"]
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
assert r.status_code == 200, r.text
server_adapter = srv.state.adapter
caps = c.get("/api/capabilities").json()
check("a remote Traktor library is normalizable", caps["tracks"]["normalizable"], str(caps["tracks"]))
print("== the plan: the server's, plus this computer's ==")
p = c.post("/api/tracks/normalize/preview", json={"track_ids": ids[:2], **OPTS}).json()
check("both tracks are measured first (the server has no value yet)",
p.get("to_measure") == 2 and all(r["outcome"] == "unmeasured" for r in p["rows"]), str(p)[:300])
check("…and what must cross the network",
p["transfer"]["download"] > 0 and p["transfer"]["upload"] > 0, p.get("transfer"))
check("Traktor draws no waveform from its own files: no lead", all(r["lead"] is None for r in p["rows"]))
print("== a run: rewritten here, swapped in on the server ==")
saved = work.read_bytes()
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": ids[:2], **OPTS}).json()["id"])
res = job.get("result") or {}
check("the job normalises both", job["state"] == "done" and sorted(res.get("normalised", [])) == sorted(ids[:2]),
job.get("error") or res)
items = server_gain_items()
check("the server's ledger holds both, awaiting Save", len(items) == 2
and all(i["state"] == "swapped" for i in items), str([i.get("state") for i in items]))
for name in FILES[:2]:
g = next(i["gain_db"] for i in items if Path(i["source"]).name == name)
check(f"{name}: the file on the server is the original at {g:+.2f} dB", at_gain(name, g) is True,
str(at_gain(name, g)))
check(f"{name}: the original is parked beside it, unchanged",
parked_name(content / name).read_bytes() == originals[name])
check("the SAVED collection is untouched until Save", work.read_bytes() == saved)
held = httpx.post(f"http://127.0.0.1:{port}/v1/loudness/get", json={"paths": [str(files[0])]},
auth=("dj", "pw")).json()["entries"]
after_lufs = held[0]["lufs"] if held else None
track = main.require_adapter().track(ids[0])
check("the server's loudness is the NEW level, and the mirror's auto gain follows it",
after_lufs is not None and abs(track.auto_gain_db - (-9.2 - after_lufs)) < 1e-4,
f"{after_lufs} {track.auto_gain_db}")
st_ = c.get("/api/state").json()
check("the state reports the pending change (from the server's ledger)",
st_["pending_gain"] and st_["pending_gain"]["tracks"] == 2, st_.get("pending_gain"))
check("…and blocks what would save or drop it", c.post("/api/reload").status_code == 409)
c.post("/api/save")
check("Save deletes the parked originals on the server",
not any(parked_name(content / n).exists() for n in FILES[:2]) and not server_gain_items())
check("…and the saved collection holds the new gain",
f'PERCEIVED_DB="{-9.2 - after_lufs:.6f}"'.encode() in work.read_bytes())
print("== Discard puts it back ==")
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[2]], **OPTS}).json()["id"])
check("(setup) a second run", job["state"] == "done" and (job.get("result") or {}).get("normalised"),
job.get("error"))
c.post("/api/discard")
check("Discard restores the original's bytes on the server, nothing parked",
(content / FILES[2]).read_bytes() == originals[FILES[2]]
and not parked_name(content / FILES[2]).exists() and not server_gain_items())
print("== the server checks the gain against its own plan ==")
adapter = main.require_adapter()
local = adapter.audio_path(ids[3])
junk = ROOT / "junk.mp3"
shutil.copy2(local, junk)
c.post("/api/tracks/loudness", json={"track_id": ids[3]})
try:
adapter.stage_gain(ids[3], junk, gain_db=12.0412, options=OPTS)
refused = False
except Exception as ex: # noqa: BLE001
refused = "planned" in str(ex) or "409" in str(ex)
check("an upload at a gain the server would not give is refused", refused)
check("…and leaves nothing", not partial_name(content / FILES[3]).exists() and not server_gain_items())
print("== Cancel deletes what the run uploaded ==")
h = Handle()
real_stage = adapter.stage_gain
def stage_then_cancel(*a, **k):
out = real_stage(*a, **k)
h.cancelled = True
return out
adapter.stage_gain = stage_then_cancel
out = remote_normalize.run(h, adapter, [ids[3], ids[4]], normalize.Options(**OPTS), still_current=lambda: True)
adapter.stage_gain = real_stage
check("a cancel after one upload stops the batch", out["cancelled"])
check("…and the uploaded file is deleted on the server",
not partial_name(content / FILES[3]).exists() and not server_gain_items(), str(server_gain_items()))
check("…nothing else changed", (content / FILES[3]).read_bytes() == originals[FILES[3]]
and not server_adapter.dirty)
print("== a takeover mid-batch loses nothing ==")
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "pw")
def stage_then_takeover(*a, **k):
out = real_stage(*a, **k)
other.acquire("other", "Studio iMac", takeover=True)
other.release()
return out
adapter.stage_gain = stage_then_takeover
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[4]], **OPTS}).json()["id"])
adapter.stage_gain = real_stage
check("(the run cannot publish once taken over)", job["state"] != "done"
or not (job.get("result") or {}).get("normalised"), str(job)[:300])
check("the verified upload stays on the server",
partial_name(content / FILES[4]).is_file() and [i["state"] for i in server_gain_items()] == ["written"])
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
p = c.post("/api/tracks/normalize/preview", json={"track_ids": [ids[4]], **OPTS}).json()
check("the next plan reuses it", p["rows"][0].get("staged") and p["transfer"]["upload"] == 0, str(p)[:300])
real_apply = level_edit.apply
level_edit.apply = lambda *a, **k: (_ for _ in ()).throw(AssertionError("rewrote a staged file"))
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[4]], **OPTS}).json()["id"])
level_edit.apply = real_apply
check("…and publishes it without rewriting", job["state"] == "done"
and (job.get("result") or {}).get("normalised") == [ids[4]], job.get("error") or job.get("result"))
c.post("/api/save")
g = next((i for i in srv.state.pending.items), None)
check("…saved, its original gone", not parked_name(content / FILES[4]).exists() and g is None)
print("== a platform that draws waveforms gets them measured HERE ==")
server_adapter = srv.state.adapter
seen = {}
server_adapter.analysis_lead = lambda path: 0.0
real_changed = server_adapter.audio_changed
def recording(track_id, change):
seen[track_id] = change
return real_changed(track_id, change)
server_adapter.audio_changed = recording
p = c.post("/api/tracks/normalize/preview", json={"track_ids": [ids[5]], **OPTS}).json()
check("the plan names the platform's lead", p["rows"][0]["lead"] == 0.0, str(p["rows"][0]))
job = wait(c, c.post("/api/tracks/normalize", json={"track_ids": [ids[5]], **OPTS}).json()["id"])
change = seen.get(ids[5])
check("the end step receives the levelled file's waveform, measured on this computer",
job["state"] == "done" and change is not None and change.measured is not None
and len(change.measured.frames.bands) > 100, job.get("error"))
c.post("/api/discard")
uv.should_exit = True
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+8
View File
@@ -137,6 +137,8 @@ with TestClient(main.app) as c:
and any(s["volume"].startswith("the server") for s in p["space"]), p["space"])
print("== a Replace batch ==")
r = c.post("/api/tracks/loudness", json={"track_id": ids[0]})
check("(setup) the original's loudness is measured, kept on the server", r.status_code == 200, r.text[:200])
saved_bytes = work.read_bytes()
r = c.post("/api/tracks/stems/convert", json={"track_ids": ids[:1], "mode": "replace"})
job = wait(c, r.json()["id"])
@@ -150,6 +152,12 @@ with TestClient(main.app) as c:
check("the server's entry now names the stem file", new_id and server_adapter.track(new_id) is not None)
check("…and the mirror here follows", main.require_adapter().track(new_id) is not None)
check("the SAVED collection is untouched until Save", work.read_bytes() == saved_bytes)
import httpx
held = httpx.post(f"http://127.0.0.1:{port}/v1/loudness/get", json={"paths": [str(target)]},
auth=("dj", "pw")).json()["entries"]
check("the stem file was measured HERE and its value stored on the server with it",
[e["path"] for e in held] == [str(target)], str(held))
st_ = c.get("/api/state").json()
check("the state reports the conversion awaiting Save (from the server's ledger)",
st_["pending_stems"] and st_["pending_stems"]["tracks"] == 1, st_.get("pending_stems"))
+101
View File
@@ -63,6 +63,14 @@ def _raises_playlist(fn) -> bool:
return False
def _raises_any(fn) -> bool:
try:
fn()
except Exception:
return True
return False
def tag_lines(b: bytes) -> list[str]:
return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines()
@@ -1341,5 +1349,98 @@ with tempfile.TemporaryDirectory() as d:
reread = TraktorStore(work)._nml.collection.entry[0].info.comment
check("…and reads back unchanged", reread == "x > y key='8A' \"z\"", repr(reread))
print("== R. track colour (INFO@COLOR) is localized, Traktor's shape, reversible ==")
# Measured in Traktor 4.5 (kit T1): COLOR="1".."7" (Red..Magenta), the LAST
# attribute of <INFO>; no file tag. Cleared = no attribute (unmeasured what
# Traktor itself leaves after "None"; absent is what an uncoloured entry has).
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = TraktorStore(work)
entry = next(e for e in store._nml.collection.entry if e.info is not None and e.info.color is None)
loc = entry.location
tid = f"{loc.volume}{loc.dir}{loc.file}"
store.set_track_color(tid, "blue")
store.save()
coloured = work.read_bytes()
o_s, o_e = _entry_span_by_file(original, loc.file)
c_s, c_e = _entry_span_by_file(coloured, loc.file)
check("only that ENTRY changes",
original[:o_s] + original[o_e:] == coloured[:c_s] + coloured[c_e:])
check("in one line: its <INFO>, with COLOR last, as Traktor writes it",
diff_count(original[o_s:o_e], coloured[c_s:c_e]) == 2 # one line: - and +
and _re.search(rb'<INFO [^>]* COLOR="5">', coloured[c_s:c_e]) is not None)
store = TraktorStore(work)
store.set_track_color(tid, "aqua")
check("aqua (rekordbox's) is stored as Traktor's Blue: a no-op", store.dirty is False)
store.set_track_color(tid, "purple")
check("purple is Traktor's Violet (6)",
store._entry_by_key[tid].info.color == 6)
store.set_track_color(tid, None)
store.save()
check("clearing restores the original bytes", work.read_bytes() == original)
check("an unknown colour is refused",
_raises_any(lambda: TraktorStore(work).set_track_color(tid, "teal")))
_KIT = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
if _KIT.exists() and b'COLOR="' in _KIT.read_bytes():
data = _KIT.read_bytes()
check("a Traktor 4.5 collection with coloured tracks renders byte-identically",
TraktorStore(_KIT)._render() == data)
else:
print(" [SKIP] no coloured Traktor 4.5 collection on this machine")
print("== S. auto gain (<LOUDNESS>) is localized, Traktor's shape, never a file tag ==")
# Measured in Traktor 4.5 (kit G1): the deck reads PERCEIVED_DB; Traktor's own
# value is -9.2 - LUFS; Konduktor writes PERCEIVED = ANALYZED as Traktor does.
from konduktor.core.loudness import Loudness # noqa: E402
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = TraktorStore(work)
keyed = next(e for e in store._nml.collection.entry if e.loudness is not None and e.info is not None)
loc = keyed.location
tid = f"{loc.volume}{loc.dir}{loc.file}"
measured = Loudness(lufs=-11.5, rms=-9.0, true_peak=-0.75, lra=5.0, plr=10.75)
store.set_auto_gain(tid, measured)
store.save()
out = work.read_bytes()
o_s, o_e = _entry_span_by_file(original, loc.file)
c_s, c_e = _entry_span_by_file(out, loc.file)
check("only that ENTRY changes",
original[:o_s] + original[o_e:] == out[:c_s] + out[c_e:])
check("in one line: its <LOUDNESS>, in Traktor's 6-decimal form",
diff_count(original[o_s:o_e], out[c_s:c_e]) == 2
and b'<LOUDNESS PEAK_DB="0.750000" PERCEIVED_DB="2.300000" ANALYZED_DB="2.300000">'
in out[c_s:c_e])
store = TraktorStore(work)
check("the projection reads PERCEIVED_DB", abs(store._entry_by_key[tid].loudness.perceived_db - 2.3) < 1e-9)
store.set_auto_gain(tid, measured)
check("writing the same gain again is not an edit", store.dirty is False)
check("auto gain is collection-only: no file tag", "auto_gain" in TraktorStore._COLLECTION_ONLY_FIELDS)
bare = next((e for e in store._nml.collection.entry if e.loudness is None and e.tempo is not None
and e.musical_key is not None), None)
if bare is None:
print(" [SKIP] no entry without LOUDNESS in this collection")
else:
bloc = bare.location
bid = f"{bloc.volume}{bloc.dir}{bloc.file}"
before = work.read_bytes()
store.set_auto_gain(bid, measured)
store.save()
after = work.read_bytes()
b_s, b_e = _entry_span_by_file(after, bloc.file)
span = after[b_s:b_e]
line = (b'<LOUDNESS PEAK_DB="0.750000" PERCEIVED_DB="2.300000" ANALYZED_DB="2.300000">'
b'</LOUDNESS>\n')
check("an entry without one gains a single <LOUDNESS> line, nothing else",
after[:b_s] + span.replace(line, b"", 1) + after[b_e:] == before)
check("…between TEMPO and MUSICAL_KEY, where Traktor puts it",
span.find(b"<TEMPO") < span.find(b"<LOUDNESS") < span.find(b"<MUSICAL_KEY"))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+10
View File
@@ -204,6 +204,16 @@ for enc in encoders:
covr = MP4(str(out)).tags.get("covr")
check(f"{enc}: the cover art is copied", bool(covr) and bytes(covr[0]) == COVER)
# Traktor on Windows skips a FIXED 1024 samples of priming where macOS honours
# the edit list: Apple-encoded stems (2112) sat ~25 ms early on a PC
# (2026-10-19). So the default encoder is FFmpeg's on every platform, and what
# it writes primes exactly 1024 — the commercial stems' value.
from konduktor.core import mp4_edit # noqa: E402
check("the default encoder is FFmpeg's aac, on every platform", sf.default_encoder() == "aac")
w = sf.build(MP3, tmp / "Default.stem.m4a", fake_separate)
prime = round((mp4_edit.priming_seconds(w.path) or 0) * SR)
check("a default-built stem file primes exactly 1024 samples", prime == 1024, str(prime))
w = sf.build(MP3_128, tmp / "low.stem.m4a", fake_separate, encoder="aac")
check("a 128 kbps source is encoded at the 256 kbps floor", w.bit_rate == 256_000, str(w.bit_rate))
w = sf.build(FLAC_SRC, tmp / "Lossless.stem.m4a", fake_separate, encoder="aac")
+15 -4
View File
@@ -172,9 +172,16 @@ with TestClient(main.app) as c:
got = ROOT / "folder-1.m4a"
got.write_bytes(r.content)
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2)))
kinds = {t["id"]: t["media_kind"] for t in listing.json()["tracks"]}
check("the listing marks the stem file as a stem track and the MP3 as audio",
kinds.get(str(stem)) == "stem" and kinds.get(str(plain)) == "audio", str(kinds))
# All three files are HELD, and a held file's row IS the collection track
# (decided 2026-10-10): its id and media_kind are the collection's, so the
# MP3 whose entry carries <STEMS> lists as a stem track. What the FILE says
# is checked on loose files below.
body = listing.json()
kinds = {t["id"]: t["media_kind"] for t in body["tracks"]}
check("held files list as their collection tracks, mapped back to the files",
body["files"].get(stem_id) == str(stem) and body["files"].get(tagged_id) == str(tagged), str(body["files"]))
check("…with the collection's media kind",
kinds.get(tagged_id) == "stem" and kinds.get(plain_id) == "audio", str(kinds))
print("== adding a stem file to the collection ==")
extra_dir = ROOT / "More"
@@ -182,7 +189,11 @@ with TestClient(main.app) as c:
extra = extra_dir / "Other.stem.m4a"
shutil.copy2(stem, extra)
extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9)
assert c.get("/api/folder/tracks", params={"path": str(extra_dir)}).status_code == 200
loose = c.get("/api/folder/tracks", params={"path": str(extra_dir)})
assert loose.status_code == 200
kinds = {t["id"]: t["media_kind"] for t in loose.json()["tracks"]}
check("a LOOSE stem file lists as a stem track (its box), the MP3 beside it as audio",
kinds.get(str(extra)) == "stem" and kinds.get(str(extra_plain)) == "audio", str(kinds))
pl_id = c.post("/api/playlists", json={"name": "Stem Adds"}).json()["id"]
job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)],
"mode": "reference", "playlist_id": pl_id}).json()
+19
View File
@@ -241,6 +241,25 @@ with TestClient(main.app) as c:
check("the original entries are still plain tracks", all(a.track(t).media_kind != "stem" for t in ids))
c.post("/api/discard")
print("== loudness: a stem file is measured when its original was ==")
from konduktor import loudness_store
work, ids, music = library("loud", ["m.mp3", "n.mp3"])
open_lib(c, work)
r = c.post("/api/tracks/loudness", json={"track_id": ids[0]})
check("the first original is measured", r.status_code == 200, r.text[:200])
j = convert(c, ids)
res = j["result"]
check("both convert", len(res["renamed"]) == 2, str(res)[:300])
stems = [str(music / "m.stem.m4a"), str(music / "n.stem.m4a")]
got = loudness_store.local().get(stems)
check("the measured original's stem file has a value of its own", stems[0] in got, str(list(got)))
check("the unmeasured original's stem file is left unmeasured", stems[1] not in got)
new = res["renamed"][ids[0]]
vals = c.post("/api/loudness", json={"track_ids": [new]}).json()["values"]
check("…shown on the converted track, fresh", new in vals and not vals[new]["stale"], str(vals))
c.post("/api/discard")
print("== after a crash: restore from the saved file, keep the work, reuse it ==")
work, ids, music = library("crash", ["a.mp3", "b.mp3"])
open_lib(c, work)
+48
View File
@@ -263,6 +263,34 @@ with tempfile.TemporaryDirectory() as d:
check("set_analysed_grid pairs the marker with a companion",
cues.grid_markers[0].companion is not None)
# ---- replace_cues: a pushed track brought up to date ------------------------
print("== replace_cues makes the prep exactly the given one ==")
with tempfile.TemporaryDirectory() as d:
from konduktor.core.model import CuePoint, GridMarker, TrackCues # noqa: E402
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
adapter = TraktorAdapter(work)
# A real entry carrying a grid WITH its white companion, hot cues and a lock.
tid = next(t.id for t in adapter.tracks
if t.grid_marker_count == 1 and t.hotcue_count >= 2
and adapter.track_cues(t.id).grid_markers[0].companion is not None)
want = TrackCues(
grid_markers=[GridMarker(start=0.25, bpm=124.0)], grid_locked=False,
cues=[CuePoint(start=4.0, length=0.0, slot=2, name="Drop"),
CuePoint(start=8.0, length=2.0, slot=3, type="loop"),
CuePoint(start=12.0, length=0.0, role="memory", name="Mem")])
got = adapter.replace_cues(tid, want)
check("the grid is exactly the new one, no companion invented",
[(m.start, m.bpm, m.companion) for m in got.grid_markers] == [(0.25, 124.0, None)],
str(got.grid_markers))
check("only the given cues remain, on their pads, the memory cue as one",
sorted((c.slot, c.role, c.name) for c in got.cues if c.slot is not None) == [(2, "hotcue", "Drop"), (3, "hotcue", None)]
and [c.name for c in got.cues if c.role == "memory"] == ["Mem"], str(got.cues))
again = adapter.replace_cues(tid, want)
check("replacing with the same prep is stable",
[(c.slot, c.start, c.role) for c in again.cues] == [(c.slot, c.start, c.role) for c in got.cues])
# ---- remap rebuilds the index (track ids change) --------------------------
print("== a path remap rebuilds the projection, because track ids change ==")
with tempfile.TemporaryDirectory() as d:
@@ -332,5 +360,25 @@ if gridded is not None:
all(c.type != "grid" for c in cues.cues) and
gridded.cue_count == len(cues.cues))
print("== track colour ==")
# `INFO@COLOR` 1-7, measured in Traktor 4.5 (kit T1): Red ... Magenta, menu order.
from konduktor.adapters.traktor import projection, track_palette # noqa: E402
_entry = next(e for e in adapter._store.iter_entries() if e.info is not None)
_was = _entry.info.color
_seen = []
for _code in (None, 0, 1, 4, 7, 8):
_entry.info.color = _code
_t = projection.to_track(_entry)
_seen.append((_t.color, _t.color_hex))
_entry.info.color = _was
check("Traktor's track colours project by name + display RGB (none for absent/0/unknown)",
_seen == [(None, None), (None, None), ("red", "#FB413E"), ("green", "#52FA52"),
("pink", "#FA51EB"), (None, None)], str(_seen))
check("Traktor offers seven colours, Violet as purple and Magenta as pink",
[s.color for s in adapter.capabilities().tracks.colors]
== ["red", "orange", "yellow", "green", "blue", "purple", "pink"])
check("aqua (rekordbox's) is stored as Traktor's Blue", track_palette.code_for("aqua") == 5)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+353
View File
@@ -0,0 +1,353 @@
"""Traktor's own block inside an audio file — removed from every copy made for a
Traktor library, so Traktor cannot restore its stale grid over the entry's.
Measured in Traktor 4.5 (2026-10-24, see `adapters/traktor/file_block.py`): an
entry Konduktor wrote has no MODIFIED_DATE, so Traktor re-reads the file and
takes the block's BPM (`HBPM`) over the collection's, LOCK or not. With the
block removed from the copy, the entry's grid, lock, cues — and the art, which
Traktor still imports from the file's ordinary tags — all survive.
Self-contained: generated audio in each format carrying a block that says 175
while the library's grid says 176, and collections built from Konduktor's own
empty Traktor skeleton. Pins:
- `file_block`: each format's block found and removed, everything else in
the file kept (audio sample-identical, other tags, a foreign PRIV frame),
a file without one never rewritten, a garbage file refused quietly;
- export: every copy for a Traktor target loses the block, the SOURCE keeps
it, the manifest records `prepared`, a re-export rewrites nothing, a copy
kept from an export made before this (no `prepared`) is cleaned IN PLACE
rather than copied again, a target without the hook leaves the block, and
adding Traktor to such a set cleans the kept copies;
- local push: the shared folder's copies lose it, the ledger records it;
- import: a copied file loses it, a file added in place is never touched.
"""
from __future__ import annotations
import base64
import json
import os
import shutil
import struct
import tempfile
import time
from pathlib import Path
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fileblock-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
import av # noqa: E402
import numpy as np # noqa: E402
import soundfile as sf # noqa: E402
from mutagen import File as MutagenFile # noqa: E402
from mutagen.flac import FLAC # noqa: E402
from mutagen.id3 import APIC, ID3, PRIV, TIT2 # noqa: E402
from mutagen.mp4 import MP4, MP4Cover # noqa: E402
from konduktor import exporter, exports, importer, local_push, prefs # noqa: E402
from konduktor.adapters.traktor import file_block # noqa: E402
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
from konduktor.app_state import STATE # noqa: E402
from konduktor.core import apps_running, pyav # noqa: E402
from konduktor.core import export as core_export # noqa: E402
from konduktor.core.export import ExportPayload, ExportTrack # noqa: E402
from konduktor.core.model import GridMarker, Track, TrackCues # noqa: E402
from konduktor.exporter import _read_manifest as read_manifest # noqa: E402
from konduktor.jobs import JOBS # noqa: E402
failed = False
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-fileblock-"))
def _jpeg() -> bytes:
import io
from PIL import Image
buf = io.BytesIO()
Image.new("RGB", (8, 8), (200, 40, 90)).save(buf, "JPEG")
return buf.getvalue()
JPEG = _jpeg() # a real (tiny) cover, so the exporters read it
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
# ---- generated audio, each carrying a block that says 175 BPM ------------------------
def block(bpm: float) -> bytes:
"""A minimal `DMRT` tree as Traktor writes it: reversed 4CCs, each chunk
= name + payload size + child count + payload."""
def chunk(name: str, payload: bytes, children: int = 0) -> bytes:
return name[::-1].encode() + struct.pack("<II", len(payload), children) + payload
data = chunk("DATA", chunk("HBPM", struct.pack("<f", bpm)), 1)
hdr = chunk("HDR ", chunk("VRSN", struct.pack("<I", 7)), 1)
return chunk("DMRT", hdr + data, 2)
def music(seconds=6, sr=44100, seed=0):
t = np.arange(int(sr * seconds)) / sr
rng = np.random.default_rng(seed)
beat = (np.sin(2 * np.pi * 2 * t) > 0.6).astype(float)
return np.vstack([0.3 * (0.5 * np.sin(2 * np.pi * 90 * t) * beat + 0.2 * rng.standard_normal(t.size))
for _ in range(2)]).astype(np.float32)
def encode(path: Path, fmt: str, codec: str, frame: int, seed: int):
x = music(seed=seed)
with av.open(str(path), "w", format=fmt) as c:
s = c.add_stream(codec, rate=44100, layout="stereo")
s.bit_rate = 192_000
for o in range(0, x.shape[1], frame):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + frame]), format="fltp", layout="stereo")
f.sample_rate, f.pts = 44100, o
for p in s.encode(f):
c.mux(p)
for p in s.encode(None):
c.mux(p)
def make(path: Path, seed: int, *, with_block: bool = True) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
ext = path.suffix
if ext == ".mp3":
encode(path, "mp3", "libmp3lame", 1152, seed)
tags = ID3()
tags.add(TIT2(encoding=3, text=path.stem))
tags.add(APIC(encoding=3, mime="image/jpeg", type=3, desc="", data=JPEG))
tags.add(PRIV(owner="SomeOtherApp", data=b"keep me"))
if with_block:
tags.add(PRIV(owner="TRAKTOR4", data=block(175.0)))
tags.save(path, v2_version=3)
elif ext == ".m4a":
encode(path, "ipod", "aac", 1024, seed)
m = MP4(path)
if m.tags is None:
m.add_tags()
m.tags["\xa9nam"] = [path.stem]
m.tags["covr"] = [MP4Cover(JPEG, imageformat=MP4Cover.FORMAT_JPEG)]
m.save()
if with_block:
m = MP4(path)
# As Traktor writes it: an atom mutagen cannot parse, kept raw.
m.tags._failed_atoms["NITR"] = [b"\x00\x00\x00\x08NTKB" + b"\x00" * 4 + block(175.0)]
m.save()
elif ext == ".flac":
sf.write(str(path), music(seed=seed).T, 44100, subtype="PCM_16")
f = FLAC(path)
f["title"] = path.stem
if with_block:
f["traktor4"] = base64.b64encode(block(175.0)).decode()
f.save()
return path
def pcm(path: Path) -> list[np.ndarray]:
out = []
with pyav.open_input(str(path)) as c:
for s in c.streams.audio:
c.seek(0)
out.append(np.concatenate([f.to_ndarray().ravel() for f in c.decode(s)]))
return out
def tag_keys(path: Path) -> set[str]:
tags = MutagenFile(path).tags
return set(tags.keys()) | set(getattr(tags, "_failed_atoms", {}))
print("== file_block on each format ==")
unit = ROOT / "unit"
for name in ("a.mp3", "b.m4a", "c.flac"):
src = make(unit / "src" / name, seed=1)
copy = unit / "copy" / (name + ".konduktor-partial") # as the runners strip it
copy.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, copy)
before = tag_keys(copy)
check(f"{name}: the block is found", file_block.has_block(copy))
check(f"{name}: strip reports it removed one", file_block.strip(copy) is True)
check(f"{name}: none is left", not file_block.has_block(copy))
lost = before - tag_keys(copy)
check(f"{name}: only the block is gone from the tags",
len(lost) == 1 and ("TRAKTOR4" in next(iter(lost)) or next(iter(lost)) in ("NITR", "traktor4")),
str(lost))
check(f"{name}: the audio is sample-identical",
all(np.array_equal(a, b) for a, b in zip(pcm(src), pcm(copy))))
data, mtime = copy.read_bytes(), copy.stat().st_mtime_ns
check(f"{name}: a second strip changes nothing, and does not rewrite the file",
file_block.strip(copy) is False and copy.read_bytes() == data and copy.stat().st_mtime_ns == mtime)
mp3 = unit / "copy" / "a.mp3.konduktor-partial"
id3 = ID3(mp3)
check("mp3: a foreign PRIV frame and the cover stay", "PRIV:SomeOtherApp:keep me" in id3 and id3.getall("APIC"))
check("mp3: the file keeps its ID3 version (2.3)", id3.version[:2] == (2, 3))
check("m4a: the cover stays", "covr" in MP4(unit / "copy" / "b.m4a.konduktor-partial").tags)
clean = make(unit / "clean.mp3", seed=2, with_block=False)
data, mtime = clean.read_bytes(), clean.stat().st_mtime_ns
check("a file without a block is never rewritten",
file_block.strip(clean) is False and clean.read_bytes() == data and clean.stat().st_mtime_ns == mtime)
junk = unit / "junk.mp3"
junk.write_bytes(b"ID3" + b"\xff" * 64)
check("an unreadable file is refused quietly", file_block.strip(junk) is False and not file_block.has_block(junk))
# ---- a source library whose grids (176) disagree with the files' blocks (175) ---------
lib_root = ROOT / "MyMusic"
files = [make(lib_root / "DnB" / n, seed=i) for i, n in enumerate(("one.mp3", "two.m4a", "three.flac"))]
files.append(make(lib_root / "DnB" / "plain.mp3", seed=9, with_block=False))
seed = []
for i, path in enumerate(files):
track = Track(id=f"seed{i}", title=path.stem, artist="Test")
cues = TrackCues(grid_markers=[GridMarker(start=0.25, bpm=176.0)], grid_locked=True)
seed.append(ExportTrack(track=track, destination=path, cues=cues))
core_export.for_platform("traktor").write(
ExportPayload(name="Source", tracks=seed, playlists=[], root_folder=True), lib_root)
source_bytes = {p: p.read_bytes() for p in files}
STATE.open(lib_root / "collection.nml")
ad = STATE.adapter
LIB = STATE.library_id
ids = [t.id for t in ad.tracks]
check("the source library holds the four tracks", len(ids) == 4, str(ids))
def run_job(kind, fn):
job = JOBS.submit(kind, fn)
while not job.finished:
time.sleep(0.02)
assert job.error is None, job.error
return job.result
def copies(dest: Path) -> dict[str, Path]:
return {p.name: p for p in (dest / "Contents").rglob("*") if p.is_file() and not p.name.startswith(".")}
def records(dest: Path) -> dict[str, dict]:
return {Path(rel).name: r for rel, r in (read_manifest(dest).get("audio") or {}).items()}
def bpms(nml: Path) -> dict[str, float]:
a = TraktorAdapter(nml)
return {Path(a.audio_path(t.id)).name: a.track_cues(t.id).grid_markers[0].bpm for t in a.tracks}
print("== an export to Traktor ==")
dest = ROOT / "GIG"
gig = exports.create(LIB, name="GIG", targets=["traktor"], destination=str(dest))
exports.add(LIB, gig.id, track_ids=ids)
gig = exports.get(LIB, gig.id)
run_job("export", lambda h: exporter.run(ad, gig, exporter.plan(ad, gig), h))
out = copies(dest)
check("every track was copied", set(out) == {p.name for p in files}, str(sorted(out)))
check("no copy carries Traktor's block", not any(file_block.has_block(p) for p in out.values()))
check("the SOURCE files are untouched", all(p.read_bytes() == b for p, b in source_bytes.items()))
check("a file that had no block is copied byte for byte", out["plain.mp3"].read_bytes() == source_bytes[files[3]])
check("the covers are still in the copies",
ID3(out["one.mp3"]).getall("APIC") and "covr" in MP4(out["two.m4a"]).tags)
recs = records(dest)
check("the manifest records each copy as prepared for Traktor",
all(r.get("prepared") == ["traktor"] for r in recs.values()), str(recs))
check("and records the copy's size as it is now (after the strip)",
all(r["copy_size"] == out[n].stat().st_size for n, r in recs.items()))
check("the exported grids are the library's (176)", all(abs(b - 176.0) < 0.01 for b in bpms(dest / "collection.nml").values()))
print("== a re-export rewrites nothing ==")
stamp = {n: (p.stat().st_ino, p.stat().st_mtime_ns) for n, p in out.items()}
run_job("export", lambda h: exporter.run(ad, gig, exporter.plan(ad, gig), h))
check("every copy kept as it was (same inode, same mtime)",
{n: (p.stat().st_ino, p.stat().st_mtime_ns) for n, p in copies(dest).items()} == stamp)
print("== a copy kept from an export made before this fix is cleaned in place ==")
# Put the block back into one copy and drop `prepared`, as an older export's
# manifest and stick would be — the record matching the file, so it is kept.
old_copy = copies(dest)["one.mp3"]
tags = ID3(old_copy)
tags.add(PRIV(owner="TRAKTOR4", data=block(175.0)))
tags.save(old_copy, v2_version=3)
manifest = read_manifest(dest)
for rel, r in manifest["audio"].items():
r.pop("prepared", None)
if Path(rel).name == "one.mp3":
st = old_copy.stat()
r["copy_size"], r["copy_mtime_ns"] = st.st_size, st.st_mtime_ns
exporter.manifest_path(dest).write_text(json.dumps(manifest))
inode = old_copy.stat().st_ino
again = exporter.plan(ad, gig)
check("the old copy is planned as KEPT, not copied again",
next(t for t in again.exportable if t.destination.name == "one.mp3").reuse is not None)
run_job("export", lambda h: exporter.run(ad, gig, again, h))
cleaned = copies(dest)["one.mp3"]
check("its block is gone", not file_block.has_block(cleaned))
check("in place: the same file, not a new copy", cleaned.stat().st_ino == inode)
check("every record says prepared again", all(r.get("prepared") == ["traktor"] for r in records(dest).values()))
check("and the next export keeps it as it is",
next(t for t in exporter.plan(ad, gig).exportable if t.destination.name == "one.mp3").reuse is not None)
print("== a target without the hook leaves the block; adding Traktor cleans the kept copies ==")
pdest = ROOT / "PIONEER"
pio = exports.create(LIB, name="PIONEER", targets=["rekordbox_export"], destination=str(pdest))
exports.add(LIB, pio.id, track_ids=ids)
pio = exports.get(LIB, pio.id)
run_job("export", lambda h: exporter.run(ad, pio, exporter.plan(ad, pio), h))
pout = copies(pdest)
check("a Rekordbox Export's copies keep Traktor's block (none of its business)",
file_block.has_block(pout["one.mp3"]) and file_block.has_block(pout["two.m4a"]))
check("and are recorded as prepared by nobody", all(r.get("prepared") == [] for r in records(pdest).values()))
inodes = {n: p.stat().st_ino for n, p in pout.items()}
pio = exports.update(LIB, pio.id, targets=["rekordbox_export", "traktor"])
run_job("export", lambda h: exporter.run(ad, pio, exporter.plan(ad, pio), h))
pout = copies(pdest)
check("with Traktor added, no copy carries the block", not any(file_block.has_block(p) for p in pout.values()))
check("cleaned in place, none copied again", {n: p.stat().st_ino for n, p in pout.items()} == inodes)
check("recorded as prepared for Traktor", all(r.get("prepared") == ["traktor"] for r in records(pdest).values()))
print("== a local push into this computer's Traktor ==")
laptop = ROOT / "laptop" / "collection.nml"
laptop.parent.mkdir(parents=True)
laptop.write_text(SKELETON, encoding="utf-8")
AUDIO = ROOT / "LocalAudio"
apps_running.running = lambda platforms: set()
prefs.update_prefs({"localLibraries": {"traktor": str(laptop), "rekordbox": str(ROOT / "none" / "master.db")},
"localAudioRoot": str(AUDIO), "localNormalise": False})
push = exports.create(LIB, name="Push", targets=["traktor"], destination="", kind="computer", mode="merge")
exports.add(LIB, push.id, track_ids=ids)
push = exports.get(LIB, push.id)
built = local_push.plan(ad, push)
check("the push can run", built.blocked is None, str(built.blocked))
run_job("local-push", lambda h: local_push.run(ad, push, built, h))
pushed = {p.name: p for p in AUDIO.rglob("*") if p.is_file() and p.suffix in (".mp3", ".m4a", ".flac")}
check("every track's copy is in the shared folder", set(pushed) == {p.name for p in files}, str(sorted(pushed)))
check("none of them carries Traktor's block", not any(file_block.has_block(p) for p in pushed.values()))
ledger = local_push._read_ledger()["audio"][str(AUDIO)]
check("the ledger records them as prepared for Traktor",
all(r.get("prepared") == ["traktor"] for r in ledger.values()), str(ledger))
check("the laptop's collection has the library's grids (176)",
all(abs(b - 176.0) < 0.01 for b in bpms(laptop).values()), str(bpms(laptop)))
check("the SOURCE files are still untouched", all(p.read_bytes() == b for p, b in source_bytes.items()))
print("== an import into a Traktor collection ==")
into = ROOT / "into" / "collection.nml"
into.parent.mkdir(parents=True)
into.write_text(SKELETON, encoding="utf-8")
dest_ad = TraktorAdapter(into)
folder = ROOT / "into" / "Imported"
run_job("import", lambda h: importer.run(ad, dest_ad, importer.plan(ad, dest_ad, folder, track_ids=ids[:2]), h))
imported = [p for p in folder.rglob("*") if p.is_file()]
check("the copied files arrived", len(imported) == 2, str(imported))
check("and carry no block", imported and not any(file_block.has_block(p) for p in imported))
ref = ROOT / "ref" / "collection.nml"
ref.parent.mkdir(parents=True)
ref.write_text(SKELETON, encoding="utf-8")
ref_ad = TraktorAdapter(ref)
run_job("import", lambda h: importer.run(ad, ref_ad, importer.plan(ad, ref_ad, None, track_ids=ids[:2]), h,
reference=True))
check("a file added IN PLACE is never touched", all(p.read_bytes() == b for p, b in source_bytes.items()))
check("so it keeps its block (it is the user's file)", file_block.has_block(files[0]))
shutil.rmtree(ROOT, ignore_errors=True)
print("\nALL PASS" if not failed else "\nSOME CHECKS FAILED")
raise SystemExit(1 if failed else 0)
+6
View File
@@ -40,6 +40,12 @@ try {
& (Join-Path $Root "backend\build_sidecar.ps1")
}
# Updater packages are signed with the release key (CI's secret). Without
# it, build the installers alone rather than fail at the signing step.
if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
$TauriArgs = @("--config", "src-tauri/tauri.unsigned.conf.json") + $TauriArgs
}
Write-Host ""
Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)"
Set-Location (Join-Path $Root "frontend")
Executable
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Build the Konduktor desktop app on macOS: freeze + stage the backend sidecar,
# then build the Tauri app (.app + .dmg). The macOS twin of build.ps1.
# One-time setup:
# python3 -m venv backend/.venv
# backend/.venv/bin/pip install -r backend/requirements.txt -r backend/requirements-build.txt
# (cd frontend && npm install)
# a Rust toolchain from https://rustup.rs
#
# ./build.sh # sidecar + app (release bundles)
# ./build.sh --skip-sidecar # frontend-only change: reuse the staged sidecar
# ./build.sh --debug # anything else is passed on to `tauri build`
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKIP_SIDECAR=0
TAURI_ARGS=()
for arg in "$@"; do
case "$arg" in
--skip-sidecar) SKIP_SIDECAR=1 ;;
*) TAURI_ARGS+=("$arg") ;;
esac
done
die() { echo "error: $*" >&2; exit 1; }
[ -x "$ROOT/backend/.venv/bin/python" ] || die "No backend venv at backend/.venv - see the one-time setup at the top of build.sh."
[ -d "$ROOT/frontend/node_modules" ] || die "No frontend/node_modules - run \`npm install\` in frontend first."
STAGED="$ROOT/frontend/src-tauri/binaries/konduktor-sidecar/konduktor-sidecar"
# rustup adds ~/.cargo/bin to PATH only in shells started AFTER the install -
# look there before giving up, rather than failing after the sidecar build.
if ! command -v cargo >/dev/null 2>&1; then
[ -x "$HOME/.cargo/bin/cargo" ] || die "No Rust toolchain (cargo) - install it from https://rustup.rs."
export PATH="$HOME/.cargo/bin:$PATH"
fi
# Bundles newer than this marker are this run's (release or --debug profile).
MARKER="$(mktemp)"
trap 'rm -f "$MARKER"' EXIT
if [ "$SKIP_SIDECAR" = 1 ]; then
[ -x "$STAGED" ] || die "No staged sidecar to reuse - run without --skip-sidecar first."
echo "==> Reusing the staged sidecar (--skip-sidecar)"
else
echo "==> 1/2 Freezing the backend sidecar"
PY="$ROOT/backend/.venv/bin/python" "$ROOT/backend/build_sidecar.sh"
fi
# Updater packages are signed with the release key (CI's secret). Without it,
# build the app and .dmg alone rather than fail at the signing step.
if [ -z "${TAURI_SIGNING_PRIVATE_KEY:-}" ]; then
TAURI_ARGS=(--config src-tauri/tauri.unsigned.conf.json ${TAURI_ARGS[@]+"${TAURI_ARGS[@]}"})
fi
# A failed .dmg step leaves its read-write image behind (`rw.<pid>.*.dmg`,
# hundreds of MB each); clear old ones.
find "$ROOT/frontend/src-tauri/target" -path '*/bundle/macos/rw.*.dmg' -delete 2>/dev/null || true
echo ""
echo "==> 2/2 Building the app (tauri build ${TAURI_ARGS[*]+${TAURI_ARGS[*]}})"
LOG="$(mktemp)"
trap 'rm -f "$MARKER" "$LOG"' EXIT
if ! (cd "$ROOT/frontend" && npx tauri build ${TAURI_ARGS[@]+"${TAURI_ARGS[@]}"}) 2>&1 | tee "$LOG"; then
# The .dmg step mounts a fresh image and has Finder lay it out, which fails
# now and then (measured: the same build passed on a rerun). The .app is
# already built by then, so retry just the .dmg once before giving up.
grep -q 'bundle_dmg.sh' "$LOG" || exit 1
echo ""
echo "==> The .dmg step failed; retrying it once"
(cd "$ROOT/frontend" && npx tauri build ${TAURI_ARGS[@]+"${TAURI_ARGS[@]}"} --bundles dmg)
fi
echo ""
BUILT="$(find "$ROOT/frontend/src-tauri/target" -path '*/bundle/*' \( -name '*.dmg' -o -name '*.app' \) \
-newer "$MARKER" -prune 2>/dev/null || true)"
if [ -n "$BUILT" ]; then
echo "Built:"
echo "$BUILT" | sed 's/^/ /'
else
echo "Done (nothing bundled - see frontend/src-tauri/target/)."
fi
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.2.9",
"version": "0.3.6",
"type": "module",
"scripts": {
"dev": "vite",
+30
View File
@@ -0,0 +1,30 @@
# Rubber Band (keylock)
`src/lib/audio/rubberband.wasm` is the [Rubber Band Library](https://breakfastquay.com/rubberband/)
3.3.0 compiled to WebAssembly with Konduktor's own glue (`glue.c`). The deck's
audio worklet uses it for keylock: tempo changes without a pitch change. It
runs the R2 ("faster") engine in real-time mode.
**Licence.** Rubber Band is GPL-2.0-or-later. Every upstream source file says
"either version 2 of the License, or (at your option) any later version", and
its bundled `src/ext` code (KissFFT, Speex resampler, getopt, pommier) is
permissive. That is what allows it to combine with Konduktor's AGPL-3.0, via
GPLv3 §13. Do NOT replace it with a prebuilt npm package:
`rubberband-wasm`'s glue is labelled "GPLv2" without "or later", and
`@echogarden/rubberband-wasm` is GPL-2.0-only. Neither can be combined with
AGPL-3.0.
**Corresponding source** for the `.wasm`: `build.sh` plus `glue.c` plus the
upstream release it downloads, which is pinned by version and SHA-256.
**Rebuilding** is needed only when bumping Rubber Band or changing the glue:
run `./build.sh`, which needs `emcc` on PATH (`brew install emscripten`). The
`.wasm` is checked in, so neither `npm run dev` nor a release build needs
emscripten.
**Measured** (2026-11-02, Apple M3 Pro, stereo 44.1 kHz, 128-frame quanta):
about 40-55x realtime in both JavaScriptCore (WKWebView) and V8 (WebView2).
p99 is about 0.17 ms per quantum against a 2.9 ms budget, so 8 stretchers
(2 stem decks) fit on the one audio render thread. The R3 ("finer") engine is
about 11x realtime and does not fit at 8. `-msimd128` measured no faster than
the `-Oz` npm build.
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more