Compare commits

..
Author SHA1 Message Date
patben8 f655bb4cf2 Implemented demucs engine 2026-09-30 19:26:00 +02:00
patben8 e4e98eda3f Implemented Discard changes button 2026-09-30 17:07:26 +02:00
patben8 4e875958a7 Implemented foundation of STEM support 2026-09-30 17:07:06 +02:00
patben8 387f97853d Fixed track collision bug 2026-09-30 15:54:49 +02:00
patben8 3c4238f60c Refined Rekordbox timing fix 2026-09-30 13:18:56 +02:00
patben8 d087310a9d Refined traktor timing fix 2026-09-30 11:18:10 +02:00
patben8 2a4c403d43 Implemented traktor utility fixes 2026-09-30 10:10:37 +02:00
361 changed files with 4538 additions and 48149 deletions

No files matched your search

-97
View File
@@ -1,97 +0,0 @@
"""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()
+6 -125
View File
@@ -55,11 +55,10 @@ jobs:
with:
python-version: "3.12"
# --- Step 1: freeze the FastAPI backend into a onedir sidecar folder ---
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
# build_sidecar.* stages it as
# 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/`.
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
# which tauri.conf.json's externalBin bundles into the app.
- name: Install backend deps
working-directory: backend
run: |
@@ -86,31 +85,20 @@ 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), 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.
# (the .msi is intentionally left out).
- 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'
@@ -118,7 +106,6 @@ 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
@@ -127,52 +114,6 @@ 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.
@@ -181,7 +122,6 @@ 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
@@ -196,73 +136,14 @@ 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 }}
body_path: release-notes.md
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
generate_release_notes: true # auto changelog from commits/PRs since last release
fail_on_unmatched_files: true
files: |
release/*.dmg
release/*.exe
release/*.tar.gz
release/latest.json
files: artifacts/**/*
-3
View File
@@ -51,6 +51,3 @@ backend/dist/
# ---- Stem engine (PyInstaller onedir build) ----
engine/build/
engine/dist/
# ---- Rubber Band build (frontend/rubberband/build.sh downloads + compiles here) ----
frontend/rubberband/upstream/
+29 -106
View File
@@ -1,27 +1,21 @@
# 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 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)).
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 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.
This mirrors the macOS build exactly; only the toolchain install and the
sidecar-build command differ.
## 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 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.
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>.
Then, from the repo root:
@@ -39,120 +33,49 @@ npm install
cd ..
```
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
cd backend
.\.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
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
cd backend
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
.\.venv\Scripts\Activate.ps1 # if not already active
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
cd ..
# 2) Build the app (its beforeBuildCommand runs the Vite build)
# 2) Build the app
cd frontend
npx tauri build --config src-tauri/tauri.unsigned.conf.json
npx tauri build
```
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\nsis\Konduktor_<version>_x64-setup.exe
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
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
```
`<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`.
Either one installs the app (bundling the sidecar `.exe` alongside it).
## Rebuilding after changes
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.
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).
## Known Windows caveats
- **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**.
- **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.)
- **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.
- **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.
- **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.
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
+103 -1564
View File
File diff suppressed because it is too large. Load diff
+197 -125
View File
@@ -1,141 +1,213 @@
<p align="center">
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
</p>
# Konduktor
<h1 align="center">Konduktor</h1>
**A fast, modern home for your Traktor collection.**
<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>
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">
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
</p>
![Konduktor: the prep deck with a track loaded, above a playlist](docs/screenshots/library.png)
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.
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.
---
## One app for every library
## Why you'll like it
<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
![The prep deck in beatgrid editing mode](docs/screenshots/deck.png)
- 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
![A stem file in the deck: drums, bass, synths and vocals each in their own lane](docs/screenshots/stems.png)
**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 |
|:---:|:---:|
| ![Auto Hotcues: choose an event for each pad](docs/screenshots/auto-hotcues.png) | ![Analyze: BPM, grid and key](docs/screenshots/analyze.png) |
| 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.
- **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.
---
## Get Konduktor
## Getting started
Download the latest build from
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows.
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.
> **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**.
### 1. Install (once)
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
> `collection.nml` when it quits, which would overwrite your changes.
**Backend** — needs Python 3.11+. Create a virtual environment and install the
dependencies:
Want to run it from source or build it yourself? See
[docs/BUILDING.md](docs/BUILDING.md).
```bash
cd backend
python3 -m venv .venv # Windows: python -m venv .venv
```
## License
Activate it, then install:
[AGPL-3.0](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.
+1 -7
View File
@@ -6,8 +6,6 @@ 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
@@ -104,9 +102,6 @@ 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"]
@@ -124,8 +119,7 @@ def main() -> int:
for name, audio, r0, rb in refs:
t0 = time.perf_counter()
try:
hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
res = detect(str(audio), **hold)
res = detect(str(audio))
except Exception as ex: # a failure is a data point, not a crash
print(f" FAIL {name[:48]:48} {ex}")
rows.append(None)
-172
View File
@@ -1,172 +0,0 @@
"""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)
-156
View File
@@ -1,156 +0,0 @@
"""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()
+10 -17
View File
@@ -1,7 +1,6 @@
# 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\
# 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\...
#
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
# cd backend
@@ -16,19 +15,13 @@ Set-Location $Root
$Py = Join-Path $Root ".venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { $Py = "python" }
# 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\"
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
# 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()
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
$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\"
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
+23 -19
View File
@@ -1,8 +1,7 @@
#!/usr/bin/env bash
# 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/
# 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/…
#
# One-time: pip install -r requirements-build.txt (into the backend venv).
set -euo pipefail
@@ -10,20 +9,25 @@ 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 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.
# 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.
# 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/"
# 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
-321
View File
@@ -1,321 +0,0 @@
"""Kit G1 — what Traktor 4.5 does with gain (dev only, like dev_stems.py).
Answers, by measuring in Traktor itself (see
.claude/discussions/discuss-gain-normalization-2026-10-19.md, "Kit G1"):
1. Does a LEVEL change to a file make Traktor re-analyse it (LOUDNESS,
BPM/grid, AUDIO_ID)? MP3 by lossless frame gain (same size; + an APE undo
tag; + the mtime put back), FLAC re-written exactly, and a control whose
mtime alone changes.
2. Does Traktor KEEP a LOUDNESS Konduktor writes — on an entry it analysed
(AUDIO_ID kept), and on one Konduktor added (AUDIO_ID empty)?
3. Which LOUDNESS attribute drives the deck's auto-gain (the three are set
to values that cannot be confused)?
python dev_gain_kit.py prepare # build the kit folder
# -> in Traktor: import the folder, analyse, quit
python dev_gain_kit.py apply # change the files + write LOUDNESS
# -> in Traktor: load each G1 track, note the gain knob, quit
python dev_gain_kit.py report # what Traktor changed
Traktor must be closed for `apply`. The collection is saved through
TraktorStore (backup-first, byte-exact render).
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
import numpy as np
NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
KITS = Path.home() / "Music/Konduktor Stem Test"
KIT = KITS / "Kit G1"
STEPS = -2 # global_gain steps of 2^(1/4): -2 = -3.01 dB
# name -> (source, what happens at `apply`)
FILES = {
"G1-A0 control touch.mp3": (KITS / "Kit 2/K2 01 All I Need.mp3", "mtime only"),
"G1-A1 mp3 framegain.mp3": (KITS / "Kit 2/K1 01 Abyss of Love - Franky Rizardo Remix.mp3", "frame gain"),
"G1-A2 mp3 framegain ape.mp3": (KITS / "Kit 2/K4 Ragga Bomb with Ragga Twins.mp3", "frame gain + APE undo tag"),
"G1-A3 flac exact.flac": (KITS / "Kit 4/K4-3 flac.flac", "exact gain, re-written"),
"G1-A4 mp3 framegain same mtime.mp3": (KITS / "Kit 4/K4-5 mp3 cbr noxing.mp3", "frame gain, mtime restored"),
"G1-B1 loudness written.mp3": (KITS / "Kit 2/K3 01 Motorola.mp3", "LOUDNESS written, AUDIO_ID kept"),
}
# Added by Konduktor at `apply` (so Traktor never analysed it): AUDIO_ID empty.
B2 = ("G1-B2 konduktor added.mp3", KITS / "Kit 4/K4-4 mp3 cbr xing.mp3")
# Values no real analysis would give, so the deck's knob says which one it read.
B1_LOUDNESS = (2.5, -6.0, 6.0) # PEAK_DB, PERCEIVED_DB, ANALYZED_DB
B2_LOUDNESS = (2.5, -4.0, 4.0)
# ── MP3 frame gain (mp3gain's edit) ──────────────────────────────────────────
_BITRATE = {
True: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
False: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
}
_RATE = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]}
def _get(buf: bytearray, bit: int, n: int) -> int:
v = 0
for i in range(n):
v = (v << 1) | ((buf[(bit + i) >> 3] >> (7 - ((bit + i) & 7))) & 1)
return v
def _put(buf: bytearray, bit: int, n: int, v: int) -> None:
for i in range(n):
b = (v >> (n - 1 - i)) & 1
byte, shift = (bit + i) >> 3, 7 - ((bit + i) & 7)
buf[byte] = (buf[byte] & ~(1 << shift) & 0xFF) | (b << shift)
def _header(buf: bytearray, pos: int):
if pos + 4 > len(buf) or buf[pos] != 0xFF or (buf[pos + 1] & 0xE0) != 0xE0:
return None
ver, layer = (buf[pos + 1] >> 3) & 3, (buf[pos + 1] >> 1) & 3
br_i, sr_i = buf[pos + 2] >> 4, (buf[pos + 2] >> 2) & 3
if ver == 1 or layer != 1 or br_i in (0, 15) or sr_i == 3:
return None
mpeg1 = ver == 3
br, sr = _BITRATE[mpeg1][br_i], _RATE[ver][sr_i]
pad = (buf[pos + 2] >> 1) & 1
length = (144000 if mpeg1 else 72000) * br // sr + pad
return {
"mpeg1": mpeg1,
"crc": (buf[pos + 1] & 1) == 0,
"nch": 1 if (buf[pos + 3] >> 6) == 3 else 2,
"len": length,
}
def _gain_bits(h: dict) -> list[int]:
"""Bit offsets (from the side info's start) of every granule's global_gain."""
nch = h["nch"]
if h["mpeg1"]:
start, block, granules = 9 + (5 if nch == 1 else 3) + 4 * nch, 59, 2
else:
start, block, granules = 8 + (1 if nch == 1 else 2), 63, 1
return [start + (g * nch + c) * block + 21 for g in range(granules) for c in range(nch)]
def mp3_frame_gain(path: Path, steps: int) -> int:
"""Add `steps` to every audio granule's global_gain in place; returns frames edited."""
buf = bytearray(path.read_bytes())
pos = 0
if buf[:3] == b"ID3":
size = (buf[6] << 21) | (buf[7] << 14) | (buf[8] << 7) | buf[9]
pos = 10 + size + (10 if buf[5] & 0x10 else 0)
frames = 0
first = True
while (h := _header(buf, pos)) is not None:
side = pos + 4 + (2 if h["crc"] else 0)
if h["crc"]:
raise SystemExit(f"{path.name}: CRC-protected frames are not handled by the kit")
side_len = (17 if h["nch"] == 1 else 32) if h["mpeg1"] else (9 if h["nch"] == 1 else 17)
tag = bytes(buf[side + side_len : side + side_len + 4])
if first and (tag in (b"Xing", b"Info") or bytes(buf[pos + 36 : pos + 40]) == b"VBRI"):
pass # the header frame is not audio (Traktor decodes it anyway — leave it as it is)
else:
for off in _gain_bits(h):
g = _get(buf, side * 8 + off, 8) + steps
if not 0 <= g <= 255:
raise SystemExit(f"{path.name}: global_gain would leave 0..255")
_put(buf, side * 8 + off, 8, g)
frames += 1
first = False
pos += h["len"]
rest = bytes(buf[pos : pos + 8])
if pos < len(buf) - 128 and not rest.startswith((b"TAG", b"APETAGEX", b"LYRICS")):
raise SystemExit(f"{path.name}: lost frame sync at {pos} of {len(buf)}")
path.write_bytes(buf)
return frames
def _decode(path: Path) -> np.ndarray:
from konduktor.core import pyav
out = []
with pyav.open_input(path) as c:
for frame in c.decode(audio=0):
a = frame.to_ndarray()
out.append(a if a.ndim == 2 and a.shape[0] <= 2 else a.reshape(1, -1))
return np.concatenate(out, axis=1).astype(np.float64)
def _check_gain(before: np.ndarray, after: Path, db: float, what: str) -> None:
b = before
a = _decode(after)
n = min(b.shape[1], a.shape[1])
want = 10 ** (db / 20)
err = np.max(np.abs(a[:, :n] - b[:, :n] * want)) / max(np.max(np.abs(b)), 1e-9)
print(f" {what}: decoded = original x {want:.4f} ({db:+.2f} dB), max error {err:.1e} of peak")
if err > 1e-3:
raise SystemExit(" gain check FAILED")
def flac_exact_gain(path: Path, db: float) -> None:
import soundfile as sf
from mutagen.flac import FLAC
info = sf.info(str(path))
data, rate = sf.read(str(path), dtype="float64", always_2d=True)
old = FLAC(str(path))
tags, pictures = list(old.tags.items()) if old.tags else [], list(old.pictures)
tmp = path.with_suffix(".tmp.flac")
sf.write(str(tmp), data * 10 ** (db / 20), rate, subtype=info.subtype, format="FLAC")
new = FLAC(str(tmp))
for k, v in tags:
new[k] = v
for p in pictures:
new.add_picture(p)
new.save()
tmp.replace(path)
# ── steps ────────────────────────────────────────────────────────────────────
def _traktor_running() -> bool:
# The executable is "Traktor Pro 4" (an exact "Traktor" never matches).
return subprocess.run(["pgrep", "-f", r"Traktor Pro 4\.app/Contents/MacOS/"], capture_output=True).returncode == 0
def prepare() -> None:
KIT.mkdir(parents=True, exist_ok=True)
for name, (src, what) in FILES.items():
shutil.copy2(src, KIT / name)
print(f" {name:38s} <- {src.name} [{what} at apply]")
print(f"\nKit at {KIT}\n"
"Next, in Traktor 4.5:\n"
" 1. Preferences > Mixer: note the Autogain setting, and turn ON\n"
" 'Set Autogain when Loading Track' (or the nearest wording).\n"
" 2. Import the Kit G1 folder; select its 6 tracks; Analyze (Async) > All.\n"
" 3. Quit Traktor (it writes the collection on exit).\n"
"Then: python dev_gain_kit.py apply")
def _entries(nml_text: str) -> dict[str, str]:
out = {}
for e in re.findall(r"<ENTRY .*?</ENTRY>", nml_text, re.S):
m = re.search(r'<LOCATION [^>]*FILE="(G1-[^"]+)"', e)
if m:
out[m.group(1)] = e
return out
def apply() -> None:
if _traktor_running():
raise SystemExit("Quit Traktor first.")
text = NML.read_text(encoding="utf-8")
have = _entries(text)
missing = [n for n in FILES if n not in have]
if missing:
raise SystemExit(f"Not in the collection yet (import + analyse in Traktor): {missing}")
unanalysed = [n for n in FILES if "<LOUDNESS" not in have[n] or 'AUDIO_ID=""' in have[n] or "AUDIO_ID" not in have[n]]
if unanalysed:
raise SystemExit(f"Not analysed by Traktor yet: {unanalysed}")
shutil.copy2(NML, KIT / "1-after-traktor-analysed.nml")
print("Changing files:")
for name, (_, what) in FILES.items():
p = KIT / name
st = p.stat()
if what == "mtime only":
os.utime(p)
print(f" {name}: mtime touched")
elif what.startswith("frame gain"):
before = _decode(p)
n = mp3_frame_gain(p, STEPS)
print(f" {name}: {n} frames, {STEPS:+d} steps")
_check_gain(before, p, STEPS * 20 * np.log10(2 ** 0.25), "check")
if "APE" in what:
from mutagen.apev2 import APEv2
tag = APEv2()
tag["MP3GAIN_UNDO"] = f"{-STEPS:+04d},{-STEPS:+04d},N"
tag.save(str(p))
print(" + APEv2 MP3GAIN_UNDO tag")
if "restored" in what:
os.utime(p, ns=(st.st_atime_ns, st.st_mtime_ns))
print(f" mtime restored, size {'same' if p.stat().st_size == st.st_size else 'CHANGED'}")
elif what.startswith("exact"):
before = _decode(p)
db = STEPS * 20 * np.log10(2 ** 0.25)
flac_exact_gain(p, db)
print(f" {name}: {db:+.2f} dB, size {st.st_size} -> {p.stat().st_size}")
_check_gain(before, p, db, "check")
from konduktor.adapters.traktor.store import TraktorStore
from konduktor.core import folder
from traktor_nml_utils.models.collection import Loudnesstype
shutil.copy2(B2[1], KIT / B2[0])
store = TraktorStore(NML)
store.add_entry(folder.read_track(KIT / B2[0]), KIT / B2[0])
def set_loudness(file: str, vals) -> None:
for e in store._nml.collection.entry:
if e.location is not None and e.location.file == file:
e.loudness = Loudnesstype(peak_db=vals[0], perceived_db=vals[1], analyzed_db=vals[2])
return
raise SystemExit(f"entry {file} not found")
set_loudness("G1-B1 loudness written.mp3", B1_LOUDNESS)
set_loudness(B2[0], B2_LOUDNESS)
store.save()
shutil.copy2(NML, KIT / "2-after-konduktor-apply.nml")
print(f"\nLOUDNESS written: B1 {B1_LOUDNESS}, B2 (added, AUDIO_ID empty) {B2_LOUDNESS}\n"
"Next, in Traktor 4.5 (do NOT run Analyze):\n"
" 1. Load EACH G1 track into deck A in turn (B1 and B2 first).\n"
" For each, note the GAIN knob's value (hover / the readout) and\n"
" whether Traktor shows it analysing.\n"
" 2. Quit Traktor.\n"
"Then: python dev_gain_kit.py report")
_FIELDS = {
"AUDIO_ID": r'AUDIO_ID="([^"]*)"',
"LOUDNESS": r"<LOUDNESS ([^>]*)>",
"TEMPO": r'<TEMPO BPM="([^"]*)"',
"GRID": r'<CUE_V2 [^>]*TYPE="4"[^>]*START="([^"]*)"',
"MODIFIED": r'MODIFIED_DATE="([^"]*)" MODIFIED_TIME="([^"]*)"',
"FILESIZE": r'FILESIZE="([^"]*)"',
"LAST_PLAYED": r'LAST_PLAYED="([^"]*)"',
}
def report() -> None:
if _traktor_running():
raise SystemExit("Quit Traktor first (it writes the collection on exit).")
shutil.copy2(NML, KIT / "3-after-traktor-load.nml")
stages = [
("analysed", _entries((KIT / "1-after-traktor-analysed.nml").read_text(encoding="utf-8"))),
("applied", _entries((KIT / "2-after-konduktor-apply.nml").read_text(encoding="utf-8"))),
("loaded", _entries(NML.read_text(encoding="utf-8"))),
]
for name in [*FILES, B2[0]]:
print(f"\n== {name} [{FILES.get(name, (None, 'added by Konduktor'))[1]}]")
for field, rx in _FIELDS.items():
vals = []
for _, ents in stages:
e = ents.get(name)
m = re.search(rx, e) if e else None
vals.append(" ".join(m.groups()) if m else ("-" if e else "(no entry)"))
flag = "" if vals[1] == vals[2] else " <-- CHANGED by Traktor"
print(f" {field:11s} analysed: {vals[0][:60]}\n"
f" {'':11s} applied: {vals[1][:60]}\n"
f" {'':11s} loaded: {vals[2][:60]}{flag}")
if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).resolve().parent))
{"prepare": prepare, "apply": apply, "report": report}[sys.argv[1] if len(sys.argv) > 1 else "prepare"]()
-336
View File
@@ -1,336 +0,0 @@
"""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:])
@@ -1,32 +0,0 @@
# Goober: a rekordbox-written stick, before and after rekordbox edited it
The stick Ben keeps for measuring the Pioneer formats, as rekordbox 7 left it:
11 tracks, 2 playlists, **both** libraries (`exportLibrary.db` and the legacy
`export.pdb` + `exportExt.pdb`). `test_onelibrary_anlz.py`,
`test_onelibrary_pdb.py` and `test_onelibrary_tracks.py` run against copies of it.
## What is here
- `PIONEER/rekordbox/` holds the three databases, **untouched**: bytes rekordbox
wrote (snapshot `s0`, 2026-10-01).
- `PIONEER/USBANLZ/` holds every track's `.DAT` and `.EXT`, trimmed by dropping
whole tags: only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for
byte. The waveforms are gone, and so are the `.2EX` files.
- `after/` holds the same tags after **rekordbox 7 itself** edited the stick
(snapshot `s1`, one edit per track):
- `black-bloc-recoloured.EXT`: pad C recoloured to `0x2D` `#FF0045`.
- `wtf-87bpm.DAT` / `.EXT`: "Result – WTF" changed from 174 to 87 BPM.
- `demo2-pad-e-added.EXT`: a hot cue added on pad E of "Demo Track 2".
There is no audio. The adapter resolves paths and never needs the files, so the
time base falls back to rekordbox's MP3 default, the same offset for reading and
writing.
## Why
Konduktor's edits are pinned against what rekordbox wrote for the SAME edit, not
against Konduktor's own reader. A recolour and a grid edit must reproduce
rekordbox's bytes exactly (colour bytes, the blanked `PQT2`, loop beats cleared).
The pdb tests prove that an in-place edit of a rekordbox-written `export.pdb`
leaves everything else as rekordbox wrote it. The full diff of the measurement is
in `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`.
@@ -1,38 +0,0 @@
# 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`.
-13
View File
@@ -56,16 +56,3 @@ implementation — open and write to it.
Not loaded by the tests; kept as documentation, and as the starting point if
Konduktor ever needs to create a drive from nothing.
## rekordbox-edited/
Analysis files from a SECOND stick (Goober), after rekordbox 7 itself edited it
(2026-10-01): a hot cue added on pad E of `demo-track-2`, and a memory cue added on
the start of `nemean`'s memory loop. Trimmed the same way as above, by dropping
whole tags: only `PPTH`, `PCOB` and `PCO2` are kept, byte for byte.
They exist for one property: rekordbox writes **compact** cue entries when it
edits (48 bytes for that hot cue, 44 with no colour for the memory cue; an export
writes 88). pyrekordbox's parser raises on the 44-byte form, which once made the
reader drop the whole `.EXT`, losing pads D-H and every colour. See
`adapters/rekordbox/anlz_file.py`.
+5 -35
View File
@@ -1,14 +1,6 @@
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
# 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.
# 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)
#
# The tricky bits this handles:
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
@@ -18,7 +10,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_all, collect_submodules, copy_metadata
from PyInstaller.utils.hooks import collect_submodules, collect_all
hiddenimports = []
datas = []
@@ -39,12 +31,6 @@ 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.
@@ -62,14 +48,6 @@ datas += [
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
]
# Which stem engine this build needs, and the pinned weights (read at import by
# konduktor/stems/engine_manager.py).
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"],
@@ -90,8 +68,9 @@ 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,
@@ -104,12 +83,3 @@ exe = EXE(
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=False,
name="konduktor-sidecar",
)
+53 -347
View File
@@ -5,30 +5,28 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
* a ``TrackIndex`` — the generic READ projection built from it.
**Editable when opened as THE library**, with parity with the Rekordbox adapter
as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
Opened `read_only` — as the sidebar's Devices do, beside the loaded library — it
reports `writable=False` with cause `browsing`, and every command is refused.
**Read-only.** Every command is refused and `capabilities.writable` is False with
cause `platform_incomplete`, so the UI never offers an edit in the first place;
the raises here are the backstop, not the mechanism.
What a write must look like was MEASURED by diffing a stick before and after
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
playlists, hot cues and the beatgrid so far; adding and removing tracks next —
and every command not written yet is refused, with its capability flag False so
the UI never offers it.
That scope is deliberate rather than provisional. The purpose of this adapter is
to make a OneLibrary drive a readable SOURCE — the half an import into another
library needs — and every genuinely unknown part of the format sits on the write
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
the update counters a drive uses to reconcile edits made on hardware. None of
those has to be guessed at to read a drive, and none of them should be guessed at
at all.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.adapter import Unsupported
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from ..rekordbox import memory_palette, palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME
from . import capabilities as caps
from . import projection
from .store import OneLibraryStore
@@ -44,28 +42,23 @@ ATTRIBUTE_SMART = 4
class OneLibraryAdapter:
platform = "onelibrary"
def __init__(self, path: Path, *, read_only: bool = False):
def __init__(self, path: Path):
self.path = Path(path)
self.read_only = read_only
self._store = OneLibraryStore(self.path, read_only=read_only)
self._store = OneLibraryStore(self.path)
self._index = TrackIndex()
self._rebuild()
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
from ...core.stem_file import is_stem_file
tracks = []
for row in self._store.iter_content():
path = self._drive_path(row)
tracks.append(projection.to_track(
row, path, stem=bool(path) and is_stem_file(path)))
self._index.rebuild(tracks)
self._index.rebuild(
[
projection.to_track(row, self._drive_path(row))
for row in self._store.iter_content()
]
)
def _drive_path(self, row) -> str | None:
# Through the store: an added track plays from its incoming copy until
# Save puts it in place.
resolved = self._store.resolve_audio(getattr(row, "path", None))
resolved = self._store.layout.resolve(getattr(row, "path", None))
return str(resolved) if resolved is not None else None
def close(self) -> None:
@@ -77,27 +70,14 @@ class OneLibraryAdapter:
self._store.close()
def reload(self) -> None:
"""Re-read the drive, DISCARDING unsaved edits."""
self._store.discard()
self._store._load()
self._rebuild()
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale."""
from ...core.stem_file import is_stem_file
row = self._store.content(track_id)
path = self._drive_path(row)
self._index.replace(projection.to_track(row, path, stem=bool(path) and is_stem_file(path)))
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(
device_name=self._store.device_name,
version=self._store.db_version,
read_only=self.read_only,
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
# A drive an export set wrote carries the export's manifest at its root.
managed_by_export=(self._store.layout.root / MANIFEST_NAME).is_file(),
)
# ---- read ------------------------------------------------------------
@@ -164,9 +144,7 @@ class OneLibraryAdapter:
rather than an absence, and treating 0 as a real id would orphan every
top-level playlist.
"""
rows = sorted(self._store.playlists(),
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
writable = not self.read_only
rows = self._store.playlists()
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
@@ -186,14 +164,13 @@ class OneLibraryAdapter:
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
selectable=kind == "playlist",
# Opened read-only, every flag is False and
# Read-only: every per-node flag is False, and
# `capabilities.writable` tells the UI why, once.
can_add_tracks=writable and kind == "playlist",
can_reorder=writable and kind == "playlist",
can_rename=writable,
can_delete=writable,
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
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
@@ -224,9 +201,6 @@ 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.
@@ -262,172 +236,32 @@ class OneLibraryAdapter:
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._store.dirty
return False
def save(self):
self._require_writable("Saving")
outcome = self._store.save()
# Save MOVES files (an added track's audio leaves its incoming copy), so
# the projection is rebuilt from what is now on the drive.
self._rebuild()
return outcome
raise Unsupported(self._readonly_reason("Saving"))
def snapshot(self) -> bytes:
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
# ---- commands -----------------------------------------------------------
# ---- commands: all refused -------------------------------------------
def _readonly_reason(self, what: str) -> str:
if self.read_only:
return (f"{what} is not possible while the drive is open for browsing. "
"Open it for editing to change it.")
return f"{what} is not supported yet for OneLibrary drives."
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def _require_writable(self, what: str) -> None:
"""Every write passes through here, so a command added later cannot
forget that a browsing drive is read-only."""
if self.read_only:
self._refuse(what)
# ---- audio placement (`tracks.places_audio`) ----------------------------
def audio_home(self) -> Path:
return self._store.audio_home()
def place_audio(self, source: Path, track) -> Path | None:
self._require_writable("Adding tracks")
return self._store.place_audio(source, track)
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks, each arriving ready to prep — as the Rekordbox adapter does.
A drive keeps the beatgrid, cues and waveforms in per-track analysis
files, and rekordbox shows neither grid nor cues without them, so every
file is decoded ONCE here and its `.DAT`/`.EXT`/`.2EX` built by the
OneLibrary exporter's own writer — the files rekordbox 7 was verified
to read. A file with no grid of its own gets Konduktor's.
Two phases, as in Rekordbox: FIRST the slow, cancellable part (decoding,
grid detection, building the analysis and artwork bytes) before the
library is touched; THEN the rows, with hot cues replayed through the
ordinary `set_cue` so they keep its conventions. Memory cues — and a hot
cue with no free pad — cross as memory cues, written with the files.
`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, key_detect, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
self._require_writable("Adding tracks")
exporter = OneLibraryExporter()
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
try:
rel = self._store.drive_relative(self._store.final_of(audio))
except ValueError:
raise InvalidCommand(f"{audio} is not on this drive") from None
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
hot, memory, taken = [], [], set()
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
if (cue.role == "hotcue" and cue.slot is not None
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
hot.append(cue)
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
# 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 = 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, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
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",
length_sec=cue.length or 0.0, name=cue.name)
code, _rgb = palette.code_for(cue.color)
if cue.color and code:
self._store.set_cue_color(track_id, cue.slot, code)
added.append(track_id)
self._rebuild()
return added
def add_tracks(self, items: list) -> list[str]:
self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
"""Remove tracks — and, on a stick, their audio and analysis files at Save
(decision 3: a stick's audio belongs to its library)."""
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
self._refuse("Removing tracks")
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
self._refuse("Converting tracks to stems")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._require_writable("Editing track metadata")
self._store.set_track_metadata(track_id, fields)
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")
self._refuse("Editing track metadata")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -436,180 +270,52 @@ class OneLibraryAdapter:
return self._store.cover_art(track_id)
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
self._refuse("Creating playlists")
def create_folder(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
self._refuse("Creating playlist folders")
def rename_playlist(self, node_id: str, name: str) -> None:
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
self._refuse("Renaming playlists")
def delete_playlist(self, node_id: str) -> None:
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)
self._refuse("Deleting playlists")
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)
self._refuse("Editing playlists")
def _refresh_cues(self, track_id: str) -> TrackCues:
"""Re-project a track AND return its fresh cues — every cue/grid command
ends here, so a route can never serve a stale projection."""
self._refresh(track_id)
return self.track_cues(track_id) or TrackCues()
def _check_cue_type(self, cue_type: str) -> None:
if cue_type not in WRITABLE_CUE_TYPES:
raise Unsupported(f"OneLibrary has no cue type {cue_type!r}")
def set_cue(
self,
track_id: str,
*,
slot: int,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
role: str = "hotcue",
name: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# 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)
return self._refresh_cues(track_id)
def set_cue(self, track_id: str, **kw) -> TrackCues:
self._refuse("Editing cues")
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's hot cue colours")
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
self._refuse("Editing cues")
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id)
self._refuse("Deleting cues")
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._require_writable("Placing cues")
for cue in cues:
self._check_cue_type(getattr(cue, "type", "cue"))
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:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
return [m if isinstance(m, GridMarker) else GridMarker(start=float(m[0]), bpm=float(m[1]))
for m in markers]
self._refuse("Placing cues")
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.add_grid_marker(track_id, start_sec, bpm)
return self._refresh_cues(track_id)
self._refuse("Editing the beatgrid")
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.move_grid_marker(track_id, index, start_sec)
return self._refresh_cues(track_id)
self._refuse("Editing the beatgrid")
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.set_grid_marker_bpm(track_id, index, bpm)
return self._refresh_cues(track_id)
self._refuse("Editing the beatgrid")
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.delete_grid_marker(track_id, index)
return self._refresh_cues(track_id)
self._refuse("Editing the beatgrid")
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.replace_grid(track_id, self._markers_from(markers))
return self._refresh_cues(track_id)
self._refuse("Editing the beatgrid")
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
"""An analysis result, as rekordbox's analyser would write it: nothing is
paired with a marker (the companion cue is Traktor's), so a replace."""
return self.replace_grid(track_id, markers)
self._refuse("Editing the beatgrid")
def delete_grid(self, track_id: str) -> TrackCues:
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
self._refuse("Deleting the beatgrid")
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")
@@ -28,8 +28,7 @@ __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag
(an `anlz_file.AnlzFile`).
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
Returns None when the file has no `PQTZ` — which is a real state, not an
error: rekordbox analyses one-shot samples too, and gives them an analysis
@@ -40,7 +39,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ":
continue
entries = tag.entries
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
if not entries:
return None
times: list[float] = []
@@ -1,27 +1,25 @@
"""What a OneLibrary drive can persist.
"""What a OneLibrary drive can persist: nothing, for now.
Opened as THE library, a drive is writable, and the per-feature flags say which
edits have landed: track metadata, playlists, hot cues, the grid, and adding
and removing tracks, so the UI never offers an edit the adapter
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
loaded library — `writable` is False with cause `browsing`, which the UI words
as "open it for editing", not as a missing feature.
`writable` is False with cause `platform_incomplete`. That is the distinction the
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
cloud-synced Rekordbox library is refused permanently to protect the user's other
machines; a OneLibrary drive simply has no write path yet, and the UI must word
those two very differently.
With `writable=False` the per-feature flags still report what the FORMAT
supports rather than being blanked, because that is what the library-level flag
is for: the UI can show a drive's cues and grid honestly and say once, in one
place, that the library is read-only. Blanking them would claim OneLibrary has no
hot cues.
The per-feature flags below still report what the FORMAT supports rather than
being blanked to false, because that is what `writable=False` is for: the UI can
show a drive's cues and grid honestly, and say once, in one place, that the whole
library is read-only. Blanking them would claim OneLibrary has no hot cues.
Two answers are worth recording now, while the evidence is in front of us, since
getting them wrong later would be a silent data bug rather than a missing
feature:
* cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
16 swatches and both are written. (This was first read as "free RGB" off the
RGB bytes alone; the code byte beside them is what decides.)
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
"palette" because `djmdCue` stores an index into a built-in table — the same
vendor, two genuinely different representations.
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
as Traktor and Rekordbox, and NOT the `separate_bank` the original
multi-platform plan assumed.
@@ -36,66 +34,44 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
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`).
HOTCUE_SLOTS = 8
def capabilities_for(
device_name: str | None = None,
version: str | None = None,
*,
read_only: bool = False,
editable_fields: list[str] | None = None,
managed_by_export: bool = False,
) -> Capabilities:
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
return Capabilities(
platform="onelibrary",
version=version,
writable=not read_only,
readonly_cause="browsing" if read_only else None,
# A roadmap gap, not a protective refusal — the UI words the two
# differently, which is the whole reason `readonly_cause` exists.
writable=False,
readonly_cause="platform_incomplete",
cues=CueCapabilities(
editable=True,
editable=False,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# Memory cues, editable as in Rekordbox — in the ANLZ files, the
# way rekordbox 7 edits them on a stick (measured, kit M2).
# OneLibrary carries memory cues, as Rekordbox does. They are
# projected and preserved; nothing here is editable anyway.
memory_cues=True,
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],
max_memory_cues=None,
types=["cue", "loop"],
color="free", # PCO2 stores RGB per cue, not a palette index
palette=[],
named=True, # PCO2 carries a per-cue comment
loops="cue_type",
),
# The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
# No per-track grid lock exists in the format.
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
# survive an export — so the format is flexible even though Konduktor
# does not write it here.
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # stored 0-5 directly, as in master.db
# The Rekordbox adapter's set: `producer`/`mix` have no column.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio", "stem"],
# A stick's audio belongs to its library: added files are copied onto
# it (laid out as rekordbox does) and a removed track's file goes
# 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
# `content.image_id` -> `image.path`.
editable_fields=[],
media_kinds=["audio"],
# `artwork` gates EDITING, and a drive is read-only here. Reading
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
artwork=False,
artwork_note=None,
),
@@ -104,18 +80,13 @@ def capabilities_for(
# A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules.
smart="none",
reorder=True,
reorder=False,
),
save=SaveCapabilities(
# Named for the DRIVE ("Save to Goober"): a person has several
# sticks, and "Save to OneLibrary" would not say which.
app_name=device_name or "OneLibrary",
library_label="exportLibrary.db",
# Another app writing the drive between open and save is CAUGHT,
# not risked: the store fingerprints the database at open and
# refuses to save over a change it did not make.
app_name="OneLibrary",
library_label=device_name or "exportLibrary.db",
# Nothing is written, so nothing can be overwritten by another app.
overwrite_risk="none",
managed_by_export=managed_by_export,
# A drive is a database plus N analysis files plus the audio itself,
# so there is no single blob that IS the library — the same reason
# Rekordbox libraries are not versioned.
+24 -54
View File
@@ -37,7 +37,6 @@ from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import memory_palette, palette
log = logging.getLogger(__name__)
@@ -48,13 +47,14 @@ NO_LOOP = 0xFFFFFFFF
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
MEMORY_SLOT = 0
# PCO2/PCOB entry kinds. The value is the same in both tags.
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
ENTRY_CUE = 1
ENTRY_LOOP = 2
def _entry_kind(value) -> int:
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
"""PCOB gives an enum, PCO2 an int — one number out of either."""
try:
return int(value)
except (TypeError, ValueError):
@@ -68,17 +68,8 @@ def _color(entry) -> str | None:
real black in principle, but rekordbox uses it as "unset" and shows such a
cue in the default colour, so it is reported as no colour rather than as
black. Memory cues in the reference export are exactly this case.
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
code is reported as that swatch; a cue with code 0 and an RGB (older
exports, the reference fixture) is reported by its RGB.
"""
swatch = palette.hex_for(getattr(entry, "color_code", None))
if swatch is not None:
return swatch
try:
# None on an entry too short to carry a colour: every PCPT, and the
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
except (AttributeError, TypeError, ValueError):
return None
@@ -87,7 +78,7 @@ def _color(entry) -> str | None:
return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try:
hot_cue = int(entry.hot_cue)
@@ -112,13 +103,6 @@ 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",
@@ -126,26 +110,16 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
start=start_ms / 1000.0,
length=length,
slot=slot,
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",
color=_color(entry) if with_color else None,
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
# command. `capabilities.writable` is what the UI actually gates on;
# this keeps the per-cue answer consistent with it.
editable=False,
readonly_reason="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.
@@ -156,14 +130,15 @@ def _entries(anlz, tag_type: str) -> list:
"""
out: list = []
for tag in getattr(anlz, "tags", []):
if tag.type == tag_type:
out.extend(tag.entries)
if tag.type != tag_type:
continue
content = getattr(tag.struct, "content", None)
out.extend(getattr(content, "entries", None) or [])
return out
def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`
(`rekordbox.anlz_file.AnlzFile`s).
def cues_from_anlz(dat, ext) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
with no cues at all yields an empty list rather than an error.
@@ -178,14 +153,14 @@ def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
for f in files:
pco2.extend(_entries(f, "PCO2"))
if pco2:
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
else:
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
# .EXT the rest, so either alone is an incomplete bank.
pcob: list = []
for f in files:
pcob.extend(_entries(f, "PCOB"))
cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
return _dedupe(cues)
@@ -193,23 +168,18 @@ def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
"""Collapse the same cue appearing in more than one tag or file.
Identity is (role, slot, start, type, length) rather than the whole cue:
the same pad can be described by both `PCOB` and `PCO2`, and by both files,
and those copies agree on all five while differing in how much detail they
carry (colour, comment). The first one wins, which — given PCO2 is read
first — is the richest.
Type and length are part of it because two MEMORY cues may share a position:
rekordbox happily stores a memory cue on the start of a memory loop (seen on
Goober), and keying on position alone silently dropped the loop.
Identity is (role, slot, start) rather than the whole cue: the same pad can
be described by both `PCOB` and `PCO2`, and by both files, and those copies
agree on position while differing in how much detail they carry. The first
one wins, which — given PCO2 is read first — is the richest.
Ordered by position, then by slot, so the projection is stable across reads
regardless of the order the tags happened to store.
"""
seen: set[tuple] = set()
seen: set[tuple[str, int | None, int]] = set()
out: list[CuePoint] = []
for c in cues:
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
key = (c.role, c.slot, round(c.start * 1000))
if key in seen:
continue
seen.add(key)
@@ -1,209 +0,0 @@
"""Keeping a stick's legacy Device Library (`export.pdb`) in step with its OneLibrary.
Most rekordbox sticks carry BOTH: `exportLibrary.db` (OneLibrary, newer players)
and `export.pdb` (the Device Library, older players and rekordbox's own "Device
Library" view). Cues and the grid live in the analysis files both share, so they
follow an edit by themselves; titles and playlists live in each database
separately. **rekordbox itself lets them drift**: measured on Goober
(2026-10-01), its edits updated the pdb's track metadata but not a new playlist
or a reorder. Konduktor rebuilds the pdb at Save instead (decision 2 of the
editing discussion), so a stick never shows different playlists depending on
which player reads it.
**Ids are mirrored, not assigned.** rekordbox exports both libraries from the
same ids — pdb track id = `content_id`, the artist/album/genre/label/key ids, the
playlist ids, playlist `sort` = `sequenceNo`, entries `(sequenceNo, content_id,
playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibrary
database IS the answer for every row the pdb shares with it.
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
(`pdb.PdbEditor`): only the tracks, the lookup tables (artist, album, genre,
label, key), artwork and the playlist tree and entries are candidates, a table is rewritten only if one of its rows changed,
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
with the edited fields overwritten, so everything the pdb holds that OneLibrary
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
dates — survives. History, colours, menus and `exportExt.pdb` are never touched.
"""
from __future__ import annotations
import re
import struct
from pathlib import Path
from ..rekordbox import pdb
#: Tables this rebuild owns. Everything else in the file is left as it is.
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS, pdb.KEYS,
pdb.ARTWORK, pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
def _lookup_name(table: int, row: bytes) -> str:
if table == pdb.ARTISTS:
sub, _shift, _rid, _b, ofs = struct.unpack_from("<HHIBB", row, 0)
if sub == 0x64:
ofs = struct.unpack_from("<H", row, 10)[0]
return pdb.read_dsql(row, ofs)
if table == pdb.ALBUMS:
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
return pdb.read_dsql(row, ofs)
if table == pdb.KEYS:
return pdb.read_dsql(row, 8)
return pdb.read_dsql(row, 4)
def _pdb_art_path(path: str | None) -> str:
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
def _tree_value(row: bytes) -> tuple:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
def _merge(old: list[bytes], new: dict, table: int, same) -> list[bytes] | None:
"""The table's rows: old ORDER kept, an unchanged row's old BYTES kept, new
rows appended by id. None when nothing changed (the table is not rewritten).
`new` maps row id -> (value, encode()); `same(old_row, value)` says whether
an old row already says `value`.
"""
out, changed, seen = [], False, set()
for row in old:
rid = pdb.row_id(table, row)
if rid not in new:
changed = True # removed
continue
seen.add(rid)
value, encode = new[rid]
if same(row, value):
out.append(row)
else:
out.append(encode())
changed = True
for rid in sorted((r for r in new if r not in seen), key=str):
out.append(new[rid][1]())
changed = True
return out if changed else None
def rebuild(existing: bytes, session) -> bytes | None:
"""`export.pdb` edited to match the OneLibrary database open in `session`
(the working copy, edits committed); None if it already matches."""
from sqlalchemy import text
tables: dict[int, list[bytes]] = {}
# ---- lookups ----------------------------------------------------------------
for table, sql, build in (
(pdb.ARTISTS, "SELECT artist_id, name FROM artist", pdb.artist_row),
# rekordbox's export leaves an album's artist 0 (see `pdb.album_row`).
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_row),
):
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
for i, name in session.execute(text(sql))}
merged = _merge(pdb.table_rows(existing, table), want, table,
lambda row, value, t=table: _lookup_name(t, row) == value)
if merged is not None:
tables[table] = merged
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
lambda row, value: pdb.read_dsql(row, 4) == value)
if merged is not None:
tables[pdb.ARTWORK] = merged
# ---- 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, 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, 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)
if cid in old_tracks:
fields, strings = pdb.track_fields(old_tracks[cid])
else:
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))), "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 ""}
want[cid] = ((fields, strings),
(lambda f=fields, s=strings: pdb.track_row(f, s)))
merged = _merge(list(old_tracks.values()), want, pdb.TRACKS,
lambda row, value: _same_track(pdb.track_fields(row), value))
if merged is not None:
tables[pdb.TRACKS] = merged
# ---- playlists ----------------------------------------------------------------
want = {int(pid): ((int(parent or 0), int(seq or 0), int(pid), int(attr or 0) == 1, name or ""),
(lambda p=pid, par=parent, s=seq, n=name, a=attr:
pdb.playlist_tree_row(int(p), int(par or 0), int(s or 0), n or "",
folder=int(a or 0) == 1)))
for pid, parent, seq, name, attr in session.execute(text(
"SELECT playlist_id, playlist_id_parent, sequenceNo, name, attribute FROM playlist"))}
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_TREE), want, pdb.PLAYLIST_TREE,
lambda row, value: _tree_value(row) == value)
if merged is not None:
tables[pdb.PLAYLIST_TREE] = merged
want = {}
for pid, cid, seq in session.execute(text(
"SELECT playlist_id, content_id, sequenceNo FROM playlist_content "
"ORDER BY playlist_id, sequenceNo")):
key = (int(seq), int(cid), int(pid))
want[key] = (key, (lambda k=key: pdb.playlist_entry_row(*k)))
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_ENTRIES), want, pdb.PLAYLIST_ENTRIES,
lambda row, value: True)
if merged is not None:
tables[pdb.PLAYLIST_ENTRIES] = merged
if not tables:
return None
editor = pdb.PdbEditor(existing)
for table in _OWNED:
if table in tables:
editor.refill(table, tables[table])
return editor.render()
def _same_track(old: tuple[dict, dict], new: tuple[dict, dict]) -> bool:
"""Equal in every field that means something: `index_shift` is the row's slot
in its page, re-stamped whenever a page is written."""
(of, os_), (nf, ns) = old, new
return ({k: v for k, v in of.items() if k != "index_shift"}
== {k: v for k, v in nf.items() if k != "index_shift"} and os_ == ns)
def _fresh_track(cid: int, path, file_name, file_size, file_type, bitrate, bit_depth,
sample_rate, length, analysis, date_added, key_id, image_id) -> tuple[dict, dict]:
"""A track the pdb has never listed (one added to the stick by Konduktor), in
the shape `device_export` writes one — the values a rekordbox device export
was measured to carry (see that module)."""
from ..rekordbox.device_export import ANALYSED, BITMASK
added = str(date_added or "")[:10]
fields = {
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": int(sample_rate or 0),
"file_size": int(file_size or 0), "u2": cid + 0x600, "artwork_id": int(image_id or 0),
"key_id": int(key_id or 0), "bitrate": int(bitrate or 0), "id": cid,
"sample_depth": int(bit_depth or 0), "duration": min(int(length or 0), 0xFFFF),
"u5": ANALYSED, "u6": int(file_type or 0), "u7": 3,
}
strings = {
"kuvo_public": "ON", "autoload_hotcues": "ON", "date_added": added,
"analyze_path": analysis or "", "analyze_date": added,
"filename": file_name or Path(str(path or "")).name, "file_path": path or "",
}
return fields, strings
@@ -49,7 +49,7 @@ class OneLibraryDriver:
def _has_onelibrary_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
@@ -73,8 +73,8 @@ class OneLibraryDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
return OneLibraryAdapter(path, read_only=read_only)
def open(self, path: Path) -> OneLibraryAdapter:
return OneLibraryAdapter(path)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
+26 -63
View File
@@ -44,8 +44,7 @@ from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, memory_palette, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox import artwork, palette, timebase
from ..rekordbox.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key
from .capabilities import capabilities_for
@@ -122,7 +121,7 @@ class OneLibraryExporter:
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
@@ -209,13 +208,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, color_id, image_id, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
"analysisDataUpdateCount, informationUpdateCount) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
content_id, track.title, (track.title or "").lower(),
int(round((track.bpm or 0) * 100)) or None, track.length,
@@ -229,7 +228,6 @@ 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,
@@ -267,21 +265,21 @@ class OneLibraryExporter:
n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True)
small, medium = jpegs
files = []
for rel, data in art_files(n, jpegs):
path = root / rel.lstrip("/")
path.write_bytes(data)
files.append(path)
for letter in ("a", "b"):
for suffix, data in (("", small), ("_m", medium)):
path = folder / f"{letter}{n}{suffix}.jpg"
path.write_bytes(data)
files.append(path)
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
(n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
return n, files
# ---- the analysis files --------------------------------------------------
def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
"""The `.DAT`, `.EXT` and `.2EX` as `(suffix, bytes)`, as rekordbox 7 writes
them — built, not written, so a library adding a track to a stick can hold
them until Save (`OneLibraryStore.add_track`).
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them.
All three, and every cue list, even for a track with no cues: rekordbox
never produces a track without them, and `PCO2` — the complete list,
@@ -320,18 +318,9 @@ class OneLibraryExporter:
tags += previews
tags += W.cue_tags(cues, extended=False)
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
if two_ex:
files.append((".2EX", W.anlz_bytes([W.path_tag(rel), *two_ex])))
return files
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
written = []
for suffix, data in self.anlz_files(item, rel):
path = dat.with_suffix(suffix)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
written.append(path)
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
return written
@staticmethod
@@ -361,29 +350,15 @@ class OneLibraryExporter:
too far along.
"""
out: list[dict] = []
memory = 0
for cue in sorted(item.cues.cues if item.cues else [], key=lambda c: c.start):
for cue in (item.cues.cues if item.cues else []):
is_loop = cue.type == "loop" or cue.length > 0
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
# 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))
out.append({
"color_id": color_id,
"hot_cue": 0 if is_memory else cue.slot + 1,
"hot_cue": 0 if cue.role == "memory" or cue.slot is None 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))
@@ -397,8 +372,7 @@ class OneLibraryExporter:
# ---- playlists -----------------------------------------------------------
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
"""The tree preserved — at the top level (parent NULL), or with
`payload.root_folder` under one folder named after the export.
"""One folder named after the export, with the tree preserved under it.
`playlist` is a flat table with `playlist_id_parent`, so folders and
playlists are the same row kind told apart by `attribute` (1 = folder).
@@ -414,8 +388,8 @@ class OneLibraryExporter:
)
return next_id[0]
root = add(payload.name, None, folder=True) if payload.root_folder else None
folders: dict[tuple[str, ...], int | None] = {(): root}
root = add(payload.name, None, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -444,23 +418,12 @@ class OneLibraryExporter:
)
#: 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.
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12}
def art_files(n: int, jpegs: tuple[bytes, bytes]) -> list[tuple[str, bytes]]:
"""Image `n`'s four files as `(drive-relative path, bytes)`: `a<n>`/`b<n>`
and their `_m`, byte-identical pairs, in `Artwork/00001/` (see `_write_art`).
`image.path` names the `b` file; `export.pdb`'s artwork table the `a` one."""
small, medium = jpegs
return [(f"/PIONEER/Artwork/00001/{letter}{n}{suffix}.jpg", data)
for letter in ("a", "b") for suffix, data in (("", small), ("_m", medium))]
def _file_type(path: Path) -> int:
return _FILE_TYPES.get(path.suffix.lower(), 1)
@@ -1,102 +0,0 @@
"""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 ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
The only place a ``devicelib_plus`` 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,7 +16,6 @@ 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
@@ -55,7 +54,7 @@ def _bpm(row) -> float | None:
return round(int(raw) / 100.0, 2)
def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
def to_track(row, drive_path: str | None = None) -> Track:
"""Project one ``Content`` row.
**The three count fields are approximations here**, and deliberately so. Cues
@@ -105,10 +104,7 @@ def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track
hotcue_count=0,
grid_marker_count=1 if (bpm and has_analysis) else 0,
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)),
media_kind="audio",
)
@@ -117,7 +113,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.
Each cue already says whether it is editable (the store knows whether the
drive was opened for editing or is only being browsed).
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
`capabilities.writable` says so at the library level.
"""
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
File diff suppressed because it is too large. Load diff
+21 -255
View File
@@ -21,14 +21,13 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
from ...core.adapter import Unsupported
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 memory_palette, palette, projection, timebase
from ...core import add_analysis
from . import projection
from .store import RekordboxStore
@@ -45,12 +44,9 @@ 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)),
auto_gain_db=gains.get(str(row.ID)))
projection.to_track(row, kinds.get(str(row.ID), ()))
for row in self._store.iter_content()
]
)
@@ -72,9 +68,7 @@ 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)),
auto_gain_db=self._store.mixer_gain(str(row.ID))))
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ())))
def close(self) -> None:
"""Release the database connection.
@@ -175,7 +169,6 @@ 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
@@ -207,13 +200,8 @@ 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.
self._rebuild()
def unresolved_path_groups(self) -> list:
"""Not checked yet: the open-time missing-files check is Traktor-only
@@ -223,10 +211,6 @@ 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)
@@ -257,30 +241,6 @@ 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")
@@ -298,10 +258,6 @@ 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)
@@ -324,8 +280,12 @@ class RekordboxAdapter:
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# 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")
# 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"
)
self._check_cue_type(cue_type)
self._store.set_cue(
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
@@ -339,70 +299,11 @@ class RekordboxAdapter:
self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(
f"{color!r} is not one of Rekordbox's hot cue colours"
)
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._require_writable("Deleting cues")
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:
@@ -460,41 +361,11 @@ 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()
@@ -529,124 +400,19 @@ 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.
Rekordbox keeps the beatgrid AND the waveforms in per-track analysis
files, and shows neither grid nor cues for a track without them — so
unlike Traktor, which re-analyses on load, every file is decoded here.
A file that brings no grid gets one from Konduktor's own detector
(decided 2026-10-01: a track should arrive ready to prep).
Two phases, and the split is the point. FIRST every file is decoded and
analysed, which is slow and may be cancelled through `checkpoint` —
before the library is touched, so a cancel leaves it as it was. THEN
each row is added and its grid and cues replayed through the ordinary
store commands (`replace_grid`, `set_cue`), so an added track inherits
their conventions and tests rather than growing a second copy.
Nothing is lost on the way in: Rekordbox has memory cues and coloured
cues, so both cross as themselves. A hot cue whose pad is out of the
bank or already taken becomes a memory cue at the same position rather
than being dropped.
"""
from ...core import audio_tags
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})",
step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}")
held.add(str(audio))
markers = list(item.cues.grid_markers) if item.cues else []
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, track, audio, measured, markers, art[0] if art else None,
getattr(analysed, "loudness", None)))
# The app's loudness store, where one is attached (see `AppState`): a
# measurement made here is worth keeping for the Mastering columns.
on_loudness = getattr(self, "on_loudness", None)
added: list[str] = []
for item, track, audio, measured, markers, art, loud in prepared:
track_id = self._store.add_track(
audio, track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), (),
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, 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"
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))
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:
code, _rgb = palette.code_for(cue.color)
self._store.set_cue(track_id, slot=slot, color_code=code or None, **common)
taken.add(slot)
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 add_tracks(self, items: list) -> list[str]:
# Not a refusal in principle — Rekordbox could receive imported
# tracks — but adding one means a djmdContent row, its lookup-table
# foreign keys, a USN, and an ANLZ file built from scratch, which
# is unexplored (see the export handoff). Traktor is the only
# import target for now.
self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
# What goes with a track was measured in Rekordbox 7 — see the store.
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
# Same shape as adding: a track is a djmdContent row plus its cues,
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
# which of those Rekordbox expects to be deleted together is unmeasured.
self._refuse("Removing tracks")
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
# Rekordbox does not play native-instruments stem files as stems.
@@ -1,324 +0,0 @@
"""Reading an ANLZ analysis file at the TAG level, by hand.
The writer half is `anlz_writer`; this is its reader. Like the writer it lives
here because the format is Pioneer's, not one product's.
**Why not `pyrekordbox`'s parser.** It decodes a cue entry with a FIXED layout,
and rekordbox does not write one. An exported entry is 88 bytes, but when
rekordbox 7 EDITS a stick it writes compact ones (measured on Goober,
2026-10-01): a hot cue added in rekordbox was a 48-byte `PCP2` (colour, no
padding), and a memory cue a 44-byte one (no colour bytes at all). pyrekordbox
raises `PaddingError` on the 44-byte form, the whole `.EXT` fails to parse, and
a reader that falls back to the `.DAT` silently loses pads D-H and every colour.
So every entry here is read at its own `len_entry`, and a field the entry is too
short to hold is simply absent.
A file is also split into its RAW tags, kept byte for byte. Editing a stick
replaces one or two tags of a file rekordbox wrote; everything else (the
waveforms, `PVBR`, tags nobody has decoded) must go back exactly as it was, and
re-serialising through a parser is how bytes get lost.
"""
from __future__ import annotations
import struct
from dataclasses import dataclass, field
#: `PMAI` · len_header · len_file · …
FILE_MAGIC = b"PMAI"
NO_LOOP = 0xFFFFFFFF
#: The cue-list kinds in `PCOB`/`PCO2`'s own header.
LIST_MEMORY = 0
LIST_HOT = 1
@dataclass
class Tag:
"""One tag, raw. `data` is the WHOLE tag: magic, both lengths, and body."""
type: str
data: bytes
_entries: list | None = field(default=None, repr=False, compare=False)
@property
def len_header(self) -> int:
return struct.unpack_from(">I", self.data, 4)[0]
@property
def list_kind(self) -> int | None:
"""`PCOB`/`PCO2`: whether this is the hot cue or the memory list."""
if self.type in ("PCOB", "PCO2") and len(self.data) >= 16:
return struct.unpack_from(">I", self.data, 12)[0]
return None
@property
def entries(self) -> list:
"""The tag's decoded entries (cues, or beats for `PQTZ`); [] otherwise."""
if self._entries is None:
decode = _DECODERS.get(self.type)
self._entries = decode(self.data) if decode else []
return self._entries
@dataclass
class AnlzFile:
"""An analysis file split into its header and raw tags."""
header: bytes
tags: list[Tag]
def to_bytes(self) -> bytes:
"""Reassemble, fixing only the header's file length."""
body = b"".join(t.data for t in self.tags)
head = bytearray(self.header)
struct.pack_into(">I", head, 8, len(head) + len(body))
return bytes(head) + body
def copy(self) -> "AnlzFile":
return AnlzFile(self.header, [Tag(t.type, t.data) for t in self.tags])
def find(self, kind: str, list_kind: int | None = None) -> int | None:
"""Index of the first `kind` tag (of that cue-list kind, if given)."""
for i, t in enumerate(self.tags):
if t.type == kind and (list_kind is None or t.list_kind == list_kind):
return i
return None
def put(self, kind: str, data: bytes, *, list_kind: int | None = None,
after: tuple[str, ...] = ()) -> None:
"""Replace the `kind` tag IN PLACE, keeping every other tag where it is.
A file without one gets it inserted after the last tag named in
`after` (rekordbox's order), else at the end.
"""
tag = Tag(kind, data)
i = self.find(kind, list_kind)
if i is not None:
self.tags[i] = tag
return
at = max((j for j, t in enumerate(self.tags) if t.type in after), default=len(self.tags) - 1)
self.tags.insert(at + 1, tag)
class AnlzError(ValueError):
pass
def parse(data: bytes) -> AnlzFile:
"""Split a file into its tags. Raises `AnlzError` on a malformed file.
Lengths are trusted only as far as the file reaches: a tag claiming more
bytes than remain ends the walk with an error rather than a short read.
"""
if len(data) < 12 or data[:4] != FILE_MAGIC:
raise AnlzError("not an ANLZ file")
len_header = struct.unpack_from(">I", data, 4)[0]
if not 12 <= len_header <= len(data):
raise AnlzError(f"bad file header length {len_header}")
tags: list[Tag] = []
off = len_header
while off < len(data):
if off + 12 > len(data):
raise AnlzError(f"truncated tag at {off}")
kind = data[off:off + 4].decode("latin-1")
len_tag = struct.unpack_from(">I", data, off + 8)[0]
if len_tag < 12 or off + len_tag > len(data):
raise AnlzError(f"bad length {len_tag} for {kind} at {off}")
tags.append(Tag(kind, data[off:off + len_tag]))
off += len_tag
return AnlzFile(header=data[:len_header], tags=tags)
def parse_file(path) -> AnlzFile:
with open(path, "rb") as f:
return parse(f.read())
# ---- cue entries ------------------------------------------------------------
@dataclass
class CueEntry:
"""One `PCPT` or `PCP2` entry. Attribute names follow pyrekordbox's, which
is what `onelibrary.cues` was written against.
`color_code` / RGB are None when the entry is too short to carry them (every
`PCPT`, and rekordbox's compact 44-byte `PCP2`).
"""
hot_cue: int
type: int
time: int
loop_time: int
comment: str = ""
loop_numerator: int = 0
loop_denominator: int = 0
color_code: int | None = None
color_red: int | None = None
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]:
"""A `PCOB`/`PCO2` tag's entries as their own bytes, each at its own length —
so an entry Konduktor does not change goes back exactly as rekordbox wrote it."""
if tag.type == "PCOB":
count, first, magic = struct.unpack_from(">H", tag.data, 18)[0], 24, b"PCPT"
elif tag.type == "PCO2":
count, first, magic = struct.unpack_from(">H", tag.data, 16)[0], 20, b"PCP2"
else:
return []
return [tag.data[off:off + n] for off, n in _walk(tag.data, first, magic, count)]
def decode_entry(entry: bytes) -> CueEntry:
"""One raw `PCPT` or `PCP2` entry, decoded."""
if entry[:4] == b"PCPT":
return _pcob(struct.pack(">4sIIIHHi", b"PCOB", 24, 24 + len(entry), 0, 0, 1, -1) + entry)[0]
return _pco2(struct.pack(">4sIIIHH", b"PCO2", 20, 20 + len(entry), 0, 1, 0) + entry)[0]
def entry_hot_cue(entry: bytes) -> int:
"""A PCPT/PCP2 entry's `hot_cue`: its pad, 1-based; 0 for a memory cue."""
return struct.unpack_from(">I", entry, 12)[0]
def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> bytes | None:
"""A `PCP2` entry with ONLY its colour bytes changed — what rekordbox itself
does to recolour a cue (measured: those 4 bytes and nothing else). None if
the entry is too short to carry a colour (rekordbox's 44-byte form)."""
if len(entry) < 44:
return None
len_comment = struct.unpack_from(">I", entry, 40)[0]
at = 44 + len_comment
if at + 4 > len(entry):
return None
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),
rather than recomputing it."""
if len(entry) < 40 or entry[36:40] == b"\0\0\0\0":
return entry
return entry[:36] + bytes(4) + entry[40:]
def _walk(data: bytes, first: int, magic: bytes, count: int):
"""(offset, len_entry) for each entry, trusting each entry's own length."""
off = first
for _ in range(count):
if off + 12 > len(data) or data[off:off + 4] != magic:
return
len_entry = struct.unpack_from(">I", data, off + 8)[0]
if len_entry < 12 or off + len_entry > len(data):
return
yield off, len_entry
off += len_entry
def _pcob(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H 0 · H count · i last
count = struct.unpack_from(">H", data, 18)[0]
out = []
for off, n in _walk(data, 24, b"PCPT", count):
if n < 44:
continue
# 4s · I len_header · I len_entry · I hot_cue · I status · I 0x10000 ·
# H order_first · H order_last · B kind · x · H 1000 · I time · I loop
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 28]
time, loop = struct.unpack_from(">II", data, off + 32)
out.append(CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n))
return out
def _pco2(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H count · H 0
count = struct.unpack_from(">H", data, 16)[0]
out = []
for off, n in _walk(data, 20, b"PCP2", count):
if n < 28:
continue
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,
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
if len_comment and colour_at <= off + n:
e.comment = data[off + 44:colour_at].decode("utf-16-be", "replace").rstrip("\x00")
if colour_at + 4 <= off + n:
e.color_code, e.color_red, e.color_green, e.color_blue = data[colour_at:colour_at + 4]
out.append(e)
return out
# ---- the beatgrid -----------------------------------------------------------
@dataclass
class Beat:
beat: int # 1-4, position in the bar
tempo: int # BPM x 100
time: int # ms
def _pqtz(data: bytes) -> list[Beat]:
# tag prefix(12) · I 0 · I 0x80000 · I count, then 8-byte entries
count = struct.unpack_from(">I", data, 20)[0]
first = struct.unpack_from(">I", data, 4)[0]
out = []
for i in range(count):
off = first + 8 * i
if off + 8 > len(data):
break
beat, tempo, time = struct.unpack_from(">HHI", data, off)
out.append(Beat(beat=beat, tempo=tempo, time=time))
return out
_DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
__all__ = [
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
"NO_LOOP", "Tag", "decode_entry", "entry_hot_cue", "entry_with_colour", "entry_without_loop_beats",
"parse", "parse_file", "raw_entries",
]
@@ -313,76 +313,30 @@ def flat_preview_tags() -> list[bytes]:
return preview_tags([0.0] * 400, [0.0] * 400)
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, color_id: int = 0) -> 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) -> 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
`1000` after the kind (the struct calls it padding) and the `1` after the
colour id. Both appear in every entry of a real export; zeros there were a
guess, and pyrekordbox's parser would never notice one.
A `comment` (the cue's name) is UTF-16BE with a terminating NUL, and
`len_comment` counts the terminator — crate-digger's layout, which both
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""
comment = b""
red, green, blue = rgb or (0, 0, 0)
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, length, hot_cue, kind, 1000,
b"PCP2", 16, PCP2_ENTRY_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, len(comment_bytes),
0, 1, beats or 0, 1 if beats else 0, len(comment),
# 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(
length - 48 - len(comment_bytes)
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
PCP2_ENTRY_LEN - 48 - len(comment)
)
#: 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:
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.
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
@@ -399,61 +353,28 @@ def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) ->
) + bytes(16)
def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
or new ones from `pcpt_entry`)."""
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
)
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
# shifts every following field and the reader sees garbage. The last field
# is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
# writes it (an export, and rekordbox's own edits, alike).
last = -1 if cue_type == 1 else len(entries) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(entries), last) + b"".join(entries))
def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCO2` around already-built `PCP2` entries."""
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(entries), 0) + b"".join(entries))
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
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)
# writes it.
last = -1 if cue_type == 1 else len(chosen) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob)
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"),
color_id=c.get("color_id", 0))
blob = b"".join(
_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))
for c in chosen
])
#: `PQT2` as rekordbox 7 leaves it after a grid edit: header kept, every count
#: and the beat list gone (56 bytes, the `len_header`). MEASURED on Goober
#: (2026-10-01): rekordbox does not recompute this "extended" grid when the grid
#: changes, it blanks it, and a CDJ then works from `PQTZ`.
_PQT2_HEADER = 56
def blank_pqt2(tag: bytes) -> bytes:
"""The blanked form of an existing `PQT2` tag, exactly as rekordbox writes it.
Bytes 12-24 (rekordbox's constants, `00000000 01000002 00000000` on every
file seen) are KEPT; the counts and first/last-beat fields after them are
zeroed, and the beat entries dropped.
"""
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
)
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
@@ -483,18 +404,13 @@ def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
_FILE_HEADER_LEN = 28
def anlz_bytes(tags: list[bytes]) -> bytes:
"""Assemble an ANLZ file from built tag bytes."""
def write_anlz(path: Path, tags: list[bytes]) -> Path:
"""Assemble and write an ANLZ file from built tag bytes."""
path.parent.mkdir(parents=True, exist_ok=True)
body = b"".join(tags)
header = struct.pack(
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
)
return header + body
def write_anlz(path: Path, tags: list[bytes]) -> Path:
"""Assemble and write an ANLZ file from built tag bytes."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(anlz_bytes(tags))
path.write_bytes(header + body)
return path
@@ -30,8 +30,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import memory_palette, palette, track_palette
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
from .cue_types import 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,25 +54,22 @@ def capabilities_for(
writable=not cloud_synced,
readonly_cause="cloud_synced" if cloud_synced else None,
cues=CueCapabilities(
# Hot AND memory cues are writable: djmdCue rows plus the
# contentCue JSON mirror, kept in step (memory cues: measured
# 2026-10-16, kit M1).
# 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.
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,
# 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),
max_memory_cues=None, # unlimited
# 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
# measured, see `palette`), offered in rekordbox's own order.
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
palette=[], # TODO milestone 2: the built-in cue colour table
named=True, # djmdCue.Comment
loops="cue_type",
),
@@ -87,17 +83,7 @@ def capabilities_for(
# column (its Composer is a different field), so they are absent
# rather than mapped onto something approximate.
editable_fields=sorted(editable_fields or []),
# A stem file is held (and played by Rekordbox as its mix);
# Konduktor's deck plays its stems.
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,
media_kinds=["audio"],
artwork=False,
artwork_note=None,
),
@@ -36,10 +36,6 @@ 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, track_palette
from . import artwork, pdb
from .projection import render_key
log = logging.getLogger(__name__)
@@ -138,7 +138,6 @@ 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,
},
{
@@ -199,9 +198,8 @@ class RekordboxDeviceExporter:
@staticmethod
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
"""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."""
"""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."""
tree: list[bytes] = []
entries: list[bytes] = []
next_id = [0]
@@ -222,7 +220,7 @@ class RekordboxDeviceExporter:
index += 1
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
root = add(payload.name, 0, folder=True) if payload.root_folder else 0
root = add(payload.name, 0, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -63,7 +63,7 @@ class RekordboxDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
def open(self, path: Path) -> RekordboxAdapter:
return RekordboxAdapter(path)
def detect(self) -> list[dict]:
+97 -55
View File
@@ -58,7 +58,8 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from . import memory_palette, new_content, palette, track_palette
from . import anlz_writer as W
from . import artwork, palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
@@ -81,8 +82,15 @@ SEED = _FIXTURES / "seed.sql"
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
FRAMES_PER_SECOND = 150
#: `djmdContent.ContentLink` — see `new_content`, where its bits are measured.
CONTENT_LINK = new_content.CONTENT_LINK
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
#: five tracks of a Konduktor-written library different values and loading it
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
#: MP3/M4A tracks carry — adds two more bits that draw an extra badge, most
#: likely claiming phrase/vocal analysis this exporter does not write. So the
#: value that claims only what is written: 0x2C060E.
CONTENT_LINK = 2885134
#: Rekordbox's playlist side file, beside master.db. It lists every playlist
#: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the
@@ -109,11 +117,6 @@ 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.
@@ -130,7 +133,7 @@ class RekordboxExporter:
)
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
# `masterdb`'s OWN key blob. `devicelib_plus` 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.
@@ -204,36 +207,24 @@ class RekordboxExporter:
from .adapter import RekordboxAdapter
adapter = RekordboxAdapter(library)
# 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.
# 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.
store = adapter._store
try:
for item in payload.tracks:
track_id = ids.get(item.source_id)
if track_id is None:
if track_id is None or not item.cues:
continue
if item.loudness is not None:
# The same row an Analyze writes (`RekordboxStore.set_auto_gain`).
store.set_auto_gain(track_id, item.loudness)
if not item.cues:
continue
memory = 0
for cue in sorted(item.cues.cues, key=lambda c: c.start):
for cue in item.cues.cues:
if cue.role == "memory" or cue.slot is None:
# 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
# rekordbox's own "unset" for a memory cue with no colour.
code, _rgb = palette.code_for(cue.color)
store.add_memory_cue(
track_id, start_sec=cue.start, cue_type=cue.type,
length_sec=cue.length, name=cue.name,
color_code=memory_palette.nearest_code(effective_color(cue)),
length_sec=cue.length, name=cue.name, color_code=code or None,
)
memory += 1
continue
# What Konduktor SHOWS — stored colour, else the type's (blue
# cue, green loop) — as a palette code, which is what
@@ -323,13 +314,32 @@ 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
@staticmethod
def _lookup(db, kind: str, name: str | None):
return new_content.lookup(db, kind, name)
"""Find-or-create a lookup row, returning its id.
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
"""
if not name:
return None
if kind == "key":
found = db.get_key(ScaleName=name).first()
if found is not None:
return found.ID
return _insert_key(db, name)
found = {"artist": db.get_artist, "album": db.get_album,
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
if found is not None:
return found.ID
created = {"artist": db.add_artist, "album": db.add_album,
"genre": db.add_genre, "label": db.add_label}[kind](name)
db.flush()
return created.ID
# ---- analysis ---------------------------------------------------------------
@@ -340,17 +350,24 @@ class RekordboxExporter:
and the file on disk have to agree — so the same derivation is used here
rather than a path of our own choosing.
"""
rel = new_content.anlz_rel(str(content.UUID))
track_uuid = str(content.UUID)
# Rekordbox derives these two levels from the track's UUID, and the
# column and the file have to agree — so the same derivation is used.
rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
content.AnalysisDataPath = rel
content.Analysed = new_content.ANALYSED
if item.cues is not None and item.cues.grid_locked:
content.Analysed |= new_content.ANALYSED_LOCKED
content.Analysed = 105 # what a rekordbox-analysed track carries
content.AnalysisUpdated = 1
db.flush()
# The same three files as a rekordbox-analysed track. The `.DAT` needs
# PVBR and the preview waveforms before rekordbox shows a grid at all
# (measured on a OneLibrary stick; the same Pioneer file here); the
# `.EXT`/`.2EX` carry the drawn waveforms. Cue lists are present but
# EMPTY — master.db keeps cues in djmdCue.
off = timebase.offset(item.destination)
measured = item.waveform(lead=off)
beats = None
path = str(item.destination)
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))]
markers = item.cues.grid_markers if item.cues else []
if markers:
duration = ((measured.duration if measured else 0.0)
@@ -360,18 +377,26 @@ class RekordboxExporter:
# Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`).
# The cues need no such line: they are replayed through
# `set_cue`, which applies the same offset itself.
beats = [(n, bpm, timebase.to_pioneer(t, off))
for n, bpm, t in zip(nums, bpms, times)]
tags.append(W.beatgrid_tag(
[(n, bpm, timebase.to_pioneer(t, off)) for n, bpm, t in zip(nums, bpms, times)]))
if measured:
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
tags += W.flat_preview_tags()
ext_waves, two_ex = [], []
tags += W.cue_tags([], extended=False)
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
# not at the library root — the read path joins it that way, and writing
# it anywhere else produces a track whose grid silently reads as empty.
dat = root / "share" / rel.lstrip("/")
written = []
for suffix, data in new_content.anlz_files(item.destination, measured, beats).items():
target = dat.with_suffix(suffix)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
written.append(target)
written = [
W.write_anlz(dat, tags),
W.write_anlz(dat.with_suffix(".EXT"), [W.path_tag(path), *ext_waves[:1],
*W.cue_tags([], extended=True), *ext_waves[1:]]),
]
if two_ex:
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(path), *two_ex]))
return written
# ---- artwork ------------------------------------------------------------------
@@ -387,14 +412,17 @@ class RekordboxExporter:
rooted at `share/` like `AnalysisDataPath`. All measured on a real
Rekordbox 7 library.
"""
files = new_content.artwork_files(item.art[0] if item.art else None)
if files is None:
if not item.art:
return []
rel = new_content.artwork_rel(str(content.UUID))
jpegs = artwork.library_jpegs(item.art[0])
if jpegs is None:
return []
track_uuid = str(content.UUID)
rel = f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
folder = root / "share" / rel.lstrip("/")
folder.mkdir(parents=True, exist_ok=True)
written = []
for name, data in files.items():
for name, data in zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs):
(folder / name).write_bytes(data)
written.append(folder / name)
content.ImagePath = f"{rel}/artwork.jpg"
@@ -403,12 +431,9 @@ class RekordboxExporter:
# ---- playlists ---------------------------------------------------------------
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
"""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()
"""The tree, under one folder named after the export."""
root = db.create_playlist_folder(payload.name)
db.flush()
folders: dict[tuple[str, ...], object] = {(): root}
for playlist in payload.playlists:
@@ -437,3 +462,20 @@ class RekordboxExporter:
db.add_to_playlist(playlist, content)
db.flush()
def _insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL for the same reason the registry row is: the
ORM's DateTime binder raises on the NULLs a real row carries."""
from pyrekordbox.masterdb import models
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
seq = (db.query(models.DjmdKey).count() or 0) + 1
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
{"id": key_id, "name": name, "seq": seq,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
return key_id
@@ -1,32 +0,0 @@
"""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)
@@ -1,95 +0,0 @@
"""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
@@ -1,147 +0,0 @@
"""A NEW track's rows and files in a `master.db` library.
Shared by the two places a track is created rather than edited: the Rekordbox
Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks`
(a track added to the user's own library). One definition, because a track
row, its lookups and its analysis files are the same thing in both, and two
copies would drift.
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. 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
import uuid as uuidlib
from datetime import datetime
from pathlib import Path
from sqlalchemy import text
from . import anlz_writer as W
from . import artwork
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
#: five tracks of a Konduktor-written library different values and loading it
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses
#: itself — adds two more bits that draw an extra badge, most likely claiming
#: phrase/vocal analysis Konduktor does not write. So the value that claims
#: 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
the track's UUID, and the column and the file have to agree."""
return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
def artwork_rel(track_uuid: str) -> str:
"""The track's artwork FOLDER — the same UUID split as its analysis."""
return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]:
"""The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`.
The same files as a rekordbox-analysed track. The `.DAT` needs PVBR and the
preview waveforms before rekordbox shows a grid at all (measured on a
OneLibrary stick; the same Pioneer file here); the `.EXT`/`.2EX` carry the
drawn waveforms. Cue lists are present but EMPTY — master.db keeps cues in
djmdCue. `measured` is `waveform.analyse`'s result (None: flat previews).
`beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes
no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later.
"""
path = str(audio)
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))]
if beats is not None:
tags.append(W.beatgrid_tag(beats))
if measured:
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
tags += W.flat_preview_tags()
ext_waves, two_ex = [], []
tags += W.cue_tags([], extended=False)
out = {
".DAT": W.anlz_bytes(tags),
".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1],
*W.cue_tags([], extended=True), *ext_waves[1:]]),
}
if two_ex:
out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex])
return out
def artwork_files(art: bytes | None) -> dict[str, bytes] | None:
"""The cover as a rekordbox-managed track carries it, by file name.
`artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and
`artwork_s.jpg` (80), the last two letterboxed square; `djmdContent.
ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library.
None when there is no art or it cannot be read.
"""
if not art:
return None
jpegs = artwork.library_jpegs(art)
if jpegs is None:
return None
return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs))
def lookup(db, kind: str, name: str | None):
"""Find-or-create a lookup row, returning its id.
Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name,
so every one is find-or-create — the same rule the in-place adapter follows.
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
"""
if not name:
return None
if kind == "key":
found = db.get_key(ScaleName=name).first()
if found is not None:
return found.ID
return insert_key(db, name)
found = {"artist": db.get_artist, "album": db.get_album,
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
if found is not None:
return found.ID
created = {"artist": db.add_artist, "album": db.add_album,
"genre": db.add_genre, "label": db.add_label}[kind](name)
db.flush()
return created.ID
def insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs
a real row carries."""
from pyrekordbox.masterdb import models
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
seq = (db.query(models.DjmdKey).count() or 0) + 1
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
{"id": key_id, "name": name, "seq": seq,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
return key_id
@@ -9,9 +9,8 @@ The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
writes the palette's exact RGB beside each code.
* The teal-green between 0x0E and 0x16 was missed by that measurement, and
found later: it is **0x13 = #00FF30**, which rekordbox 7 wrote itself as the
DEFAULT colour of a hot cue added on a stick (Goober, 2026-10-01).
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
* 0x2B (#FF0017) was observed on a real export though it is not one of the 16
swatches; it is kept so such a colour survives a round trip exactly.
* **The palette has no white or grey.** A colourless (white/grey) cue — above
@@ -33,7 +32,6 @@ PALETTE: dict[int, tuple[int, int, int]] = {
0x05: (0x00, 0x70, 0xFF), # light blue
0x09: (0x00, 0xE0, 0xFF), # cyan
0x0E: (0x00, 0xFF, 0xA3), # teal
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
0x16: (0x1A, 0xFF, 0x00), # green
0x1A: (0x80, 0xFF, 0x00), # lime
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
@@ -93,27 +91,3 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
return min(d, 1 - d)
best = min((c for c in PALETTE if c != 0x2B), key=hue_gap)
return best, PALETTE[best]
#: The swatches a user can pick, in rekordbox's own order — what
#: `capabilities.cues.palette` offers: all 16. 0x2B is not a swatch at all (see
#: the module note).
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
def hex_for(code: int | None) -> str | None:
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
An unknown code projects as no colour rather than a guessed one; it is
still kept on the row, since editing a cue's position, type or name never
rewrites its colour.
"""
rgb = PALETTE.get(code) if code else None
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
def swatch_code(color: str) -> int | None:
"""The code of an EXACT palette colour, else None — for a user's pick, which
must be a swatch, unlike `code_for`'s nearest-hue mapping for exports."""
rgb = _parse(color)
return next((code for code, value in PALETTE.items() if value == rgb), None)
-163
View File
@@ -430,166 +430,3 @@ __all__ = [
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
]
# ---- editing an existing library -----------------------------------------------
#
# Editing a stick rekordbox wrote, rather than writing one from the template:
# only the tables whose rows change are rewritten, and inside them a row that
# does not change keeps rekordbox's own bytes. Every other table — history,
# colours, menus, artwork — stays byte-identical, and so does exportExt.pdb.
def _chain(buf: bytes, first: int, last: int) -> list[int]:
"""A table's page chain, header page first."""
pages, p = [first], first
while p != last and len(pages) < 100000:
p = struct.unpack_from("<I", buf, p * PAGE + 12)[0]
pages.append(p)
return pages
def table_rows(buf: bytes, table: int) -> list[bytes]:
"""Every present row of `table`, in page order, as its own bytes (padding
included) — a row's extent is up to the next row's heap offset, or the end
of the page's used heap."""
n_tables = struct.unpack_from("<I", buf, 8)[0]
for i in range(n_tables):
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
if t != table:
continue
out = []
for p in _chain(buf, first, last)[1:]:
o = p * PAGE
if buf[o + 0x1B] & _HEADER_PAGE:
continue
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
used = struct.unpack_from("<H", buf, o + 0x1E)[0]
offs, present = [], []
# As `_rows` reads them: every bit of every group, since a page
# rekordbox has edited holds more row slots than its small count.
for g in range((n + 15) // 16):
base = o + PAGE - g * _GROUP
mask = struct.unpack_from("<H", buf, base - 4)[0]
for r in range(16):
if mask & (1 << r):
offs.append(struct.unpack_from("<H", buf, base - 6 - 2 * r)[0])
present.append(True)
ends = sorted(set(offs)) + [used]
for off, ok in zip(offs, present):
if ok:
end = next(e for e in ends if e > off)
row = bytes(buf[o + _HEADER + off:o + _HEADER + end])
if table == TRACKS:
row = row[:track_extent(row)]
out.append(row)
return out
return []
def _dsql_len(buf: bytes, off: int) -> int:
head = buf[off]
return (head >> 1) if head & 1 else struct.unpack_from("<H", buf, off + 1)[0]
def track_extent(row: bytes) -> int:
"""Where a track row really ends: past its last string, 4-aligned.
NOT the next row's offset: rekordbox reuses its heap, and the bytes between
a row and the next can be a stale tail of an older, longer string (seen on
Goober: `...mp3` followed by `ing.stem.m4a`)."""
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
end = max(o + _dsql_len(row, o) for o in offs)
return end + (-end % 4)
def track_fields(row: bytes) -> tuple[dict, dict]:
"""A raw track row as (`fields`, `strings`) — what `track_row` takes back."""
fields = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, row, 0)))
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
return fields, {name: read_dsql(row, o) for name, o in zip(TRACK_STRINGS, offs)}
def row_id(table: int, row: bytes) -> int | tuple:
"""A row's identity within its table (the triple, for playlist entries)."""
if table == TRACKS:
return track_fields(row)[0]["id"]
if table == ARTISTS:
return struct.unpack_from("<I", row, 4)[0]
if table == ALBUMS:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_TREE:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_ENTRIES:
return struct.unpack_from("<3I", row, 0)
return struct.unpack_from("<I", row, 0)[0]
class PdbEditor(PdbWriter):
"""`PdbWriter` over an EXISTING library: `refill` replaces one table's rows.
The table keeps its pages — overwritten in place, more taken from the
next-unused counter if needed, any left over unlinked and blanked (a blank
reserved page inside the file is a state rekordbox's own template has) —
and keeps its empty candidate. `render` leaves the header's
pages-with-room field as it was: rekordbox did not touch it when it edited
Goober, and it is the least understood field in the file.
"""
def __init__(self, existing: bytes):
super().__init__(existing)
self._room_field = struct.unpack_from("<I", self.buf, 16)[0]
self._blank: set[int] = set()
def refill(self, table: int, rows: list[bytes]) -> None:
slot, candidate, first, last = self.tables[table]
old = _chain(bytes(self.buf), first, last)[1:]
if candidate in old:
old.remove(candidate)
chunks = _chunk(rows) if rows else []
indices = old[:len(chunks)] + [self._alloc() for _ in chunks[len(old):]]
for p in old[len(chunks):]:
self._blank.add(p)
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
indexed = table in _INDEXED
for i, chunk in enumerate(chunks):
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
fill = None
if indexed:
fill = (len(chunk) + 1, 0) if i + 1 == len(chunks) else (_NONE, _NONE)
self.sequence += 1
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
shift_at=shift_at, fill=fill)
self._reindex(first, indices, indexed=indexed)
self.tables[table] = [slot, candidate, first, indices[-1] if indices else first]
if not indices:
# No rows: the header page points straight at the candidate again.
struct.pack_into("<I", self.buf, first * PAGE + 12, candidate)
def _reindex(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
o = header_page * PAGE
struct.pack_into("<I", self.buf, o + 12, data_pages[0] if data_pages else
struct.unpack_from("<I", self.buf, o + 12)[0])
if indexed:
# Clear the old entries first: a table that shrank must not keep
# listing pages it no longer has.
count = struct.unpack_from("<H", self.buf, o + _HEADER + 16)[0]
for k in range(max(count, len(data_pages))):
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, 0x1FFFFFF8)
if data_pages:
pages_with_room = self.pages_with_room
self._index(header_page, data_pages, indexed=indexed)
self.pages_with_room = pages_with_room
else:
struct.pack_into("<I", self.buf, o + _HEADER + 4, 0x03FFFFFF)
if indexed:
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 0, 0x1FFF)
struct.pack_into("<HH", self.buf, o + 0x20, _NONE, _NONE)
struct.pack_into("<H", self.buf, o + 0x26, 0)
def render(self) -> bytes:
out = bytearray(super().render())
struct.pack_into("<I", out, 16, self._room_field)
for p in self._blank - set(self.pages):
out[p * PAGE:(p + 1) * PAGE] = bytes(PAGE)
return bytes(out)
@@ -5,32 +5,65 @@ The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
"""
from __future__ import annotations
from ...core import musical_key
import re
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, memory_palette, palette, timebase, track_palette
from .cue_types import cue_type, kind_for, role_and_slot
from . import beatgrid, 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,
}
# 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 key name in any notation."""
return musical_key.parse(key)
"""(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)
# The inverse, for writing. A track arriving from Traktor carries `key` as
# The inverse, for EXPORT. 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 "Cm". Rendering from the wheel is the only
# correct crossing. Shared by the adapter and both Pioneer exporters.
# "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()))}
def render_key(wheel: int | None, mode: str | None) -> str | None:
"""A Pioneer key name ("Abm", "F") for a Camelot position + mode, spelt as
rekordbox spells its own (flats; see `core/musical_key`).
"""A Pioneer-style key name ("Abm", "F") for a Camelot position + mode.
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.
"""
return musical_key.render(wheel, mode, "musical")
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)
def _iso_date(value) -> str | None:
@@ -64,10 +97,10 @@ def _name_of(related) -> str | None:
return None
def to_track(row, cue_kinds=(), *, stem: bool = False, auto_gain_db: float | None = None) -> Track:
def to_track(row, cue_kinds=()) -> Track:
"""Project one ``DjmdContent`` row.
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
`cue_kinds` is this track's ``(Kind, OutMsec)`` pairs from the store's single
query — passed in rather than read off the row, which would be a per-track
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
same definition `to_track_cues` uses, so the table's count and dots agree
@@ -85,11 +118,12 @@ def to_track(row, cue_kinds=(), *, stem: bool = False, auto_gain_db: float | Non
BPM are precisely the 22 with no grid.
"""
chips: list[HotcueChip] = []
for kind, out_msec, color_code in cue_kinds:
for kind, out_msec in cue_kinds:
role, slot = role_and_slot(kind)
if role == "hotcue" and slot is not None:
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec),
color=palette.hex_for(color_code)))
# Rekordbox's colour is a palette index nobody has decoded yet (see
# `_cue_color`), so no colour is claimed and the UI uses the type's.
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec), color=None))
chips.sort(key=lambda chip: chip.slot)
key_name = _name_of(getattr(row, "Key", None))
wheel, mode = parse_key(key_name)
@@ -123,14 +157,7 @@ def to_track(row, cue_kinds=(), *, stem: bool = False, auto_gain_db: float | Non
hotcues=chips,
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
grid_locked=False, # Rekordbox has no per-track grid lock
# What the FILE is (`store.is_stem`): Rekordbox itself plays a stem
# 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,
media_kind="audio",
)
@@ -144,10 +171,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.
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.
**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.
"""
markers: list[GridMarker] = []
if grid is not None:
@@ -162,9 +189,7 @@ 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)
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)
editable = role == "hotcue"
cues.append(
CuePoint(
name=(getattr(c, "Comment", None) or None),
@@ -175,28 +200,21 @@ 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=_memory_cue_color(c) if memory else _cue_color(c),
color=_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."""
return palette.hex_for(getattr(row, "ColorTableIndex", None))
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
The generic model carries ``#RRGGBB``, and the built-in palette that index
refers to is not yet known, so no colour is claimed rather than a wrong one
being invented. `capabilities.cues.color` already says "palette", so the UI
knows not to offer a free colour picker.
"""
return None
+77 -697
View File
@@ -28,7 +28,6 @@ from __future__ import annotations
import json
import logging
import os
import uuid
from contextlib import contextmanager
from datetime import datetime
@@ -38,52 +37,15 @@ from sqlalchemy import func, select, text
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import joinedload
from ...core.adapter import (
InvalidCommand,
LibraryNotSupported,
NotFound,
SaveOutcome,
Unsupported,
)
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
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
from ...core.pathmap import PathMapping
from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__)
def _file_facts(audio: Path) -> dict:
"""What Rekordbox reads off the file itself for a new track's row."""
from datetime import date
out: dict = {}
try:
st = audio.stat()
born = getattr(st, "st_birthtime", None) or st.st_mtime
out["created"] = date.fromtimestamp(born)
except OSError:
pass
try:
import mutagen
info = mutagen.File(str(audio)).info
out["length"] = int(round(info.length)) if info.length else None
if getattr(info, "bitrate", None):
out["bitrate"] = int(round(info.bitrate / 1000)) # kbps, as Rekordbox stores it
if getattr(info, "sample_rate", None):
out["sample_rate"] = int(info.sample_rate)
if getattr(info, "bits_per_sample", None):
out["bit_depth"] = int(info.bits_per_sample)
except Exception: # noqa: BLE001 — facts are a nicety; the row stands without them
log.debug("could not read %s", audio, exc_info=True)
return out
# Where a track's analysis files live, as `contentFile.Path` spells it.
_ANLZ_ROOT = "/PIONEER/USBANLZ/"
@contextmanager
def rekordbox_probe_suppressed():
"""Stop `pyrekordbox.commit()` refusing because a Rekordbox process exists.
@@ -112,28 +74,17 @@ def _iso_stamp(value) -> str:
return str(value)
class RekordboxStore(ReplaceGridCommands):
class RekordboxStore:
"""One open Rekordbox library."""
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()
# Files of ADDED tracks, `share`-relative path -> bytes, written by
# save() BEFORE the commit (and removed again if it fails).
self._pending_new_files: dict[str, bytes] = {}
self._load()
# ---- open ------------------------------------------------------------
@@ -147,7 +98,6 @@ class RekordboxStore(ReplaceGridCommands):
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
self._grid_cache.clear()
self._stem_cache: dict[str, bool] = {}
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
@@ -167,9 +117,6 @@ 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()
def close(self) -> None:
@@ -263,9 +210,8 @@ class RekordboxStore(ReplaceGridCommands):
raise NotFound(f"No track {track_id!r}")
return row
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None, int | None]]]:
"""``{track_id: [(Kind, OutMsec, ColorTableIndex), ...]}`` for every live
cue, in one query.
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None]]]:
"""``{track_id: [(Kind, OutMsec), ...]}`` for every live cue, in one query.
Just enough per cue for the library table's count and hotcue dots,
without a per-track round trip. What a ``Kind`` means is decided in the
@@ -274,13 +220,12 @@ class RekordboxStore(ReplaceGridCommands):
"""
t = self._tables
rows = self._db.session.execute(
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec,
t.DjmdCue.ColorTableIndex)
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec)
.where(t.DjmdCue.rb_local_deleted == 0)
).all()
out: dict[str, list[tuple[int | None, int | None, int | None]]] = {}
for content_id, kind, out_msec, color_code in rows:
out.setdefault(str(content_id), []).append((kind, out_msec, color_code))
out: dict[str, list[tuple[int | None, int | None]]] = {}
for content_id, kind, out_msec in rows:
out.setdefault(str(content_id), []).append((kind, out_msec))
return out
def cues(self, track_id: str) -> list:
@@ -382,28 +327,6 @@ 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
cached per path, since the projection asks for every track at open."""
from ...core.stem_file import is_stem_file
path = self.audio_path(track_id)
if path is None:
return False
key = str(path)
if key not in self._stem_cache:
self._stem_cache[key] = is_stem_file(path)
return self._stem_cache[key]
@property
def path_mapping(self) -> PathMapping:
return self._mapping
@@ -521,107 +444,6 @@ 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
@@ -674,79 +496,6 @@ 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.
@@ -768,279 +517,13 @@ class RekordboxStore(ReplaceGridCommands):
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
.all()
)
# NOT `remove_from_playlist`: it commits, which wrote an unsaved edit
# to disk (beyond Discard's reach) and raised while Rekordbox ran.
# The list is rebuilt from 1 below, so no renumbering is needed.
for song in existing:
self._db.delete(song)
self._db.flush()
self._db.remove_from_playlist(playlist, song)
for n, track_id in enumerate(track_ids, start=1):
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
return len(track_ids)
# ---- writes: adding tracks ---------------------------------------------
#
# MEASURED, by dragging two files into Rekordbox 7.2's collection and
# diffing (2026-10-01): see `new_content`. Rekordbox fills the row from the
# FILE (size, sample rate, bit rate, and `DateCreated` from the file's
# creation date), stamps it with this library's device, and lists every
# file it writes for the track in `contentFile` with the file's MD5.
def add_track(self, audio: Path, track, *, measured, with_grid: bool,
art: bytes | None) -> str:
"""Add one track's row, return its id. Its analysis files and artwork
are held until save(); its grid and cues are the caller's to replay
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
in the `.DAT` for `replace_grid` to fill."""
from . import new_content
audio = Path(audio)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
t = self._tables
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),
Title=track.title or audio.stem,
Length=facts.get("length") or track.length,
BitRate=facts.get("bitrate") or (int(track.bitrate / 1000) if track.bitrate else None),
SampleRate=facts.get("sample_rate"),
BitDepth=facts.get("bit_depth", 16),
Rating=track.rating or 0,
Commnt=track.comment or "",
ReleaseDate=track.release_date or "",
)
year = str(track.release_date or "")[:4]
if year.isdigit():
content.ReleaseYear = int(year)
if facts.get("created"):
content.DateCreated = facts["created"]
content.ArtistID = new_content.lookup(self._db, "artist", track.artist)
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)
# 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 = new_content.ANALYSED
content.AnalysisUpdated = 1
files = new_content.anlz_files(audio, measured, [] if with_grid else None)
for suffix, data in files.items():
self._pending_new_files[str(Path(rel).with_suffix(suffix))] = data
art_files = new_content.artwork_files(art)
if art_files:
folder = new_content.artwork_rel(track_uuid)
for name, data in art_files.items():
self._pending_new_files[f"{folder}/{name}"] = data
content.ImagePath = f"{folder}/artwork.jpg"
self._db.flush()
track_id = str(content.ID)
if self._content_cache is not None and self._by_id is not None:
self._content_cache.append(content)
self._by_id[track_id] = content
self._grid_cache.pop(track_id, None)
self._journal.record("track", "add", track_id)
return track_id
def _write_new_files(self) -> list[Path]:
"""Write added tracks' files; return what was written."""
share = self.path.parent / "share"
written: list[Path] = []
try:
for rel, data in self._pending_new_files.items():
path = share / rel.lstrip("/")
path.parent.mkdir(parents=True, exist_ok=True)
written.append(path) # before the write: a partial file is cleaned too
path.write_bytes(data)
except BaseException:
for path in written:
path.unlink(missing_ok=True)
raise
return written
def _add_content_files(self, written: list[Path]) -> None:
"""One `contentFile` row per file an added track carries, as Rekordbox
writes them: `Hash` is the file's MD5, and its `_m`/`_s` artwork sizes
are not listed."""
import hashlib
from urllib.parse import quote
t = self._tables
share = self.path.parent / "share"
by_folder = {}
for row in self.iter_content():
for rel in (row.AnalysisDataPath, row.ImagePath):
if rel:
by_folder[str(Path(rel).parent)] = row
for path in written:
if path.name in ("artwork_m.jpg", "artwork_s.jpg"):
continue
rel = "/" + path.relative_to(share).as_posix()
row = by_folder.get(str(Path(rel).parent))
if row is None:
continue
self._db.add(t.ContentFile(
ID=f"{row.UUID}_{quote(rel, safe='')}",
ContentID=str(row.ID),
Path=rel,
Hash=hashlib.md5(path.read_bytes()).hexdigest(),
Size=path.stat().st_size,
rb_local_path=str(path),
UUID=str(uuid.uuid4()),
created_at=datetime.now(),
updated_at=datetime.now(),
))
self._db.flush()
# ---- writes: removing tracks -------------------------------------------
#
# MEASURED, by removing a track in Rekordbox 7.2 and diffing every row and
# every file under `share/` (Demo Track 2, 2026-10-01): Rekordbox DELETES
# the rows — it does not set `rb_local_deleted` — from these tables, leaves
# the playlist row itself alone, and deletes the files `contentFile` lists
# (there, the four ANLZ files) together with their emptied folders. That
# track had no artwork, and an Artwork folder holds `_m`/`_s` sizes that
# `contentFile` does not list, so artwork is left in place: an orphaned
# image is harmless, a guessed deletion is not.
_REMOVED_WITH_TRACK = ("DjmdCue", "ContentCue", "ContentFile", "DjmdMixerParam",
"DjmdSongPlaylist")
# Also keyed by ContentID, but empty in the measured library, so what
# Rekordbox does with them is unknown. A track that appears in one is
# refused rather than guessed at.
_UNMEASURED_LINKS = {
"djmdSongHistory": "a History list",
"djmdSongSampler": "the Sampler",
"djmdSongTagList": "the Tag List",
"djmdSongMyTag": "My Tag",
"djmdSongHotCueBanklist": "a Hot Cue Bank List",
"djmdSongRelatedTracks": "Related Tracks",
"djmdSongRequestList": "a request list",
"djmdActiveCensor": "an Active Censor",
"contentActiveCensor": "an Active Censor",
"djmdCloudExportSongPlaylist": "a cloud export",
}
def _unmeasured_links(self, ids: list[str]) -> list[tuple[str, str]]:
"""``(track_id, where)`` for each track named by an unmeasured table."""
params = {f"i{n}": tid for n, tid in enumerate(ids)}
marks = ", ".join(f":{k}" for k in params)
found: list[tuple[str, str]] = []
for table, where in self._UNMEASURED_LINKS.items():
try:
rows = self._db.session.execute(
text(f'SELECT DISTINCT ContentID FROM "{table}" '
f"WHERE ContentID IN ({marks})"), params
).all()
except Exception: # noqa: BLE001 — table absent in this schema version
continue
found += [(str(r[0]), where) for r in rows]
return found
def remove_tracks(self, track_ids: list[str]) -> int:
"""Remove tracks from the library and every playlist; return how many.
Validated as a whole first, so a refused batch changes nothing. The
audio files are never touched; the analysis files go at save().
"""
t = self._tables
self.iter_content()
assert self._by_id is not None
ids = [str(tid) for tid in dict.fromkeys(track_ids) if str(tid) in self._by_id]
if not ids:
return 0
blocked = self._unmeasured_links(ids)
if blocked:
tid, where = blocked[0]
title = self._by_id[tid].Title or tid
more = f" (and {len(blocked) - 1} more)" if len(blocked) > 1 else ""
raise Unsupported(
f"“{title}” is in {where} in Rekordbox{more}, and Konduktor does not "
"yet know how Rekordbox removes a track from there. Remove it in "
"Rekordbox instead — nothing was changed."
)
playlists: set[str] = set()
for tid in ids:
for name in self._REMOVED_WITH_TRACK:
table = getattr(t, name)
for row in self._db.session.query(table).filter(table.ContentID == tid):
if name == "ContentFile" and str(row.Path or "").startswith(_ANLZ_ROOT):
self._pending_file_removals.add(str(row.Path))
elif name == "DjmdSongPlaylist":
playlists.add(str(row.PlaylistID))
self._db.delete(row)
self._db.delete(self._by_id[tid])
self._pending_grids.pop(tid, None)
self._grid_cache.pop(tid, None)
self._journal.record("track", "remove", tid)
self._db.flush()
for playlist_id in playlists:
self._renumber(playlist_id)
self._content_cache = None
self._by_id = None
return len(ids)
def _renumber(self, playlist_id: str) -> None:
"""Close the gaps removed entries left in a playlist's `TrackNo`s, as
`pyrekordbox.remove_from_playlist` does — one 'move' for the registry,
not an update per row."""
t = self._tables
moved = []
now = datetime.now()
rows = (
self._db.session.query(t.DjmdSongPlaylist)
.filter(t.DjmdSongPlaylist.PlaylistID == playlist_id)
.order_by(t.DjmdSongPlaylist.TrackNo)
)
with self._db.registry.disabled():
for n, row in enumerate(rows, start=1):
if row.TrackNo != n:
row.TrackNo = n
row.updated_at = now
moved.append(row)
if moved:
self._db.registry.on_move(moved)
def _delete_removed_files(self) -> None:
"""Delete removed tracks' analysis/artwork files, then their emptied
folders. Called after the commit; a file another track still lists is
kept, and a failure only leaves an orphan behind, so it is logged."""
t = self._tables
share = (self.path.parent / "share").resolve()
still_listed = {str(p) for (p,) in self._db.session.query(t.ContentFile.Path)}
for rel in sorted(self._pending_file_removals - still_listed):
parts = Path(rel.lstrip("/\\")).parts
path = (share / Path(*parts)).resolve()
# Folders below e.g. `PIONEER/USBANLZ` are the track's own; that
# level and above are Rekordbox's and stay even when emptied.
keep = (share / Path(*parts[:2])).resolve()
if len(parts) < 3 or keep not in path.parents:
continue
try:
path.unlink(missing_ok=True)
folder = path.parent
while folder != keep and not any(folder.iterdir()):
folder.rmdir()
folder = folder.parent
except OSError as ex:
log.warning("Could not delete %s: %s", path, ex)
self._pending_file_removals.clear()
# ---- save --------------------------------------------------------------
@property
def dirty(self) -> bool:
@@ -1063,21 +546,9 @@ class RekordboxStore(ReplaceGridCommands):
"""
summary = self._journal.summary()
# Files first: if an analysis file cannot be written, nothing should have
# been committed to the database either. An added track's files go
# before the grids, which write into them, and their `contentFile`
# 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()
except BaseException:
for path in written:
path.unlink(missing_ok=True)
raise
self._pending_new_files.clear()
self._delete_removed_files()
# been committed to the database either.
self._flush_grids()
self._commit()
self._journal.clear()
# Reads go through the same session, so nothing needs re-projecting from
# scratch — but the grid cache is keyed by track and survives a save.
@@ -1198,42 +669,19 @@ class RekordboxStore(ReplaceGridCommands):
) -> None:
"""Create or replace the cue in `slot`. A loop is a cue with a length.
`color_code` is a rekordbox palette code (`palette.PALETTE`). None KEEPS
the colour of the cue already in the slot — the colour belongs to the
pad, so a rename, a type change or an Auto Hotcues Replace leaves it as
the user set it — and a new cue is uncoloured. Only `set_cue_color`
clears one.
`color_code` is a rekordbox palette code (`palette.PALETTE`); None or 0
writes the uncoloured convention, which is what every edit through the
adapter does — only the exporter passes a colour.
"""
if int(slot) < 0:
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
existing = self._cue_row(track_id, slot)
if color_code is None and existing is not None:
color_code = existing.ColorTableIndex or None
self._write_cue(
track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
)
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,
@@ -1243,59 +691,23 @@ 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); a memory loop when `length_sec` > 0.
"""Add a MEMORY cue (`Kind` 0) — for the exporter building a new library.
`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.
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.
"""
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.
`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."""
`contentCue` mirror — the single definition of a cue row's fields."""
if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track")
row = self.content(track_id)
@@ -1336,63 +748,25 @@ class RekordboxStore(ReplaceGridCommands):
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
cue.ActiveLoop = 0
cue.CueMicrosec = 0
cue.Color = 255
cue.ColorTableIndex = 0
else:
cue.BeatLoopSize = None
cue.ActiveLoop = None
cue.CueMicrosec = 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)
@staticmethod
def _apply_color(cue, color_code: int | None, is_loop: bool) -> None:
"""A row's two colour columns — the one definition of both conventions."""
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. Coloured loops store the
# same; verified in Rekordbox 7 through the master.db export.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
elif is_loop:
# What Rekordbox writes on the loops and auto-cues it creates.
cue.Color = 255
cue.ColorTableIndex = 0
else:
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:
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. How rekordbox stores a
# COLOURED LOOP is not in the reference library; the same column is
# assumed and is what the smoke test checks.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
cue.Comment = name or None
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."""
cue = self._cue_row(track_id, slot)
if cue is None:
raise NotFound(f"No cue in slot {slot}")
self._apply_color(cue, color_code, (cue.OutMsec or 0) > 0)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
cue = self._cue_row(track_id, slot)
@@ -1451,13 +825,11 @@ 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(text("djmdCue.rowid"))
.order_by(t.DjmdCue.InMsec)
.all()
)
fields = (
@@ -1558,44 +930,52 @@ 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 delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
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
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
from ...core.model import GridMarker
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()
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
def _flush_grids(self) -> None:
"""Write buffered grids into their ANLZ files. Called by save().
@@ -1,50 +0,0 @@
"""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
Loaded 100 of 361 files, more files were not shown because too many files have changed in this diff. Show more