mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Compare commits
91
Commits
v0.2.1-b10
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fdb2b7ce1 | ||
|
|
65fbc775ce | ||
|
|
b57dd74445 | ||
|
|
31287bdeb7 | ||
|
|
210c1ab135 | ||
|
|
e211fd180a | ||
|
|
5d059c7604 | ||
|
|
667068c2f1 | ||
|
|
75cb0c8138 | ||
|
|
068e4da08b | ||
|
|
1a28ad6102 | ||
|
|
dd82fa99bb | ||
|
|
fae91e8772 | ||
|
|
68128a123e | ||
|
|
23a5cd72f4 | ||
|
|
17c177e34e | ||
|
|
ee0e055b3f | ||
|
|
21e249ff97 | ||
|
|
3e9d5d5528 | ||
|
|
13ba2c721a | ||
|
|
4cb630d0d5 | ||
|
|
64b0396d66 | ||
|
|
284a7514fe | ||
|
|
6eecb2288a | ||
|
|
d70a7c5de2 | ||
|
|
5c9387f136 | ||
|
|
9329236955 | ||
|
|
2821ba124d | ||
|
|
f9ef38d826 | ||
|
|
518542c7bb | ||
|
|
bf427a628e | ||
|
|
4340e948ac | ||
|
|
fe63acc2a2 | ||
|
|
06361a851f | ||
|
|
0605dbabe6 | ||
|
|
6be99e6d7e | ||
|
|
0eac972173 | ||
|
|
422297d890 | ||
|
|
ee48e80440 | ||
|
|
0aeb5019ad | ||
|
|
1f2ca18e8a | ||
|
|
19a604f730 | ||
|
|
83b0978b14 | ||
|
|
0ced274f73 | ||
|
|
fc4e7804b3 | ||
|
|
77b063ba0e | ||
|
|
16c3552be6 | ||
|
|
32cfb034e2 | ||
|
|
b70798a0fe | ||
|
|
4c51f57fe9 | ||
|
|
7b2d6de411 | ||
|
|
8230722105 | ||
|
|
1464b1e211 | ||
|
|
10f175b206 | ||
|
|
a65ef959b2 | ||
|
|
87cbd3720e | ||
|
|
591f2bc791 | ||
|
|
ebe30c1128 | ||
|
|
cd1914216f | ||
|
|
d10b11f8eb | ||
|
|
79a8a843c5 | ||
|
|
0204a322ff | ||
|
|
05051e7056 | ||
|
|
b5dabbc8a0 | ||
|
|
86bbb7b961 | ||
|
|
d474c662db | ||
|
|
a0df683fee | ||
|
|
3385b794e9 | ||
|
|
2c352b76a1 | ||
|
|
40630ff78e | ||
|
|
966f3fe8c5 | ||
|
|
a03b9056a9 | ||
|
|
26b556d975 | ||
|
|
c87444bda5 | ||
|
|
7ba71981c8 | ||
|
|
89c7dade25 | ||
|
|
b154df430a | ||
|
|
e5c7b67626 | ||
|
|
9f79f5a849 | ||
|
|
c8b86100f0 | ||
|
|
0fac84cb73 | ||
|
|
71ee877784 | ||
|
|
920146f2c0 | ||
|
|
ba7b662b93 | ||
|
|
e5fb0f0dbb | ||
|
|
e8a53eee07 | ||
|
|
36a6df4d3b | ||
|
|
72a52d3291 | ||
|
|
c3571fd054 | ||
|
|
b5b3dd04c3 | ||
|
|
4e9472c14a |
No files matched your search
@@ -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()
|
||||
+125
-6
@@ -55,10 +55,11 @@ jobs:
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
|
||||
# --- Step 1: freeze the FastAPI backend into a onedir sidecar folder ---
|
||||
# build_sidecar.* stages it as
|
||||
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
|
||||
# which tauri.conf.json's externalBin bundles into the app.
|
||||
# frontend/src-tauri/binaries/konduktor-sidecar/
|
||||
# which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) /
|
||||
# tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`.
|
||||
- name: Install backend deps
|
||||
working-directory: backend
|
||||
run: |
|
||||
@@ -85,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'
|
||||
@@ -106,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
|
||||
@@ -114,6 +127,52 @@ jobs:
|
||||
if-no-files-found: error
|
||||
path: installer/*
|
||||
|
||||
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
|
||||
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
|
||||
# can name the tag that matches the app it is opened from.
|
||||
server-image:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write # push to ghcr.io
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Resolve version and image name
|
||||
id: meta
|
||||
run: |
|
||||
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
|
||||
# GHCR names must be lower-case; the owner may not be.
|
||||
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
env:
|
||||
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
|
||||
with:
|
||||
context: .
|
||||
file: server/Dockerfile
|
||||
platforms: linux/amd64
|
||||
push: true
|
||||
tags: |
|
||||
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
|
||||
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
|
||||
${{ steps.meta.outputs.image }}:latest
|
||||
labels: |
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
|
||||
|
||||
# Gather both platforms' installers and publish them as a single new Release.
|
||||
# Runs once, after both builds succeed, so the two matrix jobs never race to
|
||||
# create the same tag/release.
|
||||
@@ -122,6 +181,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # required to create the tag + release
|
||||
pull-requests: read # to read the merged PR's patch notes
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -136,14 +196,73 @@ jobs:
|
||||
- name: Download installers from both builds
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
# Only the installers: the run also holds server-image's Docker build
|
||||
# record, which is not a release asset (and once failed to download).
|
||||
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. 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:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \
|
||||
--jq '[.[] | select(.base.ref == "main" and .merged_at != null)][0].body // ""' \
|
||||
> pr-body.md || : > pr-body.md
|
||||
python3 - <<'EOF'
|
||||
import os, re
|
||||
body = open("pr-body.md", encoding="utf-8").read().replace("\r\n", "\n")
|
||||
body = re.sub(r"<!--.*?-->", "", body, flags=re.S)
|
||||
section, level = [], None
|
||||
for line in body.split("\n"):
|
||||
m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line)
|
||||
if level is None:
|
||||
if m and re.fullmatch(r"patch[\s-]?notes:?", m.group(2), re.I):
|
||||
level = len(m.group(1))
|
||||
elif m and len(m.group(1)) <= level:
|
||||
break
|
||||
else:
|
||||
section.append(line)
|
||||
notes = "\n".join(section).strip()
|
||||
found = bool(notes)
|
||||
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.")
|
||||
EOF
|
||||
|
||||
- name: Publish release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
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 }}
|
||||
generate_release_notes: true # auto changelog from commits/PRs since last release
|
||||
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
|
||||
+107
-30
@@ -1,21 +1,27 @@
|
||||
# Building Konduktor for Windows
|
||||
|
||||
The desktop app can't be cross-compiled — a Windows build must be produced **on
|
||||
Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the
|
||||
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
|
||||
The desktop app can't be cross-compiled. A Windows build must be produced **on
|
||||
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
|
||||
freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately
|
||||
on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)).
|
||||
|
||||
This mirrors the macOS build exactly; only the toolchain install and the
|
||||
sidecar-build command differ.
|
||||
The recipe is the same as on macOS. Only the toolchain install and the
|
||||
sidecar-build command differ. CI does exactly this on `windows-latest`
|
||||
([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build
|
||||
disagrees with CI, check that workflow first.
|
||||
|
||||
## One-time setup
|
||||
|
||||
1. **Rust** — install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
|
||||
1. **Rust**: install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
|
||||
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
|
||||
development with C++" from the Visual Studio Build Tools installer.
|
||||
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
|
||||
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
|
||||
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
|
||||
4. **Node 18+** — <https://nodejs.org>.
|
||||
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
|
||||
get the Evergreen runtime from Microsoft (Tauri's installer can also
|
||||
bootstrap it).
|
||||
3. **Python 3.11–3.14**: <https://python.org> (tick "Add to PATH"). CI builds
|
||||
with **3.12**, the safest choice.
|
||||
4. **Node 20.19+ or 22.12+**: <https://nodejs.org>. Vite 8 refuses older
|
||||
versions, so Node 18 no longer works. CI uses Node 20.
|
||||
|
||||
Then, from the repo root:
|
||||
|
||||
@@ -33,49 +39,120 @@ npm install
|
||||
cd ..
|
||||
```
|
||||
|
||||
## Build
|
||||
If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is
|
||||
disabled on this system"), either allow local scripts once with
|
||||
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with
|
||||
`powershell -ExecutionPolicy Bypass -File .\dev.ps1`.
|
||||
|
||||
## Develop (no build)
|
||||
|
||||
```powershell
|
||||
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
|
||||
```
|
||||
|
||||
Then open <http://localhost:5173> in a browser. `dev.ps1` is the Windows
|
||||
counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules`
|
||||
from the setup above. It runs the Python source, not the frozen sidecar, so it
|
||||
can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file
|
||||
drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this
|
||||
still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend
|
||||
changes need `build_sidecar.ps1` first.
|
||||
|
||||
### Tests
|
||||
|
||||
`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't
|
||||
run as-is on Windows. Run a suite directly with the venv's Python instead:
|
||||
|
||||
```powershell
|
||||
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
|
||||
cd backend
|
||||
.\.venv\Scripts\Activate.ps1 # if not already active
|
||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
|
||||
.\.venv\Scripts\python.exe test_save_fidelity.py
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
One command does both steps and lists the installers it produced:
|
||||
|
||||
```powershell
|
||||
.\build.ps1 # sidecar + app
|
||||
.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
|
||||
.\build.ps1 --debug # any other argument is passed on to `tauri build`
|
||||
```
|
||||
|
||||
By hand, that is:
|
||||
|
||||
```powershell
|
||||
# 1) Freeze + stage the backend sidecar
|
||||
cd backend
|
||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
|
||||
cd ..
|
||||
|
||||
# 2) Build the app
|
||||
# 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.
|
||||
|
||||
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
|
||||
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
|
||||
gotcha 4 in [CLAUDE.md](CLAUDE.md).
|
||||
|
||||
## Output
|
||||
|
||||
Installers land in:
|
||||
|
||||
```
|
||||
frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
|
||||
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
|
||||
frontend\src-tauri\target\release\bundle\nsis\Konduktor_<version>_x64-setup.exe
|
||||
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
|
||||
```
|
||||
|
||||
Either one installs the app (bundling the sidecar `.exe` alongside it).
|
||||
`<version>` is the `version` in [frontend/package.json](frontend/package.json),
|
||||
the app's only version source. Either installer works. Releases ship only the
|
||||
NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource
|
||||
folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
|
||||
`sidecar\konduktor-sidecar.exe`.
|
||||
|
||||
## Rebuilding after changes
|
||||
|
||||
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
|
||||
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
|
||||
(its `beforeBuildCommand` rebuilds the web app).
|
||||
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
|
||||
then `npx tauri build` as above). Frontend-only changes just need
|
||||
`.\build.ps1 -SkipSidecar`.
|
||||
|
||||
## Not part of this build: the stem engine
|
||||
|
||||
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
|
||||
released on its own channel by
|
||||
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
|
||||
and `windows-x64-cuda`). The app downloads it at runtime into a short
|
||||
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
|
||||
limit. You don't need it to build or run the app.
|
||||
|
||||
## Known Windows caveats
|
||||
|
||||
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
|
||||
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
|
||||
(Signing is a future step.)
|
||||
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
|
||||
launch shows a "Windows protected your PC" prompt. Click **More info → Run
|
||||
anyway**.
|
||||
- **Mixed content is already handled.** The webview is forced to the `http`
|
||||
custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so
|
||||
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
|
||||
Leave that setting as-is.
|
||||
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
|
||||
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
|
||||
without a visible window; if a console flashes on launch, tell me and we'll add
|
||||
the `CREATE_NO_WINDOW` spawn flag.
|
||||
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
|
||||
- **The sidecar is a console app, but no console appears.** It's frozen with
|
||||
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
|
||||
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
|
||||
flashes.
|
||||
- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its
|
||||
stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS
|
||||
DLL, which hung the first analysis, so it waits on the parent process instead
|
||||
(`backend/sidecar.py`). Keep this in mind before touching that watcher.
|
||||
- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads
|
||||
AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` /
|
||||
`.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg.
|
||||
- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run.
|
||||
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
|
||||
@@ -1,213 +1,141 @@
|
||||
# Konduktor
|
||||
<p align="center">
|
||||
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
|
||||
</p>
|
||||
|
||||
**A fast, modern home for your Traktor collection.**
|
||||
<h1 align="center">Konduktor</h1>
|
||||
|
||||
Konduktor is a lightweight desktop-style app for DJs who run **Native
|
||||
Instruments Traktor** (Pro 4 / NML v20). It opens your existing
|
||||
`collection.nml`, gives you a beautiful dark library to explore, and lets you
|
||||
build playlists and prep tracks — without launching the whole heavyweight
|
||||
Traktor app just to tidy up your tags or drop a few cue points.
|
||||
<p align="center">
|
||||
<b>Prep your tracks and run your DJ libraries in one fast app.</b><br>
|
||||
Traktor, Rekordbox, or the USB stick in your pocket.
|
||||
</p>
|
||||
|
||||
Your collection stays exactly where it is. Konduktor reads and writes the same
|
||||
file Traktor uses, so everything you do shows up next time you open Traktor.
|
||||
<p align="center">
|
||||
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
Konduktor opens the library you already have, in the format it already uses.
|
||||
You can tidy tags, build playlists, set grids and cues, and pack a USB stick
|
||||
for the gig without launching your full DJ software. When you open your DJ
|
||||
software again, everything you changed is there.
|
||||
|
||||
---
|
||||
|
||||
## Why you'll like it
|
||||
## One app for every library
|
||||
|
||||
- **Instant, searchable library.** Your whole collection loads into a snappy,
|
||||
virtualized grid. Search, filter by genre / key / BPM / rating, and sort by
|
||||
any column — all instant, no waiting.
|
||||
- **Make it yours.** Show only the columns you care about, drag them into the
|
||||
order you like, and resize them to fit. Your layout is remembered.
|
||||
- **Edit tags without the ceremony.** Double-click any field to fix a title or
|
||||
genre on the spot, click the stars to rate a track, or right-click for a full
|
||||
tag + cover-art editor. Great for quick one-off fixes.
|
||||
- **Playlists, the easy way.** Create, rename, and delete playlists, then
|
||||
drag-and-drop to reorder or add tracks.
|
||||
- **A real prep deck.** Load any track into the deck at the top and:
|
||||
- play it with a **frequency-colored waveform** (Traktor-style Spectrum look),
|
||||
scrolling under a fixed playhead with zoom in/out
|
||||
- scratch it by dragging the waveform
|
||||
- see and adjust the **beatgrid** and BPM
|
||||
- set, jump to, and delete **hotcues** (with a color-coded 8-slot bar)
|
||||
- build **loops** in fixed beat sizes, tied into the hotcue system
|
||||
- use keyboard shortcuts: **Space** to play/pause, **1–8** to fire hotcues,
|
||||
**Shift+1–8** to clear them
|
||||
- **Your data is safe.** Every save makes a timestamped backup first, and only
|
||||
ever touches the parts you changed — the rest of the file stays byte-for-byte
|
||||
identical.
|
||||
<img src="docs/screenshots/platforms.png" align="right" width="420" alt="Choosing a platform: Rekordbox, Traktor, OneLibrary or Remote">
|
||||
|
||||
- **Traktor** collections.
|
||||
- **Rekordbox** libraries.
|
||||
- **OneLibrary** USB sticks, the format CDJs read. Plug one in to browse it,
|
||||
preview tracks off it, import them, or edit the stick directly.
|
||||
- **Remote** libraries: keep your whole library and music on a home server and
|
||||
open it from any laptop ([set up a server](docs/REMOTE-SERVER.md)).
|
||||
- **Any folder or drive**: browse loose audio files, preview them, and add
|
||||
them to your library.
|
||||
|
||||
Your library is never converted into a Konduktor database. Saves write back to
|
||||
the original file and change only what you edited.
|
||||
|
||||
<br clear="right">
|
||||
|
||||
## A real prep deck
|
||||
|
||||

|
||||
|
||||
- A scrolling waveform, coloured by frequency, with zoom, scratching and an
|
||||
overview of the whole track.
|
||||
- Eight hotcue pads with names, types and colours, plus beat loops, beat jump
|
||||
and tap tempo.
|
||||
- **Beatgrid editing**, including grids with tempo changes. Nudge, retempo,
|
||||
halve or double without opening your DJ software.
|
||||
- Keyboard shortcuts for the whole deck: Space to play, 1–8 for hotcues,
|
||||
arrow keys to jump or move a loop.
|
||||
|
||||
## Stems, built in
|
||||
|
||||

|
||||
|
||||
**Play stem files as stems.** Load a stem file and the deck splits into
|
||||
drums, bass, synths and vocals, each drawn in its own lane. Click a lane's
|
||||
button to mute it, Alt/Option-click to solo it, or use Q W E R.
|
||||
|
||||
**Convert to Stems.** In a Traktor collection, right-click any tracks and
|
||||
choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and
|
||||
beatgrid intact.
|
||||
|
||||
- The separation runs on your own computer, so your music isn't sent to an
|
||||
online service.
|
||||
- Replace the originals, or save the stems to a folder and add them as new
|
||||
tracks.
|
||||
- Convert a whole playlist in one go.
|
||||
|
||||
## Let it do the boring parts
|
||||
|
||||
| Auto Hotcues | Analyze |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. |
|
||||
|
||||
## Export to USB for CDJs, or other platforms
|
||||
|
||||
<img src="docs/screenshots/export.png" align="right" width="380" alt="An export set for OneLibrary, Traktor and Rekordbox">
|
||||
|
||||
Make an **export** in the sidebar, drag playlists onto it, and press Export.
|
||||
One stick can carry a Traktor collection, a OneLibrary library for current
|
||||
CDJs and a Rekordbox Device Library for older players, all sharing **one copy
|
||||
of the audio**.
|
||||
|
||||
- Hotcues, memory cues, loops, grids, keys and cover art are converted for
|
||||
each platform.
|
||||
- Playlists stay linked: edit a playlist, re-export, and the stick catches up.
|
||||
- Re-exports copy only what changed, so updating a stick is quick.
|
||||
- Konduktor only ever clears a folder that it wrote itself.
|
||||
|
||||
<br clear="right">
|
||||
|
||||
## Your library is safe
|
||||
|
||||
- **Saves are surgical.** A Traktor save changes only the entries you edited.
|
||||
The rest of the file stays byte-for-byte identical.
|
||||
- **Backups and history.** Every Traktor save makes a backup first and is kept
|
||||
in a version history that you can restore from in the app.
|
||||
- **Nothing is written until you press Save.** Discard changes throws away
|
||||
everything you did since your last save.
|
||||
- Tag edits are also written into the audio files themselves, so other apps
|
||||
see them too.
|
||||
|
||||
## And also
|
||||
|
||||
- A fast library with search, filters, sorting and columns you can rearrange,
|
||||
even with thousands of tracks.
|
||||
- Edit tags inline or in a full tag and cover-art editor.
|
||||
- Drag and drop tracks onto playlists, exports or the deck, and drag playlists
|
||||
to reorganise them.
|
||||
- If you open a Traktor collection on a different computer or drive,
|
||||
Konduktor finds the missing files for you.
|
||||
|
||||
---
|
||||
|
||||
## Getting started
|
||||
## Get Konduktor
|
||||
|
||||
Konduktor runs as two small local servers (a Python backend and a web
|
||||
frontend). Do the one-time setup, then start them — the same steps work on
|
||||
macOS, Linux, and Windows.
|
||||
Download the latest build from
|
||||
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
|
||||
a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows.
|
||||
|
||||
### 1. Install (once)
|
||||
> **First launch:** builds aren't notarised yet, so your OS will warn you the
|
||||
> first time.
|
||||
> **macOS:** right-click the app, choose **Open**, then **Open** again. If it
|
||||
> still refuses, run `xattr -cr /Applications/Konduktor.app` once.
|
||||
> **Windows:** click **More info → Run anyway**.
|
||||
|
||||
**Backend** — needs Python 3.11+. Create a virtual environment and install the
|
||||
dependencies:
|
||||
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
|
||||
> `collection.nml` when it quits, which would overwrite your changes.
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 -m venv .venv # Windows: python -m venv .venv
|
||||
```
|
||||
Want to run it from source or build it yourself? See
|
||||
[docs/BUILDING.md](docs/BUILDING.md).
|
||||
|
||||
Activate it, then install:
|
||||
## License
|
||||
|
||||
```bash
|
||||
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements.txt
|
||||
cd ..
|
||||
```
|
||||
|
||||
**Frontend** — needs Node 18+ (same on every platform):
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
cd ..
|
||||
```
|
||||
|
||||
### 2. Run it (development)
|
||||
|
||||
Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`).
|
||||
|
||||
**macOS / Linux** — one command starts both:
|
||||
|
||||
```bash
|
||||
./dev.sh
|
||||
```
|
||||
|
||||
**Windows** — start each server in its own terminal:
|
||||
|
||||
```powershell
|
||||
# Terminal 1 — backend
|
||||
cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000
|
||||
|
||||
# Terminal 2 — frontend
|
||||
cd frontend; npm run dev
|
||||
```
|
||||
|
||||
Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a
|
||||
server). This is the fastest way to try Konduktor or hack on it — the frontend
|
||||
hot-reloads as you edit. To package a real double-clickable app instead, see
|
||||
[Build a standalone app](#build-a-standalone-app-production) below.
|
||||
|
||||
### 3. Open your collection
|
||||
|
||||
On launch, Konduktor offers to:
|
||||
|
||||
- **Automatically** open the collection from your latest installed Traktor,
|
||||
- reopen the **last collection** you used, or
|
||||
- **browse** for a `collection.nml` yourself.
|
||||
|
||||
That's it — you're in.
|
||||
|
||||
---
|
||||
|
||||
## Build a standalone app (production)
|
||||
|
||||
Prefer a real double-clickable app over running the dev servers? Konduktor
|
||||
packages into a native desktop app (via **Tauri**) that bundles the Python
|
||||
backend as a sidecar — no terminal, no servers to start by hand.
|
||||
|
||||
### Extra prerequisites
|
||||
|
||||
On top of the Python 3.11+ and Node 18+ from above:
|
||||
|
||||
- **Rust** — install from <https://rustup.rs> (the app shell is Tauri/Rust).
|
||||
- **PyInstaller** — into the backend venv:
|
||||
`pip install -r backend/requirements-build.txt`
|
||||
- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see
|
||||
[BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup.
|
||||
|
||||
The build is a two-step recipe on both platforms: **freeze the backend into a
|
||||
sidecar binary**, then **build the app**. The only difference is which sidecar
|
||||
script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its
|
||||
own OS (the app can't be cross-compiled).
|
||||
|
||||
### macOS / Linux
|
||||
|
||||
```bash
|
||||
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
|
||||
cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd ..
|
||||
|
||||
# 2) Build the app
|
||||
cd frontend && npx tauri build
|
||||
```
|
||||
|
||||
The installer lands at
|
||||
`frontend/src-tauri/target/release/bundle/dmg/Konduktor_<version>_aarch64.dmg`
|
||||
(with the `.app` beside it).
|
||||
|
||||
### Windows
|
||||
|
||||
```powershell
|
||||
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
|
||||
cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd ..
|
||||
|
||||
# 2) Build the app
|
||||
cd frontend; npx tauri build
|
||||
```
|
||||
|
||||
The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and
|
||||
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
|
||||
walkthrough and Windows-specific notes.
|
||||
|
||||
> **First launch — getting past the OS security prompt.** Builds are
|
||||
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
|
||||
> the OS flags them the first time. This is expected — the app isn't damaged.
|
||||
>
|
||||
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
|
||||
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
|
||||
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
|
||||
> quarantines — clear the quarantine flag once from Terminal:
|
||||
> ```bash
|
||||
> xattr -cr /Applications/Konduktor.app
|
||||
> ```
|
||||
> - **Windows:** click **More info → Run anyway** past SmartScreen.
|
||||
>
|
||||
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
|
||||
|
||||
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
|
||||
> optimizer and the installer, giving you a runnable app in seconds — handy while
|
||||
> iterating.
|
||||
|
||||
### Rebuilding after changes
|
||||
|
||||
Changed **backend** Python? Re-run the sidecar script for your OS
|
||||
(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`.
|
||||
Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you.
|
||||
|
||||
---
|
||||
|
||||
## Saving back to Traktor
|
||||
|
||||
Playlist edits, tag changes, and prep tweaks all apply live in the app. When
|
||||
you're happy, hit **Save to Traktor** to write them to `collection.nml`.
|
||||
|
||||
> ⚠️ **Close Traktor before saving.** Traktor rewrites `collection.nml` when it
|
||||
> quits, so if it's open it will overwrite your changes. Konduktor always writes
|
||||
> a backup first (into a `backups/` folder next to your collection), but closing
|
||||
> Traktor first is the safe habit.
|
||||
|
||||
Want to experiment risk-free? Point Konduktor at a *copy* of your collection and
|
||||
play around.
|
||||
|
||||
---
|
||||
|
||||
## Good to know
|
||||
|
||||
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
|
||||
and speaks Traktor's real file format — no import/export, no separate database.
|
||||
- Run it in your browser from source, or package it into a native desktop app
|
||||
(macOS `.dmg` / Windows `.msi`) that bundles the backend — see
|
||||
[Build a standalone app](#build-a-standalone-app-production). A mobile version
|
||||
is on the horizon.
|
||||
- Under the hood: **FastAPI** (Python) backend + **React / TypeScript / Vite**
|
||||
frontend. Curious about internals or contributing? See
|
||||
[CLAUDE.md](CLAUDE.md) for the architecture and conventions.
|
||||
[AGPL-3.0](LICENSE)
|
||||
@@ -6,6 +6,8 @@ compare rather than a pass/fail. Every open is read-only — nothing is saved.
|
||||
python bench_grid_detect.py # the local Rekordbox library
|
||||
python bench_grid_detect.py path/to/collection.nml path/to/master.db
|
||||
python bench_grid_detect.py --legacy # score the old librosa beat_track
|
||||
python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM
|
||||
python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor
|
||||
|
||||
The reference is each track's own grid, and only single-marker grids are used:
|
||||
a multi-marker grid is either a real tempo change (which a constant-tempo
|
||||
@@ -102,6 +104,9 @@ def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("libraries", nargs="*", type=Path)
|
||||
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
|
||||
ap.add_argument("--hold", choices=("bpm", "anchor"),
|
||||
help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's "
|
||||
"'Grid' tick — phase is all that is scored) or its anchor ('BPM')")
|
||||
args = ap.parse_args()
|
||||
|
||||
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
|
||||
@@ -119,7 +124,8 @@ def main() -> int:
|
||||
for name, audio, r0, rb in refs:
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
res = detect(str(audio))
|
||||
hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
|
||||
res = detect(str(audio), **hold)
|
||||
except Exception as ex: # a failure is a data point, not a crash
|
||||
print(f" FAIL {name[:48]:48} {ex}")
|
||||
rows.append(None)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Benchmark key detection (`core/key_detect.py`).
|
||||
|
||||
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
|
||||
compare rather than a pass/fail.
|
||||
|
||||
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
|
||||
python bench_key_detect.py ~/Music # files with a key TAG
|
||||
|
||||
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
|
||||
and the number to quote; the model never trained on it (see
|
||||
`train_key_model.py`). A folder's key tags were written by some other
|
||||
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
|
||||
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
|
||||
source) count once, by title.
|
||||
|
||||
Errors are classed the MIREX way, because they are not equally wrong for a
|
||||
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
|
||||
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
|
||||
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import warnings
|
||||
from collections import Counter
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from konduktor.core import key_detect, musical_key # noqa: E402
|
||||
|
||||
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
|
||||
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
|
||||
|
||||
|
||||
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
|
||||
"""How a detected (wheel, mode) relates to the reference."""
|
||||
(dw, dm), (rw, rm) = det, ref
|
||||
if (dw, dm) == (rw, rm):
|
||||
return "exact"
|
||||
if dw == rw:
|
||||
return "relative"
|
||||
if dm == rm and (dw - rw) % 12 in (1, 11):
|
||||
return "fifth"
|
||||
if dm != rm:
|
||||
major, minor = (dw, rw) if dm == "major" else (rw, dw)
|
||||
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
|
||||
return "parallel"
|
||||
return "other"
|
||||
|
||||
|
||||
def parse_any(text: str) -> tuple[int, str] | None:
|
||||
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
|
||||
w, m = musical_key.parse(text)
|
||||
return (w, m) if w else None
|
||||
|
||||
|
||||
def _tag_key(path: Path) -> tuple[str, str] | None:
|
||||
import mutagen
|
||||
|
||||
try:
|
||||
f = mutagen.File(path)
|
||||
except Exception:
|
||||
return None
|
||||
if not f or not f.tags:
|
||||
return None
|
||||
t = f.tags
|
||||
|
||||
def has(name: str) -> bool:
|
||||
try:
|
||||
return name in t
|
||||
except ValueError: # a Vorbis comment refuses an MP4-style atom name
|
||||
return False
|
||||
|
||||
key = title = None
|
||||
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
|
||||
if has(name):
|
||||
v = t[name]
|
||||
v = v.text[0] if hasattr(v, "text") else v[0]
|
||||
key = v.decode() if isinstance(v, bytes) else str(v)
|
||||
break
|
||||
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
|
||||
if has(name):
|
||||
v = t[name]
|
||||
title = str(v.text[0] if hasattr(v, "text") else v[0])
|
||||
break
|
||||
return (key, title or path.stem) if key else None
|
||||
|
||||
|
||||
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
seen, out = set(), []
|
||||
for root in roots:
|
||||
for dp, dirs, files in os.walk(root):
|
||||
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
|
||||
for name in sorted(files):
|
||||
p = Path(dp) / name
|
||||
if p.suffix.lower() not in AUDIO or name.startswith("."):
|
||||
continue
|
||||
tagged = _tag_key(p)
|
||||
if not tagged or not (ref := parse_any(tagged[0])):
|
||||
continue
|
||||
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
|
||||
if title not in seen:
|
||||
seen.add(title)
|
||||
out.append((p, ref, tagged[1]))
|
||||
return out
|
||||
|
||||
|
||||
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
out = []
|
||||
for f in sorted((gs / "annotations/key").glob("*.key")):
|
||||
audio = gs / "audio" / f"{f.stem}.mp3"
|
||||
ref = parse_any(f.read_text()) # "C minor"
|
||||
if audio.exists() and ref:
|
||||
out.append((audio, ref, f.stem))
|
||||
return out
|
||||
|
||||
|
||||
def _detect(path: Path):
|
||||
warnings.filterwarnings("ignore")
|
||||
try:
|
||||
r = key_detect.detect_key(str(path))
|
||||
except Exception as ex: # an undecodable file is reported, not fatal
|
||||
return None, str(ex)
|
||||
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
|
||||
|
||||
|
||||
def run(refs, label: str, verbose: bool) -> None:
|
||||
with ProcessPoolExecutor() as ex:
|
||||
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
|
||||
rels, misses = [], []
|
||||
for (path, ref, title), (det, err) in zip(refs, results):
|
||||
if det is None:
|
||||
print(f" could not analyse {title}: {err or 'silent / too short'}")
|
||||
continue
|
||||
rel = relation(det[:2], ref)
|
||||
rels.append(rel)
|
||||
if rel != "exact":
|
||||
misses.append((title, ref, det, rel))
|
||||
n = len(rels)
|
||||
if not n:
|
||||
print(f"{label}: nothing to score")
|
||||
return
|
||||
c = Counter(rels)
|
||||
print(f"\n{label}: {n} tracks")
|
||||
for k in WEIGHT:
|
||||
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
|
||||
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
|
||||
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
|
||||
if verbose:
|
||||
for title, ref, det, rel in misses:
|
||||
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
|
||||
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
|
||||
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
|
||||
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
|
||||
a = ap.parse_args()
|
||||
if not a.folders and not a.giantsteps:
|
||||
ap.error("give --giantsteps and/or folders")
|
||||
if a.giantsteps:
|
||||
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
|
||||
if a.folders:
|
||||
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
|
||||
sys.exit(0)
|
||||
@@ -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()
|
||||
+17
-10
@@ -1,6 +1,7 @@
|
||||
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
|
||||
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
|
||||
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
|
||||
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
|
||||
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
|
||||
# tauri.conf.json bundles as a resource folder (`sidecar\` in the app).
|
||||
# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\
|
||||
#
|
||||
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
|
||||
# cd backend
|
||||
@@ -15,13 +16,19 @@ Set-Location $Root
|
||||
$Py = Join-Path $Root ".venv\Scripts\python.exe"
|
||||
if (-not (Test-Path $Py)) { $Py = "python" }
|
||||
|
||||
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
|
||||
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
|
||||
# native command's stderr into an error record, which "Stop" makes fatal on the
|
||||
# first INFO line — so relax it for this call and judge by the exit code.
|
||||
$ErrorActionPreference = "Continue"
|
||||
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
|
||||
Write-Host "Built: $Root\dist\konduktor-sidecar\"
|
||||
|
||||
# Stage for Tauri: name with the host target triple + .exe so the shell plugin
|
||||
# resolves it. (rustc must be on PATH.)
|
||||
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
|
||||
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
|
||||
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
|
||||
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
|
||||
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
|
||||
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
|
||||
$Staged = Join-Path $Dest "konduktor-sidecar"
|
||||
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
|
||||
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
|
||||
Write-Host "Staged: $Staged\"
|
||||
+19
-23
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the frozen backend sidecar (single-file binary) with PyInstaller and
|
||||
# stage it for Tauri as binaries/konduktor-sidecar-<target-triple>.
|
||||
# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/…
|
||||
# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage
|
||||
# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which
|
||||
# tauri.conf.json bundles as a resource folder (`sidecar/` in the app).
|
||||
# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/
|
||||
#
|
||||
# One-time: pip install -r requirements-build.txt (into the backend venv).
|
||||
set -euo pipefail
|
||||
@@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
cd "$ROOT"
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
echo "Built: $ROOT/dist/konduktor-sidecar"
|
||||
echo "Built: $ROOT/dist/konduktor-sidecar/"
|
||||
|
||||
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
|
||||
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
|
||||
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
|
||||
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
|
||||
# fails with "different Team IDs" and the sidecar dies on launch (which makes
|
||||
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
|
||||
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||
# which seals this binary without re-signing it.
|
||||
# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc
|
||||
# signs the executable AND its collected libraries (Python, the .so/.dylib
|
||||
# files) with a matching identity. Re-signing only some of them desyncs the
|
||||
# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on
|
||||
# launch (the app then shows "Konduktor couldn't start"). The app bundle is
|
||||
# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||
# which seals this folder as a resource without re-signing it.
|
||||
|
||||
# Stage for Tauri: the sidecar must be named with the host target triple so the
|
||||
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
|
||||
if command -v rustc >/dev/null 2>&1; then
|
||||
TRIPLE="$(rustc -vV | sed -n 's/host: //p')"
|
||||
DEST="$ROOT/../frontend/src-tauri/binaries"
|
||||
mkdir -p "$DEST"
|
||||
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE"
|
||||
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
|
||||
else
|
||||
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
|
||||
fi
|
||||
# Stage for Tauri. Replace the whole folder so no file from an older build
|
||||
# survives; `cp -R` keeps PyInstaller's symlinks as symlinks.
|
||||
DEST="$ROOT/../frontend/src-tauri/binaries"
|
||||
mkdir -p "$DEST"
|
||||
rm -rf "$DEST/konduktor-sidecar"
|
||||
cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
|
||||
echo "Staged: $DEST/konduktor-sidecar/"
|
||||
@@ -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"]()
|
||||
@@ -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:])
|
||||
@@ -0,0 +1,38 @@
|
||||
# Memory-cue edits rekordbox 7 made on a stick
|
||||
|
||||
Analysis files of six tracks on a OneLibrary test stick written by
|
||||
rekordbox, before and after **rekordbox 7 itself** edited their MEMORY cues
|
||||
(kit M2, 2026-10-16; the stick was backed up first and restored afterwards).
|
||||
`test_onelibrary_anlz.py` replays each edit with Konduktor's helpers on
|
||||
`before/` and compares the memory lists with `after/` byte for byte.
|
||||
|
||||
Only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for byte — the
|
||||
waveforms were dropped, as in `onelibrary-goober/`. There is no database and
|
||||
no audio: `exportLibrary.db` and both pdbs had NO row change for any of these
|
||||
edits (memory cues on a stick live only in the analysis files).
|
||||
|
||||
| File | Track | Edit (one per track) |
|
||||
|---|---|---|
|
||||
| `black-bloc` | Justin Hawkes – Black Bloc (VIP) | memory cue ADDED at 2:11.206 |
|
||||
| `formula` | RL Grime & Juelz – Formula (IMANU Remix) | 4-beat memory LOOP added at 1:20.378 |
|
||||
| `lift-it` | Tian – Lift It (Hexa Remix) | 8 memory cues added (2 → 10, the cap) |
|
||||
| `wtf` | Result – WTF (Phace Remix) | the memory loop at 1:53 recoloured Blue |
|
||||
| `sell-my-soul` | Bensley, Justin Hawkes & Kumarion – Sell My Soul | comment "Loopy" on the memory loop at 1:18 |
|
||||
| `doomed` | Nemean – Doomed | the memory loop at 2:01 DELETED |
|
||||
|
||||
What they show (the full write-up is in
|
||||
`.claude/discussions/discuss-memory-cues-2026-10-16.md`, kit M2):
|
||||
- `.DAT` `PCOB` memory list: a new entry is PREPENDED; every entry has status 0
|
||||
and bytes 24–27 = previous / next index in the list (`ffff` at the ends), so
|
||||
any add or delete relinks the whole list; the header i32 at offset 20 is
|
||||
count − 1.
|
||||
- `.EXT` `PCO2` memory list: a new entry is APPENDED in rekordbox's compact
|
||||
44-byte form; the others stay byte-identical. The `.EXT`'s `PCOB` memory list
|
||||
stays empty.
|
||||
- When rekordbox rewrites a `.DAT` (any memory add or delete), it ALSO
|
||||
re-sorts the untouched hot-cue `PCOB` into ascending pad order (an export
|
||||
writes it highest pad first); the entries themselves are unchanged.
|
||||
Konduktor changes only the list it edits, so the test compares that tag's
|
||||
entries regardless of order.
|
||||
- Colour: `PCP2` byte 28, 1-based (Blue = 7), 0 = none. Comment: UTF-16BE + NUL
|
||||
at byte 44, `len_comment` at 40. Neither touches the `.DAT`.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,6 +1,14 @@
|
||||
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
|
||||
# build). Produces a single-file binary that serves the FastAPI API on a free
|
||||
# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
|
||||
# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the
|
||||
# executable plus `_internal/` — that serves the FastAPI API on a free loopback
|
||||
# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
|
||||
#
|
||||
# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390
|
||||
# native libraries) into a NEW temp folder on every launch, and macOS checks
|
||||
# every library it has not seen before (XProtect / syspolicyd) as it is
|
||||
# dlopen()ed, keyed per file — so every launch paid ~10 s before the window
|
||||
# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once
|
||||
# seen). Installed as a folder inside the app, they are checked once.
|
||||
#
|
||||
# The tricky bits this handles:
|
||||
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
|
||||
@@ -10,7 +18,7 @@
|
||||
# - python-multipart is imported as `multipart` by starlette → hidden import
|
||||
# - dulwich (version-history backups) imports git backends dynamically →
|
||||
# collect_submodules('dulwich')
|
||||
from PyInstaller.utils.hooks import collect_submodules, collect_all
|
||||
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
|
||||
|
||||
hiddenimports = []
|
||||
datas = []
|
||||
@@ -31,6 +39,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"):
|
||||
# Imported by name, not statically discoverable.
|
||||
hiddenimports += ["multipart", "anyio"]
|
||||
|
||||
# A remote library's password lives in the OS keychain through `keyring`, which
|
||||
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
|
||||
# — so both the modules AND the package metadata that names them must ship.
|
||||
hiddenimports += collect_submodules("keyring")
|
||||
datas += copy_metadata("keyring")
|
||||
|
||||
# Bundle the canonical version file so konduktor.__version__ can read it at
|
||||
# runtime from sys._MEIPASS (frontend/package.json is the single source of the
|
||||
# app version — see konduktor/__init__.py). Path is relative to this spec.
|
||||
@@ -54,6 +68,8 @@ datas += [
|
||||
("konduktor/stems/engine.json", "konduktor/stems"),
|
||||
("konduktor/stems/weights.json", "konduktor/stems"),
|
||||
]
|
||||
# The key-detection network's weights (konduktor/core/key_detect.py).
|
||||
datas += [("konduktor/core/key_model.npz", "konduktor/core")]
|
||||
|
||||
a = Analysis(
|
||||
["sidecar.py"],
|
||||
@@ -74,9 +90,8 @@ pyz = PYZ(a.pure)
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name="konduktor-sidecar",
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
@@ -89,3 +104,12 @@ exe = EXE(
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
name="konduktor-sidecar",
|
||||
)
|
||||
@@ -21,12 +21,12 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import InvalidCommand, Unsupported
|
||||
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox import memory_palette, palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
from ...exporter import MANIFEST_NAME
|
||||
from . import capabilities as caps
|
||||
@@ -193,6 +193,7 @@ class OneLibraryAdapter:
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
||||
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
||||
@@ -223,6 +224,9 @@ class OneLibraryAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Ignored: a drive's paths are relative to wherever it is mounted.
|
||||
|
||||
@@ -312,7 +316,7 @@ class OneLibraryAdapter:
|
||||
`audio_path` is where `place_audio` said to copy it (or the file itself,
|
||||
already on the stick); Save moves copies into place.
|
||||
"""
|
||||
from ...core import audio_tags, grid_detect, waveform
|
||||
from ...core import audio_tags, grid_detect, key_detect, waveform
|
||||
from ...core.export import ExportTrack
|
||||
from ..rekordbox import artwork, timebase
|
||||
from .export import OneLibraryExporter
|
||||
@@ -348,21 +352,23 @@ class OneLibraryAdapter:
|
||||
taken.add(cue.slot)
|
||||
else:
|
||||
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
|
||||
export_track = ExportTrack(track=item.track, destination=audio,
|
||||
# A file with no key of its own gets one, as it gets a grid.
|
||||
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
|
||||
export_track = ExportTrack(track=track, destination=audio,
|
||||
cues=TrackCues(grid_markers=markers, cues=memory))
|
||||
# Decoded once above; the writer must not decode it again.
|
||||
export_track.waveform = lambda *, lead=0.0, m=measured: m
|
||||
art = item.art or audio_tags.read_cover(audio)
|
||||
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
|
||||
length = item.track.length or (int(measured.duration) if measured else None)
|
||||
prepared.append((item, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
|
||||
length = track.length or (int(measured.duration) if measured else None)
|
||||
prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
|
||||
markers, hot, length))
|
||||
|
||||
added: list[str] = []
|
||||
for item, audio, rel, anlz, jpegs, markers, hot, length in prepared:
|
||||
for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
|
||||
track_id = self._store.add_track(
|
||||
audio, item.track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
|
||||
jpegs=jpegs, bpm=markers[0].bpm if markers else item.track.bpm, length=length)
|
||||
audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
|
||||
jpegs=jpegs, bpm=markers[0].bpm if markers else track.bpm, length=length)
|
||||
for cue in hot:
|
||||
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
|
||||
cue_type="loop" if cue.length else "cue",
|
||||
@@ -392,6 +398,37 @@ class OneLibraryAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
self._require_writable("Setting the key")
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
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")
|
||||
|
||||
@@ -414,6 +451,10 @@ class OneLibraryAdapter:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
@@ -441,10 +482,8 @@ class OneLibraryAdapter:
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
# A memory cue has no slot to set; it has its own commands.
|
||||
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||
length_sec=length_sec, name=name)
|
||||
@@ -478,6 +517,53 @@ class OneLibraryAdapter:
|
||||
self._store.place_cues(track_id, cues, overwrite=overwrite)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- commands: memory cues --------------------------------------------
|
||||
@staticmethod
|
||||
def _memory_byte(color: str | None) -> int:
|
||||
if color is None:
|
||||
return 0
|
||||
code = memory_palette.code_for(color)
|
||||
if code is None:
|
||||
raise InvalidCommand(f"{color!r} is not one of rekordbox's memory cue colours")
|
||||
return memory_palette.anlz_byte(code)
|
||||
|
||||
def add_memory_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color: str | None = None,
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.add_memory_cue(track_id, start_sec=start_sec, cue_type=cue_type,
|
||||
length_sec=length_sec, name=name,
|
||||
color_id=self._memory_byte(color))
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._store.rename_memory_cue(track_id, cue_id, name)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
|
||||
# rekordbox has one point type, so there is nothing to choose; a memory
|
||||
# cue is a cue or a loop by its length.
|
||||
raise Unsupported("rekordbox memory cues have no type to change")
|
||||
|
||||
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._store.set_memory_cue_color(track_id, cue_id, self._memory_byte(color))
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_memory_cue(track_id, cue_id)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- commands: beatgrid -----------------------------------------------
|
||||
@staticmethod
|
||||
def _markers_from(markers: list) -> list:
|
||||
@@ -522,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,8 +36,8 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
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,
|
||||
# so the bank really is 1..8 (see `cues.py`).
|
||||
@@ -61,10 +61,12 @@ def capabilities_for(
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# OneLibrary carries memory cues, as Rekordbox does: projected and
|
||||
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
|
||||
# Memory cues, editable as in Rekordbox — in the ANLZ files, the
|
||||
# way rekordbox 7 edits them on a stick (measured, kit M2).
|
||||
memory_cues=True,
|
||||
max_memory_cues=None,
|
||||
max_memory_cues=MAX_MEMORY_CUES,
|
||||
memory_color="palette",
|
||||
memory_palette=list(memory_palette.SWATCHES),
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
color="palette",
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
@@ -84,6 +86,12 @@ def capabilities_for(
|
||||
# with it, at Save — so the library, not the user, places the audio.
|
||||
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
|
||||
|
||||
@@ -37,7 +37,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from ...core.model import CuePoint
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox import memory_palette, palette
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -112,6 +112,13 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
|
||||
slot = None if role == "memory" else hot_cue - 1
|
||||
|
||||
comment = getattr(entry, "comment", None)
|
||||
if role == "memory":
|
||||
# A memory cue's colour is byte 28 (`memory_palette`), not the hot-cue
|
||||
# code + RGB tail, which stays zero on one.
|
||||
color = (memory_palette.hex_for(memory_palette.from_anlz_byte(
|
||||
int(getattr(entry, "color_id", 0) or 0))) if with_color else None)
|
||||
else:
|
||||
color = _color(entry) if with_color else None
|
||||
return CuePoint(
|
||||
name=(str(comment) or None) if comment else None,
|
||||
type="loop" if length > 0 else "cue",
|
||||
@@ -119,16 +126,26 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
|
||||
start=start_ms / 1000.0,
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_color(entry) if with_color else None,
|
||||
# Hot cues are editable on a drive opened for editing (the caller says
|
||||
# so). MEMORY cues never are — preserved-but-uneditable, as in the
|
||||
# Rekordbox adapter (the two-platform rule).
|
||||
editable=editable and role == "hotcue",
|
||||
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
|
||||
color=color,
|
||||
# Editable on a drive opened for editing (the caller says so), memory
|
||||
# cues included; browsing a device is read-only.
|
||||
editable=editable,
|
||||
readonly_reason=None if editable else "platform_managed",
|
||||
grid_marker=None,
|
||||
id=memory_cue_id(entry) if role == "memory" else None,
|
||||
)
|
||||
|
||||
|
||||
def memory_cue_id(entry) -> str:
|
||||
"""A memory cue's `CuePoint.id`: its STORED position, kind and loop end.
|
||||
|
||||
Content-derived, so it is the same on every read and in both lists (`PCOB`
|
||||
in the .DAT, `PCO2` in the .EXT, which order the same cues differently);
|
||||
an index would not be. Two memory cues identical in all three are one cue
|
||||
to `_dedupe` already, so the first match is the one meant."""
|
||||
return f"m:{int(entry.time)}:{_entry_kind(getattr(entry, 'type', ENTRY_CUE))}:{int(getattr(entry, 'loop_time', NO_LOOP))}"
|
||||
|
||||
|
||||
def _entries(anlz, tag_type: str) -> list:
|
||||
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
|
||||
|
||||
|
||||
@@ -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 ""}
|
||||
|
||||
@@ -49,7 +49,7 @@ class OneLibraryDriver:
|
||||
def _has_onelibrary_schema(path: Path) -> bool:
|
||||
try:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.onelibrary.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
except ImportError: # pragma: no cover — dependency missing
|
||||
return False
|
||||
|
||||
@@ -44,7 +44,8 @@ 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, 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
|
||||
from .capabilities import capabilities_for
|
||||
@@ -121,7 +122,7 @@ class OneLibraryExporter:
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
import sqlcipher3.dbapi2 as sqlcipher
|
||||
from pyrekordbox.devicelib_plus.database import BLOB
|
||||
from pyrekordbox.onelibrary.database import BLOB
|
||||
from pyrekordbox.utils import deobfuscate
|
||||
|
||||
root = Path(destination)
|
||||
@@ -208,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,
|
||||
@@ -228,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,
|
||||
@@ -359,15 +361,29 @@ class OneLibraryExporter:
|
||||
too far along.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
for cue in (item.cues.cues if item.cues else []):
|
||||
memory = 0
|
||||
for cue in sorted(item.cues.cues if item.cues else [], key=lambda c: c.start):
|
||||
is_loop = cue.type == "loop" or cue.length > 0
|
||||
# A hot cue carries what Konduktor SHOWS — stored colour, else the
|
||||
# type's (blue cue, green loop) — as a rekordbox palette CODE, which
|
||||
# is what rekordbox draws from; "unset" draws its own defaults. A
|
||||
# memory cue keeps rekordbox's own "unset".
|
||||
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue))
|
||||
is_memory = cue.role == "memory" or cue.slot is None
|
||||
if is_memory:
|
||||
# rekordbox keeps 10 (earliest first; the rest are dropped, per
|
||||
# the lossiness rule). A memory cue's colour is PCP2 byte 28 from
|
||||
# its own 8-colour palette — what Konduktor SHOWS (stored, else
|
||||
# the type's), as for a hot cue; the hot-cue code + RGB stay zero.
|
||||
if memory >= MAX_MEMORY_CUES:
|
||||
continue
|
||||
memory += 1
|
||||
code, rgb = 0, (0, 0, 0)
|
||||
color_id = memory_palette.anlz_byte(memory_palette.nearest_code(effective_color(cue)))
|
||||
else:
|
||||
# What Konduktor SHOWS — stored colour, else the type's (blue cue,
|
||||
# green loop) — as a rekordbox palette CODE, which is what
|
||||
# rekordbox draws from; "unset" draws its own defaults.
|
||||
code, rgb = palette.code_for(effective_color(cue))
|
||||
color_id = 0
|
||||
out.append({
|
||||
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1,
|
||||
"color_id": color_id,
|
||||
"hot_cue": 0 if is_memory else cue.slot + 1,
|
||||
"kind": 2 if is_loop else 1,
|
||||
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
|
||||
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
|
||||
@@ -381,7 +397,8 @@ class OneLibraryExporter:
|
||||
# ---- playlists -----------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
|
||||
"""One folder named after the export, with the tree preserved under it.
|
||||
"""The tree preserved — at the top level (parent NULL), or with
|
||||
`payload.root_folder` under one folder named after the export.
|
||||
|
||||
`playlist` is a flat table with `playlist_id_parent`, so folders and
|
||||
playlists are the same row kind told apart by `attribute` (1 = folder).
|
||||
@@ -397,8 +414,8 @@ class OneLibraryExporter:
|
||||
)
|
||||
return next_id[0]
|
||||
|
||||
root = add(payload.name, None, folder=True)
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
root = add(payload.name, None, folder=True) if payload.root_folder else None
|
||||
folders: dict[tuple[str, ...], int | None] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
@@ -427,8 +444,10 @@ class OneLibraryExporter:
|
||||
)
|
||||
|
||||
|
||||
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
|
||||
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
|
||||
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
|
||||
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
|
||||
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
|
||||
#: both still write 4.
|
||||
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
|
||||
".aif": 12, ".aiff": 12}
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Memory-cue edits on a track's two analysis files, the way rekordbox 7 makes them.
|
||||
|
||||
Pure functions over parsed `AnlzFile`s, so they are pinned byte for byte
|
||||
against rekordbox's own edits (`fixtures/onelibrary-memory-edits`, kit M2,
|
||||
2026-10-16) without a drive; the store adds the drive, the time base and Save.
|
||||
|
||||
A stick keeps memory cues ONLY in the analysis files — the database and both
|
||||
pdbs keep every row — in two lists kept in OPPOSITE orders:
|
||||
|
||||
* `.DAT` `PCOB` memory: a new cue is PREPENDED, and the whole list is
|
||||
relinked (`anlz_writer.relinked_memory_pcpts`: status 0, prev/next
|
||||
indexes) on any add or delete; header field = count − 1.
|
||||
* `.EXT` `PCO2` memory: a new cue is APPENDED in the compact 44-byte form;
|
||||
every other entry keeps its bytes. The `.EXT`'s own `PCOB` memory list
|
||||
stays empty.
|
||||
|
||||
A colour is `PCP2` byte 28 and a name the `PCP2` comment; neither touches the
|
||||
`.DAT`. A cue is addressed by `cues.memory_cue_id` (stored time, kind, loop
|
||||
end), which is the same in both lists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ..rekordbox import anlz_file
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from .cues import memory_cue_id
|
||||
|
||||
DAT_ORDER = ("PPTH", "PVBR", "PQTZ", "PWAV", "PWV2", "PCOB")
|
||||
EXT_ORDER = ("PPTH", "PWV3", "PCOB", "PCO2")
|
||||
|
||||
|
||||
def entries(f: anlz_file.AnlzFile, kind: str) -> list[bytes]:
|
||||
"""The raw entries of a file's `kind` (PCOB / PCO2) MEMORY list."""
|
||||
i = f.find(kind, anlz_file.LIST_MEMORY)
|
||||
return anlz_file.raw_entries(f.tags[i]) if i is not None else []
|
||||
|
||||
|
||||
def count(ext: anlz_file.AnlzFile) -> int:
|
||||
return len(entries(ext, "PCO2"))
|
||||
|
||||
|
||||
def _matches(entry: bytes, cue_id: str) -> bool:
|
||||
return memory_cue_id(anlz_file.decode_entry(entry)) == cue_id
|
||||
|
||||
|
||||
def _put(dat, ext, pcob: list[bytes] | None, pco2: list[bytes] | None) -> None:
|
||||
if pcob is not None:
|
||||
dat.put("PCOB", W.pcob_tag(anlz_file.LIST_MEMORY, W.relinked_memory_pcpts(pcob)),
|
||||
list_kind=anlz_file.LIST_MEMORY, after=DAT_ORDER)
|
||||
if pco2 is not None:
|
||||
ext.put("PCO2", W.pco2_tag(anlz_file.LIST_MEMORY, pco2),
|
||||
list_kind=anlz_file.LIST_MEMORY, after=EXT_ORDER)
|
||||
|
||||
|
||||
def add(dat, ext, *, kind: int, time_ms: int, loop_ms: int | None, beats: int | None,
|
||||
name: str | None = None, color_id: int = 0) -> None:
|
||||
"""Add one memory cue (kind 1 cue, 2 loop): prepended to the `.DAT`'s list,
|
||||
appended — compact unless named — to the `.EXT`'s."""
|
||||
pcp2 = W.pcp2_compact_entry(kind=kind, time_ms=time_ms, loop_ms=loop_ms,
|
||||
beats=beats, color_id=color_id)
|
||||
if name:
|
||||
pcp2 = anlz_file.entry_with_comment(pcp2, name)
|
||||
pcpt = W.pcpt_entry(hot_cue=0, kind=kind, time_ms=time_ms, loop_ms=loop_ms)
|
||||
_put(dat, ext, [pcpt] + entries(dat, "PCOB"), entries(ext, "PCO2") + [pcp2])
|
||||
|
||||
|
||||
def _index(ext, cue_id: str) -> tuple[list[bytes], int | None]:
|
||||
pco2 = entries(ext, "PCO2")
|
||||
return pco2, next((n for n, e in enumerate(pco2) if _matches(e, cue_id)), None)
|
||||
|
||||
|
||||
def rename(ext, cue_id: str, name: str | None) -> bool:
|
||||
"""Rename in the `.EXT` only; False if no such cue."""
|
||||
pco2, i = _index(ext, cue_id)
|
||||
if i is None:
|
||||
return False
|
||||
pco2[i] = anlz_file.entry_with_comment(pco2[i], name)
|
||||
_put(None, ext, None, pco2)
|
||||
return True
|
||||
|
||||
|
||||
def recolour(ext, cue_id: str, color_id: int) -> bool:
|
||||
"""Byte 28 of the cue's `PCP2` entry, nothing else; False if no such cue."""
|
||||
pco2, i = _index(ext, cue_id)
|
||||
if i is None:
|
||||
return False
|
||||
pco2[i] = anlz_file.entry_with_color_id(pco2[i], color_id)
|
||||
_put(None, ext, None, pco2)
|
||||
return True
|
||||
|
||||
|
||||
def delete(dat, ext, cue_id: str) -> bool:
|
||||
"""Out of both lists (the `.DAT`'s relinked); False if no such cue."""
|
||||
pco2, i = _index(ext, cue_id)
|
||||
if i is None:
|
||||
return False
|
||||
del pco2[i]
|
||||
pcob = entries(dat, "PCOB")
|
||||
j = next((n for n, e in enumerate(pcob) if _matches(e, cue_id)), None)
|
||||
if j is not None:
|
||||
del pcob[j]
|
||||
_put(dat, ext, pcob if j is not None else None, pco2)
|
||||
return True
|
||||
@@ -1,6 +1,6 @@
|
||||
"""OneLibrary rows -> the generic projection.
|
||||
|
||||
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
|
||||
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
|
||||
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||
|
||||
Field conventions are read off a real rekordbox 7 export rather than guessed:
|
||||
@@ -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)),
|
||||
)
|
||||
|
||||
|
||||
@@ -114,7 +117,7 @@ def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
|
||||
|
||||
`cues` are already generic — see `store.cues` for why that boundary sits
|
||||
where it does — so this is the assembly point rather than a translation.
|
||||
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
|
||||
`capabilities.writable` says so at the library level.
|
||||
Each cue already says whether it is editable (the store knows whether the
|
||||
drive was opened for editing or is only being browsed).
|
||||
"""
|
||||
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
|
||||
@@ -1,7 +1,7 @@
|
||||
"""The retained native model for a OneLibrary drive.
|
||||
|
||||
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
|
||||
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
|
||||
place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
|
||||
|
||||
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
|
||||
with a **different and universal key**: every OneLibrary drive from every vendor
|
||||
@@ -54,8 +54,9 @@ from ...core.edit_journal import EditJournal
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.model import CuePoint
|
||||
from ... import paths
|
||||
from . import beatgrid, cues as cue_reader
|
||||
from ..rekordbox import anlz_file, palette, timebase
|
||||
from . import beatgrid, cues as cue_reader, memory_cues
|
||||
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
|
||||
from .layout import DriveLayout
|
||||
@@ -133,8 +134,8 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating", "release_date"}
|
||||
# Written into the audio file's own tags at Save, as rekordbox does when it
|
||||
# edits a stick (measured: the title reached the MP3's TIT2, the rating did
|
||||
# not). Everything editable except the rating.
|
||||
FILE_TAG_FIELDS = EDITABLE_FIELDS - {"rating"}
|
||||
# not). Everything editable except the rating, plus the key `set_key` sets.
|
||||
FILE_TAG_FIELDS = (EDITABLE_FIELDS - {"rating"}) | {"key"}
|
||||
|
||||
def __init__(self, path: Path, *, read_only: bool = False):
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
@@ -170,10 +171,10 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
def _load(self) -> None:
|
||||
"""Copy the drive's database into app-data and open the copy."""
|
||||
try:
|
||||
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
|
||||
from pyrekordbox.onelibrary import OneLibrary
|
||||
except ImportError as ex: # pragma: no cover — dependency missing
|
||||
raise LibraryNotSupported(
|
||||
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
|
||||
"Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
|
||||
) from ex
|
||||
_clear_stale_work()
|
||||
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
|
||||
@@ -186,7 +187,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
sidecar = self.path.with_name(self.path.name + suffix)
|
||||
if sidecar.is_file() and sidecar.stat().st_size:
|
||||
shutil.copyfile(sidecar, working.with_name(working.name + suffix))
|
||||
db = DeviceLibraryPlus(str(working))
|
||||
db = OneLibrary(str(working))
|
||||
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
|
||||
@@ -206,7 +207,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"""Release the working copy and delete it.
|
||||
|
||||
The drive itself is never held open (see the module docstring); the copy
|
||||
is, and `DeviceLibraryPlus.close()` only unregisters events, so the
|
||||
is, and `OneLibrary.close()` only unregisters events, so the
|
||||
session and engine are closed here explicitly.
|
||||
"""
|
||||
db, self._db = self._db, None
|
||||
@@ -316,7 +317,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
image_id = getattr(self.content(track_id), "image_id", None)
|
||||
if not image_id:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
|
||||
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
|
||||
@@ -456,7 +457,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
model = getattr(models, model_name)
|
||||
pk = f"{model.__tablename__}_id"
|
||||
@@ -490,6 +491,34 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
pass
|
||||
raise InvalidCommand(f"Release date must be a year or YYYY-MM-DD, got {text!r}")
|
||||
|
||||
def _key_id(self, wheel: int | None, mode: str | None) -> int | None:
|
||||
"""The `key` row for a key, found by what it MEANS: a stick's table holds
|
||||
rekordbox's names ("Abm") beside imported tag text ("12A" — the goober
|
||||
fixture has both), so a rendered-name match would duplicate a key the
|
||||
stick already has. A new key gets rekordbox's own spelling."""
|
||||
if wheel is None or mode is None:
|
||||
return None
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
from ..rekordbox.projection import parse_key, render_key
|
||||
|
||||
for k in self._require_db().query(models.Key).all():
|
||||
if parse_key(k.name) == (wheel, mode):
|
||||
return int(k.key_id)
|
||||
return self._lookup_id("Key", render_key(wheel, mode))
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
db = self._require_db()
|
||||
row = self.content(track_id)
|
||||
before = row.key_id
|
||||
row.key_id = self._key_id(wheel, mode)
|
||||
self._journal.record("track", "set", track_id, "key", before, row.key_id)
|
||||
# A foreign key: flush + expire, or re-projecting reads the old name.
|
||||
db.flush()
|
||||
db.session.expire(row)
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
from sqlalchemy import text
|
||||
|
||||
@@ -537,9 +566,61 @@ 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.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
try:
|
||||
pid = int(node_id)
|
||||
@@ -551,14 +632,14 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
return row
|
||||
|
||||
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
|
||||
rows = [r for r in rows if r.playlist_id != excluding]
|
||||
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
|
||||
|
||||
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
name = (name or "").strip()
|
||||
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
|
||||
@@ -603,7 +684,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
"""Delete a playlist, or a folder WITH everything in it, and close the gap
|
||||
its `sequenceNo` leaves among its siblings."""
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
db = self._require_db()
|
||||
row = self._playlist(node_id)
|
||||
@@ -624,9 +705,48 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
db.flush()
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s children, renumbering
|
||||
`sequenceNo` from 0 in both parents as create and delete do. The
|
||||
Device Library's playlist tree follows at Save (`device_library`
|
||||
mirrors parent and sort from these rows)."""
|
||||
db = self._require_db()
|
||||
row = self._playlist(node_id)
|
||||
dest = 0
|
||||
if parent_id:
|
||||
folder = self._playlist(parent_id)
|
||||
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
|
||||
raise InvalidCommand("A playlist can only be moved into a folder")
|
||||
dest = int(folder.playlist_id)
|
||||
ancestor = folder
|
||||
while ancestor is not None:
|
||||
if int(ancestor.playlist_id) == int(row.playlist_id):
|
||||
raise InvalidCommand("A folder cannot be moved into itself")
|
||||
up = int(ancestor.playlist_id_parent or 0)
|
||||
ancestor = self._playlist(str(up)) if up else None
|
||||
source = int(row.playlist_id_parent or 0)
|
||||
siblings = self._siblings(dest, excluding=row.playlist_id)
|
||||
index = max(0, min(int(index), len(siblings)))
|
||||
order = siblings[:index] + [row] + siblings[index:]
|
||||
if source == dest and [r.playlist_id for r in order] == [
|
||||
r.playlist_id for r in self._siblings(dest)
|
||||
]:
|
||||
return str(row.playlist_id)
|
||||
row.playlist_id_parent = dest
|
||||
for n, r in enumerate(order):
|
||||
if int(r.sequenceNo or 0) != n:
|
||||
r.sequenceNo = n
|
||||
if source != dest:
|
||||
for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)):
|
||||
if int(r.sequenceNo or 0) != n:
|
||||
r.sequenceNo = n
|
||||
db.flush()
|
||||
self._journal.record("playlist", "move", row.name)
|
||||
return str(row.playlist_id)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in order, numbered from 1 (measured)."""
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
from pyrekordbox.onelibrary import models
|
||||
|
||||
db = self._require_db()
|
||||
playlist = self._playlist(node_id)
|
||||
@@ -849,6 +969,60 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
self._replace_hot(track_id, hot, None, None)
|
||||
self._journal.record("cue", "delete", track_id, f"slot:{slot}")
|
||||
|
||||
# ---- memory cues -------------------------------------------------------
|
||||
# The list edits — and what rekordbox was measured doing — are in
|
||||
# `memory_cues`; here: the drive, the time base, the cap and the journal.
|
||||
MAX_MEMORY_CUES = MAX_MEMORY_CUES # rekordbox stops storing at 10, silently (measured)
|
||||
|
||||
def _memory_files(self, track_id: str):
|
||||
dat, ext = self._editing(track_id)
|
||||
self._ensure_pco2(dat, ext)
|
||||
return dat, ext
|
||||
|
||||
def add_memory_cue(self, track_id: str, *, start_sec: float, cue_type: str,
|
||||
length_sec: float = 0.0, name: str | None = None,
|
||||
color_id: int = 0) -> None:
|
||||
"""Add a memory cue (a memory loop with a length) the way rekordbox does.
|
||||
|
||||
`color_id` is `PCP2` byte 28 (`memory_palette.anlz_byte`), 0 = none."""
|
||||
from .export import _loop_beats
|
||||
|
||||
if start_sec < 0:
|
||||
raise InvalidCommand("A cue cannot be before the start of the track")
|
||||
dat, ext = self._memory_files(track_id)
|
||||
if memory_cues.count(ext) >= self.MAX_MEMORY_CUES:
|
||||
raise InvalidCommand(
|
||||
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
|
||||
)
|
||||
is_loop = cue_type == "loop" and length_sec > 0
|
||||
off = self._offset(track_id)
|
||||
time_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000))
|
||||
loop_ms = int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000)) if is_loop else None
|
||||
grid = self.anlz_grid(track_id)
|
||||
beats = (_loop_beats(start_sec, length_sec, list(zip(grid[2], grid[1], grid[0])))
|
||||
if is_loop and grid else None)
|
||||
memory_cues.add(dat, ext, kind=2 if is_loop else 1, time_ms=time_ms, loop_ms=loop_ms,
|
||||
beats=beats, name=name, color_id=color_id)
|
||||
self._journal.record("cue", "add", track_id, "memory")
|
||||
|
||||
def _memory_edit(self, track_id: str, cue_id: str, op: str, edit) -> None:
|
||||
dat, ext = self._memory_files(track_id)
|
||||
if not edit(dat, ext):
|
||||
raise NotFound(f"No memory cue {cue_id!r} on this track")
|
||||
self._journal.record("cue", op, track_id, "memory")
|
||||
|
||||
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
|
||||
self._memory_edit(track_id, cue_id, "modify",
|
||||
lambda _d, ext: memory_cues.rename(ext, cue_id, name))
|
||||
|
||||
def set_memory_cue_color(self, track_id: str, cue_id: str, color_id: int) -> None:
|
||||
self._memory_edit(track_id, cue_id, "modify",
|
||||
lambda _d, ext: memory_cues.recolour(ext, cue_id, color_id))
|
||||
|
||||
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
|
||||
self._memory_edit(track_id, cue_id, "delete",
|
||||
lambda dat, ext: memory_cues.delete(dat, ext, cue_id))
|
||||
|
||||
def hot_slots(self, track_id: str) -> set[int]:
|
||||
"""Occupied 0-based slots (pending edits included)."""
|
||||
return {c.slot for c in self.cues(track_id) if c.role == "hotcue" and c.slot is not None}
|
||||
@@ -1026,7 +1200,6 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"""
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..rekordbox.projection import render_key
|
||||
from .export import ANALYSED_BITS, CONTENT_LINK, _audio_format, _file_type, _kbps, art_files
|
||||
|
||||
if rel in (self._by_id or {}) or any(self.track_id(r) == rel for r in self.iter_content()):
|
||||
@@ -1061,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,
|
||||
@@ -1070,7 +1243,8 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"album": lookup("Album", track.album), "genre": lookup("Genre", track.genre),
|
||||
"label": lookup("Label", track.label),
|
||||
# Rendered from the parsed wheel: a source's "10m" means nothing here.
|
||||
"key": lookup("Key", render_key(track.key_wheel, track.key_mode)),
|
||||
"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,
|
||||
@@ -1312,9 +1486,9 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
|
||||
|
||||
def _reopen_working(self, work: Path) -> None:
|
||||
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
|
||||
from pyrekordbox.onelibrary import OneLibrary
|
||||
|
||||
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work
|
||||
self._db, self._work = OneLibrary(str(work / self.path.name)), work
|
||||
self._content_cache = None
|
||||
self._by_id = None
|
||||
|
||||
@@ -1375,7 +1549,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
t = projection.to_track(self.content(track_id))
|
||||
return {"title": t.title, "artist": t.artist, "album": t.album, "genre": t.genre,
|
||||
"label": t.label, "remixer": t.remixer, "comment": t.comment,
|
||||
"release_date": t.release_date}
|
||||
"release_date": t.release_date, "key": t.key}
|
||||
|
||||
|
||||
def _prune_empty(folder: Path, *, stop: Path) -> None:
|
||||
|
||||
@@ -21,13 +21,14 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import InvalidCommand, Unsupported
|
||||
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
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import palette, projection, timebase
|
||||
from . import memory_palette, palette, projection, timebase
|
||||
from ...core import add_analysis
|
||||
from .store import RekordboxStore
|
||||
|
||||
|
||||
@@ -44,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()
|
||||
]
|
||||
)
|
||||
@@ -70,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.
|
||||
@@ -171,6 +175,7 @@ class RekordboxAdapter:
|
||||
can_rename=writable,
|
||||
can_delete=writable,
|
||||
can_contain_children=kind == "folder",
|
||||
can_move=writable,
|
||||
)
|
||||
parent = str(r.ParentID or "root")
|
||||
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
||||
@@ -202,6 +207,9 @@ class RekordboxAdapter:
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
# The FILE decides a track's media kind, and the mapping moves files.
|
||||
@@ -215,6 +223,10 @@ class RekordboxAdapter:
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
return None
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
|
||||
self._store.set_write_stored_paths(enabled)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
paths = self._store.all_audio_paths()
|
||||
primary = common_dir_prefix(paths)
|
||||
@@ -245,6 +257,30 @@ class RekordboxAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
self._require_writable("Setting the key")
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
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")
|
||||
@@ -262,6 +298,10 @@ class RekordboxAdapter:
|
||||
self._require_writable("Deleting playlists")
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
self._require_writable("Moving playlists")
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
self._require_writable("Editing playlists")
|
||||
return self._store.set_playlist_entries(node_id, track_ids)
|
||||
@@ -284,12 +324,8 @@ class RekordboxAdapter:
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Rekordbox is the ONLY platform with memory cues, so under the
|
||||
# two-platform promotion rule they stay preserved-but-uneditable:
|
||||
# they are projected and shown, never written.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
# A memory cue has no slot to set; it has its own commands.
|
||||
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue(
|
||||
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||
@@ -320,6 +356,53 @@ class RekordboxAdapter:
|
||||
self._store.delete_cue(track_id, slot)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
# ---- commands: memory cues --------------------------------------------
|
||||
def _memory_code(self, color: str | None) -> int | None:
|
||||
if color is None:
|
||||
return None
|
||||
code = memory_palette.code_for(color)
|
||||
if code is None:
|
||||
raise InvalidCommand(f"{color!r} is not one of rekordbox's memory cue colours")
|
||||
return code
|
||||
|
||||
def add_memory_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color: str | None = None,
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.add_memory_cue(
|
||||
track_id, start_sec=start_sec, cue_type=cue_type, length_sec=length_sec,
|
||||
name=name, color_code=self._memory_code(color),
|
||||
)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._store.rename_memory_cue(track_id, cue_id, name)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
|
||||
# rekordbox has one point type, so there is nothing to choose; a memory
|
||||
# cue is a cue or a loop by its length.
|
||||
raise Unsupported("rekordbox memory cues have no type to change")
|
||||
|
||||
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
self._store.set_memory_cue_color(track_id, cue_id, self._memory_code(color))
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
|
||||
self._require_writable("Deleting cues")
|
||||
self._store.delete_memory_cue(track_id, cue_id)
|
||||
return self._refresh_cues(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
self._require_writable("Placing cues")
|
||||
for cue in cues:
|
||||
@@ -377,11 +460,41 @@ 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:
|
||||
return self._store.dirty
|
||||
|
||||
def edit_summary(self) -> str:
|
||||
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
|
||||
tracks; added 6 hotcues") — what a server tells the next computer to
|
||||
open the library about the edits it is inheriting."""
|
||||
return self._store._journal.summary()
|
||||
|
||||
def save(self):
|
||||
self._require_writable("Saving")
|
||||
return self._store.save()
|
||||
@@ -416,6 +529,14 @@ class RekordboxAdapter:
|
||||
if self._cloud_synced:
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def analysis_lead(self, audio: Path) -> float:
|
||||
"""The time-base lead `add_tracks` measures a file's waveform with —
|
||||
rekordbox's clock against the decoded audio, read from the file's
|
||||
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
|
||||
not analyse what it adds has none, and whoever prepares an analysis
|
||||
for this one (a client of a server-held library) asks for it."""
|
||||
return timebase.offset(Path(audio))
|
||||
|
||||
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
|
||||
"""Add tracks that came from somewhere else, with their prep.
|
||||
|
||||
@@ -437,7 +558,7 @@ class RekordboxAdapter:
|
||||
bank or already taken becomes a memory cue at the same position rather
|
||||
than being dropped.
|
||||
"""
|
||||
from ...core import audio_tags, grid_detect, waveform
|
||||
from ...core import audio_tags
|
||||
|
||||
self._require_writable("Adding tracks")
|
||||
held = set(self._store.all_audio_paths())
|
||||
@@ -453,48 +574,71 @@ class RekordboxAdapter:
|
||||
if str(audio) in held:
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
held.add(str(audio))
|
||||
samples = waveform.decode(audio)
|
||||
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
|
||||
markers = list(item.cues.grid_markers) if item.cues else []
|
||||
if not markers and samples is not None:
|
||||
try:
|
||||
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
|
||||
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
|
||||
except ValueError:
|
||||
pass # no pulse to fit (a one-shot, silence): no grid
|
||||
if item.analysis is not None:
|
||||
# Measured by whoever added it — a library held by a server is
|
||||
# never asked to decode audio (see `PreparedAnalysis`).
|
||||
analysed = item.analysis
|
||||
if not markers:
|
||||
markers = list(analysed.markers)
|
||||
else:
|
||||
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
|
||||
detect=not markers,
|
||||
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, 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, audio, measured, markers, art in prepared:
|
||||
for item, track, audio, measured, markers, art, loud in prepared:
|
||||
track_id = self._store.add_track(
|
||||
audio, item.track, measured=measured, with_grid=bool(markers), art=art)
|
||||
audio, track, measured=measured, with_grid=bool(markers), art=art)
|
||||
self._index.add(projection.to_track(self._store.content(track_id), (),
|
||||
stem=self._store.is_stem(track_id)))
|
||||
if markers:
|
||||
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
|
||||
|
||||
def _place_imported_cues(self, track_id: str, cues) -> None:
|
||||
"""Hot cues on their own pads; memory cues — and a hot cue with no
|
||||
free pad — as memory cues. Colour as the nearest palette swatch."""
|
||||
free pad — as memory cues, up to rekordbox's 10 (earliest first; the
|
||||
rest are dropped, per the lossiness rule). Colour as the nearest swatch
|
||||
of the palette the cue lands in: a hot cue's 16, a memory cue's 8."""
|
||||
taken: set[int] = set()
|
||||
memory = 0
|
||||
for cue in sorted(cues.cues or [], key=lambda c: c.start):
|
||||
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
common = dict(start_sec=cue.start, cue_type=cue_type,
|
||||
length_sec=getattr(cue, "length", 0.0) or 0.0,
|
||||
name=getattr(cue, "name", None), color_code=code or None)
|
||||
name=getattr(cue, "name", None))
|
||||
slot = cue.slot if cue.role == "hotcue" else None
|
||||
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
|
||||
self._store.set_cue(track_id, slot=slot, **common)
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
self._store.set_cue(track_id, slot=slot, color_code=code or None, **common)
|
||||
taken.add(slot)
|
||||
else:
|
||||
self._store.add_memory_cue(track_id, **common)
|
||||
elif memory < self._store.MAX_MEMORY_CUES:
|
||||
self._store.add_memory_cue(
|
||||
track_id, color_code=memory_palette.nearest_code(cue.color), **common)
|
||||
memory += 1
|
||||
|
||||
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||
# What goes with a track was measured in Rekordbox 7 — see the store.
|
||||
|
||||
@@ -158,6 +158,9 @@ class CueEntry:
|
||||
color_green: int | None = None
|
||||
color_blue: int | None = None
|
||||
len_entry: int = 0
|
||||
#: `PCP2` byte 28: a MEMORY cue's colour, 1-based, 0 = none (also present
|
||||
#: in the compact 44-byte form, which has no hot-cue colour tail).
|
||||
color_id: int = 0
|
||||
|
||||
|
||||
def raw_entries(tag: Tag) -> list[bytes]:
|
||||
@@ -197,6 +200,35 @@ def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> byt
|
||||
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
|
||||
|
||||
|
||||
def entry_color_id(entry: bytes) -> int:
|
||||
"""A `PCP2` entry's byte 28 — a MEMORY cue's colour, 1-based, 0 = none."""
|
||||
return entry[28] if len(entry) > 28 and entry[:4] == b"PCP2" else 0
|
||||
|
||||
|
||||
def entry_with_color_id(entry: bytes, value: int) -> bytes:
|
||||
"""A `PCP2` entry with ONLY byte 28 changed — what rekordbox does to recolour
|
||||
a memory cue (measured: that one byte, in any entry length, compact too)."""
|
||||
return entry[:28] + bytes([value & 0xFF]) + entry[29:]
|
||||
|
||||
|
||||
def entry_with_comment(entry: bytes, name: str | None) -> bytes:
|
||||
"""A `PCP2` entry renamed, every other byte kept.
|
||||
|
||||
Measured on a memory loop (rekordbox 7, 2026-10-16): the comment goes in at
|
||||
byte 44 as UTF-16BE plus a NUL, `len_comment` (byte 40) counts it, and the
|
||||
entry GROWS by exactly that much — 88 -> 100 for "Loopy" — the colour tail
|
||||
and padding following it unchanged. A compact 44-byte entry has no tail, so
|
||||
it first takes a full entry's (4 colour bytes + 40 zeros); that case is
|
||||
unmeasured."""
|
||||
if len(entry) < 44:
|
||||
raise AnlzError("A PCP2 entry shorter than 44 bytes has no comment field")
|
||||
old_len = struct.unpack_from(">I", entry, 40)[0]
|
||||
tail = entry[44 + old_len:] if len(entry) > 44 else bytes(44)
|
||||
comment = (name.encode("utf-16-be") + b"\0\0") if name else b""
|
||||
head = entry[:8] + struct.pack(">I", 44 + len(comment) + len(tail)) + entry[12:40]
|
||||
return head + struct.pack(">I", len(comment)) + comment + tail
|
||||
|
||||
|
||||
def entry_without_loop_beats(entry: bytes) -> bytes:
|
||||
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
|
||||
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
|
||||
@@ -245,7 +277,8 @@ def _pco2(data: bytes) -> list[CueEntry]:
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 16]
|
||||
time, loop = struct.unpack_from(">II", data, off + 20)
|
||||
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
|
||||
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n,
|
||||
color_id=data[off + 28] if n > 28 else 0)
|
||||
if n >= 44:
|
||||
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
|
||||
colour_at = off + 44 + len_comment
|
||||
|
||||
@@ -315,7 +315,7 @@ def flat_preview_tags() -> list[bytes]:
|
||||
|
||||
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
|
||||
comment: str | None = None) -> bytes:
|
||||
comment: str | None = None, color_id: int = 0) -> bytes:
|
||||
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
Two constants in here are rekordbox's, not the documented struct's: the
|
||||
@@ -328,6 +328,9 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
Konduktor's reader and pyrekordbox's agree with. No reference cue carries
|
||||
one, so that detail is documented rather than measured. The entry stays the
|
||||
exported 88 bytes unless the name needs more.
|
||||
|
||||
`color_id` is byte 28: a MEMORY cue's colour, 1-based (`memory_palette`),
|
||||
0 = none. A hot cue's colour is the code + RGB tail instead.
|
||||
"""
|
||||
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
|
||||
red, green, blue = rgb or (0, 0, 0)
|
||||
@@ -336,7 +339,7 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
">4sIIIBxHIIBB6xHHI",
|
||||
b"PCP2", 16, length, hot_cue, kind, 1000,
|
||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||
0, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
|
||||
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
|
||||
# The colour is the palette CODE, then RGB: rekordbox draws from the code
|
||||
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
|
||||
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
|
||||
@@ -344,6 +347,41 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
||||
)
|
||||
|
||||
|
||||
#: rekordbox's COMPACT `PCP2` entry: the first 44 bytes of a full one — no
|
||||
#: comment and no colour tail. What rekordbox 7 appends when it ADDS a memory cue
|
||||
#: on a stick (measured 2026-10-16, `fixtures/onelibrary-memory-edits`).
|
||||
PCP2_COMPACT_LEN = 44
|
||||
|
||||
|
||||
def pcp2_compact_entry(*, kind: int, time_ms: int, loop_ms: int | None,
|
||||
beats: int | None, color_id: int = 0, hot_cue: int = 0) -> bytes:
|
||||
"""A compact 44-byte `PCP2` entry, byte for byte as rekordbox 7 writes one
|
||||
for a memory cue it adds: the same fields as `pcp2_entry` up to
|
||||
`len_comment` (0), including the `1000` and the `1` after byte 28."""
|
||||
return struct.pack(
|
||||
">4sIIIBxHIIBB6xHHI",
|
||||
b"PCP2", 16, PCP2_COMPACT_LEN, hot_cue, kind, 1000,
|
||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, 0,
|
||||
)
|
||||
|
||||
|
||||
def relinked_memory_pcpts(entries: list[bytes]) -> list[bytes]:
|
||||
"""A `PCOB` MEMORY list's entries with their link fields rewritten, as
|
||||
rekordbox 7 leaves them after ANY add or delete (measured 2026-10-16,
|
||||
`fixtures/onelibrary-memory-edits`): status (bytes 16-19) 0, and bytes 24-27 the
|
||||
previous / next entry's INDEX IN THE LIST, 0xFFFF at either end — so every
|
||||
entry changes when one is added or removed. rekordbox's exports agree on any
|
||||
list of two or more; a lone exported entry is status 4, 0xFFFF/0xFFFF."""
|
||||
n = len(entries)
|
||||
out = []
|
||||
for i, e in enumerate(entries):
|
||||
prev = i - 1 if i > 0 else 0xFFFF
|
||||
nxt = i + 1 if i < n - 1 else 0xFFFF
|
||||
out.append(e[:16] + struct.pack(">I", 0) + e[20:24] + struct.pack(">HH", prev, nxt) + e[28:])
|
||||
return out
|
||||
|
||||
|
||||
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
|
||||
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
|
||||
|
||||
@@ -378,18 +416,25 @@ def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
|
||||
|
||||
|
||||
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
return pcob_tag(cue_type, [
|
||||
entries = [
|
||||
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"])
|
||||
for c in chosen
|
||||
])
|
||||
]
|
||||
if cue_type == 0 and len(entries) > 1:
|
||||
# A memory list of two or more is linked, status 0 — what rekordbox's
|
||||
# own exports (two test sticks) and edits hold. A lone entry keeps the
|
||||
# status 4 / 0xFFFF form the reference export pins.
|
||||
entries = relinked_memory_pcpts(entries)
|
||||
return pcob_tag(cue_type, entries)
|
||||
|
||||
|
||||
def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
|
||||
return pco2_tag(cue_type, [
|
||||
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
|
||||
code=c.get("code", 0), comment=c.get("comment"))
|
||||
code=c.get("code", 0), comment=c.get("comment"),
|
||||
color_id=c.get("color_id", 0))
|
||||
for c in chosen
|
||||
])
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import palette
|
||||
from .cue_types import WRITABLE_CUE_TYPES
|
||||
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
|
||||
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps
|
||||
@@ -55,18 +55,19 @@ def capabilities_for(
|
||||
writable=not cloud_synced,
|
||||
readonly_cause="cloud_synced" if cloud_synced else None,
|
||||
cues=CueCapabilities(
|
||||
# Hot cues are writable: djmdCue rows plus the contentCue JSON
|
||||
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
|
||||
# Rekordbox is the only platform that has them, and the two-platform
|
||||
# promotion rule says a one-platform concept does not become an
|
||||
# editing feature.
|
||||
# Hot AND memory cues are writable: djmdCue rows plus the
|
||||
# contentCue JSON mirror, kept in step (memory cues: measured
|
||||
# 2026-10-16, kit M1).
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# Rekordbox is the only platform with memory cues, so they are
|
||||
# projected and PRESERVED but not editable (two-platform rule).
|
||||
memory_cues=True,
|
||||
max_memory_cues=None, # unlimited
|
||||
# rekordbox stops storing at 10, silently; the store refuses the 11th.
|
||||
max_memory_cues=MAX_MEMORY_CUES,
|
||||
# A memory cue's colour is its own 8-colour palette (`Color`, not
|
||||
# `ColorTableIndex`) — see `memory_palette`.
|
||||
memory_color="palette",
|
||||
memory_palette=list(memory_palette.SWATCHES),
|
||||
# Both cue types write; Rekordbox has no fade/load types.
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
# A hot cue's colour is one of rekordbox's 16 swatches (all
|
||||
@@ -91,6 +92,12 @@ def capabilities_for(
|
||||
media_kinds=["audio", "stem"],
|
||||
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,
|
||||
),
|
||||
|
||||
@@ -36,6 +36,10 @@ has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
|
||||
from __future__ import annotations
|
||||
|
||||
MEMORY_KIND = 0
|
||||
#: rekordbox stores at most this many memory cues per track — on the computer
|
||||
#: AND on a stick — and enforces it SILENTLY (measured 2026-10-16: MEMORY simply
|
||||
#: stops storing), so Konduktor refuses the next one itself, with a reason.
|
||||
MAX_MEMORY_CUES = 10
|
||||
|
||||
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
|
||||
CUE_TYPES = ["cue", "loop"]
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
{
|
||||
@@ -198,8 +199,9 @@ class RekordboxDeviceExporter:
|
||||
|
||||
@staticmethod
|
||||
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
|
||||
"""The tree under one folder named after the export, as the other
|
||||
targets build it. `sort_order` is a node's position among its siblings."""
|
||||
"""The tree as the other targets build it — at the top level (parent
|
||||
0), or with `payload.root_folder` under one folder named after the
|
||||
export. `sort_order` is a node's position among its siblings."""
|
||||
tree: list[bytes] = []
|
||||
entries: list[bytes] = []
|
||||
next_id = [0]
|
||||
@@ -220,7 +222,7 @@ class RekordboxDeviceExporter:
|
||||
index += 1
|
||||
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
|
||||
|
||||
root = add(payload.name, 0, folder=True)
|
||||
root = add(payload.name, 0, folder=True) if payload.root_folder else 0
|
||||
folders: dict[tuple[str, ...], int] = {(): root}
|
||||
for playlist in payload.playlists:
|
||||
parent = root
|
||||
|
||||
@@ -58,7 +58,7 @@ from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from . import 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.
|
||||
@@ -125,7 +130,7 @@ class RekordboxExporter:
|
||||
)
|
||||
|
||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
|
||||
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
|
||||
# OneLibrary drive uses a universal key shared across vendors, and
|
||||
# master.db does not. Mixing them up produces a database Rekordbox
|
||||
# cannot open, and pyrekordbox rejects the wrong one outright.
|
||||
@@ -199,24 +204,36 @@ class RekordboxExporter:
|
||||
from .adapter import RekordboxAdapter
|
||||
|
||||
adapter = RekordboxAdapter(library)
|
||||
# The store, not the adapter's commands: the adapter refuses memory cues
|
||||
# (editing them in a user's library is off-limits) and takes no colour.
|
||||
# Building a NEW library is neither an edit nor lossy by choice, so the
|
||||
# exporter writes both — through the same `_write_cue` every edit uses.
|
||||
# The store, not the adapter's commands: the adapter's set_cue takes no
|
||||
# colour and its memory-cue command takes only a swatch. A NEW library
|
||||
# maps any source colour to the nearest one instead — through the same
|
||||
# `_write_cue` every edit uses.
|
||||
store = adapter._store
|
||||
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
|
||||
for cue in item.cues.cues:
|
||||
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):
|
||||
if cue.role == "memory" or cue.slot is None:
|
||||
# rekordbox's own "unset" for a memory cue with no colour.
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
# rekordbox keeps 10 (earliest first; the rest are
|
||||
# dropped, per the lossiness rule). Colour: what
|
||||
# Konduktor SHOWS — stored, else the type's — as the
|
||||
# nearest of the memory palette's 8, as for a hot cue.
|
||||
if memory >= store.MAX_MEMORY_CUES:
|
||||
continue
|
||||
store.add_memory_cue(
|
||||
track_id, start_sec=cue.start, cue_type=cue.type,
|
||||
length_sec=cue.length, name=cue.name, color_code=code or None,
|
||||
length_sec=cue.length, name=cue.name,
|
||||
color_code=memory_palette.nearest_code(effective_color(cue)),
|
||||
)
|
||||
memory += 1
|
||||
continue
|
||||
# What Konduktor SHOWS — stored colour, else the type's (blue
|
||||
# cue, green loop) — as a palette code, which is what
|
||||
@@ -306,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
|
||||
|
||||
@@ -324,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()
|
||||
|
||||
@@ -383,9 +403,12 @@ class RekordboxExporter:
|
||||
# ---- playlists ---------------------------------------------------------------
|
||||
|
||||
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
|
||||
"""The tree, under one folder named after the export."""
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
"""The tree — at the top level, or with `payload.root_folder` under one
|
||||
folder named after the export (None = the top level)."""
|
||||
root = None
|
||||
if payload.root_folder:
|
||||
root = db.create_playlist_folder(payload.name)
|
||||
db.flush()
|
||||
folders: dict[tuple[str, ...], object] = {(): root}
|
||||
|
||||
for playlist in payload.playlists:
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""rekordbox's MEMORY-cue colours — a palette of its own, not the hot cues'.
|
||||
|
||||
rekordbox 7 offers a memory cue eight colours plus "No Color" (Pink, Red,
|
||||
Orange, Yellow, Green, Aqua, Blue, Purple — the same eight names as its track
|
||||
colours), against sixteen swatches for a hot cue. MEASURED 2026-10-16 (kits M1 /
|
||||
M2 in `.claude/discussions/discuss-memory-cues-2026-10-16.md`), by colouring
|
||||
memory cues one per colour, in that order, in rekordbox itself:
|
||||
|
||||
* `master.db`: the code is `djmdCue.Color`, **0-based** in menu order (Pink 0
|
||||
… Purple 7) and `ColorTableIndex` stays NULL — the opposite of a hot cue,
|
||||
which keeps its code in `ColorTableIndex` with `Color = -1`. "No colour" is
|
||||
`-1` on a cue never coloured and **255** on one set back to "No Color".
|
||||
* the ANLZ `.EXT`: `PCP2` byte 28, **1-based** (Blue = 7), 0 = none. The
|
||||
hot-cue colour tail after the comment stays zero on a memory cue.
|
||||
|
||||
The RGB values are DISPLAY colours only — nothing stores them. They were
|
||||
sampled from the dots in rekordbox 7's own colour menu (a screenshot), so they
|
||||
are what rekordbox shows, not what it writes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import colorsys
|
||||
|
||||
from .palette import _parse
|
||||
|
||||
#: code (0-based, master.db) -> display RGB, in rekordbox's menu order.
|
||||
COLOURS: list[tuple[str, tuple[int, int, int]]] = [
|
||||
("Pink", (0xE5, 0x77, 0xEF)),
|
||||
("Red", (0xE1, 0x31, 0x21)),
|
||||
("Orange", (0xEA, 0xA3, 0x49)),
|
||||
("Yellow", (0xF2, 0xE2, 0x57)),
|
||||
("Green", (0x65, 0xDB, 0x41)),
|
||||
("Aqua", (0x55, 0xBB, 0xF1)),
|
||||
("Blue", (0x1F, 0x4E, 0xED)),
|
||||
("Purple", (0x8A, 0x1D, 0xED)),
|
||||
]
|
||||
|
||||
#: `master.db`'s `Color` for a memory cue set back to "No Color" (measured);
|
||||
#: a cue never coloured keeps -1. Both read as uncoloured.
|
||||
CLEARED = 255
|
||||
|
||||
#: Below this saturation a colour is white/grey, which the palette cannot show.
|
||||
_GREY = 0.2
|
||||
|
||||
|
||||
def _hex(rgb: tuple[int, int, int]) -> str:
|
||||
return f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
|
||||
|
||||
|
||||
#: The swatches a user can pick — what `capabilities.cues.memory_palette` offers.
|
||||
SWATCHES: list[str] = [_hex(rgb) for _name, rgb in COLOURS]
|
||||
|
||||
|
||||
def hex_for(code: int | None) -> str | None:
|
||||
"""`#RRGGBB` for a stored 0-based code; None for -1, 255 or anything unknown."""
|
||||
if code is None or not 0 <= code < len(COLOURS):
|
||||
return None
|
||||
return _hex(COLOURS[code][1])
|
||||
|
||||
|
||||
def code_for(color: str | None) -> int | None:
|
||||
"""The 0-based code of an EXACT swatch (a user's pick), else None."""
|
||||
rgb = _parse(color) if color else None
|
||||
return next((i for i, (_n, value) in enumerate(COLOURS) if value == rgb), None)
|
||||
|
||||
|
||||
def nearest_code(color: str | None) -> int | None:
|
||||
"""The swatch nearest in hue to any `#RRGGBB` — for a colour arriving from
|
||||
another platform (an import, an export). None for no colour or a grey."""
|
||||
exact = code_for(color)
|
||||
if exact is not None:
|
||||
return exact
|
||||
rgb = _parse(color) if color else None
|
||||
if rgb is None:
|
||||
return None
|
||||
h, _l, s = colorsys.rgb_to_hls(*(v / 255 for v in rgb))
|
||||
if s < _GREY or max(rgb) - min(rgb) < 40:
|
||||
return None
|
||||
|
||||
def hue_gap(i: int) -> float:
|
||||
ph = colorsys.rgb_to_hls(*(v / 255 for v in COLOURS[i][1]))[0]
|
||||
d = abs(ph - h)
|
||||
return min(d, 1 - d)
|
||||
|
||||
return min(range(len(COLOURS)), key=hue_gap)
|
||||
|
||||
|
||||
def anlz_byte(code: int | None) -> int:
|
||||
"""`PCP2` byte 28 for a 0-based code: code + 1, and 0 for none."""
|
||||
return 0 if code is None else code + 1
|
||||
|
||||
|
||||
def from_anlz_byte(value: int) -> int | None:
|
||||
"""The 0-based code from `PCP2` byte 28 (0 = none)."""
|
||||
return value - 1 if 1 <= value <= len(COLOURS) else None
|
||||
@@ -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
|
||||
|
||||
@@ -5,65 +5,32 @@ The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core import musical_key
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, palette, timebase
|
||||
from .cue_types import cue_type, role_and_slot
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
|
||||
# Open Key notation. Parsing that is platform knowledge and belongs here.
|
||||
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
|
||||
|
||||
# Camelot wheel position for each pitch class, per mode.
|
||||
_CAMELOT_MINOR = {
|
||||
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
|
||||
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
|
||||
"F": 4, "C": 5, "G": 6, "D": 7,
|
||||
}
|
||||
_CAMELOT_MAJOR = {
|
||||
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
|
||||
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
|
||||
"F": 7,
|
||||
}
|
||||
|
||||
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
|
||||
# holds whatever text a track's key TAG carried when it was imported, so a real
|
||||
# stick has "12A" beside "Abm". Parsing therefore accepts every notation.
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
|
||||
if not key:
|
||||
return None, None
|
||||
m = _KEY_RE.match(key.strip())
|
||||
if not m:
|
||||
return None, None
|
||||
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
|
||||
pitch = letter + (accidental.replace("B", "b") if accidental else "")
|
||||
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
|
||||
n = table.get(pitch)
|
||||
return (n, "minor" if minor else "major") if n else (None, None)
|
||||
"""(Camelot wheel position 1-12, mode) for a key name in any notation."""
|
||||
return musical_key.parse(key)
|
||||
|
||||
|
||||
# The inverse, for EXPORT. A track arriving from Traktor carries `key` as
|
||||
# The inverse, for writing. A track arriving from Traktor carries `key` as
|
||||
# Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed
|
||||
# position — so writing the string verbatim into a Pioneer library would show
|
||||
# "10m" where the deck expects "Abm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared with the OneLibrary exporter: same vendor, same
|
||||
# notation, and two tables would drift.
|
||||
_MINOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MINOR.items()))}
|
||||
_MAJOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MAJOR.items()))}
|
||||
|
||||
|
||||
# "10m" where the deck expects "Cm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared by the adapter and both Pioneer exporters.
|
||||
def render_key(wheel: int | None, mode: str | None) -> str | None:
|
||||
"""A Pioneer-style key name ("Abm", "F") for a Camelot position + mode.
|
||||
"""A Pioneer key name ("Abm", "F") for a Camelot position + mode, spelt as
|
||||
rekordbox spells its own (flats; see `core/musical_key`).
|
||||
|
||||
Returns None when the position is unknown, which is honest: a made-up key is
|
||||
worse than a blank one, and Pioneer software shows blanks without complaint.
|
||||
"""
|
||||
if not wheel or not (1 <= wheel <= 12):
|
||||
return None
|
||||
if mode == "minor":
|
||||
name = _MINOR_NAMES.get(wheel)
|
||||
return f"{name}m" if name else None
|
||||
return _MAJOR_NAMES.get(wheel)
|
||||
return musical_key.render(wheel, mode, "musical")
|
||||
|
||||
|
||||
def _iso_date(value) -> str | None:
|
||||
@@ -97,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
|
||||
@@ -160,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -173,10 +144,10 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
|
||||
`editable` says whether the adapter will accept a command on THIS cue, which
|
||||
is the only thing the UI gates on. Every hot cue is editable, loops included.
|
||||
|
||||
**Memory cues are not**: Rekordbox is the only platform that has them, so
|
||||
under the two-platform promotion rule they are shown and never written. A cue
|
||||
sitting on the reserved `Kind` occupies no pad and is projected the same way,
|
||||
because that is how Rekordbox itself displays one.
|
||||
So is every memory cue (`Kind` 0), addressed by its row id (`CuePoint.id`)
|
||||
since it has no pad. A cue sitting on the reserved `Kind` 4 occupies no pad
|
||||
either and is SHOWN as a memory cue, because that is how Rekordbox itself
|
||||
displays one — but it is not one, so it is not editable.
|
||||
"""
|
||||
markers: list[GridMarker] = []
|
||||
if grid is not None:
|
||||
@@ -191,7 +162,9 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
|
||||
length = 0.0
|
||||
if out_msec is not None and out_msec > 0:
|
||||
length = max(0.0, (out_msec - in_msec) / 1000.0)
|
||||
editable = role == "hotcue"
|
||||
memory = role == "memory"
|
||||
# Kind 4 (reserved) displays as a memory cue but is not one.
|
||||
editable = not memory or getattr(c, "Kind", None) == kind_for("memory", None)
|
||||
cues.append(
|
||||
CuePoint(
|
||||
name=(getattr(c, "Comment", None) or None),
|
||||
@@ -202,15 +175,27 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
|
||||
start=timebase.from_pioneer(in_msec / 1000.0, time_offset),
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_cue_color(c),
|
||||
color=_memory_cue_color(c) if memory else _cue_color(c),
|
||||
editable=editable,
|
||||
readonly_reason=None if editable else "platform_managed",
|
||||
grid_marker=None,
|
||||
# A memory cue is addressed by its row id (`CuePoint.id`).
|
||||
id=str(c.ID) if memory and editable and getattr(c, "ID", None) is not None else None,
|
||||
)
|
||||
)
|
||||
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
|
||||
|
||||
|
||||
def _memory_cue_color(row) -> str | None:
|
||||
"""A memory cue keeps its 0-based `memory_palette` code in `Color` (-1 and
|
||||
255 = none). A row Konduktor wrote before that was measured carries a
|
||||
hot-cue code in `ColorTableIndex` instead; read it rather than lose it."""
|
||||
colour = memory_palette.hex_for(getattr(row, "Color", None))
|
||||
if colour is None and (getattr(row, "OutMsec", -1) or -1) <= 0:
|
||||
colour = palette.hex_for(getattr(row, "ColorTableIndex", None))
|
||||
return colour
|
||||
|
||||
|
||||
def _cue_color(row) -> str | None:
|
||||
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
|
||||
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
|
||||
|
||||
@@ -28,6 +28,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
@@ -46,9 +47,9 @@ from ...core.adapter import (
|
||||
)
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.pathmap import PathMapping
|
||||
from . import timebase
|
||||
from .cue_types import beat_loop_size, kind_for, role_and_slot
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
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__)
|
||||
|
||||
@@ -117,11 +118,16 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._mapping = PathMapping()
|
||||
# Write an added file in the library's STORED form (`pathmap.stored_form`).
|
||||
self._write_stored_paths = False
|
||||
self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
|
||||
self._journal = EditJournal()
|
||||
# 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()
|
||||
@@ -161,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()
|
||||
@@ -375,6 +382,14 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._mapping = mapping or PathMapping()
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
self._write_stored_paths = bool(enabled)
|
||||
|
||||
def _stored(self, audio: Path) -> Path:
|
||||
if not self._write_stored_paths:
|
||||
return Path(audio)
|
||||
return stored_form(Path(audio), [self._mapping])
|
||||
|
||||
def is_stem(self, track_id: str) -> bool:
|
||||
"""Whether the track's FILE is a native-instruments stem file — read
|
||||
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
|
||||
@@ -506,6 +521,107 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: musical key ---------------------------------------------
|
||||
def _key_id(self, wheel: int | None, mode: str | None) -> str | None:
|
||||
"""The `djmdKey` row for a key, found by what it MEANS, not its text.
|
||||
|
||||
A library's key table holds rekordbox's own names ("Abm") and whatever
|
||||
key tags imported ("12A"), so matching on a rendered name would add a
|
||||
second row for a key the library already has. Only a key it has never
|
||||
seen gets a row — created as rekordbox creates its own (measured on the
|
||||
local library, which rekordbox fills lazily as it analyses): named in
|
||||
its spelling, `Seq` NULL, and through the ORM so `commit()` stamps the
|
||||
row's `rb_local_usn` like any other change. (The exporters' raw insert
|
||||
would leave it unstamped.)"""
|
||||
from .projection import parse_key, render_key
|
||||
|
||||
if wheel is None or mode is None:
|
||||
return None
|
||||
for k in self._db.query(self._tables.DjmdKey).all():
|
||||
if parse_key(k.ScaleName) == (wheel, mode):
|
||||
return str(k.ID)
|
||||
row = self._tables.DjmdKey(
|
||||
ID=str(uuid.uuid4().int % 2_147_483_647),
|
||||
ScaleName=render_key(wheel, mode),
|
||||
UUID=str(uuid.uuid4()),
|
||||
)
|
||||
self._db.add(row)
|
||||
self._db.flush()
|
||||
return str(row.ID)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
row = self.content(track_id)
|
||||
before = row.KeyID
|
||||
row.KeyID = self._key_id(wheel, mode)
|
||||
self._journal.record("track", "set", track_id, "key", before, row.KeyID)
|
||||
# A foreign key, like artist: flush + expire, or the re-projection
|
||||
# reads the old key back through the cached relationship.
|
||||
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
|
||||
@@ -558,6 +674,79 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
self._db.delete_playlist(row)
|
||||
self._journal.record("playlist", "delete", name)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s visible children.
|
||||
|
||||
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
|
||||
parent", so nothing can be moved to the top level with it. The same
|
||||
writes are made here — `ParentID`, the moved row's `updated_at`, and
|
||||
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
|
||||
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
|
||||
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
|
||||
share the table and the numbering, so `index` is placed relative to
|
||||
the VISIBLE siblings and the hidden ones keep their order around it."""
|
||||
import datetime
|
||||
|
||||
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
|
||||
|
||||
t = self._tables
|
||||
row = self._playlist(node_id)
|
||||
dest = self._playlist(parent_id) if parent_id else None
|
||||
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
|
||||
raise InvalidCommand("A playlist can only be moved into a folder")
|
||||
ancestor = dest
|
||||
while ancestor is not None:
|
||||
if str(ancestor.ID) == str(row.ID):
|
||||
raise InvalidCommand("A folder cannot be moved into itself")
|
||||
up = str(ancestor.ParentID or "root")
|
||||
ancestor = None if up in ("root", "0", "") else self._playlist(up)
|
||||
|
||||
def children(key: str) -> list:
|
||||
return (
|
||||
self._db.session.query(t.DjmdPlaylist)
|
||||
.filter(t.DjmdPlaylist.ParentID == key)
|
||||
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdPlaylist.Seq)
|
||||
.all()
|
||||
)
|
||||
|
||||
old_key = str(row.ParentID or "root")
|
||||
new_key = str(dest.ID) if dest is not None else "root"
|
||||
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
|
||||
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
|
||||
index = max(0, min(int(index), len(visible)))
|
||||
if index < len(visible):
|
||||
at = siblings.index(visible[index])
|
||||
else:
|
||||
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
|
||||
order = siblings[:at] + [row] + siblings[at:]
|
||||
if old_key == new_key and [str(c.ID) for c in order] == [
|
||||
str(c.ID) for c in children(new_key)
|
||||
]:
|
||||
return str(row.ID)
|
||||
|
||||
row.ParentID = new_key
|
||||
with self._db.registry.disabled():
|
||||
row.updated_at = datetime.datetime.now()
|
||||
for n, c in enumerate(order, start=1):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
if old_key != new_key:
|
||||
for n, c in enumerate(
|
||||
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
|
||||
):
|
||||
if c.Seq != n:
|
||||
c.Seq = n
|
||||
xml = getattr(self._db, "playlist_xml", None)
|
||||
if xml is not None:
|
||||
try:
|
||||
xml.update(row.ID, parent_id=new_key)
|
||||
except ValueError:
|
||||
pass # a playlist the XML never listed: nothing to keep in step
|
||||
self._db.flush()
|
||||
self._journal.record("playlist", "move", row.Name)
|
||||
return str(row.ID)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents, in the given order.
|
||||
|
||||
@@ -604,14 +793,15 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
|
||||
in the `.DAT` for `replace_grid` to fill."""
|
||||
from . import new_content
|
||||
from .projection import render_key
|
||||
|
||||
audio = Path(audio)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
t = self._tables
|
||||
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count():
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
stored = self._stored(audio)
|
||||
for form in {str(audio), str(stored)}:
|
||||
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=form).count():
|
||||
raise InvalidCommand(f"The library already holds {audio}")
|
||||
facts = _file_facts(audio)
|
||||
content = self._db.add_content(
|
||||
str(audio),
|
||||
@@ -633,16 +823,20 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
content.AlbumID = new_content.lookup(self._db, "album", track.album)
|
||||
content.GenreID = new_content.lookup(self._db, "genre", track.genre)
|
||||
content.LabelID = new_content.lookup(self._db, "label", track.label)
|
||||
# Rendered from the wheel, never copied: the source's notation is not
|
||||
# Rekordbox's ("10m" is "Cm" here).
|
||||
content.KeyID = new_content.lookup(
|
||||
self._db, "key", render_key(track.key_wheel, track.key_mode))
|
||||
# From the wheel, never the source's text: its notation is not
|
||||
# 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).
|
||||
content.FolderPath = str(stored)
|
||||
|
||||
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():
|
||||
@@ -874,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()
|
||||
@@ -1020,6 +1215,25 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
)
|
||||
self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}")
|
||||
|
||||
MAX_MEMORY_CUES = MAX_MEMORY_CUES # see `cue_types`
|
||||
|
||||
def memory_cue_rows(self, track_id: str) -> list:
|
||||
"""A track's memory cues (`Kind` 0), in row order."""
|
||||
t = self._tables
|
||||
return list(
|
||||
self._db.session.query(t.DjmdCue)
|
||||
.filter(t.DjmdCue.ContentID == str(track_id))
|
||||
.filter(t.DjmdCue.Kind == kind_for("memory", None))
|
||||
.filter(t.DjmdCue.rb_local_deleted == 0)
|
||||
)
|
||||
|
||||
def _memory_cue_row(self, track_id: str, cue_id: str):
|
||||
"""The memory cue whose `djmdCue.ID` is `cue_id` (`CuePoint.id`)."""
|
||||
row = next((c for c in self.memory_cue_rows(track_id) if str(c.ID) == str(cue_id)), None)
|
||||
if row is None:
|
||||
raise NotFound(f"No memory cue {cue_id!r} on this track")
|
||||
return row
|
||||
|
||||
def add_memory_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
@@ -1029,23 +1243,59 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color_code: int | None = None,
|
||||
enforce_cap: bool = True,
|
||||
) -> None:
|
||||
"""Add a MEMORY cue (`Kind` 0) — for the exporter building a new library.
|
||||
"""Add a MEMORY cue (`Kind` 0); a memory loop when `length_sec` > 0.
|
||||
|
||||
The adapter never calls this: editing memory cues in a user's library
|
||||
stays refused under the two-platform promotion rule. A new export is not
|
||||
an edit, and dropping the source's memory cues would lose prep.
|
||||
`color_code` is a 0-based `memory_palette` code — NOT a hot-cue palette
|
||||
code: a memory cue keeps its colour in `Color`, not `ColorTableIndex`.
|
||||
`enforce_cap` refuses the 11th (an edit); the exporter, building a
|
||||
library from a source that may hold more, trims before calling.
|
||||
"""
|
||||
if enforce_cap and len(self.memory_cue_rows(track_id)) >= self.MAX_MEMORY_CUES:
|
||||
raise InvalidCommand(
|
||||
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
|
||||
)
|
||||
self._write_cue(
|
||||
track_id, None, kind=kind_for("memory", None), start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
|
||||
)
|
||||
self._journal.record("cue", "add", track_id, "memory")
|
||||
|
||||
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
|
||||
"""A memory cue's name is rekordbox's `Comment`; only that column changes."""
|
||||
cue = self._memory_cue_row(track_id, cue_id)
|
||||
is_loop = (cue.OutMsec or 0) > 0
|
||||
# An unnamed memory LOOP is '' (measured); an unnamed point cue NULL.
|
||||
cue.Comment = name or ("" if is_loop else None)
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", "modify", track_id, "memory")
|
||||
|
||||
def set_memory_cue_color(self, track_id: str, cue_id: str, color_code: int | None) -> None:
|
||||
"""Recolour a memory cue; None = rekordbox's "No Color" (255, measured)."""
|
||||
cue = self._memory_cue_row(track_id, cue_id)
|
||||
self._apply_memory_color(cue, color_code, (cue.OutMsec or 0) > 0, cleared=True)
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", "modify", track_id, "memory")
|
||||
|
||||
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
|
||||
"""Delete the row outright, as rekordbox does (never `rb_local_deleted`)."""
|
||||
cue = self._memory_cue_row(track_id, cue_id)
|
||||
self._db.delete(cue)
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
self._journal.record("cue", "delete", track_id, "memory")
|
||||
|
||||
def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str,
|
||||
length_sec: float, name: str | None, color_code: int | None) -> None:
|
||||
"""Fill one `djmdCue` row (a new one when `cue` is None) and resync the
|
||||
`contentCue` mirror — the single definition of a cue row's fields."""
|
||||
`contentCue` mirror — the single definition of a cue row's fields.
|
||||
|
||||
`color_code` is a hot-cue palette code on a hot cue and a 0-based
|
||||
`memory_palette` code on a memory cue (`Kind` 0): the two keep their
|
||||
colour in different columns."""
|
||||
if start_sec < 0:
|
||||
raise InvalidCommand("A cue cannot be before the start of the track")
|
||||
row = self.content(track_id)
|
||||
@@ -1090,8 +1340,13 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
cue.BeatLoopSize = None
|
||||
cue.ActiveLoop = None
|
||||
cue.CueMicrosec = None
|
||||
self._apply_color(cue, color_code, is_loop)
|
||||
cue.Comment = name or None
|
||||
if kind == kind_for("memory", None):
|
||||
self._apply_memory_color(cue, color_code, is_loop)
|
||||
# Measured: an unnamed memory LOOP has Comment '', a point cue NULL.
|
||||
cue.Comment = name or ("" if is_loop else None)
|
||||
else:
|
||||
self._apply_color(cue, color_code, is_loop)
|
||||
cue.Comment = name or None
|
||||
|
||||
self._db.flush()
|
||||
self._sync_content_cue(track_id)
|
||||
@@ -1113,6 +1368,21 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
cue.Color = -1
|
||||
cue.ColorTableIndex = None
|
||||
|
||||
@staticmethod
|
||||
def _apply_memory_color(cue, code: int | None, is_loop: bool, *, cleared: bool = False) -> None:
|
||||
"""A MEMORY cue's colour columns (measured 2026-10-16, kit M1): the
|
||||
0-based `memory_palette` code in `Color`, `ColorTableIndex` untouched by
|
||||
colour — NULL on a point cue, 0 on a loop (rekordbox's loop marker).
|
||||
Uncoloured is -1 on a new point cue, 255 on a loop and on any cue set
|
||||
back to "No Color" (`cleared`)."""
|
||||
cue.ColorTableIndex = 0 if is_loop else None
|
||||
if code is not None:
|
||||
cue.Color = int(code)
|
||||
elif cleared or is_loop:
|
||||
cue.Color = memory_palette.CLEARED
|
||||
else:
|
||||
cue.Color = -1
|
||||
|
||||
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
|
||||
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
|
||||
colour columns, so the position does not take a time-base round trip."""
|
||||
@@ -1181,11 +1451,13 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
"""
|
||||
t = self._tables
|
||||
row = self.content(track_id)
|
||||
# In ROW order, as rekordbox writes it (measured: a memory cue added at
|
||||
# 1:55 is listed after older ones at 2:04 and 3:26), not by position.
|
||||
cues = (
|
||||
self._db.session.query(t.DjmdCue)
|
||||
.filter(t.DjmdCue.ContentID == str(track_id))
|
||||
.filter(t.DjmdCue.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdCue.InMsec)
|
||||
.order_by(text("djmdCue.rowid"))
|
||||
.all()
|
||||
)
|
||||
fields = (
|
||||
@@ -1286,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
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Remote libraries: a library held by a Konduktor server, opened from here.
|
||||
|
||||
NOT a registered driver: a remote is not a file `can_open` could probe, and it
|
||||
is chosen from the picker's own "Remote" step, by the saved remote's id. What
|
||||
opening one returns is everything `AppState.open_remote` installs — the
|
||||
adapter, the services that keep history and export sets on the server, and the
|
||||
session that keeps this computer's hold on it.
|
||||
|
||||
Imports no platform adapter (`test_layering.py`): what platform the server
|
||||
holds is the server's business, and reaches this side only as capabilities.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ... import exports
|
||||
from . import config
|
||||
from .adapter import RemoteAdapter
|
||||
from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch
|
||||
from .services import RemoteLoudnessStore, RemotePending, RemoteServices, RemoteSetStore
|
||||
from .session import RemoteSession
|
||||
|
||||
__all__ = [
|
||||
"AuthFailed", "InUse", "Opened", "RemoteAdapter", "SessionLost", "Unreachable",
|
||||
"VersionMismatch", "handshake", "open_remote",
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Opened:
|
||||
remote: config.Remote
|
||||
path: Path
|
||||
adapter: RemoteAdapter
|
||||
services: RemoteServices
|
||||
session: RemoteSession
|
||||
library_id: str
|
||||
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,
|
||||
password: str | None = None, cache=None) -> Opened:
|
||||
"""Connect, take the session, and mirror the library. Raises `InUse` when
|
||||
another computer holds it (and `takeover` is not set), `AuthFailed`,
|
||||
`VersionMismatch` or `Unreachable` — all before anything is installed."""
|
||||
secret = password if password is not None else config.password(remote.id)
|
||||
if not secret:
|
||||
raise AuthFailed("No password is saved for this remote — edit it to enter one")
|
||||
client = RemoteClient(remote, secret)
|
||||
try:
|
||||
client_id = config.client_id()
|
||||
hello = client.hello(client_id)
|
||||
machine = config.machine_name()
|
||||
acquired = client.acquire(client_id, machine, takeover=takeover)
|
||||
session = RemoteSession(client, batch_probe=batch_probe, identity=(client_id, machine))
|
||||
adapter = RemoteAdapter(client, session, hello, cache=cache)
|
||||
session.on_reacquired = adapter.refresh
|
||||
except Exception:
|
||||
client.release()
|
||||
client.close()
|
||||
raise
|
||||
# The server's id for the library, namespaced: this computer's export-set
|
||||
# store for it is the SERVER (`RemoteSetStore`), and nothing this computer
|
||||
# keeps under the server's own id may be mistaken for it.
|
||||
library_id = f"remote:{hello['library_id']}"
|
||||
exports.use_store(library_id, RemoteSetStore(client))
|
||||
session.start()
|
||||
return Opened(
|
||||
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),
|
||||
)
|
||||
|
||||
|
||||
def handshake(remote: config.Remote, password: str) -> list[dict]:
|
||||
"""Try each of the remote's addresses on its own: what a Save of the
|
||||
remote's settings reports. Each result is {address, url, ok, error, kind},
|
||||
`kind` one of ok / unreachable / auth / version / other."""
|
||||
results = []
|
||||
for label, url in remote.addresses():
|
||||
single = config.Remote(id=remote.id, name=remote.name, host=url, username=remote.username)
|
||||
client = RemoteClient(single, password, timeout=8.0)
|
||||
try:
|
||||
info = client.hello()
|
||||
results.append({"address": label, "url": url, "ok": True, "error": None, "kind": "ok",
|
||||
"name": info.get("name"), "platform": info.get("platform")})
|
||||
except Unreachable as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "unreachable"})
|
||||
except AuthFailed as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "auth"})
|
||||
except VersionMismatch as ex:
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "version"})
|
||||
except Exception as ex: # noqa: BLE001 — anything else is that address's answer
|
||||
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "other"})
|
||||
finally:
|
||||
client.close()
|
||||
return results
|
||||
@@ -0,0 +1,584 @@
|
||||
"""`RemoteAdapter`: a library held by a Konduktor server, as a `LibraryAdapter`.
|
||||
|
||||
Everything above the adapter layer — routes, export, import, batches, the UI —
|
||||
works on a remote library unchanged, because this IS the adapter: the server
|
||||
holds the native model (`konduktor.server`), and every command travels to it
|
||||
over `remote_protocol`.
|
||||
|
||||
* **The projection is mirrored here.** The server's tracks are fetched once
|
||||
into a local `TrackIndex`, and each command's answer carries the tracks it
|
||||
changed — so filtering, sorting, facets and stats are as instant as on a
|
||||
local library, and use the SAME query code (`core/query.py`). Every answer
|
||||
carries the server's revision; a gap (an answer out of order, a reconnect)
|
||||
re-fetches the whole projection rather than guessing.
|
||||
* **`audio_path` downloads.** It must return a readable file on THIS
|
||||
computer, so it fetches the track into the shared cache (`cache.py`).
|
||||
Anything that only needs to know WHICH file a track is asks `audio_facts`,
|
||||
which never downloads.
|
||||
* **Read-only when the session is not ours** — taken over, or the server out
|
||||
of reach — through `capabilities()`, so the UI gates itself as it does for
|
||||
any read-only library. A command the server refuses for that reason (423)
|
||||
turns the session `taken_over` on the spot, not at the next heartbeat.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AudioFacts,
|
||||
FileTagResult,
|
||||
NotFound,
|
||||
SaveOutcome,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.query import TrackIndex
|
||||
from .cache import RemoteAudioCache, StaleFacts
|
||||
from .cache import shared as shared_cache
|
||||
from .client import RemoteClient, SessionLost
|
||||
from .folder import ServerFile, ServerFiles
|
||||
from .session import RemoteSession
|
||||
|
||||
_NOT_HERE = "A remote library's paths are the server's configuration"
|
||||
|
||||
|
||||
class RemoteAdapter:
|
||||
def __init__(self, client: RemoteClient, session: RemoteSession, hello: dict, *,
|
||||
cache: RemoteAudioCache | None = None):
|
||||
self.platform = hello["platform"]
|
||||
self.path = Path(hello.get("path") or "")
|
||||
self.hello = hello
|
||||
self.client = client
|
||||
self.session = session
|
||||
self.cache = cache or shared_cache()
|
||||
self._index = TrackIndex()
|
||||
self._lock = threading.RLock()
|
||||
self._rev: int | None = None
|
||||
self._caps: tuple[int, Capabilities] | None = None
|
||||
self._facts: dict[str, AudioFacts] = {}
|
||||
#: Server path of an upload → (the local file it came from, its analysis lead).
|
||||
self._uploads: dict[str, tuple[Path, float | None]] = {}
|
||||
#: Content-folder files a listing returned, by their server path.
|
||||
self._listed: dict[str, ServerFile] = {}
|
||||
#: `str(Path(p))` → `p` for every server path this side has turned into
|
||||
#: a `Path` (an upload's target, a listed file): on Windows that
|
||||
#: conversion rewrites the separators, and the server must get its own
|
||||
#: spelling back.
|
||||
self._server_paths: dict[str, str] = {}
|
||||
self._dirty = bool(hello.get("dirty"))
|
||||
self._load()
|
||||
|
||||
# ---- following the server ---------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
envelope = self.client.rpc("tracks")
|
||||
with self._lock:
|
||||
self._index.rebuild(list(envelope["result"]))
|
||||
self._rev = envelope["rev"]
|
||||
self._facts.clear()
|
||||
self._caps = None
|
||||
|
||||
def _apply(self, envelope: dict) -> None:
|
||||
"""Fold a command's answer into the mirror — or re-fetch on any gap."""
|
||||
with self._lock:
|
||||
rev = envelope.get("rev")
|
||||
if envelope.get("reset") or self._rev is None or rev != self._rev + 1:
|
||||
in_order = False
|
||||
else:
|
||||
in_order = True
|
||||
from ...core.model import Track
|
||||
|
||||
removed = set(envelope.get("removed") or [])
|
||||
if removed:
|
||||
self._index.rebuild([t for t in self._index.tracks if t.id not in removed])
|
||||
for raw in envelope.get("changed") or []:
|
||||
track = Track.model_validate(raw)
|
||||
self._index.add(track)
|
||||
self._facts.pop(track.id, None)
|
||||
for track_id in removed:
|
||||
self._facts.pop(track_id, None)
|
||||
self._rev = rev
|
||||
if not in_order:
|
||||
self._load()
|
||||
|
||||
def _call(self, method: str, /, **args):
|
||||
try:
|
||||
envelope = self.client.rpc(method, **args)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
if rp.RPC[method].mutating:
|
||||
self.session.reached()
|
||||
self._apply(envelope)
|
||||
return envelope["result"]
|
||||
|
||||
def refresh(self) -> None:
|
||||
"""Re-read everything from the server (after a restore, a reconnect)."""
|
||||
self._load()
|
||||
|
||||
# ---- identity -----------------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities:
|
||||
with self._lock:
|
||||
cached = self._caps
|
||||
if cached is None or cached[0] != self._rev:
|
||||
try:
|
||||
caps = self._call("capabilities")
|
||||
except Unavailable:
|
||||
# Out of reach: the last answer, read-only (below) — the UI
|
||||
# must still render, and gate every edit.
|
||||
if cached is None:
|
||||
raise
|
||||
caps = cached[1]
|
||||
else:
|
||||
with self._lock:
|
||||
self._caps = (self._rev, caps)
|
||||
else:
|
||||
caps = cached[1]
|
||||
if self.session.writable:
|
||||
return caps
|
||||
return caps.model_copy(update={"writable": False, "readonly_cause": self.session.readonly_cause})
|
||||
|
||||
def reload(self) -> None:
|
||||
# The server is what holds (and drops) the edits — `AppState.discard`
|
||||
# asks it to discard first; this is the mirror following.
|
||||
self._load()
|
||||
|
||||
# ---- read projection (the mirror) -------------------------------------------
|
||||
@property
|
||||
def tracks(self):
|
||||
return self._index.tracks
|
||||
|
||||
def track(self, track_id: str):
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
# ---- read projection (the server) -------------------------------------------
|
||||
def playlist_tree(self):
|
||||
return self._call("playlist_tree")
|
||||
|
||||
def playlist_count(self) -> int:
|
||||
return self._call("playlist_count")
|
||||
|
||||
def playlist_entries(self, node_id: str):
|
||||
return self._call("playlist_entries", node_id=node_id)
|
||||
|
||||
def playlist_tracks(self, node_id: str):
|
||||
entries = self.playlist_entries(node_id)
|
||||
if entries is None:
|
||||
return None
|
||||
return [t for k in entries if (t := self._index.get(k)) is not None]
|
||||
|
||||
def track_cues(self, track_id: str):
|
||||
return self._call("track_cues", track_id=track_id)
|
||||
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
try:
|
||||
self._dirty = self._call("dirty")
|
||||
except Unavailable:
|
||||
pass # out of reach: what it was
|
||||
return self._dirty
|
||||
|
||||
# ---- commands -------------------------------------------------------------------
|
||||
def create_playlist(self, name, parent_id=None):
|
||||
return self._call("create_playlist", name=name, parent_id=parent_id)
|
||||
|
||||
def create_folder(self, name, parent_id=None):
|
||||
return self._call("create_folder", name=name, parent_id=parent_id)
|
||||
|
||||
def rename_playlist(self, node_id, name):
|
||||
return self._call("rename_playlist", node_id=node_id, name=name)
|
||||
|
||||
def delete_playlist(self, node_id):
|
||||
return self._call("delete_playlist", node_id=node_id)
|
||||
|
||||
def move_playlist(self, node_id, parent_id, index):
|
||||
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
|
||||
|
||||
def set_playlist_entries(self, node_id, track_ids):
|
||||
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
|
||||
|
||||
def remove_tracks(self, track_ids):
|
||||
return self._call("remove_tracks", track_ids=list(track_ids))
|
||||
|
||||
def set_track_metadata(self, track_id, fields):
|
||||
return self._call("set_track_metadata", track_id=track_id, fields=fields)
|
||||
|
||||
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)
|
||||
|
||||
def set_cue_type(self, track_id, slot, cue_type):
|
||||
return self._call("set_cue_type", track_id=track_id, slot=slot, cue_type=cue_type)
|
||||
|
||||
def set_cue_color(self, track_id, slot, color):
|
||||
return self._call("set_cue_color", track_id=track_id, slot=slot, color=color)
|
||||
|
||||
def delete_cue(self, track_id, slot):
|
||||
return self._call("delete_cue", track_id=track_id, slot=slot)
|
||||
|
||||
def place_cues(self, track_id, cues, *, overwrite=False):
|
||||
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
|
||||
|
||||
def add_memory_cue(self, track_id, *, start_sec, cue_type, length_sec=0.0, name=None, color=None):
|
||||
return self._call("add_memory_cue", track_id=track_id, start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, name=name, color=color)
|
||||
|
||||
def rename_memory_cue(self, track_id, cue_id, name):
|
||||
return self._call("rename_memory_cue", track_id=track_id, cue_id=cue_id, name=name)
|
||||
|
||||
def set_memory_cue_type(self, track_id, cue_id, cue_type):
|
||||
return self._call("set_memory_cue_type", track_id=track_id, cue_id=cue_id, cue_type=cue_type)
|
||||
|
||||
def set_memory_cue_color(self, track_id, cue_id, color):
|
||||
return self._call("set_memory_cue_color", track_id=track_id, cue_id=cue_id, color=color)
|
||||
|
||||
def delete_memory_cue(self, track_id, cue_id):
|
||||
return self._call("delete_memory_cue", track_id=track_id, cue_id=cue_id)
|
||||
|
||||
def add_grid_marker(self, track_id, start_sec, bpm=None):
|
||||
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
|
||||
|
||||
def move_grid_marker(self, track_id, index, start_sec):
|
||||
return self._call("move_grid_marker", track_id=track_id, index=index, start_sec=start_sec)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id, index, bpm):
|
||||
return self._call("set_grid_marker_bpm", track_id=track_id, index=index, bpm=bpm)
|
||||
|
||||
def delete_grid_marker(self, track_id, index):
|
||||
return self._call("delete_grid_marker", track_id=track_id, index=index)
|
||||
|
||||
def replace_grid(self, track_id, markers):
|
||||
return self._call("replace_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def set_analysed_grid(self, track_id, markers):
|
||||
return self._call("set_analysed_grid", track_id=track_id, markers=_pairs(markers))
|
||||
|
||||
def delete_grid(self, track_id):
|
||||
return self._call("delete_grid", track_id=track_id)
|
||||
|
||||
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
|
||||
taken name gets `-2`…, as a local copy does). What a local import's
|
||||
file copy becomes when the library's destination is the server's."""
|
||||
try:
|
||||
landed = self.client.upload(Path(source), folder, name, progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
|
||||
self._server_paths[str(Path(landed["path"]))] = landed["path"]
|
||||
return Path(landed["path"])
|
||||
|
||||
def free_space(self, path: str) -> int:
|
||||
"""Free space on the SERVER's disk at `path` (an import's destination)."""
|
||||
return self.client.fs_space(path)
|
||||
|
||||
def delete_upload(self, path) -> None:
|
||||
"""Undo `upload_audio` (a cancelled or failed import)."""
|
||||
key = self._server_key(path)
|
||||
self._uploads.pop(key, None)
|
||||
self.client.delete_upload(key)
|
||||
|
||||
def _server_key(self, path) -> str:
|
||||
text = str(path)
|
||||
return self._server_paths.get(text, text)
|
||||
|
||||
def add_tracks(self, items, *, checkpoint=None):
|
||||
"""Add uploaded files. Where the platform analyses what it adds (the
|
||||
server said so with an analysis lead), the analysis is done HERE, on
|
||||
the copy this computer uploaded — the server never decodes audio."""
|
||||
from ...core import add_analysis
|
||||
|
||||
wire = []
|
||||
total = len(items)
|
||||
keys = [self._server_key(item.audio_path) for item in items]
|
||||
# Files already in the content folder (added in place): the server says
|
||||
# whether the platform analyses, and only then is the file fetched.
|
||||
in_place = [k for k, item in zip(keys, items)
|
||||
if item.analysis is None and k not in self._uploads and k in self._listed]
|
||||
leads = self.client.folder_leads(in_place) if in_place else {}
|
||||
for n, (item, key) in enumerate(zip(items, keys), start=1):
|
||||
source, lead = self._uploads.get(key, (None, None))
|
||||
analysis = item.analysis
|
||||
if analysis is None and source is None and leads.get(key) is not None:
|
||||
lead = leads[key]
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
|
||||
source = self.folder_audio(key)
|
||||
if analysis is None and lead is not None and source is not None:
|
||||
if checkpoint is not None:
|
||||
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,
|
||||
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,
|
||||
analysis=rp.pack_analysis(analysis)))
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Adding {total} track{'' if total == 1 else 's'} on the server",
|
||||
step=total, of=total)
|
||||
try:
|
||||
envelope = self.client.rpc("add_tracks", items=wire, timeout=None)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply(envelope)
|
||||
for key in keys:
|
||||
self._uploads.pop(key, None)
|
||||
return envelope["result"]
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
raise Unsupported("A remote library's stem files are swapped in on the server")
|
||||
|
||||
# ---- Convert to Stems (the library side lives on the server) ---------------------
|
||||
# `stems/remote_convert.py` drives these: the server plans and swaps, this
|
||||
# computer separates. See the server's stem routes for why.
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
return self.client.stems_plan(body)
|
||||
|
||||
def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int,
|
||||
duration: float, loudness: dict | 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:
|
||||
return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(),
|
||||
bit_rate=bit_rate, duration=duration, loudness=loudness,
|
||||
progress=progress)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
|
||||
def abandon_stems(self, targets: list[str]) -> None:
|
||||
self.client.stems_abandon(targets)
|
||||
|
||||
def publish_stems(self, items: list[dict], options: dict) -> dict:
|
||||
try:
|
||||
result = self.client.stems_publish(items, options)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
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:
|
||||
envelope = self.client.put_art(track_id, data, mime)
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply({**envelope, "removed": [], "reset": False})
|
||||
|
||||
def cover_art(self, track_id):
|
||||
return self.client.art(track_id)
|
||||
|
||||
# ---- audio ------------------------------------------------------------------------------
|
||||
def audio_facts(self, track_ids):
|
||||
wanted = list(dict.fromkeys(track_ids))
|
||||
with self._lock:
|
||||
missing = [t for t in wanted if t not in self._facts]
|
||||
if missing:
|
||||
found = {}
|
||||
for start in range(0, len(missing), 2000):
|
||||
found.update(self._call("audio_facts", track_ids=missing[start:start + 2000]))
|
||||
with self._lock:
|
||||
self._facts.update(found)
|
||||
with self._lock:
|
||||
return {t: self._facts[t] for t in wanted if t in self._facts}
|
||||
|
||||
def audio_path(self, track_id, *, progress=None):
|
||||
"""A local copy of the track's audio, downloaded if this computer has
|
||||
none of this version. None when the server has no file for it."""
|
||||
for attempt in range(2):
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
if facts is None:
|
||||
return None
|
||||
cached = self.cache.get(facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
facts, lambda partial: self.client.download(track_id, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
with self._lock:
|
||||
self._facts.pop(track_id, None)
|
||||
if attempt:
|
||||
raise
|
||||
return None
|
||||
|
||||
def cached_audio(self, track_id) -> Path | None:
|
||||
"""The local copy if there already is one — never downloads."""
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
return self.cache.get(facts) if facts else None
|
||||
|
||||
# ---- the content folder, browsed --------------------------------------------------
|
||||
def folder_listing(self, path: str | None) -> ServerFiles:
|
||||
"""The audio directly inside a content folder (None: the folder itself),
|
||||
as the server lists it — and remembered, so a file can then be played
|
||||
or added by its path."""
|
||||
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
|
||||
with self._lock:
|
||||
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
|
||||
self._listed.update(listing.files)
|
||||
self._server_paths.update({str(Path(k)): k for k in listing.files})
|
||||
return listing
|
||||
|
||||
def listed_files(self, paths) -> ServerFiles | None:
|
||||
"""The listed files among `paths` as one source (they may come from
|
||||
several folders); None when none of them was listed."""
|
||||
with self._lock:
|
||||
found = [self._listed[p] for p in paths if p in self._listed]
|
||||
return ServerFiles(self, found[0].folder, found) if found else None
|
||||
|
||||
def folder_audio(self, path: str, *, progress=None) -> Path:
|
||||
"""A local copy of a listed file, downloaded into the shared cache —
|
||||
keyed by the same facts as a library track's, so a file that is both
|
||||
downloads once."""
|
||||
for attempt in range(2):
|
||||
with self._lock:
|
||||
found = self._listed.get(path)
|
||||
if found is None:
|
||||
raise NotFound("File not found — browse to its folder first")
|
||||
cached = self.cache.get(found.facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
if attempt:
|
||||
raise
|
||||
self.folder_listing(found.folder) # changed on the server: re-read it
|
||||
raise NotFound(path)
|
||||
|
||||
# ---- paths: the server's business ------------------------------------------------
|
||||
def set_path_mapping(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def set_session_mappings(self, mappings):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def unresolved_path_groups(self):
|
||||
return []
|
||||
|
||||
def path_prefix_suggestions(self):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_preview(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
def remap_locations(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
# ---- save ----------------------------------------------------------------------------
|
||||
def save(self):
|
||||
try:
|
||||
result = self.client.save()
|
||||
except SessionLost as ex:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
outcome = SaveOutcome(
|
||||
summary=result.get("summary") or "",
|
||||
snapshot=None,
|
||||
tag_results=[FileTagResult(**r) for r in result.get("tag_results") or []],
|
||||
)
|
||||
# Versioned on the server; `RemoteServices.commit_save` hands it on.
|
||||
outcome.commit = result.get("commit")
|
||||
self._load()
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
raise Unsupported("A remote library's version history is kept on the server")
|
||||
|
||||
def close(self) -> None:
|
||||
self.session.stop()
|
||||
self.client.release()
|
||||
self.client.close()
|
||||
|
||||
|
||||
def _pairs(markers) -> list[tuple[float, float]]:
|
||||
out = []
|
||||
for m in markers:
|
||||
if hasattr(m, "start"):
|
||||
out.append((float(m.start), float(m.bpm)))
|
||||
else:
|
||||
start, bpm = m
|
||||
out.append((float(start), float(bpm)))
|
||||
return out
|
||||
@@ -0,0 +1,194 @@
|
||||
"""This computer's copies of a remote library's audio.
|
||||
|
||||
Everything that needs a track's audio as a FILE runs here, not on the server —
|
||||
the deck's decode, grid and cue analysis, stem separation and extraction, an
|
||||
export's copy onto a stick. One cache serves them all, so a track analysed and
|
||||
then exported downloads once.
|
||||
|
||||
* **Keyed by what the server says the file IS** — its path there, size and
|
||||
mtime (`AudioFacts`) — never by when it was fetched: an edited file (Save
|
||||
writes tags into it) is a new entry, and the same file fetched again after
|
||||
an eviction, or by another computer exporting the same set, is recognised.
|
||||
* **A partial, renamed into place**, so a cut connection never leaves a
|
||||
truncated file under a real entry's name, and a download whose size does
|
||||
not match the facts is refused rather than kept.
|
||||
* **Least recently used, under a cap** (`remoteCacheBytes` in prefs). The
|
||||
entry just written and anything touched in the last few minutes are never
|
||||
the ones evicted: they are being played or copied right now.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from ... import paths, prefs
|
||||
from ...core.adapter import AudioFacts, Unavailable
|
||||
|
||||
DEFAULT_CAP = 10 * 1024 ** 3
|
||||
_RECENT = 300.0 # seconds: an entry touched this recently is in use
|
||||
_PART = ".part"
|
||||
|
||||
|
||||
class StaleFacts(Unavailable):
|
||||
"""The server's file changed between asking about it and downloading it."""
|
||||
|
||||
|
||||
def cache_root() -> Path:
|
||||
return paths.app_data_dir() / "remote-cache"
|
||||
|
||||
|
||||
def cap_bytes() -> int:
|
||||
try:
|
||||
value = int(prefs.load_prefs().get("remoteCacheBytes") or DEFAULT_CAP)
|
||||
except (TypeError, ValueError):
|
||||
value = DEFAULT_CAP
|
||||
return max(value, 256 * 1024 ** 2)
|
||||
|
||||
|
||||
class RemoteAudioCache:
|
||||
def __init__(self, root: Path | None = None, *, cap=None, clock=time.time):
|
||||
self.root = Path(root) if root is not None else cache_root()
|
||||
self._cap = cap if cap is not None else cap_bytes
|
||||
self._clock = clock
|
||||
self._locks: dict[str, threading.Lock] = {}
|
||||
self._guard = threading.Lock()
|
||||
#: Recent download speeds (bytes/s), newest last — for time estimates.
|
||||
self._speeds: list[float] = []
|
||||
|
||||
# ---- naming ----------------------------------------------------------------
|
||||
@staticmethod
|
||||
def key(facts: AudioFacts) -> str:
|
||||
text = f"{facts.key}|{facts.size}|{facts.mtime_ns}"
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:32]
|
||||
|
||||
def path_for(self, facts: AudioFacts) -> Path:
|
||||
# The original's suffix, so a MIME type and a decoder's guess still work.
|
||||
suffix = Path(facts.key.replace("\\", "/")).suffix.lower()
|
||||
return self.root / f"{self.key(facts)}{suffix}"
|
||||
|
||||
def _lock_for(self, key: str) -> threading.Lock:
|
||||
with self._guard:
|
||||
return self._locks.setdefault(key, threading.Lock())
|
||||
|
||||
# ---- use -------------------------------------------------------------------
|
||||
def get(self, facts: AudioFacts) -> Path | None:
|
||||
path = self.path_for(facts)
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
return None
|
||||
|
||||
def fetch(self, facts: AudioFacts, download) -> Path:
|
||||
"""The cached copy, downloading it first if needed. `download(partial)`
|
||||
writes the file and returns the server's `{size, mtime_ns}` for it."""
|
||||
path = self.path_for(facts)
|
||||
with self._lock_for(path.name):
|
||||
if path.is_file():
|
||||
self._touch(path)
|
||||
return path
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
partial = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}{_PART}")
|
||||
started = time.monotonic()
|
||||
try:
|
||||
meta = download(partial) or {}
|
||||
got = partial.stat().st_size
|
||||
if got != facts.size or (meta.get("size") and meta["size"] != facts.size):
|
||||
raise StaleFacts(f"{Path(facts.key).name} changed on the server while downloading")
|
||||
os.replace(partial, path)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
elapsed = max(time.monotonic() - started, 1e-3)
|
||||
if facts.size > 1 << 20:
|
||||
self._speeds = (self._speeds + [facts.size / elapsed])[-8:]
|
||||
self._touch(path)
|
||||
self.prune(keep={path})
|
||||
return path
|
||||
|
||||
def speed(self) -> float | None:
|
||||
"""A recent download speed in bytes/s, or None before the first."""
|
||||
if not self._speeds:
|
||||
return None
|
||||
ordered = sorted(self._speeds)
|
||||
return ordered[len(ordered) // 2]
|
||||
|
||||
def _touch(self, path: Path) -> None:
|
||||
now = self._clock()
|
||||
try:
|
||||
os.utime(path, (now, now))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ---- housekeeping ------------------------------------------------------------
|
||||
def _entries(self) -> list[tuple[float, int, Path]]:
|
||||
out = []
|
||||
if not self.root.is_dir():
|
||||
return out
|
||||
for p in self.root.iterdir():
|
||||
if p.name.endswith(_PART) or not p.is_file():
|
||||
continue
|
||||
try:
|
||||
st = p.stat()
|
||||
except OSError:
|
||||
continue
|
||||
out.append((st.st_mtime, st.st_size, p))
|
||||
return out
|
||||
|
||||
def prune(self, keep: set[Path] | None = None) -> int:
|
||||
"""Evict least-recently-used entries until under the cap. Returns bytes freed."""
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
entries = sorted(self._entries())
|
||||
total = sum(size for _, size, _ in entries)
|
||||
freed = 0
|
||||
now = self._clock()
|
||||
for used, size, p in entries:
|
||||
if total <= cap:
|
||||
break
|
||||
if (keep and p in keep) or now - used < _RECENT:
|
||||
continue
|
||||
try:
|
||||
p.unlink()
|
||||
except OSError:
|
||||
continue # held open (Windows): next time
|
||||
total -= size
|
||||
freed += size
|
||||
return freed
|
||||
|
||||
def usage(self) -> dict:
|
||||
entries = self._entries()
|
||||
cap = self._cap() if callable(self._cap) else self._cap
|
||||
return {"bytes": sum(s for _, s, _ in entries), "files": len(entries), "cap": cap,
|
||||
"free": _free(self.root)}
|
||||
|
||||
def clear(self) -> int:
|
||||
freed = 0
|
||||
for _, size, p in self._entries():
|
||||
try:
|
||||
p.unlink()
|
||||
freed += size
|
||||
except OSError:
|
||||
pass
|
||||
return freed
|
||||
|
||||
|
||||
def _free(folder: Path) -> int:
|
||||
probe = folder
|
||||
while not probe.exists() and probe != probe.parent:
|
||||
probe = probe.parent
|
||||
try:
|
||||
return shutil.disk_usage(probe).free
|
||||
except OSError:
|
||||
return 0
|
||||
|
||||
|
||||
_shared: RemoteAudioCache | None = None
|
||||
|
||||
|
||||
def shared() -> RemoteAudioCache:
|
||||
global _shared
|
||||
if _shared is None:
|
||||
_shared = RemoteAudioCache()
|
||||
return _shared
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Talking to a Konduktor server: addresses, sign-in, and the error vocabulary.
|
||||
|
||||
Every request tries the address that last worked, then the others in the
|
||||
remote's order (primary, then fallback) — so a laptop that leaves the house
|
||||
moves from the LAN address to the VPN one without being asked, and back again.
|
||||
Only a CONNECT failure moves on: the request never reached that server, so
|
||||
sending it to the other one cannot apply it twice. A request that reached a
|
||||
server and then failed is that server's answer.
|
||||
|
||||
The server's refusals come back as the adapter's own error classes (the same
|
||||
status codes `main.py` maps them from), so a route on this computer reports a
|
||||
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
|
||||
|
||||
import httpx
|
||||
|
||||
from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AdapterError,
|
||||
InvalidCommand,
|
||||
LibraryNotSupported,
|
||||
NotFound,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
)
|
||||
from .config import Remote
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
|
||||
|
||||
|
||||
class Unreachable(Unavailable):
|
||||
"""No address of the remote answered."""
|
||||
|
||||
|
||||
class AuthFailed(LibraryNotSupported):
|
||||
"""The server refused the username or password."""
|
||||
|
||||
|
||||
class VersionMismatch(LibraryNotSupported):
|
||||
def __init__(self, update: str, server_version: str):
|
||||
side = "Konduktor on this computer" if update == "app" else "the Konduktor server"
|
||||
super().__init__(
|
||||
f"This server speaks a different version of Konduktor's protocol "
|
||||
f"(server {server_version}): update {side}."
|
||||
)
|
||||
self.update = update
|
||||
|
||||
|
||||
class InUse(AdapterError):
|
||||
"""Another computer holds the session: `holder` = {machine, since, batch}."""
|
||||
|
||||
def __init__(self, holder: dict):
|
||||
super().__init__(f"In use by {holder.get('machine') or 'another computer'}")
|
||||
self.holder = holder
|
||||
|
||||
|
||||
class SessionLost(Unavailable):
|
||||
"""This computer no longer holds the session (another one took over)."""
|
||||
|
||||
def __init__(self, holder: dict | None):
|
||||
who = (holder or {}).get("machine")
|
||||
super().__init__(
|
||||
f"{who} has taken over this library — it is read-only here" if who
|
||||
else "This computer no longer holds the library's session"
|
||||
)
|
||||
self.holder = holder
|
||||
|
||||
|
||||
def _detail(response: httpx.Response):
|
||||
try:
|
||||
return response.json().get("detail")
|
||||
except Exception: # noqa: BLE001
|
||||
return response.text[:300]
|
||||
|
||||
|
||||
class RemoteClient:
|
||||
def __init__(self, remote: Remote, password: str, *, timeout: float = 30.0):
|
||||
self.remote = remote
|
||||
self._addresses = remote.addresses()
|
||||
self._active: int | None = None
|
||||
self.token: str | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._http = httpx.Client(
|
||||
auth=(remote.username, password),
|
||||
timeout=httpx.Timeout(timeout, connect=4.0),
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self._http.close()
|
||||
|
||||
@property
|
||||
def via(self) -> str | None:
|
||||
"""Which address is in use: "primary" / "fallback" (None until one answers)."""
|
||||
return None if self._active is None else self._addresses[self._active][0]
|
||||
|
||||
# ---- transport ----------------------------------------------------------------
|
||||
def _order(self) -> list[int]:
|
||||
everything = list(range(len(self._addresses)))
|
||||
if self._active is None:
|
||||
return everything
|
||||
return [self._active] + [i for i in everything if i != self._active]
|
||||
|
||||
def request(self, method: str, path: str, *, retry: bool = True, session: bool = True,
|
||||
**kw) -> httpx.Response:
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if session and self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
order = self._order() if retry else ([self._active] if self._active is not None else [0])
|
||||
last: Exception | None = None
|
||||
for i in order:
|
||||
base = self._addresses[i][1]
|
||||
try:
|
||||
response = self._http.request(method, base + path, headers=headers, **kw)
|
||||
except _CONNECT_ERRORS as ex:
|
||||
last = ex
|
||||
continue
|
||||
except httpx.TimeoutException as ex:
|
||||
self._active = i
|
||||
raise Unreachable(f"The server at {base} stopped answering") from ex
|
||||
except httpx.TransportError as ex:
|
||||
last = ex
|
||||
continue
|
||||
self._active = i
|
||||
return self.check(response)
|
||||
names = " or ".join(b for _, b in (self._addresses[i] for i in order))
|
||||
raise Unreachable(f"Cannot reach the server at {names}") from last
|
||||
|
||||
def stream(self, method: str, path: str, **kw):
|
||||
"""A streaming request on the address in use (a download)."""
|
||||
headers = dict(kw.pop("headers", None) or {})
|
||||
if self.token:
|
||||
headers[rp.SESSION_HEADER] = self.token
|
||||
# Pick the address first with a cheap call, so the stream itself is not
|
||||
# the request that discovers the primary is gone.
|
||||
if self._active is None:
|
||||
self.request("GET", "/v1/hello", session=False)
|
||||
base = self._addresses[self._active][1]
|
||||
return self._http.stream(method, base + path, headers=headers, **kw)
|
||||
|
||||
@staticmethod
|
||||
def check(response: httpx.Response) -> httpx.Response:
|
||||
status = response.status_code
|
||||
if status < 400:
|
||||
return response
|
||||
detail = _detail(response)
|
||||
if status == 401:
|
||||
raise AuthFailed("The server refused the username or password")
|
||||
if status == 423:
|
||||
raise SessionLost((detail or {}).get("holder") if isinstance(detail, dict) else None)
|
||||
if status == 409 and isinstance(detail, dict) and detail.get("code") == "in_use":
|
||||
raise InUse(detail)
|
||||
text = detail if isinstance(detail, str) else (detail or {}).get("message", str(detail))
|
||||
cls = {404: NotFound, 400: InvalidCommand, 422: Unsupported, 503: Unavailable}.get(status)
|
||||
if cls is not None:
|
||||
raise cls(text)
|
||||
raise AdapterError(f"The server answered {status}: {text}")
|
||||
|
||||
# ---- handshake + session ----------------------------------------------------------
|
||||
def hello(self, client_id: str | None = None) -> dict:
|
||||
info = self.request("GET", "/v1/hello", params={"client_id": client_id} if client_id else None,
|
||||
session=False).json()
|
||||
server_version = tuple(info.get("api_version") or (0, 0))
|
||||
update = rp.compatible(rp.API_VERSION, (int(server_version[0]), int(server_version[1])))
|
||||
if update:
|
||||
raise VersionMismatch(update, info.get("app_version") or ".".join(map(str, server_version)))
|
||||
return info
|
||||
|
||||
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> dict:
|
||||
body = self.request("POST", "/v1/session/acquire", session=False,
|
||||
json={"client_id": client_id, "machine": machine, "takeover": takeover}).json()
|
||||
self.token = body["token"]
|
||||
return body
|
||||
|
||||
def heartbeat(self, batch: str | None) -> dict:
|
||||
return self.request("POST", "/v1/session/heartbeat", json={"batch": batch}).json()
|
||||
|
||||
def release(self, *, timeout: float | None = None) -> None:
|
||||
if not self.token:
|
||||
return
|
||||
try:
|
||||
kw = {"timeout": timeout} if timeout is not None else {}
|
||||
self.request("POST", "/v1/session/release", retry=False, **kw)
|
||||
except AdapterError:
|
||||
pass
|
||||
self.token = None
|
||||
|
||||
# ---- the protocol -------------------------------------------------------------------
|
||||
def rpc(self, method: str, /, *, timeout=..., **args) -> dict:
|
||||
"""Call one protocol method; the envelope `{result, rev, changed, removed, reset}`
|
||||
with `result` already deserialised."""
|
||||
kw = {} if timeout is ... else {"timeout": timeout}
|
||||
body = self.request("POST", f"/v1/rpc/{method}", json={"args": rp.dump_args(method, args)}, **kw).json()
|
||||
body["result"] = rp.load_result(method, body.get("result"))
|
||||
return body
|
||||
|
||||
# ---- bytes -----------------------------------------------------------------------------
|
||||
def download(self, track_id: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a track's audio into `target`; its server-side size and mtime."""
|
||||
with self.stream("GET", "/v1/audio", params={"track_id": track_id}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def upload(self, source: Path, folder: str, name: str, *, 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("POST", "/v1/upload", params={"dir": folder, "name": name},
|
||||
content=body(), retry=False, timeout=None).json()
|
||||
|
||||
def delete_upload(self, path: str) -> None:
|
||||
self.request("DELETE", "/v1/upload", params={"path": path})
|
||||
|
||||
def art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
try:
|
||||
r = self.request("GET", "/v1/art", params={"track_id": track_id})
|
||||
except NotFound:
|
||||
return None
|
||||
return r.content, r.headers.get("content-type", "image/jpeg").split(";")[0]
|
||||
|
||||
def put_art(self, track_id: str, data: bytes, mime: str) -> dict:
|
||||
return self.request("PUT", "/v1/art", params={"track_id": track_id, "mime": mime},
|
||||
content=data).json()
|
||||
|
||||
def fs_list(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
|
||||
|
||||
def folder_tracks(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
|
||||
timeout=None).json()
|
||||
|
||||
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
|
||||
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
|
||||
|
||||
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a listed content-folder file into `target` (as `download`)."""
|
||||
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def fs_space(self, path: str | None) -> int:
|
||||
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
|
||||
|
||||
# ---- Convert to Stems ----------------------------------------------------------------
|
||||
def stems_plan(self, body: dict) -> dict:
|
||||
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, loudness: dict | None = None, 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/stems/stage",
|
||||
params={"track_id": track_id, "target": target, "sha256": sha256,
|
||||
"bit_rate": bit_rate, "duration": duration,
|
||||
**({"loudness": json.dumps(loudness)} if loudness else {})},
|
||||
content=body(), retry=False, timeout=None,
|
||||
).json()
|
||||
|
||||
def stems_abandon(self, targets: list[str]) -> None:
|
||||
self.request("POST", "/v1/stems/abandon", json={"targets": targets})
|
||||
|
||||
def stems_publish(self, items: list[dict], options: dict) -> dict:
|
||||
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()
|
||||
|
||||
# ---- save / history / export sets -------------------------------------------------
|
||||
def save(self) -> dict:
|
||||
return self.request("POST", "/v1/save", timeout=None).json()
|
||||
|
||||
def discard(self) -> dict:
|
||||
return self.request("POST", "/v1/discard", timeout=None).json()
|
||||
|
||||
def history(self) -> list[dict]:
|
||||
return self.request("GET", "/v1/history").json()
|
||||
|
||||
def restore(self, commit_id: str) -> dict:
|
||||
return self.request("POST", f"/v1/history/{commit_id}/restore", timeout=None).json()
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.request("DELETE", "/v1/history")
|
||||
|
||||
def export_sets(self) -> dict:
|
||||
return self.request("GET", "/v1/export-sets").json()
|
||||
|
||||
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})
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Saved remotes: the servers this computer knows how to reach.
|
||||
|
||||
A remote is where a Konduktor server is (an address, an optional port, and a
|
||||
fallback address — typically the LAN address first and a VPN one second) and
|
||||
who to sign in as. Everything but the password is a plain preference
|
||||
(`userprefs.json`, key `remotes`); the password lives in the OS keychain
|
||||
(macOS Keychain, Windows Credential Manager) through `keyring`, never in a JSON
|
||||
file beside the app's other data.
|
||||
|
||||
This computer also has a stable `client_id`, which is how a server tells "the
|
||||
same laptop back from sleep" (renew its session silently) from "another
|
||||
computer" (offer a takeover).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
from ... import prefs
|
||||
|
||||
DEFAULT_PORT = 8765
|
||||
_PREFS_KEY = "remotes"
|
||||
_CLIENT_KEY = "remoteClientId"
|
||||
_KEYRING_SERVICE = "Konduktor"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Remote:
|
||||
id: str
|
||||
name: str
|
||||
host: str
|
||||
port: int | None = None
|
||||
fallback_host: str | None = None
|
||||
fallback_port: int | None = None
|
||||
username: str = ""
|
||||
|
||||
def addresses(self) -> list[tuple[str, str]]:
|
||||
"""`(label, base url)`, primary first — the order every connect tries.
|
||||
|
||||
Each address keeps its OWN port. The fallback once borrowed the
|
||||
primary's, so a reverse-proxied fallback (`konduktor.example.net`,
|
||||
served on 443) was tried at `:8765` because the LAN address named it.
|
||||
"""
|
||||
out = [("primary", _base(self.host, self.port))]
|
||||
if self.fallback_host:
|
||||
out.append(("fallback", _base(self.fallback_host, self.fallback_port)))
|
||||
return out
|
||||
|
||||
def public(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _base(host: str, port: int | None) -> str:
|
||||
"""An address as typed → a base URL. A full URL (`https://…`, the way to
|
||||
reach a server behind the user's own reverse proxy) is taken exactly as
|
||||
given, port and all; anything else is plain HTTP on its port, else 8765."""
|
||||
host = host.strip()
|
||||
if host.startswith("http://") or host.startswith("https://"):
|
||||
return host.rstrip("/")
|
||||
bare, inline = split_host(host)
|
||||
if inline is not None:
|
||||
host, port = bare, port or inline
|
||||
if ":" in host and not host.startswith("["):
|
||||
host = f"[{host}]" # an IPv6 literal
|
||||
return f"http://{host}:{port or DEFAULT_PORT}"
|
||||
|
||||
|
||||
def split_host(text: str) -> tuple[str, int | None]:
|
||||
"""`"nas.local:9000"` → `("nas.local", 9000)`; a bare host keeps no port."""
|
||||
text = (text or "").strip()
|
||||
if text.startswith("http://") or text.startswith("https://"):
|
||||
return text, None
|
||||
if text.count(":") == 1:
|
||||
host, _, port = text.partition(":")
|
||||
if port.isdigit():
|
||||
return host, int(port)
|
||||
return text, None
|
||||
|
||||
|
||||
# ---- the list ------------------------------------------------------------------
|
||||
|
||||
|
||||
def remotes() -> list[Remote]:
|
||||
raw = prefs.load_prefs().get(_PREFS_KEY) or []
|
||||
out = []
|
||||
for item in raw if isinstance(raw, list) else []:
|
||||
try:
|
||||
out.append(Remote(**{k: item.get(k) for k in Remote.__dataclass_fields__ if k in item}))
|
||||
except TypeError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def get(remote_id: str) -> Remote | None:
|
||||
return next((r for r in remotes() if r.id == remote_id), None)
|
||||
|
||||
|
||||
def save(remote: Remote) -> Remote:
|
||||
items = [r for r in remotes() if r.id != remote.id] + [remote]
|
||||
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
|
||||
return remote
|
||||
|
||||
|
||||
def delete(remote_id: str) -> bool:
|
||||
before = remotes()
|
||||
items = [r for r in before if r.id != remote_id]
|
||||
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
|
||||
forget_password(remote_id)
|
||||
return len(items) != len(before)
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
# ---- this computer ---------------------------------------------------------------
|
||||
|
||||
|
||||
def client_id() -> str:
|
||||
current = prefs.load_prefs().get(_CLIENT_KEY)
|
||||
if isinstance(current, str) and current:
|
||||
return current
|
||||
fresh = uuid.uuid4().hex
|
||||
prefs.update_prefs({_CLIENT_KEY: fresh})
|
||||
return fresh
|
||||
|
||||
|
||||
def machine_name() -> str:
|
||||
"""What another computer is told holds the library ("Ben's MacBook")."""
|
||||
try:
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
if sys.platform == "darwin":
|
||||
name = subprocess.run(["scutil", "--get", "ComputerName"], capture_output=True,
|
||||
text=True, timeout=2).stdout.strip()
|
||||
if name:
|
||||
return name
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
name = socket.gethostname()
|
||||
return name[:-6] if name.endswith(".local") else name
|
||||
|
||||
|
||||
# ---- the password ------------------------------------------------------------------
|
||||
# A seam for tests (and any machine without a keychain): `use_password_store`.
|
||||
|
||||
|
||||
class _Keyring:
|
||||
def get(self, account: str) -> str | None:
|
||||
import keyring
|
||||
|
||||
return keyring.get_password(_KEYRING_SERVICE, account)
|
||||
|
||||
def set(self, account: str, password: str) -> None:
|
||||
import keyring
|
||||
|
||||
keyring.set_password(_KEYRING_SERVICE, account, password)
|
||||
|
||||
def delete(self, account: str) -> None:
|
||||
import keyring
|
||||
from keyring.errors import PasswordDeleteError
|
||||
|
||||
try:
|
||||
keyring.delete_password(_KEYRING_SERVICE, account)
|
||||
except PasswordDeleteError:
|
||||
pass
|
||||
|
||||
|
||||
_store = _Keyring()
|
||||
|
||||
|
||||
def use_password_store(store) -> None:
|
||||
"""Replace the keychain (`get`/`set`/`delete` by account) — tests only."""
|
||||
global _store
|
||||
_store = store if store is not None else _Keyring()
|
||||
|
||||
|
||||
def _account(remote_id: str) -> str:
|
||||
return f"remote:{remote_id}"
|
||||
|
||||
|
||||
def password(remote_id: str) -> str | None:
|
||||
try:
|
||||
return _store.get(_account(remote_id))
|
||||
except Exception: # noqa: BLE001 — a locked keychain reads as "no password"
|
||||
return None
|
||||
|
||||
|
||||
def set_password(remote_id: str, value: str) -> None:
|
||||
_store.set(_account(remote_id), value)
|
||||
|
||||
|
||||
def forget_password(remote_id: str) -> None:
|
||||
try:
|
||||
_store.delete(_account(remote_id))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1,102 @@
|
||||
"""The server's content folder, browsed from this computer like a drive.
|
||||
|
||||
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
|
||||
remote library the music lives in the server's content folder, which this
|
||||
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
|
||||
facts, and which files the library already holds) and this module holds the
|
||||
answer as a read-only SOURCE, the shape the table, the deck and the importer
|
||||
already read.
|
||||
|
||||
Adding one of these files never uploads anything: it is already where the
|
||||
library can reach it, so it is added IN PLACE (`on_library_host`), and the
|
||||
importer skips both the copy and the copy-or-reference question.
|
||||
|
||||
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
|
||||
until the importer needs one, because a server path is not a path here (on a
|
||||
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import AudioFacts
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerFile:
|
||||
folder: str
|
||||
track: Track
|
||||
facts: AudioFacts
|
||||
#: The library's id for this file, when it already points at it.
|
||||
held: str | None = None
|
||||
|
||||
|
||||
class ServerFiles:
|
||||
"""Files in the content folder, as the read half of a source."""
|
||||
|
||||
#: The importer's cue that these are already on the machine holding the
|
||||
#: library: added where they are, neither copied nor uploaded.
|
||||
on_library_host = True
|
||||
|
||||
def __init__(self, adapter, path: str, files: list[ServerFile]):
|
||||
self.adapter = adapter
|
||||
self.path = path
|
||||
self._files = {f.track.id: f for f in files}
|
||||
|
||||
@classmethod
|
||||
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
|
||||
folder = body["path"]
|
||||
facts = body.get("files") or {}
|
||||
held = body.get("held") or {}
|
||||
files = []
|
||||
for raw in body.get("tracks") or []:
|
||||
track = Track.model_validate(raw)
|
||||
fact = facts.get(track.id)
|
||||
if fact is None:
|
||||
continue
|
||||
files.append(ServerFile(
|
||||
folder=folder, track=track,
|
||||
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
|
||||
held=held.get(track.id),
|
||||
))
|
||||
return cls(adapter, folder, files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, ServerFile]:
|
||||
return self._files
|
||||
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return [f.track for f in self._files.values()]
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.track if found else None
|
||||
|
||||
def held(self, track_id: str) -> str | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.held if found else None
|
||||
|
||||
def size(self, track_id: str) -> int:
|
||||
found = self._files.get(track_id)
|
||||
return found.facts.size if found else 0
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
|
||||
|
||||
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
|
||||
return {t: self._files[t].facts for t in track_ids if t in self._files}
|
||||
|
||||
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
|
||||
"""A local copy (downloaded into the shared cache, like a library track)."""
|
||||
if track_id not in self._files:
|
||||
return None
|
||||
return self.adapter.folder_audio(track_id, progress=progress)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
return None
|
||||
@@ -0,0 +1,130 @@
|
||||
"""A remote library's app-level bookkeeping — kept on the server, beside it.
|
||||
|
||||
Version history, export sets and the stems ledger belong with the library, not
|
||||
with whichever computer opened it: they are what every computer that opens it
|
||||
should see. So for a remote library these are calls to the server, and this
|
||||
computer's app-data holds none of them (`services.py` is the local half).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.adapter import NotFound
|
||||
from ...history import HistoryEntry
|
||||
from .client import RemoteClient, SessionLost
|
||||
|
||||
|
||||
class RemoteServices:
|
||||
remote = True
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def baseline(self) -> None:
|
||||
pass # the server records its own "as I found it" version when it opens
|
||||
|
||||
def commit_save(self, adapter, outcome) -> str | None:
|
||||
# The server versioned the save itself; its commit rides on the outcome.
|
||||
return getattr(outcome, "commit", None)
|
||||
|
||||
def history(self) -> list[HistoryEntry]:
|
||||
return [HistoryEntry(**e) for e in self.client.history()]
|
||||
|
||||
def restore(self, commit_id: str) -> bool:
|
||||
try:
|
||||
self.client.restore(commit_id)
|
||||
except NotFound:
|
||||
return False
|
||||
return True
|
||||
|
||||
def clear_history(self) -> None:
|
||||
self.client.clear_history()
|
||||
|
||||
def discard(self) -> None:
|
||||
self.client.discard()
|
||||
|
||||
|
||||
class RemoteSetStore:
|
||||
"""`exports.use_store`'s store for a remote library: its sets, on the server."""
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def read(self) -> dict:
|
||||
return self.client.export_sets()
|
||||
|
||||
def write(self, doc: dict) -> None:
|
||||
self.client.put_export_sets(doc)
|
||||
|
||||
|
||||
class RemotePending:
|
||||
"""`AppState.pending` for a remote library: the SERVER keeps the ledger of
|
||||
converted tracks awaiting Save (and commits, restores and recovers it
|
||||
itself), so on this computer there is nothing to commit or restore — only
|
||||
the server's summary to report, and its "blocking" to honour."""
|
||||
|
||||
items: list = []
|
||||
|
||||
def __init__(self, client: RemoteClient):
|
||||
self.client = client
|
||||
|
||||
def summary(self) -> dict:
|
||||
try:
|
||||
return self.client.stems_pending()
|
||||
except Exception: # noqa: BLE001 — out of reach: nothing known to be pending
|
||||
return {"tracks": 0, "parked": 0, "bytes": 0}
|
||||
|
||||
def blocking(self) -> bool:
|
||||
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 []
|
||||
|
||||
def restore(self) -> int:
|
||||
return 0
|
||||
|
||||
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
|
||||
@@ -0,0 +1,159 @@
|
||||
"""This computer's hold on a remote library's session.
|
||||
|
||||
The server lets ONE computer edit at a time (`server/session.py`); this keeps
|
||||
this computer's hold alive with a heartbeat every `HEARTBEAT_SECONDS`, and is
|
||||
the one place that knows how this computer stands:
|
||||
|
||||
connected — holding the session; edits go through
|
||||
reconnecting — a heartbeat failed to reach the server; edits still try
|
||||
(each request walks the addresses again)
|
||||
offline — several in a row failed; read-only until one gets through
|
||||
taken_over — another computer took the session; read-only, for good
|
||||
|
||||
Coming back from `reconnecting` or `offline` needs no new sign-in: the server
|
||||
renews a lapsed lease for the computer that held it, as long as nobody else
|
||||
has taken it meanwhile — and says so (423) if somebody has.
|
||||
|
||||
The heartbeat names the batch running here, so a computer asking to take over
|
||||
is told what it would cancel. Being taken over cancels it (`on_change`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from ...core.adapter import Unavailable
|
||||
from ...remote_protocol import HEARTBEAT_SECONDS
|
||||
from .client import RemoteClient, SessionLost
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: Missed heartbeats in a row before `reconnecting` becomes `offline`.
|
||||
OFFLINE_AFTER = 3
|
||||
|
||||
|
||||
class RemoteSession:
|
||||
def __init__(self, client: RemoteClient, *, batch_probe=None, interval: float = HEARTBEAT_SECONDS,
|
||||
identity: tuple[str, str] | None = None):
|
||||
self.client = client
|
||||
self.interval = interval
|
||||
self._batch_probe = batch_probe or (lambda: None)
|
||||
#: (client_id, machine) — to take the session back when the server has
|
||||
#: forgotten it (a restart) and nobody else holds it.
|
||||
self.identity = identity
|
||||
self.state = "connected"
|
||||
self.machine: str | None = None # who took it over
|
||||
#: The last thing worth telling the user that is not a state ("the
|
||||
#: server restarted"), with a counter so the UI shows each once.
|
||||
self.notice: str | None = None
|
||||
self.notices = 0
|
||||
#: Called after the session was taken back: the library must be re-read.
|
||||
self.on_reacquired = None
|
||||
self._failures = 0
|
||||
self._listeners: list = []
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# ---- facts ---------------------------------------------------------------------
|
||||
@property
|
||||
def writable(self) -> bool:
|
||||
return self.state in ("connected", "reconnecting")
|
||||
|
||||
@property
|
||||
def readonly_cause(self) -> str | None:
|
||||
return {"taken_over": "taken_over", "offline": "offline"}.get(self.state)
|
||||
|
||||
def describe(self) -> dict:
|
||||
return {"state": self.state, "via": self.client.via if self.state != "offline" else None,
|
||||
"machine": self.machine, "notice": self.notice, "notices": self.notices}
|
||||
|
||||
def on_change(self, listener) -> None:
|
||||
"""`listener(state)` after every change of state (from the heartbeat thread)."""
|
||||
self._listeners.append(listener)
|
||||
|
||||
# ---- running -------------------------------------------------------------------
|
||||
def start(self) -> None:
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, name="konduktor-remote-heartbeat",
|
||||
daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.wait(self.interval):
|
||||
if self.state == "taken_over":
|
||||
return
|
||||
self.beat()
|
||||
|
||||
def beat(self) -> None:
|
||||
try:
|
||||
self.client.heartbeat(self._batch_probe())
|
||||
except SessionLost as ex:
|
||||
self.lost(ex.holder)
|
||||
return
|
||||
except Unavailable:
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
except Exception: # noqa: BLE001 — a bad answer is a missed beat, not a crash
|
||||
log.exception("heartbeat failed")
|
||||
self._failures += 1
|
||||
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
|
||||
return
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _take_back(self) -> bool:
|
||||
"""The server no longer knows this computer's token and nobody holds the
|
||||
session — it restarted (unsaved edits went with it, an accepted loss).
|
||||
Take the session back without asking, unless the library now holds
|
||||
someone ELSE's unsaved edits: those deserve the Save / Discard question
|
||||
that reopening asks, so then this stays read-only."""
|
||||
if self.identity is None:
|
||||
return False
|
||||
try:
|
||||
got = self.client.acquire(*self.identity)
|
||||
except Exception: # noqa: BLE001 — someone got there first, or no server
|
||||
return False
|
||||
if got.get("pending_edits"):
|
||||
self.client.release()
|
||||
return False
|
||||
if self.on_reacquired is not None:
|
||||
try:
|
||||
self.on_reacquired()
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("re-reading the library after a reconnect failed")
|
||||
self.notice = "The server restarted — any edits not yet saved there were lost"
|
||||
self.notices += 1
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
return True
|
||||
|
||||
def lost(self, holder: dict | None) -> None:
|
||||
"""Another computer holds the session — from a heartbeat, or a command
|
||||
the server refused with 423. Nobody holding it means the server forgot
|
||||
this computer's token (a restart): take it back if that is safe."""
|
||||
if holder is None and self.state != "taken_over" and self._take_back():
|
||||
return
|
||||
self.machine = (holder or {}).get("machine")
|
||||
self._set("taken_over")
|
||||
|
||||
def reached(self) -> None:
|
||||
"""A request got through: whatever the heartbeat last saw, the server is there."""
|
||||
if self.state in ("reconnecting", "offline"):
|
||||
self._failures = 0
|
||||
self._set("connected")
|
||||
|
||||
def _set(self, state: str) -> None:
|
||||
with self._lock:
|
||||
if state == self.state:
|
||||
return
|
||||
self.state = state
|
||||
for listener in list(self._listeners):
|
||||
try:
|
||||
listener(state)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("remote session listener failed")
|
||||
@@ -15,7 +15,7 @@ from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
@@ -131,6 +131,10 @@ class TraktorAdapter:
|
||||
with _translate():
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
with _translate():
|
||||
return self._store.move_playlist(node_id, parent_id, index)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents. The adapter resolves each id to its
|
||||
native entry kind, so callers never see Traktor's STEM/TRACK split."""
|
||||
@@ -146,6 +150,30 @@ class TraktorAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
with _translate():
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
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)
|
||||
@@ -187,10 +215,11 @@ class TraktorAdapter:
|
||||
Lossiness follows the settled rule — degrade to the nearest equivalent,
|
||||
drop only where none exists:
|
||||
|
||||
* **Memory cues become hot cues in spare slots.** Traktor has no
|
||||
memory cues, and every Traktor cue occupies a slot. Filling the
|
||||
leftovers preserves the positions a DJ actually marked; when the
|
||||
bank is full the rest are dropped, because there is nowhere left.
|
||||
* **Memory cues stay memory cues** — Traktor's cues on no pad
|
||||
(HOTCUE="-1"), decided 2026-10-16 once Traktor was measured keeping
|
||||
them. They used to be promoted to spare pads.
|
||||
* **A hot cue whose pad is taken** moves to a spare pad, else becomes a
|
||||
memory cue — never dropped.
|
||||
* **Cue colour is dropped.** Traktor derives a cue's colour from its
|
||||
type, so a free RGB value has nowhere to go.
|
||||
|
||||
@@ -225,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}
|
||||
@@ -240,29 +273,43 @@ class TraktorAdapter:
|
||||
self._place_imported_cue(track_id, cue.slot, cue)
|
||||
taken.add(cue.slot)
|
||||
|
||||
# Everything without a pad of its own competes for what is left: memory
|
||||
# cues, which Traktor has no equivalent for, and any hot cue whose pad
|
||||
# was already occupied. Earliest first, so that when the bank runs out
|
||||
# it is the late cues that are lost rather than an arbitrary set — and
|
||||
# a displaced hot cue is moved rather than dropped, because losing one
|
||||
# silently is much worse than having it turn up on the wrong pad.
|
||||
leftovers = displaced + [c for c in (cues.cues or []) if c.role != "hotcue"]
|
||||
# A hot cue whose pad was taken (or is past the bank) moves to a spare
|
||||
# pad, earliest first, because muscle memory is most of what a hot cue
|
||||
# layout is; once the bank is full it becomes a memory cue rather than
|
||||
# being lost. Memory cues cross as memory cues.
|
||||
spare = (s for s in range(slots) if s not in taken)
|
||||
for cue in sorted(leftovers, key=lambda c: c.start):
|
||||
for cue in sorted(displaced, key=lambda c: c.start):
|
||||
slot = next(spare, None)
|
||||
if slot is None:
|
||||
break # bank full: the rest are dropped, per the lossiness rule
|
||||
self._place_imported_cue(track_id, slot, cue)
|
||||
self._place_imported_memory_cue(track_id, cue)
|
||||
else:
|
||||
self._place_imported_cue(track_id, slot, cue)
|
||||
for cue in sorted((c for c in (cues.cues or []) if c.role != "hotcue" or c.slot is None),
|
||||
key=lambda c: c.start):
|
||||
self._place_imported_memory_cue(track_id, cue)
|
||||
|
||||
@staticmethod
|
||||
def _imported_type(cue) -> str:
|
||||
"""A loop stays a loop; Traktor's own point types (fade, load) survive."""
|
||||
if getattr(cue, "length", 0):
|
||||
return "loop"
|
||||
return cue.type if cue.type in ("cue", "fade_in", "fade_out", "load") else "cue"
|
||||
|
||||
def _place_imported_cue(self, track_id: str, slot: int, cue) -> None:
|
||||
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
|
||||
if cue_type not in CUE_TYPE_TO_NATIVE:
|
||||
return
|
||||
self.set_cue(
|
||||
track_id,
|
||||
slot=slot,
|
||||
start_sec=cue.start,
|
||||
cue_type=cue_type,
|
||||
cue_type=self._imported_type(cue),
|
||||
length_sec=getattr(cue, "length", 0.0) or 0.0,
|
||||
name=getattr(cue, "name", None),
|
||||
)
|
||||
|
||||
def _place_imported_memory_cue(self, track_id: str, cue) -> None:
|
||||
self.add_memory_cue(
|
||||
track_id,
|
||||
start_sec=cue.start,
|
||||
cue_type=self._imported_type(cue),
|
||||
length_sec=getattr(cue, "length", 0.0) or 0.0,
|
||||
name=getattr(cue, "name", None),
|
||||
)
|
||||
@@ -286,8 +333,8 @@ class TraktorAdapter:
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
if role != "hotcue":
|
||||
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot.
|
||||
raise Unsupported("Traktor cues always occupy a hotcue slot")
|
||||
# A memory cue has no slot to set; it has its own commands.
|
||||
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
|
||||
with _translate():
|
||||
self._store.set_hotcue(
|
||||
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
|
||||
@@ -308,6 +355,45 @@ class TraktorAdapter:
|
||||
self._store.delete_hotcue(track_id, slot)
|
||||
return self._refresh(track_id)
|
||||
|
||||
# ---- memory cues: cues on no pad (HOTCUE="-1") ----------------------------
|
||||
def add_memory_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color: str | None = None,
|
||||
) -> TrackCues:
|
||||
# Traktor colours a cue by its type, so a colour has nowhere to go; an
|
||||
# import passes none, and the capabilities offer none.
|
||||
if color is not None:
|
||||
raise Unsupported("Traktor colours cues by their type")
|
||||
with _translate():
|
||||
self._store.add_memory_cue(
|
||||
track_id, start_sec, self._native_cue_type(cue_type), length_sec, name
|
||||
)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.rename_memory_cue(track_id, cue_id, name)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_memory_cue_type(track_id, cue_id, self._native_cue_type(cue_type))
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
|
||||
raise Unsupported("Traktor colours cues by their type")
|
||||
|
||||
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_memory_cue(track_id, cue_id)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
native = [
|
||||
SimpleNamespace(
|
||||
@@ -373,16 +459,68 @@ 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)
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
self._store.set_session_mappings(mappings)
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
"""OPTIONAL: write a file added through the path mapping in the
|
||||
library's STORED form (see `pathmap.stored_form`). A Konduktor server
|
||||
holding a collection made on another computer turns this on, so a
|
||||
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()
|
||||
|
||||
@@ -405,6 +543,12 @@ class TraktorAdapter:
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def edit_summary(self) -> str:
|
||||
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
|
||||
tracks; added 6 hotcues") — what a server tells the next computer to
|
||||
open the library about the edits it is inheriting."""
|
||||
return self._store._edit_summary()
|
||||
|
||||
def save(self):
|
||||
outcome = self._store.save()
|
||||
self._rebuild() # save() re-parses, so every object identity changed
|
||||
|
||||
@@ -19,6 +19,7 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import track_palette
|
||||
|
||||
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
|
||||
|
||||
@@ -46,8 +47,11 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
editable=True,
|
||||
hotcue_slots=8,
|
||||
slot_labels="number",
|
||||
# Traktor has no memory cues — every cue occupies a bank slot.
|
||||
memory_cues=False,
|
||||
# Memory cues are CUE_V2s on no pad (HOTCUE="-1"), any type, no
|
||||
# limit (measured in Traktor 4.5, 2026-10-16). No colour: by type.
|
||||
memory_cues=True,
|
||||
max_memory_cues=None,
|
||||
memory_color="none",
|
||||
types=CUE_TYPES,
|
||||
# Traktor colours a cue by its TYPE; the only COLOR it stores is a
|
||||
# grid marker's white companion, so there is nothing to pick.
|
||||
@@ -64,6 +68,13 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
removable=True,
|
||||
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"],
|
||||
@@ -73,7 +84,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
"need a manual Import Cover Art to show up."
|
||||
),
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
playlists=PlaylistCapabilities(
|
||||
folders=True, smart="read_only", reorder=True,
|
||||
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
|
||||
# itself adds a track twice when asked.
|
||||
duplicates=True,
|
||||
),
|
||||
save=SaveCapabilities(
|
||||
app_name="Traktor",
|
||||
library_label="collection.nml",
|
||||
|
||||
@@ -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()
|
||||
@@ -106,42 +118,8 @@ class TraktorExporter:
|
||||
return WrittenLibrary(library=library)
|
||||
|
||||
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
|
||||
"""Recreate the tree under one folder named after the export.
|
||||
|
||||
Nested under the export's own name for the same reason import nests a
|
||||
drive's playlists under the drive's name: a collection swapped onto
|
||||
another machine should say where its playlists came from.
|
||||
"""
|
||||
root = adapter.create_folder(payload.name)
|
||||
folders: dict[tuple[str, ...], str] = {(): 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) -> str:
|
||||
"""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
|
||||
]
|
||||
"""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
|
||||
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
|
||||
@@ -7,15 +7,14 @@ from __future__ import annotations
|
||||
|
||||
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"),
|
||||
# depending on a user preference — so the library can contain either. Parsing
|
||||
# notation is platform knowledge and belongs here, not in the UI.
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
# depending on a user preference, and INFO@KEY also holds whatever a file's key
|
||||
# tag said ("Gm", "Amin") — so every notation is parsed (`core/musical_key`).
|
||||
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
|
||||
# "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
|
||||
# timestamp's date part is the date).
|
||||
@@ -23,23 +22,42 @@ _ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$")
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor display key.
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor key string."""
|
||||
return musical_key.parse(key)
|
||||
|
||||
Open Key numbers the wheel seven semitones round from Camelot, so
|
||||
Open Key 1 == Camelot 8 (both are C major / A minor).
|
||||
"""
|
||||
if not key:
|
||||
|
||||
def musical_key_value(wheel: int, mode: str) -> int:
|
||||
"""`<MUSICAL_KEY VALUE>`: the tonic's pitch class (C = 0), plus 12 for minor
|
||||
— read off the real collection, where 12 pairs with "10m" (C minor) and 21
|
||||
with "1m" (A minor) on every entry carrying both."""
|
||||
return musical_key.pitch_class_of(wheel, mode) + (12 if mode == "minor" else 0)
|
||||
|
||||
|
||||
def _from_musical_key(value: int | None) -> tuple[int | None, str | None]:
|
||||
if value is None or not 0 <= value <= 23:
|
||||
return None, None
|
||||
k = key.strip()
|
||||
if m := _CAMELOT.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return n, "minor" if m.group(2).lower() == "a" else "major"
|
||||
if m := _OPEN_KEY.match(k):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
|
||||
return None, None
|
||||
mode = "minor" if value >= 12 else "major"
|
||||
return musical_key.wheel_of(value % 12, mode), mode
|
||||
|
||||
|
||||
def entry_key(e) -> tuple[str | None, int | None, str | None]:
|
||||
"""(display string, wheel, mode) for an ENTRY.
|
||||
|
||||
INFO@KEY is the text Traktor shows and writes to the file's tag; the
|
||||
analysed key itself is `<MUSICAL_KEY>`. 1,354 of the real collection's
|
||||
8,485 entries carry only the latter — analysed, with every value 0-23
|
||||
present, just never given a text — and Traktor shows a key for them, so
|
||||
they fall back to it, rendered in Open Key (Traktor's own default).
|
||||
"""
|
||||
info = e.info
|
||||
text = info.key if info else None
|
||||
wheel, mode = parse_key(text)
|
||||
if wheel is None:
|
||||
mk = e.musical_key.value_attribute if e.musical_key is not None else None
|
||||
wheel, mode = _from_musical_key(mk)
|
||||
if wheel is not None and not text:
|
||||
text = musical_key.render(wheel, mode, "open_key")
|
||||
return text, wheel, mode
|
||||
|
||||
|
||||
def iso_date(value: str | None) -> str | None:
|
||||
@@ -122,7 +140,7 @@ def to_track(e) -> Track:
|
||||
),
|
||||
key=lambda chip: chip.slot,
|
||||
)
|
||||
wheel, mode = parse_key(info.key if info else None)
|
||||
key_text, wheel, mode = entry_key(e)
|
||||
return Track(
|
||||
id=primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
@@ -137,7 +155,7 @@ def to_track(e) -> Track:
|
||||
# Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING).
|
||||
comment2=info.rating if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
key=key_text,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
@@ -154,9 +172,50 @@ 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,
|
||||
)
|
||||
|
||||
|
||||
#: Traktor's NAME for a cue nobody named.
|
||||
UNNAMED = "n.n."
|
||||
|
||||
|
||||
def is_memory_cue(c) -> bool:
|
||||
"""A cue on no pad that is not a grid marker — Traktor's memory cue.
|
||||
|
||||
Traktor stores it as an ordinary CUE_V2 with HOTCUE="-1", any type, drawn
|
||||
on the waveform and reached with the cue panel's ‹ › (measured in Traktor
|
||||
4.5, 2026-10-16). A grid marker is ALSO HOTCUE="-1"; its <GRID> child is
|
||||
what tells them apart — never its name or position.
|
||||
"""
|
||||
return getattr(c, "grid", None) is None and (c.hotcue is None or c.hotcue < 0)
|
||||
|
||||
|
||||
def memory_cue_id(c, n: int) -> str:
|
||||
"""`CuePoint.id` for a memory cue: its stored START, TYPE and LEN, plus `n`
|
||||
— how many identical memory cues come before it (Traktor allows several at
|
||||
one START). Content-derived, so it is the same on every read."""
|
||||
return f"m:{c.start or 0.0:.6f}:{c.type}:{c.len or 0.0:.6f}:{n}"
|
||||
|
||||
|
||||
def with_memory_ids(entry) -> list:
|
||||
"""(cue, its memory id or None) for every CUE_V2 of an entry, in order."""
|
||||
seen: dict[str, int] = {}
|
||||
out = []
|
||||
for c in entry.cue_v2 or []:
|
||||
if not is_memory_cue(c):
|
||||
out.append((c, None))
|
||||
continue
|
||||
base = memory_cue_id(c, 0)
|
||||
n = seen.get(base, 0)
|
||||
seen[base] = n + 1
|
||||
out.append((c, memory_cue_id(c, n)))
|
||||
return out
|
||||
|
||||
|
||||
def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
|
||||
"""Project an ENTRY's beatgrid + cues.
|
||||
|
||||
@@ -182,20 +241,30 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
|
||||
)
|
||||
for i, m in enumerate(markers)
|
||||
]
|
||||
# A pad MAP put on a memory cue leaves the memory cue in place at the same
|
||||
# START (measured in Traktor 4.5); Traktor draws ONE marker, so the pad
|
||||
# stands for both (decided 2026-10-16).
|
||||
pad_starts = {c.start for c in entry.cue_v2 or []
|
||||
if getattr(c, "grid", None) is None and c.hotcue is not None and c.hotcue >= 0}
|
||||
cues = []
|
||||
for c in entry.cue_v2 or []:
|
||||
for c, memory_id in with_memory_ids(entry):
|
||||
if getattr(c, "grid", None) is not None:
|
||||
continue # a grid marker is projected as a beatgrid marker, not a cue
|
||||
if memory_id is not None and c.start in pad_starts:
|
||||
continue
|
||||
marker = marker_of.get(id(c))
|
||||
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
|
||||
cues.append(
|
||||
CuePoint(
|
||||
name=c.name,
|
||||
# "n.n." is the name Traktor gives every cue the user did not
|
||||
# name — a placeholder, not a name, so it crosses as none
|
||||
# (it once landed in rekordbox as a comment reading "n.n.").
|
||||
name=None if c.name in (None, "", UNNAMED) else c.name,
|
||||
# An unknown TYPE is projected as a plain cue rather than dropped:
|
||||
# preserving a cue we cannot name beats hiding it from the user.
|
||||
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
|
||||
# Every Traktor cue lives in the hotcue bank.
|
||||
role="hotcue",
|
||||
# A cue on no pad (HOTCUE="-1") is a memory cue.
|
||||
role="hotcue" if slot is not None else "memory",
|
||||
start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
|
||||
length=(c.len or 0.0) / 1000.0,
|
||||
slot=slot,
|
||||
@@ -203,6 +272,7 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
|
||||
editable=True,
|
||||
readonly_reason=None,
|
||||
grid_marker=marker,
|
||||
id=memory_id,
|
||||
)
|
||||
)
|
||||
return TrackCues(
|
||||
|
||||
@@ -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 (
|
||||
@@ -35,7 +36,9 @@ from traktor_nml_utils.models.collection import (
|
||||
Entrytype,
|
||||
GridType,
|
||||
Infotype,
|
||||
MusicalKeytype,
|
||||
Locationtype,
|
||||
Loudnesstype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
Primarykeytype,
|
||||
@@ -48,13 +51,14 @@ from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import common_dir_prefix
|
||||
from ...core.pathmap import PathMapping
|
||||
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 .projection import iso_date, traktor_date
|
||||
from ...core import musical_key
|
||||
from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
|
||||
|
||||
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
|
||||
# this email is what makes the stars show up in Traktor itself.
|
||||
@@ -77,6 +81,9 @@ class TraktorStore:
|
||||
self.dirty = False
|
||||
# Active OS-path prefix remapping (empty = identity). Survives _load().
|
||||
self._path_mapping = PathMapping()
|
||||
# Write a file added through a mapping in the library's STORED form
|
||||
# (`pathmap.stored_form`) — a Konduktor server sets this.
|
||||
self._write_stored_paths = False
|
||||
# Mappings the user confirmed in the open-time missing-files check.
|
||||
# Session-only: never saved, re-derived on every open.
|
||||
self._session_mappings: list[PathMapping] = []
|
||||
@@ -99,6 +106,7 @@ class TraktorStore:
|
||||
self._journal = EditJournal()
|
||||
# track_id -> (image_bytes, mime) of staged replacement cover art
|
||||
self._track_art: dict[str, tuple[bytes, str]] = {}
|
||||
self._notation: str | None = None
|
||||
self.dirty = False
|
||||
|
||||
def _note(
|
||||
@@ -154,11 +162,13 @@ class TraktorStore:
|
||||
can_reorder=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
if ntype == "SMARTLIST" or node.smartplaylist is not None:
|
||||
# Rule-based, so it has no static entry list to show or edit.
|
||||
return PlaylistNode(
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart"
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
|
||||
can_move=True,
|
||||
)
|
||||
path = parent_path + [name]
|
||||
return PlaylistNode(
|
||||
@@ -169,6 +179,7 @@ class TraktorStore:
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
can_move=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -342,6 +353,79 @@ class TraktorStore:
|
||||
self._note("playlist-delete", node.name)
|
||||
self.dirty = True
|
||||
|
||||
def _find_node(self, node_id: str) -> Nodetype:
|
||||
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
|
||||
smart playlist's `sl:` path (its folder path plus its own name)."""
|
||||
if node_id.startswith("fld:"):
|
||||
return self._find_folder(node_id)
|
||||
if node_id.startswith("sl:"):
|
||||
*folders, name = node_id[len("sl:"):].split("/")
|
||||
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
|
||||
match = next(
|
||||
(c for c in self._children(parent)
|
||||
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise PlaylistError(f"Smart playlist not found: {node_id}")
|
||||
return match
|
||||
node = self._find_playlist_node(node_id)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {node_id}")
|
||||
return node
|
||||
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
|
||||
"""Move a node to `index` among `parent_id`'s children (counted without
|
||||
it) and return its id afterwards — a folder's and a smart playlist's id
|
||||
is their path of names, so moving one changes it (and its subtree's).
|
||||
|
||||
A folder or smart playlist landing beside a namesake of its own kind is
|
||||
refused, as rename refuses it: the two paths would be one, and one of
|
||||
them unaddressable. Playlists are UUIDs, so their names may repeat."""
|
||||
with self._lock:
|
||||
node = self._find_node(node_id)
|
||||
if node is self._root():
|
||||
raise PlaylistError("Cannot move the root folder")
|
||||
dest = self._find_folder(parent_id)
|
||||
if dest is node or any(n is dest for n in self._iter_nodes(node)):
|
||||
raise PlaylistError("A folder cannot be moved into itself")
|
||||
is_folder = node.playlist is None and node.smartplaylist is None and (
|
||||
node.type or "FOLDER") == "FOLDER"
|
||||
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
|
||||
if is_folder or is_smart:
|
||||
kind = "folder" if is_folder else "smart playlist"
|
||||
for c in self._children(dest):
|
||||
same_kind = (
|
||||
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
|
||||
and c.smartplaylist is None
|
||||
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
|
||||
if c is not node and same_kind and c.name == node.name:
|
||||
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
|
||||
source = self._find_parent_of(node)
|
||||
if source is None:
|
||||
raise PlaylistError("Cannot move a top-level node")
|
||||
siblings = [c for c in self._children(dest) if c is not node]
|
||||
index = max(0, min(int(index), len(siblings)))
|
||||
if source is dest and self._children(dest).index(node) == index:
|
||||
return self._node_id(node, parent_id) # already there
|
||||
source.subnodes.node.remove(node)
|
||||
source.subnodes.count = len(source.subnodes.node)
|
||||
if dest.subnodes is None:
|
||||
dest.subnodes = Subnodestype(node=[], count=0)
|
||||
dest.subnodes.node.insert(index, node)
|
||||
dest.subnodes.count = len(dest.subnodes.node)
|
||||
self._note("playlist-move", node.name)
|
||||
self.dirty = True
|
||||
return self._node_id(node, parent_id)
|
||||
|
||||
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
|
||||
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
|
||||
if node.playlist is not None:
|
||||
return node.playlist.uuid
|
||||
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
|
||||
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
|
||||
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
@@ -364,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:
|
||||
@@ -399,6 +485,125 @@ class TraktorStore:
|
||||
self._journal.record("track", "set", track_id, k)
|
||||
self.dirty = True
|
||||
|
||||
# ---- musical key ----------------------------------------------------
|
||||
def _collection_notation(self) -> str | None:
|
||||
"""The notation this collection's INFO@KEY values are written in — a
|
||||
Traktor preference (Open Key / Camelot / musical) the NML does not
|
||||
record, so it is read off the keys themselves; the majority wins. None
|
||||
when the collection holds no keys — never cached, since adding entries
|
||||
to an empty collection (an export) is exactly when it changes. Once
|
||||
known it is kept for the session: every key Konduktor writes is in it,
|
||||
so it can only move if one could out-vote thousands."""
|
||||
from collections import Counter
|
||||
|
||||
if self._notation is not None:
|
||||
return self._notation
|
||||
seen = Counter(
|
||||
musical_key.notation_of(e.info.key)
|
||||
for e in self._nml.collection.entry
|
||||
if e.info is not None and e.info.key
|
||||
)
|
||||
seen.pop(None, None)
|
||||
self._notation = seen.most_common(1)[0][0] if seen else None
|
||||
return self._notation
|
||||
|
||||
def key_notation(self) -> str:
|
||||
"""`_collection_notation`, or Open Key (Traktor's default) when there
|
||||
are no keys to go by. A key in another notation would display fine but
|
||||
read as foreign beside its neighbours."""
|
||||
return self._collection_notation() or "open_key"
|
||||
|
||||
def _added_key_text(self, track) -> str | None:
|
||||
"""INFO@KEY for an entry `add_entry` creates: rendered from the wheel in
|
||||
this collection's notation, never copied — a Pioneer source says "Abm",
|
||||
which reads as foreign beside "9m". A collection with no keys yet (an
|
||||
export's fresh skeleton) takes a Traktor-native source's own notation,
|
||||
so Traktor -> Traktor keeps the user's (the export decision). Text that
|
||||
names no key is kept as it was: dropping it would lose information."""
|
||||
text = getattr(track, "key", None) or None
|
||||
wheel, mode = getattr(track, "key_wheel", None), getattr(track, "key_mode", None)
|
||||
if not (wheel and mode):
|
||||
return text
|
||||
notation = self._collection_notation()
|
||||
if notation is None:
|
||||
own = musical_key.notation_of(text)
|
||||
notation = own if own in ("open_key", "camelot") else "open_key"
|
||||
return musical_key.render(wheel, mode, notation)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
"""Set a track's key as Traktor's analysis writes one: the display
|
||||
text in INFO@KEY (in the collection's notation; also what reaches the
|
||||
file's tag at Save) AND the analysed value in `<MUSICAL_KEY>`."""
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
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.key
|
||||
entry.info.key = musical_key.render(wheel, mode, self.key_notation())
|
||||
entry.musical_key = MusicalKeytype(value_attribute=musical_key_value(wheel, mode))
|
||||
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.
|
||||
@@ -428,7 +633,7 @@ class TraktorStore:
|
||||
# Read before the lock: it opens the file.
|
||||
stems = nml_stems_for(audio_path)
|
||||
with self._lock:
|
||||
volume, dir_, file = os_path_to_location(Path(audio_path))
|
||||
volume, dir_, file = os_path_to_location(self._stored(Path(audio_path)))
|
||||
key = f"{volume}{dir_}{file}"
|
||||
if key in self._entry_by_key:
|
||||
raise PlaylistError(
|
||||
@@ -443,7 +648,7 @@ class TraktorStore:
|
||||
remixer=getattr(track, "remixer", None) or None,
|
||||
producer=getattr(track, "producer", None) or None,
|
||||
mix=getattr(track, "mix", None) or None,
|
||||
key=getattr(track, "key", None) or None,
|
||||
key=self._added_key_text(track),
|
||||
bitrate=getattr(track, "bitrate", None) or None,
|
||||
playcount=getattr(track, "playcount", None) or None,
|
||||
# The generic model carries ISO dates; Traktor writes "YYYY/M/D".
|
||||
@@ -453,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):
|
||||
@@ -469,6 +675,12 @@ class TraktorStore:
|
||||
# projected BPM so a track with no grid still shows a tempo;
|
||||
# `replace_grid` overwrites it from the markers when they land.
|
||||
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
|
||||
# The analysed key, as Traktor's own analysis stores it.
|
||||
musical_key=(
|
||||
MusicalKeytype(value_attribute=musical_key_value(track.key_wheel, track.key_mode))
|
||||
if getattr(track, "key_wheel", None) and getattr(track, "key_mode", None)
|
||||
else None
|
||||
),
|
||||
cue_v2=[],
|
||||
stems=Stemstype(stems=stems) if stems else None,
|
||||
)
|
||||
@@ -619,21 +831,7 @@ class TraktorStore:
|
||||
if name is not None:
|
||||
existing.name = name
|
||||
else:
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name=name or "n.n.", # Traktor's default name for a manual cue
|
||||
displ_order=0,
|
||||
type=cue_type,
|
||||
start=start_ms,
|
||||
len=len_ms,
|
||||
repeats=-1,
|
||||
hotcue=slot,
|
||||
color=None,
|
||||
grid=None,
|
||||
)
|
||||
)
|
||||
self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, slot, name))
|
||||
# "add" only when it's a genuinely new hotcue; repositioning/retyping
|
||||
# an existing slot is a "modify" (keeps the net add/remove count honest).
|
||||
self._note(
|
||||
@@ -665,6 +863,87 @@ class TraktorStore:
|
||||
name=getattr(spec, "name", None),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _new_cue(cue_type: int, start_ms: float, len_ms: float, hotcue: int,
|
||||
name: str | None) -> CueV2Type:
|
||||
"""A CUE_V2 as Traktor writes one by hand — on a pad, or on none
|
||||
(`hotcue` -1, a memory cue: the same element, measured in Traktor 4.5)."""
|
||||
return CueV2Type(
|
||||
name=name or "n.n.", # Traktor's default name for a manual cue
|
||||
displ_order=0,
|
||||
type=cue_type,
|
||||
start=start_ms,
|
||||
len=len_ms,
|
||||
repeats=-1,
|
||||
hotcue=hotcue,
|
||||
color=None,
|
||||
grid=None,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _insert_cue(entry: Entrytype, cue: CueV2Type) -> None:
|
||||
"""Insert a new cue at its place BY START, after every cue at or before
|
||||
it — Traktor keeps CUE_V2 sorted by START (8485/8485 reference entries,
|
||||
and its own saves), so a later Traktor save moves nothing. Nothing else
|
||||
moves either, unlike a re-sort of an entry another tool left unsorted."""
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
at = len(entry.cue_v2)
|
||||
while at > 0 and (entry.cue_v2[at - 1].start or 0.0) > (cue.start or 0.0):
|
||||
at -= 1
|
||||
entry.cue_v2.insert(at, cue)
|
||||
|
||||
# ---- memory cues: CUE_V2 on no pad (HOTCUE="-1"), not a grid marker -----
|
||||
# Measured in Traktor 4.5 (2026-10-16, kit M3): any type, no limit, drawn
|
||||
# on the waveform and reached with the cue panel's ‹ ›, a name shown in the
|
||||
# cue panel — and a cue written here survives Traktor's own save byte for
|
||||
# byte. Addressed by `projection.memory_cue_id`.
|
||||
def _memory_cue(self, entry: Entrytype, cue_id: str) -> CueV2Type:
|
||||
cue = next((c for c, mid in with_memory_ids(entry) if mid == cue_id), None)
|
||||
if cue is None:
|
||||
raise PlaylistError(f"Memory cue {cue_id!r} not found on this track")
|
||||
return cue
|
||||
|
||||
def add_memory_cue(self, track_id: str, start_sec: float, cue_type: int,
|
||||
length_sec: float = 0.0, name: str | None = None) -> None:
|
||||
if cue_type not in self.CREATABLE_TYPES:
|
||||
raise PlaylistError(f"Unsupported cue type: {cue_type}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
|
||||
len_ms = max(0.0, length_sec * 1000.0)
|
||||
self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, -1, name))
|
||||
self._note("hotcue", "add", track_id, "memory")
|
||||
self.dirty = True
|
||||
|
||||
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
self._memory_cue(entry, cue_id).name = name or "n.n."
|
||||
self._note("hotcue", "modify", track_id, "memory")
|
||||
self.dirty = True
|
||||
|
||||
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: int) -> None:
|
||||
"""A point type only, as for a hot cue: a loop is not retyped."""
|
||||
if cue_type not in self.POINT_CUE_TYPES:
|
||||
raise PlaylistError(f"Unsupported cue type: {cue_type}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
cue = self._memory_cue(entry, cue_id)
|
||||
if cue.type not in self.POINT_CUE_TYPES:
|
||||
raise PlaylistError("A memory loop keeps its type")
|
||||
cue.type = cue_type
|
||||
self._note("hotcue", "modify", track_id, "memory")
|
||||
self.dirty = True
|
||||
|
||||
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
cue = self._memory_cue(entry, cue_id)
|
||||
entry.cue_v2 = [c for c in entry.cue_v2 if c is not cue]
|
||||
self._note("hotcue", "delete", track_id, "memory")
|
||||
self.dirty = True
|
||||
|
||||
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
|
||||
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
|
||||
if cue_type not in self.POINT_CUE_TYPES:
|
||||
@@ -969,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
|
||||
|
||||
@@ -988,6 +1277,15 @@ class TraktorStore:
|
||||
with self._lock:
|
||||
self._path_mapping = mapping
|
||||
|
||||
def set_write_stored_paths(self, enabled: bool) -> None:
|
||||
self._write_stored_paths = bool(enabled)
|
||||
|
||||
def _stored(self, os_path: Path) -> Path:
|
||||
"""Where a NEW entry points, as the collection stores paths."""
|
||||
if not self._write_stored_paths:
|
||||
return Path(os_path)
|
||||
return stored_form(Path(os_path), [self._path_mapping, *self._session_mappings])
|
||||
|
||||
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
|
||||
"""Set the mappings confirmed for this session (applied at resolve time)."""
|
||||
with self._lock:
|
||||
@@ -1283,7 +1581,7 @@ class TraktorStore:
|
||||
if swap.mode not in ("repoint", "add"):
|
||||
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
|
||||
seen_ids.add(swap.track_id)
|
||||
loc = os_path_to_location(Path(swap.stem_path))
|
||||
loc = os_path_to_location(self._stored(Path(swap.stem_path)))
|
||||
new_key = "".join(x or "" for x in loc)
|
||||
if new_key in self._entry_by_key or new_key in new_keys:
|
||||
raise PlaylistError(
|
||||
|
||||
@@ -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)
|
||||
+170
-26
@@ -24,15 +24,19 @@ human summary, and this module versions them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
from . import adapters, library_id, prefs # noqa: F401 — registers adapters
|
||||
from .core import registry
|
||||
from .core.adapter import LibraryAdapter
|
||||
from .core.pathmap import PathMapping
|
||||
from .relocation import RelocationCheck
|
||||
from .services import LibraryServices, LocalServices
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AppState:
|
||||
@@ -61,6 +65,33 @@ class AppState:
|
||||
# and what the last open's crash recovery did about any left over.
|
||||
self.pending = None
|
||||
self.recovery: dict | None = None
|
||||
# Where this library's history (and, for a remote, its export sets and
|
||||
# ledger) are kept — see `services.py`.
|
||||
self.services: LibraryServices | None = None
|
||||
# The open remote's connection (`adapters/remote/session.py`), or None
|
||||
# for a library on this computer.
|
||||
self.remote = None
|
||||
# …and the saved remote it was opened through (`adapters/remote/config.py`).
|
||||
self.remote_config = None
|
||||
# Called with the adapter at the end of every open (and so after a
|
||||
# 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:
|
||||
@@ -120,22 +151,16 @@ class AppState:
|
||||
# write-ahead log beside a file another process replaces is how a SQLite
|
||||
# library gets corrupted. Only close once the new one has parsed, so a
|
||||
# failed open leaves the current library intact.
|
||||
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()
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
self._release_previous()
|
||||
# Apply this library's saved OS-path remapping (per-machine, keyed by the
|
||||
# library's local path) so runtime translation is live on open.
|
||||
saved = prefs.get_path_mapping(str(path))
|
||||
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
|
||||
@@ -152,18 +177,88 @@ 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)
|
||||
# Version history: record an "as I found it" baseline (deduped, so
|
||||
# re-opening an unchanged library is a no-op). Best-effort.
|
||||
history.ensure_baseline(path)
|
||||
self.services = LocalServices(path)
|
||||
self.services.baseline()
|
||||
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()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block the open
|
||||
pass
|
||||
if self.remote is not None and self.library_id:
|
||||
# A remote library's export sets were the server's; stop asking it.
|
||||
from . import exports
|
||||
|
||||
exports.use_store(self.library_id, None)
|
||||
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.
|
||||
|
||||
`opened` is what `adapters.remote.open_remote` returns: the adapter, its
|
||||
services and session, and the server's identity for the library. The
|
||||
connection (handshake, version check, session) is made BEFORE this, so
|
||||
a refusal leaves the current library intact, as a failed parse does.
|
||||
"""
|
||||
with self.mutation:
|
||||
self._release_previous()
|
||||
self.path = opened.path
|
||||
self.adapter = opened.adapter
|
||||
self.services = opened.services
|
||||
self.remote = opened.session
|
||||
self.remote_config = opened.remote
|
||||
# The server's id for the library: export sets are keyed by it, and
|
||||
# they live on the server too, so every computer sees the same ones.
|
||||
self.library_id = opened.library_id
|
||||
# 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
|
||||
|
||||
def save(self):
|
||||
"""Write the library, then record the saved bytes in version history.
|
||||
@@ -177,16 +272,29 @@ class AppState:
|
||||
return self._save()
|
||||
|
||||
def _save(self):
|
||||
outcome = self.adapter.save()
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
# capabilities rather than this module knowing which platforms those are.
|
||||
versioned = self.adapter.capabilities().save.history
|
||||
commit = None
|
||||
if versioned and outcome.snapshot is not None:
|
||||
commit = history.commit(
|
||||
self.path, outcome.snapshot, outcome.summary, __version__
|
||||
)
|
||||
# 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.
|
||||
@@ -209,8 +317,26 @@ 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()
|
||||
self.adapter.reload()
|
||||
|
||||
def restore_version(self, commit_id: str) -> bool:
|
||||
"""Write a past version back as a new save and re-read the library.
|
||||
False when the version is unknown."""
|
||||
assert self.adapter is not None and self.services is not None
|
||||
with self.mutation:
|
||||
if not self.services.restore(commit_id):
|
||||
return False
|
||||
if self.services.remote:
|
||||
# The server reopened its own library; follow it.
|
||||
self.adapter.reload()
|
||||
else:
|
||||
self._open(self.path) # rebuild read + edit models from the restored file
|
||||
return True
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
|
||||
@@ -221,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
|
||||
@@ -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())
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -65,6 +66,63 @@ class SaveOutcome:
|
||||
tag_results: list = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioFacts:
|
||||
"""One track's audio file as its library's host sees it — WITHOUT reading it.
|
||||
|
||||
`key` is the file's path on the machine that holds it (a string, because on
|
||||
a remote library that is not this machine), `size` and `mtime_ns` its stat.
|
||||
Together they name one version of one file: what an export's manifest
|
||||
records, what the analysis cache keys on, and how a downloaded copy is
|
||||
recognised. Callers that only need a file's IDENTITY ask for these rather
|
||||
than `audio_path`, which on a remote library means downloading it.
|
||||
"""
|
||||
|
||||
key: str
|
||||
size: int
|
||||
mtime_ns: int
|
||||
|
||||
|
||||
def local_audio_facts(adapter, track_ids) -> dict[str, AudioFacts]:
|
||||
"""`audio_facts` for a library whose files are on this machine: stat each
|
||||
`audio_path`. A track whose file is missing is left out."""
|
||||
out: dict[str, AudioFacts] = {}
|
||||
for track_id in track_ids:
|
||||
try:
|
||||
path = adapter.audio_path(track_id)
|
||||
if path is None:
|
||||
continue
|
||||
st = Path(path).stat()
|
||||
except (OSError, AdapterError):
|
||||
continue
|
||||
if not Path(path).is_file():
|
||||
continue
|
||||
out[track_id] = AudioFacts(key=str(path), size=st.st_size, mtime_ns=st.st_mtime_ns)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreparedAnalysis:
|
||||
"""What adding a track would otherwise decode the file to learn.
|
||||
|
||||
A platform that must ANALYSE what it adds (Rekordbox: the waveform and grid
|
||||
live in its ANLZ files) decodes each file in `add_tracks`. When the library
|
||||
lives on a server that never decodes audio, the client does that work on
|
||||
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), 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
|
||||
class NewTrack:
|
||||
"""A track to ADD to a library, described generically.
|
||||
@@ -93,6 +151,9 @@ class NewTrack:
|
||||
# For a platform that keeps its own copy of the art (Rekordbox); one that
|
||||
# reads the file's tags (Traktor) ignores it.
|
||||
art: tuple[bytes, str] | None = None
|
||||
# Precomputed analysis for a platform that would otherwise decode the file
|
||||
# (see `PreparedAnalysis`); ignored by one that does not analyse.
|
||||
analysis: PreparedAnalysis | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -124,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.
|
||||
@@ -153,6 +227,11 @@ class Unsupported(AdapterError):
|
||||
"""The platform cannot represent this edit at all."""
|
||||
|
||||
|
||||
class Unavailable(AdapterError):
|
||||
"""The library's host cannot be reached, or no longer lets this computer
|
||||
write (a library held by a server, taken over by another computer)."""
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryAdapter(Protocol):
|
||||
"""One open library. Stateful; exactly one is loaded at a time."""
|
||||
@@ -172,6 +251,7 @@ class LibraryAdapter(Protocol):
|
||||
def facets(self) -> Facets: ...
|
||||
def stats(self, playlist_count: int) -> Stats: ...
|
||||
def playlist_tree(self) -> list[PlaylistNode]: ...
|
||||
def playlist_count(self) -> int: ...
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None: ...
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
|
||||
def track_cues(self, track_id: str) -> TrackCues | None: ...
|
||||
@@ -184,6 +264,12 @@ class LibraryAdapter(Protocol):
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
# Move a node (playlist, folder or smart playlist) to `index` among
|
||||
# `parent_id`'s children (None = the top level), counted with the moved
|
||||
# node left out. Returns the node's id AFTER the move: an id is opaque, and
|
||||
# on a platform that addresses a folder by its path it changes. A folder
|
||||
# cannot go into itself or a descendant (InvalidCommand).
|
||||
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: adding tracks ----------------------------------------
|
||||
@@ -218,11 +304,30 @@ 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": ...
|
||||
|
||||
# ---- commands: track metadata / art ---------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
|
||||
# The musical key, as a Camelot wheel position (1-12) + mode — what key
|
||||
# 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: ...
|
||||
|
||||
@@ -244,6 +349,35 @@ 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`.
|
||||
# Past `cues.max_memory_cues` -> InvalidCommand; an unknown id -> NotFound;
|
||||
# `color` is from `cues.memory_palette` (Unsupported where memory_color is
|
||||
# "none"). There is deliberately no move: rekordbox has none either, so a
|
||||
# move is a delete and an add.
|
||||
def add_memory_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color: str | None = None,
|
||||
) -> TrackCues: ...
|
||||
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues: ...
|
||||
# A POINT type from `cues.types` (Traktor: cue / fade in / fade out / load);
|
||||
# a loop is not retyped. Unsupported where the platform has one point type.
|
||||
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues: ...
|
||||
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues: ...
|
||||
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues: ...
|
||||
|
||||
# ---- commands: beatgrid ---------------------------------------------
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: ...
|
||||
@@ -256,7 +390,12 @@ class LibraryAdapter(Protocol):
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
|
||||
|
||||
# ---- audio / paths ---------------------------------------------------
|
||||
# A READABLE file on this machine — which, for a library held by a server,
|
||||
# means downloading it. Anything that only needs to know WHICH file a track
|
||||
# is (an export plan, "is this already in the library?") asks `audio_facts`
|
||||
# instead, which never reads the file and never downloads.
|
||||
def audio_path(self, track_id: str) -> Path | None: ...
|
||||
def audio_facts(self, track_ids: list[str]) -> dict[str, AudioFacts]: ...
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None: ...
|
||||
# The open-time missing-files check (`core/relocate.py`): the stored volumes
|
||||
# in which NO track resolves, and the mappings the user confirmed for them —
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""The analysis a platform that ANALYSES what it adds needs for one new track.
|
||||
|
||||
Rekordbox draws a new track's waveform and grid from its ANLZ files, so adding a
|
||||
track means decoding it once: the waveform measured on the platform's own clock
|
||||
(`lead`, read from the file's header by that platform) plus a detected grid and
|
||||
key when the track brings none. One definition, used both by the adapter (a library on
|
||||
this computer) and by the client of a library held by a server — which never
|
||||
decodes audio, so the client measures its own copy and sends the result
|
||||
(`PreparedAnalysis`) with the track.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from .adapter import PreparedAnalysis
|
||||
from .model import GridMarker
|
||||
|
||||
|
||||
def prepare(path: Path, *, lead: float, detect: bool = True,
|
||||
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. `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))
|
||||
measured = waveform.analyse_samples(samples, lead=lead)
|
||||
markers: list[GridMarker] = []
|
||||
if detect and samples is not None:
|
||||
try:
|
||||
found = grid_detect.detect_grid(str(path), y=samples, sr=waveform.SR)
|
||||
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
|
||||
except ValueError:
|
||||
pass # no pulse to fit (a one-shot, silence): no grid
|
||||
key = None
|
||||
if detect_key and samples is not None:
|
||||
from . import key_detect
|
||||
|
||||
try:
|
||||
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)
|
||||
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):
|
||||
"""`track` (a generic `Track`) with the detected `key` if it has none of its
|
||||
own. A key the track already carries (its tags, its source library) is
|
||||
never second-guessed."""
|
||||
if key is None or getattr(track, "key_wheel", None) is not None:
|
||||
return track
|
||||
return track.model_copy(update={"key": key.name, "key_wheel": key.wheel, "key_mode": key.mode})
|
||||
@@ -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)}
|
||||
@@ -22,7 +22,10 @@ DEFAULT_POPM_EMAIL = "no@email"
|
||||
# The safe, editable metadata we sync to files (the adapter's editable field set).
|
||||
# rating is 0–5 stars.
|
||||
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
|
||||
# comment, mix, release_date, rating
|
||||
# comment, mix, release_date, rating, key
|
||||
# `key` is written as the library holds it ("9m", "Abm") into the frame DJ
|
||||
# software reads: ID3 TKEY, MP4/FLAC `initialkey` — where Traktor writes its
|
||||
# own (every key-tagged file on the dev machine has it there).
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -170,6 +173,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
|
||||
TDRC,
|
||||
TIT2,
|
||||
TIT3,
|
||||
TKEY,
|
||||
TPE1,
|
||||
TPE4,
|
||||
TPUB,
|
||||
@@ -185,6 +189,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
|
||||
"remixer": TPE4,
|
||||
"mix": TIT3,
|
||||
"release_date": TDRC,
|
||||
"key": TKEY,
|
||||
}
|
||||
for field, frame in simple.items():
|
||||
if field in meta:
|
||||
@@ -262,7 +267,8 @@ def _write_mp4(path: Path, meta: TagMeta) -> None:
|
||||
else:
|
||||
t[atom] = [val]
|
||||
# No standard MP4 atoms for these — use iTunes-style freeform atoms.
|
||||
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"}
|
||||
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX",
|
||||
"key": "initialkey"}
|
||||
for field, name in freeform.items():
|
||||
if field in meta:
|
||||
key = f"----:com.apple.iTunes:{name}"
|
||||
@@ -297,6 +303,7 @@ def _write_flac(path: Path, meta: TagMeta) -> None:
|
||||
"comment": "comment",
|
||||
"mix": "mixname",
|
||||
"release_date": "date",
|
||||
"key": "initialkey",
|
||||
}
|
||||
for field, vc in mapping.items():
|
||||
if field in meta:
|
||||
|
||||
@@ -25,12 +25,31 @@ from pydantic import BaseModel
|
||||
# `browsing` is an editable library opened only to READ alongside the loaded one
|
||||
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
|
||||
# as THE library, which one SaveBar and one dirty state can then follow.
|
||||
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"]
|
||||
# `taken_over` is a library held by a server that another computer has taken
|
||||
# over; `offline` one whose server cannot be reached. Both are temporary, and
|
||||
# both mean "nothing you do here can be saved" until the session is back.
|
||||
ReadonlyCause = Literal[
|
||||
"platform_incomplete", "cloud_synced", "not_in_library", "browsing", "taken_over", "offline",
|
||||
]
|
||||
|
||||
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):
|
||||
@@ -40,10 +59,17 @@ class CueCapabilities(BaseModel):
|
||||
editable: bool = False
|
||||
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
|
||||
slot_labels: Literal["number", "letter"] = "number"
|
||||
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
|
||||
# but not editable anywhere yet (the two-platform promotion rule).
|
||||
# Cues on no pad, listed in time order and called CDJ-style (decided
|
||||
# 2026-10-16). Editable wherever `editable` is: every platform that has them
|
||||
# can store them (Rekordbox, OneLibrary, and Traktor's HOTCUE="-1").
|
||||
memory_cues: bool = False
|
||||
# Per track; None = no limit. rekordbox stops storing at 10 WITHOUT saying
|
||||
# so, so the adapter refuses the 11th itself.
|
||||
max_memory_cues: int | None = None
|
||||
# A memory cue's colour is its own palette, not `palette` (rekordbox offers
|
||||
# 8 colours for memory cues against 16 for hot cues).
|
||||
memory_color: Literal["none", "palette"] = "none"
|
||||
memory_palette: list[str] = []
|
||||
types: list[CueType] = ["cue"]
|
||||
color: Literal["none", "free", "palette"] = "none"
|
||||
palette: list[str] = []
|
||||
@@ -78,18 +104,48 @@ class TrackCapabilities(BaseModel):
|
||||
# Tracks can be converted to native-instruments STEM files, which this
|
||||
# platform plays as stems (`apply_stem_swaps`).
|
||||
stem_convertible: bool = False
|
||||
# The musical key can be set (`set_key`) — what key analysis writes. Not
|
||||
# in `editable_fields`: a key is a wheel position, not free text.
|
||||
key_writable: bool = False
|
||||
# The audio files this library can hold, as lower-case suffixes. What a
|
||||
# browsed folder offers to add — a file the library would refuse, or that
|
||||
# the DJ app cannot play, is not worth listing as addable.
|
||||
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
|
||||
artwork: bool = False
|
||||
artwork_note: str | None = None
|
||||
# Whose filesystem an import destination is on. "host": this computer's,
|
||||
# browsed with the ordinary file browser. "library": the machine that holds
|
||||
# the library (a server), whose folders are listed through the library —
|
||||
# added audio is UPLOADED there.
|
||||
audio_destination: Literal["host", "library"] = "host"
|
||||
# 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):
|
||||
folders: bool = False
|
||||
smart: Literal["none", "read_only"] = "none"
|
||||
reorder: bool = False
|
||||
# A playlist can hold the same track more than once. Where it cannot, a
|
||||
# drop of tracks already there skips them rather than asking.
|
||||
duplicates: bool = False
|
||||
|
||||
|
||||
class PathCapabilities(BaseModel):
|
||||
# Path mapping, path rewriting and the open-time missing-files check apply.
|
||||
# False for a library held by a server: its mapping is the server's own
|
||||
# configuration, and this computer's drives are not where its files are.
|
||||
remappable: bool = True
|
||||
|
||||
|
||||
class SaveCapabilities(BaseModel):
|
||||
@@ -126,4 +182,5 @@ class Capabilities(BaseModel):
|
||||
grid: GridCapabilities = GridCapabilities()
|
||||
tracks: TrackCapabilities = TrackCapabilities()
|
||||
playlists: PlaylistCapabilities = PlaylistCapabilities()
|
||||
paths: PathCapabilities = PathCapabilities()
|
||||
save: SaveCapabilities
|
||||
@@ -25,9 +25,8 @@ MEMORY_COLOR = "#9AA1B2" # grey
|
||||
|
||||
|
||||
def effective_color(cue: CuePoint) -> str:
|
||||
"""`#RRGGBB` — the stored colour, or the type's."""
|
||||
"""`#RRGGBB` — the stored colour, or the type's: hot and memory cues alike
|
||||
(a memory cue's type colours it too, decided 2026-10-16)."""
|
||||
if cue.color:
|
||||
return cue.color.upper()
|
||||
if cue.role == "memory":
|
||||
return MEMORY_COLOR
|
||||
return TYPE_COLORS.get(cue.type, MEMORY_COLOR)
|
||||
@@ -167,21 +167,23 @@ class EditJournal:
|
||||
else:
|
||||
parts.append(f"{verb} {len(names)} {noun}s")
|
||||
|
||||
# --- hotcues: net change in count, scoped by how many tracks were touched ---
|
||||
hc_add = hc_del = 0
|
||||
hc_tracks: set[str] = set()
|
||||
# --- cues: net change in count, scoped by how many tracks were touched.
|
||||
# Memory cues (detail "memory") are counted apart from hotcues, so a
|
||||
# session of memory-cue edits is not described as hotcue work.
|
||||
counts = {kind: [0, 0, set()] for kind in ("hotcue", "memory cue")}
|
||||
grid_edit: set[str] = set()
|
||||
grid_del: set[str] = set()
|
||||
lock_on: set[str] = set()
|
||||
lock_off: set[str] = set()
|
||||
for c in self.changes:
|
||||
if c.scope == "cue":
|
||||
bucket = counts["memory cue" if c.detail == "memory" else "hotcue"]
|
||||
if c.target:
|
||||
hc_tracks.add(c.target)
|
||||
bucket[2].add(c.target)
|
||||
if c.op == "add":
|
||||
hc_add += 1
|
||||
bucket[0] += 1
|
||||
elif c.op == "delete":
|
||||
hc_del += 1
|
||||
bucket[1] += 1
|
||||
elif c.scope == "grid":
|
||||
# "delete" is the ONLY deletion op. Everything else — including
|
||||
# ops added later — counts as an edit, because mis-labelling an
|
||||
@@ -190,15 +192,17 @@ class EditJournal:
|
||||
elif c.scope == "lock":
|
||||
(lock_on if c.op == "on" else lock_off).add(c.target or "")
|
||||
|
||||
if hc_tracks:
|
||||
net = hc_add - hc_del
|
||||
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else ""
|
||||
for noun, (added, deleted, touched) in counts.items():
|
||||
if not touched:
|
||||
continue
|
||||
net = added - deleted
|
||||
scope = f" across {tracks(len(touched))}" if len(touched) > 1 else ""
|
||||
if net > 0:
|
||||
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}")
|
||||
parts.append(f"added {net} {noun}{'' if net == 1 else 's'}{scope}")
|
||||
elif net < 0:
|
||||
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}")
|
||||
parts.append(f"removed {-net} {noun}{'' if -net == 1 else 's'}{scope}")
|
||||
else: # net zero but there was activity (moves / retypes / add-then-delete)
|
||||
parts.append(f"adjusted hotcues{scope}")
|
||||
parts.append(f"adjusted {noun}s{scope}")
|
||||
|
||||
# --- beatgrids & lock: per-track counts ---
|
||||
if grid_edit:
|
||||
|
||||
@@ -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
|
||||
@@ -94,8 +102,14 @@ class ExportPayload:
|
||||
|
||||
tracks: list[ExportTrack] = field(default_factory=list)
|
||||
playlists: list[ExportPlaylist] = field(default_factory=list)
|
||||
#: The export's name, used for the folder its playlists are nested under.
|
||||
#: The export's name, used for the folder its playlists are nested under
|
||||
#: when `root_folder` is set.
|
||||
name: str = "Export"
|
||||
#: Nest the whole playlist tree (and "Other") in one folder named `name`.
|
||||
#: Off — the default, a Konduktor setting — the playlists sit at the
|
||||
#: library's top level: an export is a library of its own, so a folder
|
||||
#: saying where it came from is one more click at the gig.
|
||||
root_folder: bool = False
|
||||
#: Called by a writer before each slow step (e.g. decoding a track for its
|
||||
#: waveform) with a message for the status bar, and — for a per-track loop —
|
||||
#: `step` of `of`, which drives the progress bar. RAISES when the user has
|
||||
@@ -105,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.
|
||||
@@ -144,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."""
|
||||
|
||||
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
|
||||
Three rules:
|
||||
|
||||
* **This folder only.** Subfolders are not scanned — the tree is how you get to
|
||||
them — so a click on a drive root never walks the whole drive.
|
||||
them — so a click on a drive root never walks the whole drive. A folder
|
||||
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
|
||||
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
|
||||
* **A track id is the file's absolute path.** It is the one identity a loose
|
||||
file has, and it is what the audio route checks a request against.
|
||||
* **Tags are read once per folder state.** Reading tags opens every file, which
|
||||
@@ -26,6 +28,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
|
||||
@@ -150,6 +153,11 @@ class FolderSource:
|
||||
def audio_path(self, track_id: str) -> Path | None:
|
||||
return Path(track_id) if track_id in self._by_id else None
|
||||
|
||||
def audio_facts(self, track_ids: list[str]):
|
||||
from .adapter import local_audio_facts
|
||||
|
||||
return local_audio_facts(self, track_ids)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
@@ -160,17 +168,88 @@ class FolderSource:
|
||||
return capabilities_for(self.path)
|
||||
|
||||
|
||||
# A drop of a whole drive must not read tags for hours: past this many audio
|
||||
# files the rest are left out and the answer says so.
|
||||
MAX_DROPPED = 20_000
|
||||
|
||||
|
||||
@dataclass
|
||||
class Dropped:
|
||||
"""What a drop onto the window resolved to."""
|
||||
|
||||
tracks: list[Track] = field(default_factory=list)
|
||||
# Dropped FILES that are not audio this library can hold (or are gone).
|
||||
# Non-audio inside a dropped folder is not counted: an album folder's
|
||||
# cover and cue sheet are not something the user asked to add.
|
||||
skipped: int = 0
|
||||
# More than MAX_DROPPED audio files: the rest were left out.
|
||||
truncated: bool = False
|
||||
|
||||
|
||||
class FolderScanner:
|
||||
"""Scans folders on request, caching each until its contents change.
|
||||
|
||||
Also the gatekeeper for streaming: `source_for_file` answers only for a file
|
||||
found by a scan, so the audio route cannot be used to read an arbitrary path
|
||||
off the disk — only audio the user has browsed to.
|
||||
found by a scan — or dropped onto the window by the user — so the audio
|
||||
route cannot be used to read an arbitrary path off the disk, only audio the
|
||||
user has browsed to or handed over.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
|
||||
# Files dropped one by one: their folder was never scanned (and is not
|
||||
# cached as if it had been — a partial listing would hide its other
|
||||
# files from the sidebar), so each is held on its own.
|
||||
self._files: dict[str, Track] = {}
|
||||
|
||||
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
|
||||
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
|
||||
and OS-housekeeping folders left out, as the tree leaves them out),
|
||||
files as themselves. Every audio file found becomes addable and
|
||||
playable through the folder routes, exactly as if it had been browsed."""
|
||||
wanted = {f.lower() for f in formats}
|
||||
out = Dropped()
|
||||
seen: set[str] = set()
|
||||
|
||||
def take(tracks: list[Track]) -> bool:
|
||||
for t in tracks:
|
||||
if t.id in seen:
|
||||
continue
|
||||
if len(out.tracks) >= limit:
|
||||
out.truncated = True
|
||||
return False
|
||||
seen.add(t.id)
|
||||
out.tracks.append(t)
|
||||
return True
|
||||
|
||||
for raw in paths:
|
||||
path = Path(raw).expanduser()
|
||||
if path.is_dir():
|
||||
for folder in _walk(path):
|
||||
if not audio_files(folder, formats):
|
||||
continue
|
||||
if not take(self.scan(folder, formats).tracks):
|
||||
return out
|
||||
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
|
||||
track = self._file_track(path)
|
||||
if not take([track]):
|
||||
return out
|
||||
else:
|
||||
out.skipped += 1
|
||||
return out
|
||||
|
||||
def _file_track(self, path: Path) -> Track:
|
||||
key = str(path)
|
||||
with self._lock:
|
||||
hit = self._cache.get(str(path.parent))
|
||||
known = hit[2].track(key) if hit is not None else None
|
||||
if known is not None:
|
||||
return known
|
||||
track = read_track(path)
|
||||
with self._lock:
|
||||
self._files[key] = track
|
||||
return track
|
||||
|
||||
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
|
||||
folder = Path(folder)
|
||||
@@ -193,10 +272,32 @@ class FolderScanner:
|
||||
folder = str(Path(track_id).parent)
|
||||
with self._lock:
|
||||
hit = self._cache.get(folder)
|
||||
if hit is None or hit[2].track(track_id) is None:
|
||||
return None
|
||||
return hit[2]
|
||||
loose = self._files.get(track_id)
|
||||
if hit is not None and hit[2].track(track_id) is not None:
|
||||
return hit[2]
|
||||
if loose is not None:
|
||||
return FolderSource(Path(folder), [loose])
|
||||
return None
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._cache.clear()
|
||||
self._files.clear()
|
||||
|
||||
|
||||
def _walk(root: Path):
|
||||
"""`root` and every visible folder under it, depth first, sorted by name."""
|
||||
yield root
|
||||
try:
|
||||
with os.scandir(root) as it:
|
||||
subs = []
|
||||
for entry in it:
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
|
||||
subs.append(Path(entry.path))
|
||||
except OSError:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
for sub in sorted(subs, key=lambda p: p.name.lower()):
|
||||
yield from _walk(sub)
|
||||
@@ -213,24 +213,71 @@ def detect_grid(
|
||||
*,
|
||||
y: np.ndarray | None = None,
|
||||
sr: int = _SR,
|
||||
bpm: float | None = None,
|
||||
anchor: float | None = None,
|
||||
) -> GridResult:
|
||||
"""Detect a track's constant tempo and first beat.
|
||||
|
||||
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly.
|
||||
Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot).
|
||||
|
||||
Either half can be held fixed — the Analyze dialog's BPM and Grid ticks:
|
||||
- ``bpm`` given ("Grid" alone): that tempo is KEPT — no search, no
|
||||
round-BPM snap — and only where its beats fall is found. For a BPM the
|
||||
user trusts (typed, or a store's) and a grid that sits off the beat.
|
||||
- ``anchor`` given ("BPM" alone): the tempo is detected and the anchor
|
||||
returned as given, so the grid's downbeat stays where the user put it.
|
||||
``drift_ms`` is then measured against THAT anchor: large means the kept
|
||||
anchor does not sit on the detected beat.
|
||||
"""
|
||||
if bpm is not None and anchor is not None:
|
||||
raise ValueError("Hold the BPM or the anchor, not both — there would be nothing to detect")
|
||||
if bpm is not None and not (20.0 <= bpm <= 400.0):
|
||||
raise ValueError(f"Not a usable BPM: {bpm}")
|
||||
if y is None:
|
||||
import librosa
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
from . import waveform
|
||||
y, sr = waveform.load(audio_path, sr=sr)
|
||||
y = np.asarray(y, dtype=np.float32)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.5:
|
||||
raise ValueError("Track is too short to detect a tempo")
|
||||
|
||||
lo, hi = bpm_range
|
||||
low = _onset(_band_env(y, sr, 30.0, 150.0))
|
||||
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
|
||||
attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3))
|
||||
|
||||
if bpm is not None:
|
||||
period = 60.0 / bpm
|
||||
if not np.isfinite(attack).all() or attack.max() <= 0:
|
||||
raise ValueError("No onsets found")
|
||||
phase = _phase(low, attack, period)
|
||||
return GridResult(
|
||||
bpm=float(bpm),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(_drift(attack, bpm, phase) * 1000.0, 1),
|
||||
)
|
||||
|
||||
found_bpm, phase, drift = _detect_tempo(y, sr, low, attack, bpm_range, duration)
|
||||
period = 60.0 / found_bpm
|
||||
if anchor is not None:
|
||||
return GridResult(
|
||||
bpm=round(found_bpm, 4),
|
||||
anchor=float(anchor),
|
||||
duration=duration,
|
||||
drift_ms=round(_drift(attack, found_bpm, float(anchor) % period) * 1000.0, 1),
|
||||
)
|
||||
return GridResult(
|
||||
bpm=round(found_bpm, 4),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(drift * 1000.0, 1),
|
||||
)
|
||||
|
||||
|
||||
def _detect_tempo(y, sr, low, attack, bpm_range, duration) -> tuple[float, float, float]:
|
||||
"""(bpm, phase, drift) — the tempo search, octave rule and round snap."""
|
||||
lo, hi = bpm_range
|
||||
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
|
||||
full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
|
||||
o_tempo = low + mid + 0.5 * full
|
||||
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0:
|
||||
@@ -260,15 +307,7 @@ def detect_grid(
|
||||
bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
|
||||
phase = _phase(low, attack, 60.0 / bpm)
|
||||
drift = _drift(attack, bpm, phase)
|
||||
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration)
|
||||
|
||||
period = 60.0 / bpm
|
||||
return GridResult(
|
||||
bpm=round(bpm, 4),
|
||||
anchor=round(_first_beat(low + attack, phase, period), 4),
|
||||
duration=duration,
|
||||
drift_ms=round(drift * 1000.0, 1),
|
||||
)
|
||||
return _snap_round(low, attack, bpm, phase, drift, duration)
|
||||
|
||||
|
||||
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]:
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""What an analysis does to one track's grid, given the BPM / Grid ticks.
|
||||
|
||||
One pure function, so the batch, the dialog's counts and the tests cannot come
|
||||
to mean different things. Decided with the user (2026-10-04, see
|
||||
`.claude/discussions/discuss-key-analysis-2026-10-04.md`):
|
||||
|
||||
- BPM + Grid: a full analysis. A track that already has a grid is replaced
|
||||
only when the user ticked "Replace" — a grid may hold hand edits.
|
||||
- BPM alone: re-detect the tempo, KEEP the anchor (the first marker).
|
||||
- Grid alone: KEEP the BPM, find only where the beats fall.
|
||||
- With one tick, adjusting the existing grid is the point, so "Replace" does
|
||||
not apply; a track with nothing to keep (no grid / no BPM) is analysed in
|
||||
full rather than skipped — one tick never leaves a track worse off.
|
||||
- A multi-marker (flexible) grid is skipped by BPM alone and Grid alone: its
|
||||
tempo changes are exactly what one constant tempo would flatten.
|
||||
- A locked grid is skipped whatever is ticked.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal, Sequence
|
||||
|
||||
Action = Literal["none", "full", "bpm", "phase", "skip"]
|
||||
SkipReason = Literal["locked", "existing", "flexible"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GridStep:
|
||||
action: Action
|
||||
reason: SkipReason | None = None
|
||||
hold_bpm: float | None = None # "phase": the tempo kept
|
||||
hold_anchor: float | None = None # "bpm": the anchor kept (seconds)
|
||||
|
||||
|
||||
def plan_grid(
|
||||
*,
|
||||
bpm: bool,
|
||||
grid: bool,
|
||||
markers: Sequence, # the track's grid markers (`.start`, `.bpm`), any order
|
||||
track_bpm: float | None,
|
||||
locked: bool,
|
||||
replace_existing: bool,
|
||||
) -> GridStep:
|
||||
if not (bpm or grid):
|
||||
return GridStep("none")
|
||||
if locked:
|
||||
return GridStep("skip", "locked")
|
||||
ordered = sorted(markers, key=lambda m: m.start)
|
||||
if bpm and grid:
|
||||
if ordered and not replace_existing:
|
||||
return GridStep("skip", "existing")
|
||||
return GridStep("full")
|
||||
if len(ordered) > 1:
|
||||
return GridStep("skip", "flexible")
|
||||
if bpm: # BPM alone
|
||||
if not ordered:
|
||||
return GridStep("full")
|
||||
return GridStep("bpm", hold_anchor=float(ordered[0].start))
|
||||
# Grid alone
|
||||
held = float(ordered[0].bpm) if ordered else (float(track_bpm) if track_bpm else None)
|
||||
if not held or held <= 0:
|
||||
return GridStep("full")
|
||||
return GridStep("phase", hold_bpm=held)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Musical key detection: a small convolutional network, run in numpy.
|
||||
|
||||
Why a network and not key profiles. The classic method — fold the spectrum
|
||||
into a 12-bin chroma vector and correlate it with a major / minor template —
|
||||
was benchmarked first on GiantSteps (604 Beatport previews, keys corrected by
|
||||
hand), over Krumhansl, Temperley, Sha'ath (KeyFinder) and Faraldo's EDM
|
||||
templates and every combination of octave range, compression and harmonic
|
||||
filtering tried: the best got 49.5% exactly right. A template sees only how
|
||||
much of each pitch class there is; a network also sees WHERE in pitch it is
|
||||
(the bass line, the pad, the lead) and learns from data what states a key.
|
||||
|
||||
The model follows Korzeniowski & Widmer, "End-to-end musical key estimation
|
||||
using a convolutional neural network" (EUSIPCO 2017): five 5x5 convolutions,
|
||||
then a per-frame dense layer over the whole pitch axis — a key is NOT
|
||||
pitch-invariant, so nothing pools over frequency — then 24 logits averaged
|
||||
over the track. ~76 k weights per network; `key_model.npz` holds an ensemble
|
||||
of three (logits averaged), trained by `backend/train_key_model.py` on the
|
||||
SEPARATE GiantSteps MTG dataset. torch is used only to train: the backend
|
||||
never imports it.
|
||||
|
||||
Measured (`bench_key_detect.py`, 2026-10-04): GiantSteps 69.4% exact, 83.4%
|
||||
harmonically mixable (exact, a fifth, or the relative key), MIREX 0.758 —
|
||||
about the published figure for this design. Against the key tags of 47 local
|
||||
files (Traktor's analysis, not ground truth) it agrees on 62%, 77% mixable.
|
||||
`confidence` tracks correctness (82% exact above 0.7, ~40% below 0.4) but even
|
||||
a low one is ten times better than chance, so a key is always returned for
|
||||
music; only silence and clips under 5 s get None.
|
||||
|
||||
Cost on a 6.7-minute track: CQT 0.1 s, the three networks 0.5 s — beside the
|
||||
decode, which the grid analysis shares.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import musical_key
|
||||
|
||||
SR = 22050
|
||||
HOP = 4096 # ~5.4 frames/s: key is a slow property
|
||||
BINS_PER_OCTAVE = 36 # three per semitone, so a detuned track still lands in one
|
||||
FMIN_NOTE = "C1"
|
||||
OCTAVES = 7 # C1..C8: the input window plus room to pitch-shift it
|
||||
# The network's input: C2..C7 (65 Hz - 2.1 kHz), where bass lines, pads and
|
||||
# leads state the key. The octave either side is only there so training can
|
||||
# shift the window by up to six semitones.
|
||||
WINDOW = (36, 216)
|
||||
|
||||
_MODEL = Path(__file__).with_name("key_model.npz")
|
||||
_TIME_CHUNK = 256 # frames per im2col block: bounds memory to tens of MB
|
||||
|
||||
PITCH_NAMES = musical_key.SPELLING
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KeyResult:
|
||||
pitch_class: int # tonic, 0 = C
|
||||
mode: Literal["major", "minor"]
|
||||
wheel: int # Camelot position 1-12, the generic model's key
|
||||
confidence: float # the network's probability for this key, 0-1
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return PITCH_NAMES[self.pitch_class] + ("m" if self.mode == "minor" else "")
|
||||
|
||||
|
||||
def camelot_wheel(pitch_class: int, mode: str) -> int:
|
||||
"""Camelot position: C major = 8B, A minor = 8A; one step = a fifth."""
|
||||
return musical_key.wheel_of(pitch_class, mode)
|
||||
|
||||
|
||||
def features(y: np.ndarray, sr: int = SR) -> np.ndarray:
|
||||
"""Log-magnitude constant-Q spectrogram, (OCTAVES * 36, frames), float32.
|
||||
|
||||
Normalised to the track's own loudest bin, so a quiet master and a loud
|
||||
one give the same picture. Training calls this same function."""
|
||||
import librosa
|
||||
|
||||
if sr != SR:
|
||||
y = librosa.resample(y, orig_sr=sr, target_sr=SR)
|
||||
C = np.abs(librosa.cqt(
|
||||
y, sr=SR, hop_length=HOP, fmin=librosa.note_to_hz(FMIN_NOTE),
|
||||
n_bins=OCTAVES * BINS_PER_OCTAVE, bins_per_octave=BINS_PER_OCTAVE, tuning=0.0,
|
||||
))
|
||||
peak = float(C.max()) or 1.0
|
||||
return np.log1p(1000.0 * C / peak).astype(np.float32)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _members() -> list[dict[str, np.ndarray]]:
|
||||
"""The ensemble: `key_model.npz` holds N networks as `m<i>.<param>`, plus
|
||||
`pool` (frequency bins averaged before the dense layer; 1 = none)."""
|
||||
with np.load(_MODEL) as z:
|
||||
flat = {k: z[k] for k in z.files}
|
||||
pool = int(flat.pop("pool"))
|
||||
members: dict[int, dict[str, np.ndarray]] = {}
|
||||
for k, v in flat.items():
|
||||
i, name = k.split(".", 1)
|
||||
members.setdefault(int(i[1:]), {})[name] = v.astype(np.float32)
|
||||
for m in members.values():
|
||||
m["pool"] = np.array(pool)
|
||||
return [members[i] for i in sorted(members)]
|
||||
|
||||
|
||||
def _elu(x: np.ndarray) -> np.ndarray:
|
||||
return np.where(x > 0, x, np.expm1(np.minimum(x, 0)))
|
||||
|
||||
|
||||
def _conv5(x: np.ndarray, w: np.ndarray, b: np.ndarray) -> np.ndarray:
|
||||
"""'same' 5x5 convolution (cross-correlation, as torch's Conv2d).
|
||||
x: (cin, F, T), w: (cout, cin, 5, 5) -> (cout, F, T)."""
|
||||
cin, f, t = x.shape
|
||||
xp = np.pad(x, ((0, 0), (2, 2), (2, 2)))
|
||||
out = np.empty((w.shape[0], f, t), np.float32)
|
||||
for t0 in range(0, t, _TIME_CHUNK):
|
||||
t1 = min(t, t0 + _TIME_CHUNK)
|
||||
view = np.lib.stride_tricks.sliding_window_view(xp[:, :, t0:t1 + 4], (5, 5), axis=(1, 2))
|
||||
out[:, :, t0:t1] = np.tensordot(w, view, axes=([1, 2, 3], [0, 3, 4]))
|
||||
return out + b[:, None, None]
|
||||
|
||||
|
||||
def _network(x: np.ndarray, w: dict[str, np.ndarray]) -> np.ndarray:
|
||||
"""One member's 24 logits, averaged over time. x: (1, F, T)."""
|
||||
n = sum(1 for k in w if k.startswith("conv") and k.endswith(".weight"))
|
||||
for i in range(n):
|
||||
x = _elu(_conv5(x, w[f"conv{i}.weight"], w[f"conv{i}.bias"]))
|
||||
pool = int(w["pool"]) # average within a semitone
|
||||
if pool > 1:
|
||||
f = x.shape[1] // pool * pool
|
||||
x = x[:, :f].reshape(x.shape[0], f // pool, pool, -1).mean(axis=2)
|
||||
dw = w["dense.weight"][..., 0] # (hid, ch, F)
|
||||
h = _elu(np.tensordot(dw, x, axes=([1, 2], [0, 1])) + w["dense.bias"][:, None])
|
||||
out = w["out.weight"][:, :, 0, 0] @ h + w["out.bias"][:, None] # (24, T)
|
||||
return out.mean(axis=1)
|
||||
|
||||
|
||||
def logits(spec: np.ndarray) -> np.ndarray:
|
||||
"""The ensemble's 24 logits — major C..B, then minor C..B — for a
|
||||
`features()` spectrogram: each member's, averaged."""
|
||||
x = spec[WINDOW[0]:WINDOW[1]][None]
|
||||
return np.mean([_network(x, w) for w in _members()], axis=0)
|
||||
|
||||
|
||||
def detect_key_samples(y: np.ndarray, sr: int) -> KeyResult | None:
|
||||
"""The key of decoded mono audio, or None for silence / too short to say."""
|
||||
if y.size < sr * 5 or not np.any(y):
|
||||
return None
|
||||
z = logits(features(y, sr)).astype(np.float64)
|
||||
p = np.exp(z - z.max())
|
||||
p /= p.sum()
|
||||
k = int(np.argmax(p))
|
||||
pc, mode = k % 12, ("minor" if k >= 12 else "major")
|
||||
return KeyResult(pc, mode, camelot_wheel(pc, mode), float(p[k]))
|
||||
|
||||
|
||||
def with_detected_key(track, y: np.ndarray | None, sr: int):
|
||||
"""`track` (a generic `Track`) with a detected key if it has none of its
|
||||
own — for a file being ADDED, which is decoded anyway. A key the track
|
||||
already carries (its tags, its source library) is never second-guessed,
|
||||
and a detection failure leaves the track as it was: a missing key is not
|
||||
worth failing an add over."""
|
||||
if getattr(track, "key_wheel", None) is not None or y is None:
|
||||
return track
|
||||
try:
|
||||
found = detect_key_samples(y, sr)
|
||||
except Exception: # noqa: BLE001
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
|
||||
return track
|
||||
if found is None:
|
||||
return track
|
||||
return track.model_copy(update={"key": found.name, "key_wheel": found.wheel, "key_mode": found.mode})
|
||||
|
||||
|
||||
def detect_key(audio_path: str) -> KeyResult | None:
|
||||
from . import waveform
|
||||
|
||||
y, sr = waveform.load(audio_path, sr=SR)
|
||||
return detect_key_samples(y, sr)
|
||||
Binary file not shown.
@@ -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)")
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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):
|
||||
@@ -130,6 +139,9 @@ class PlaylistNode(BaseModel):
|
||||
can_rename: bool = False
|
||||
can_delete: bool = False
|
||||
can_contain_children: bool = False # a valid parent for a new playlist
|
||||
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
|
||||
# its siblings or moved into another folder.
|
||||
can_move: bool = False
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
@@ -141,8 +153,8 @@ PlaylistNode.model_rebuild()
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: CueType = "cue"
|
||||
# "memory" cues have no bank slot. Only Rekordbox has them, so they are
|
||||
# modelled and preserved but not yet editable anywhere.
|
||||
# A "memory" cue has no bank slot: Rekordbox's / OneLibrary's memory cues,
|
||||
# Traktor's cues on no pad (HOTCUE="-1"). Addressed by `id`, not `slot`.
|
||||
role: CueRole = "hotcue"
|
||||
start: float # seconds
|
||||
length: float # seconds (>0 for loops)
|
||||
@@ -155,6 +167,10 @@ class CuePoint(BaseModel):
|
||||
# Index of the grid marker this cue mirrors, where the platform pairs them.
|
||||
# A display hint only; None on platforms that do not.
|
||||
grid_marker: int | None = None
|
||||
# The handle the memory-cue commands take (None on a hot cue, which is
|
||||
# addressed by slot). Opaque and adapter-defined; an edit of THIS cue may
|
||||
# change it, which is fine because every command returns fresh TrackCues.
|
||||
id: str | None = None
|
||||
|
||||
|
||||
class GridMarker(BaseModel):
|
||||
@@ -194,6 +210,9 @@ class LibraryInfo(BaseModel):
|
||||
path: str
|
||||
display_name: str # short label for the status bar
|
||||
version: str | None = None
|
||||
# Set when the library is held by a server: {id, name, via} of the saved
|
||||
# remote it was opened through. None for a library on this computer.
|
||||
remote: dict | None = None
|
||||
|
||||
|
||||
class PlatformOption(BaseModel):
|
||||
@@ -208,7 +227,7 @@ class PlatformOption(BaseModel):
|
||||
platform: str
|
||||
name: str
|
||||
library_label: str
|
||||
selects: Literal["file", "directory"] = "file"
|
||||
selects: Literal["file", "directory", "remote"] = "file"
|
||||
installed: bool = False
|
||||
#: How many libraries this platform has right now; `installed` is `found > 0`.
|
||||
found: int = 0
|
||||
@@ -219,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):
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Musical keys: the generic form and the notations DJ software writes.
|
||||
|
||||
The generic model carries a key as a Camelot wheel position (1-12) plus a mode
|
||||
(`Track.key_wheel` / `key_mode`); one step round the wheel is a fifth, and the
|
||||
minor key on a number is the relative of the major one. Each platform STORES a
|
||||
key in its own notation, and a library also holds whatever another tool put
|
||||
there — a rekordbox stick's key table carries "12A" beside "Abm" when tracks
|
||||
arrived with Camelot tags. So parsing accepts every notation, and rendering is
|
||||
always explicit about which one it writes.
|
||||
|
||||
Notations:
|
||||
- "camelot": 8A / 8B (Mixed In Key's wheel; A = minor)
|
||||
- "open_key": 1m / 1d (Traktor's default; Open Key 1 = Camelot 8)
|
||||
- "musical": Am / C, with rekordbox's spelling: flats for Db Eb Ab Bb, and
|
||||
F# — measured from the key rows rekordbox 7 itself created (Abm, Dbm, Ebm,
|
||||
Eb; the six-sharp key was not among them).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
Mode = Literal["major", "minor"]
|
||||
Notation = Literal["camelot", "open_key", "musical"]
|
||||
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_MUSICAL = re.compile(r"^([A-G])\s*([#b♯♭]?)\s*(m|min|minor|maj|major)?$", re.I)
|
||||
|
||||
_PITCH = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
|
||||
SPELLING = ("C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
|
||||
|
||||
|
||||
def wheel_of(pitch_class: int, mode: Mode) -> int:
|
||||
"""Camelot position of a tonic: C major = 8B, A minor = 8A."""
|
||||
return (((7 * pitch_class) % 12 + (7 if mode == "major" else 4)) % 12) + 1
|
||||
|
||||
|
||||
def pitch_class_of(wheel: int, mode: Mode) -> int:
|
||||
"""The tonic (0 = C) at a Camelot position — `wheel_of`'s inverse."""
|
||||
return (7 * ((wheel - 1) - (7 if mode == "major" else 4))) % 12
|
||||
|
||||
|
||||
def parse(text: str | None) -> tuple[int | None, Mode | None]:
|
||||
"""(wheel, mode) for a key in any notation; (None, None) if unreadable.
|
||||
|
||||
A bare number-and-letter is ambiguous only in principle: Camelot uses A/B
|
||||
and Open Key m/d, so the letter says which."""
|
||||
if not text:
|
||||
return None, None
|
||||
s = text.strip()
|
||||
if m := _CAMELOT.match(s):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return n, "minor" if m.group(2).lower() == "a" else "major"
|
||||
return None, None
|
||||
if m := _OPEN_KEY.match(s):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
|
||||
return None, None
|
||||
if m := _MUSICAL.match(s):
|
||||
letter, accidental, quality = m.group(1).upper(), m.group(2), (m.group(3) or "")
|
||||
pc = _PITCH[letter] + {"#": 1, "♯": 1, "b": -1, "♭": -1}.get(accidental, 0)
|
||||
# "m" alone is minor; "maj"/"major" major; "min"/"minor" minor.
|
||||
q = quality.lower()
|
||||
mode: Mode = "minor" if q in ("m", "min", "minor") else "major"
|
||||
return wheel_of(pc % 12, mode), mode
|
||||
return None, None
|
||||
|
||||
|
||||
def render(wheel: int | None, mode: str | None, notation: Notation) -> str | None:
|
||||
"""A key in `notation`, or None when the position is unknown — a made-up
|
||||
key is worse than a blank one."""
|
||||
if not wheel or not (1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
return None
|
||||
if notation == "camelot":
|
||||
return f"{wheel}{'A' if mode == 'minor' else 'B'}"
|
||||
if notation == "open_key":
|
||||
return f"{((wheel + 4) % 12) + 1}{'m' if mode == 'minor' else 'd'}"
|
||||
return SPELLING[pitch_class_of(wheel, mode)] + ("m" if mode == "minor" else "")
|
||||
|
||||
|
||||
def notation_of(text: str | None) -> Notation | None:
|
||||
"""Which notation a stored key string is written in."""
|
||||
if not text:
|
||||
return None
|
||||
s = text.strip()
|
||||
if _CAMELOT.match(s):
|
||||
return "camelot"
|
||||
if _OPEN_KEY.match(s):
|
||||
return "open_key"
|
||||
if _MUSICAL.match(s):
|
||||
return "musical"
|
||||
return None
|
||||
@@ -54,6 +54,10 @@ class PathMapping:
|
||||
return True
|
||||
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
|
||||
|
||||
def inverted(self) -> "PathMapping":
|
||||
"""The mapping back: a path HERE → the form the library stores."""
|
||||
return PathMapping(self.to_prefix, self.from_prefix)
|
||||
|
||||
def apply(self, os_path: Path) -> Path:
|
||||
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
|
||||
path unchanged when it doesn't match (non-matching tracks untouched)."""
|
||||
@@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str:
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
|
||||
|
||||
def stored_form(os_path: Path, mappings) -> Path:
|
||||
"""`os_path` as the library STORES its paths, when it sits under where one
|
||||
of `mappings` points (the first that does).
|
||||
|
||||
A library opened through a mapping (a server holding a collection made on
|
||||
another computer) stores every path in the other computer's form. A file
|
||||
added through that mapping is written in the same form, so the library
|
||||
keeps ONE convention — and still opens, mapping and all, where it was made.
|
||||
"""
|
||||
for mapping in mappings:
|
||||
if mapping is None or mapping.empty:
|
||||
continue
|
||||
back = mapping.inverted()
|
||||
if back.matches(os_path):
|
||||
return back.apply(os_path)
|
||||
return os_path
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Opening a file for reading with PyAV, on every PyAV version the app ships.
|
||||
|
||||
A file whose tags are not valid UTF-8 must still open: it is still audio.
|
||||
PyAV 18 decodes tags strictly by default and raises UnicodeDecodeError at open
|
||||
unless given `metadata_errors="ignore"`; PyAV 19 REMOVED that keyword (passing
|
||||
it is a TypeError) and opens such a file as it is, the bad bytes as surrogates.
|
||||
Measured on both with a generated M4A and MP3 whose title is invalid UTF-8.
|
||||
|
||||
The keyword once went straight into `av.open`, which worked on the dev venv's
|
||||
18.1 while CI's fresh install took 19.0.1: every stem file then failed to open
|
||||
in the released app, and the deck played stem tracks as the mix. Every read
|
||||
goes through `open_input`, so the difference lives in one place.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@cache
|
||||
def _takes_metadata_errors() -> bool:
|
||||
import av
|
||||
|
||||
return int(av.__version__.split(".")[0]) < 19
|
||||
|
||||
|
||||
def open_input(path: Path | str):
|
||||
"""`av.open(path)` for reading, tolerant of tags that are not UTF-8."""
|
||||
import av
|
||||
|
||||
if _takes_metadata_errors():
|
||||
return av.open(str(path), metadata_errors="ignore")
|
||||
return av.open(str(path))
|
||||
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user