Compare commits

..
129 Commits
Author SHA1 Message Date
patben8 65fbc775ce Merge pull request #18 from MrPatben8/dev
Fixed leftover Traktor data blocks from overwriting BPM
2026-10-30 23:34:50 +01:00
patben8 b57dd74445 Bumped version number 2026-10-30 23:33:32 +01:00
patben8 31287bdeb7 Exports now strip Traktor song data blocks that overwrite BPM from collection 2026-10-26 09:42:19 +01:00
patben8 210c1ab135 Merge pull request #17 from MrPatben8/dev
Fixed local export issues & Subtractive playlist edditing
2026-10-22 11:58:34 +02:00
patben8 e211fd180a Bumped version number 2026-10-22 11:56:13 +02:00
patben8 5d059c7604 Improved cue/grid button switch layout and style 2026-10-22 11:48:00 +02:00
patben8 667068c2f1 Mode switch chan now be clicked anywhere to swap options 2026-10-22 11:39:35 +02:00
patben8 75cb0c8138 Added + button next to playlists in sidebar 2026-10-22 10:03:35 +02:00
patben8 068e4da08b Implemented subtractive playlist editing 2026-10-22 09:58:57 +02:00
patben8 1a28ad6102 Local exports are no longer blocked by missing local library 2026-10-21 22:15:45 +02:00
patben8 dd82fa99bb Merge pull request #16 from MrPatben8/dev
Implemented local exports
2026-10-21 19:50:15 +02:00
patben8 fae91e8772 Bumped version number 2026-10-21 19:50:02 +02:00
patben8 68128a123e Update dialog now shows accumulated changes 2026-10-20 11:54:33 +02:00
patben8 23a5cd72f4 Implemented local export system 2026-10-20 11:49:20 +02:00
patben8 17c177e34e Merge pull request #15 from MrPatben8/feature/mastering-tools
Implemented mastering tools
2026-10-20 09:43:58 +02:00
patben8 ee0e055b3f Bumped version number 2026-10-20 09:40:17 +02:00
patben8 21e249ff97 Fixed STEM encoding for consistent conversion 2026-10-19 23:57:28 +02:00
patben8 3e9d5d5528 Implemented AAC normalizing 2026-10-19 22:02:51 +02:00
patben8 13ba2c721a Implemented remote side 2026-10-19 21:39:47 +02:00
patben8 4cb630d0d5 Implemented normalization and auto gain export options 2026-10-19 21:20:57 +02:00
patben8 64b0396d66 Implemented basic track normalizing 2026-10-19 20:45:35 +02:00
patben8 284a7514fe Implemented auto gain analysis 2026-10-19 18:20:13 +02:00
patben8 6eecb2288a Improved loudness calculation 2026-10-19 17:18:05 +02:00
patben8 d70a7c5de2 Implemented track loudness analysis 2026-10-19 14:07:54 +02:00
patben8 5c9387f136 Added quick target location change button in export dialog 2026-10-19 11:33:23 +02:00
patben8 9329236955 Implemented export track grid locking 2026-10-19 10:48:59 +02:00
patben8 2821ba124d Merge pull request #14 from MrPatben8/dev
Improved drag and drop import
2026-10-17 22:55:03 +02:00
patben8 f9ef38d826 Bumped version number 2026-10-17 22:54:08 +02:00
patben8 518542c7bb Improved drag to import dialog 2026-10-17 22:53:37 +02:00
patben8 bf427a628e Fixed drag and drop position accuracy 2026-10-17 22:53:37 +02:00
patben8 4340e948ac Bumped version number 2026-10-17 20:21:28 +02:00
patben8 fe63acc2a2 Merge pull request #13 from MrPatben8/dev
Implemented Cross-Platform Track Color Support
2026-10-17 20:08:02 +02:00
patben8 06361a851f Implemented cross-platform track color support 2026-10-17 19:50:56 +02:00
patben8 0605dbabe6 Improved release description and file names 2026-10-16 18:04:54 +02:00
patben8 6be99e6d7e Merge pull request #12 from MrPatben8/dev
Implemented self-updating
2026-10-16 17:39:28 +02:00
patben8 0eac972173 Implemented self-updating 2026-10-16 17:38:35 +02:00
patben8 422297d890 Merge pull request #11 from MrPatben8/dev
Implemented Memory Cue Support
2026-10-16 16:06:47 +02:00
patben8 ee48e80440 Bumped version number 2026-10-16 16:04:49 +02:00
patben8 0aeb5019ad Fixed issue with Traktor 4.5 collection round-trip 2026-10-16 15:53:52 +02:00
patben8 1f2ca18e8a Fixed issues with cross-platform memory-cue naming and coloring 2026-10-16 15:04:43 +02:00
patben8 19a604f730 Added full support for memory-cues 2026-10-16 14:50:46 +02:00
patben8 83b0978b14 Merge pull request #10 from MrPatben8/dev
Implemented Raw Waveform View
2026-10-15 17:51:59 +02:00
patben8 0ced274f73 Bumped version number 2026-10-15 17:48:40 +02:00
patben8 fc4e7804b3 Changed how patchnotes are compiled 2026-10-15 17:48:17 +02:00
patben8 77b063ba0e Implemented time readout accuracy setting 2026-10-15 17:42:26 +02:00
patben8 16c3552be6 Changed option keyboard shortcuts to use command instead 2026-10-15 16:36:10 +02:00
patben8 32cfb034e2 Implemented better shortcut menu 2026-10-15 16:30:34 +02:00
patben8 b70798a0fe Implemented track info dialog popup 2026-10-15 15:46:39 +02:00
patben8 4c51f57fe9 Improved context menu positioning when near the bottom of the window 2026-10-15 14:22:40 +02:00
patben8 7b2d6de411 Implemented new set playlist position mode 2026-10-15 10:48:14 +02:00
patben8 8230722105 Implemented raw waveform mode 2026-10-15 10:26:41 +02:00
patben8 1464b1e211 Merge pull request #9 from MrPatben8/dev
Fixed issues on Windows, Implemented drag & drop importing, Improved STEM encoding speed
2026-10-13 17:47:09 +02:00
patben8 10f175b206 Bumped version number 2026-10-13 17:43:20 +02:00
patben8 a65ef959b2 Implemented drag to import 2026-10-13 17:42:24 +02:00
patben8 87cbd3720e Fixed STEM analysis not working on Windows 2026-10-13 10:59:22 +02:00
patben8 591f2bc791 Pararellized STEM aac encoding 2026-10-13 10:45:52 +02:00
patben8 ebe30c1128 Fixed analysis not working on windows 2026-10-12 23:49:19 +02:00
patben8 cd1914216f Fixed library options not appearing in windows 2026-10-12 23:26:33 +02:00
patben8 d10b11f8eb Merge pull request #8 from MrPatben8/dev
Fixed Rekordbox exports
2026-10-12 19:12:41 +02:00
patben8 79a8a843c5 Bumped version number 2026-10-12 19:12:09 +02:00
patben8 0204a322ff Fixed and pinned rekordbox exports 2026-10-12 19:10:20 +02:00
patben8 05051e7056 Merge pull request #7 from MrPatben8/dev
Implemented remote file exploring, fixed STEM playback and improved startup time.
2026-10-12 15:04:40 +02:00
patben8 b5dabbc8a0 Updated the readme 2026-10-12 15:02:46 +02:00
patben8 86bbb7b961 Bumped version number 2026-10-12 13:51:23 +02:00
patben8 d474c662db Fixed slow build startup time and implemented loading screen 2026-10-12 13:20:00 +02:00
patben8 a0df683fee Fixed stem playback not working in build 2026-10-12 11:31:44 +02:00
patben8 3385b794e9 Added setting for export playlist root folder toggle 2026-10-12 10:56:32 +02:00
patben8 2c352b76a1 Added konduktor settings menu 2026-10-12 10:15:14 +02:00
patben8 40630ff78e Added support for remote file exploring 2026-10-12 09:23:34 +02:00
patben8 966f3fe8c5 Bumped version number 2026-10-10 17:42:17 +02:00
patben8 a03b9056a9 Merge pull request #6 from MrPatben8/dev
Implemented dragging engine
2026-10-10 17:40:06 +02:00
patben8 26b556d975 Updated remote protocol version 2026-10-06 23:17:21 +02:00
patben8 c87444bda5 Implemented drag and drop loading 2026-10-06 23:08:34 +02:00
patben8 7ba71981c8 Implemented library rearrangement 2026-10-06 22:51:34 +02:00
patben8 89c7dade25 Tracks can be added to playlists via drag 2026-10-06 22:41:29 +02:00
patben8 b154df430a Implemented drag core and song reorganizing 2026-10-06 22:32:31 +02:00
patben8 e5c7b67626 Implemented playlist reorganizing 2026-10-06 22:25:01 +02:00
patben8 9f79f5a849 Search now includes comments 2026-10-05 23:16:12 +02:00
patben8 c8b86100f0 Track position in playlist can now be typed 2026-10-05 21:01:25 +02:00
patben8 0fac84cb73 Fixed issue with release pipeline 2026-10-04 21:57:40 +02:00
patben8 71ee877784 Merge pull request #5 from MrPatben8/dev
Implemented Key Analysis & Remote Library Management
2026-10-04 18:35:08 +02:00
patben8 920146f2c0 Bumped version number 2026-10-04 18:33:33 +02:00
patben8 ba7b662b93 Fixed port assumption 2026-10-04 17:13:24 +02:00
patben8 e5fb0f0dbb Initial implementation of remote library system 2026-10-04 17:13:24 +02:00
patben8 e8a53eee07 Added analyze dialog 2026-10-04 17:00:33 +02:00
patben8 36a6df4d3b Build analyze backend 2026-10-04 16:33:37 +02:00
patben8 72a52d3291 Reworked analysis menu 2026-10-04 16:18:43 +02:00
patben8 c3571fd054 Implemented key setting into adapters 2026-10-04 16:06:36 +02:00
patben8 b5b3dd04c3 Implemented key analysis system 2026-10-04 15:26:34 +02:00
patben8 4e9472c14a Unified prefs writing 2026-10-03 10:31:32 +02:00
patben8 957525393b Merge pull request #4 from MrPatben8/dev
Implemented STEM generation & OneLibrary editing support
2026-10-01 17:18:05 +02:00
patben8 bdc62f2c1b Added OneLibrary testing fixtures 2026-10-01 17:00:13 +02:00
patben8 7960a5a68f Implemented OneLibrary track addition and removal 2026-10-01 16:43:37 +02:00
patben8 c5280a95f2 Implemented Device Library and OneLibrary sync 2026-10-01 16:00:33 +02:00
patben8 e73fa05e1f Implemented OneLibrary cue and grid edits 2026-10-01 15:48:44 +02:00
patben8 775e94168c Begun implementing OneLibrary editing 2026-10-01 15:07:43 +02:00
patben8 2784879872 Added a clear button for the search bar 2026-10-01 13:32:54 +02:00
patben8 702e5d86a6 Stem tracks are now correctly labeled in the song list 2026-10-01 13:25:13 +02:00
patben8 d7f8768d4c Implemented importing into Rekordbox 2026-10-01 13:12:10 +02:00
patben8 5c193e0ab7 Fixed Stem track importing. Added remove from collection for Rekordbox 2026-10-01 11:42:55 +02:00
patben8 badf12b991 Improved progress status section layout 2026-10-01 10:55:09 +02:00
patben8 ecc0e4c8df Implemented STEM playback 2026-10-01 10:55:09 +02:00
patben8 ae03a93f98 Implemented front end for stem conversion 2026-10-01 10:55:09 +02:00
patben8 c560876c02 Implemented stem conversion API 2026-10-01 10:55:09 +02:00
patben8 e805635383 More stem engine implementation
# Conflicts:
#	backend/konduktor/schemas.py
2026-10-01 10:55:09 +02:00
patben8 27471a82cd Implemented demucs engine 2026-10-01 10:54:27 +02:00
patben8 28b705173e Implemented Discard changes button 2026-10-01 10:54:27 +02:00
patben8 681add852a Implemented foundation of STEM support 2026-10-01 10:54:27 +02:00
patben8 376569ec75 Fixed track collision bug 2026-10-01 10:54:27 +02:00
patben8 b5b0fa91fe Refined Rekordbox timing fix 2026-10-01 10:54:27 +02:00
patben8 34b18893ef Refined traktor timing fix 2026-10-01 10:54:27 +02:00
patben8 2c02019bb2 Implemented traktor utility fixes 2026-10-01 10:54:27 +02:00
patben8 08c53e1150 Added support for coloring Rekordbox hotcues 2026-10-01 10:54:14 +02:00
patben8 9be2c029b2 Loop controls now adjust to active hotcue loop 2026-09-28 23:36:43 +02:00
patben8 a6f96d5943 Improved play buttons in list 2026-09-28 22:15:36 +02:00
patben8 bd35418a89 Track tags are now refreshed correctly when editing from within an export folder 2026-09-28 21:25:37 +02:00
patben8 86b26e3229 Fixed Rekordbox export preview waveform not matching playhead position 2026-09-28 21:15:11 +02:00
patben8 bb9f6e2bd3 Implemented efficient re-exporting 2026-09-28 20:44:14 +02:00
patben8 3a9dc90344 Added warning for Rekordbox Library exports 2026-09-28 18:21:31 +02:00
patben8 4b9716d47a Added support for legacy Rekordbox exports 2026-09-27 23:19:53 +02:00
patben8 0b909a84f4 Implemented feature parity between Rekordbox and OneLibrary exporters 2026-09-27 22:37:14 +02:00
patben8 157c2c0a04 Fixed issues with OneLibrary export 2026-09-27 20:06:09 +02:00
patben8 4878d82671 Fixed OneLibrary export missing data 2026-09-27 16:27:55 +02:00
patben8 c2f5191962 Exports can now be multiplatform 2026-09-27 14:35:27 +02:00
patben8 99d590a051 Implemented automatic path remapping 2026-09-27 13:39:17 +02:00
patben8 eccd352ae5 Added support for comment 2 2026-09-26 22:25:59 +02:00
patben8 90beeef226 Fixed hot cue scaling 2026-09-26 18:13:03 +02:00
patben8 84947bb0bb Fixed sidebar scaling 2026-09-26 17:55:23 +02:00
patben8 08884ca6bd Updated icon 2026-09-26 17:49:16 +02:00
413 changed files with 50987 additions and 2856 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
"""Lay out one release's assets under user-facing names, plus the updater's
latest.json and the release notes' Download section.
Run by build.yml's release job:
python3 .github/scripts/release_assets.py artifacts release \\
--version 0.6.0 --tag v0.6.0-b42 --repo owner/konduktor
Finds, anywhere under `artifacts`, what `tauri build` produced: the macOS
`*.dmg` and `*.app.tar.gz` (+ `.sig`) and the Windows `*-setup.exe` (+ `.sig`).
Copies them into `release` as
Konduktor-<version>-macOS.dmg (download)
Konduktor-<version>-Windows-Setup.exe (download; the Windows updater runs it too)
Konduktor-<version>-app-updater.tar.gz (the macOS updater's package)
latest.json (the updater's manifest)
and writes `download.md`. Renaming is safe: the signatures cover contents,
not names, and latest.json is written from the final names. `latest.json`
itself keeps its name: the app asks for releases/download/<tag>/latest.json.
Fails if anything is missing: a manifest lacking a platform is refused by the
updater as a whole.
"""
import argparse
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote
def find_one(root: Path, suffix: str) -> Path:
found = [p for p in root.rglob(f"*{suffix}") if p.is_file()]
if len(found) != 1:
sys.exit(f"expected exactly one *{suffix} under {root}, found {len(found)}")
return found[0]
def signature(asset: Path) -> str:
sig = asset.with_name(asset.name + ".sig")
if not sig.is_file():
sys.exit(f"missing signature {sig}")
return sig.read_text(encoding="utf-8").strip()
def lay_out(artifacts: Path, out: Path, version: str, tag: str, repo: str) -> None:
def url(name: str) -> str:
return f"https://github.com/{repo}/releases/download/{quote(tag)}/{quote(name)}"
dmg = find_one(artifacts, ".dmg")
app = find_one(artifacts, ".app.tar.gz")
setup = find_one(artifacts, "-setup.exe")
names = {
dmg: f"Konduktor-{version}-macOS.dmg",
setup: f"Konduktor-{version}-Windows-Setup.exe",
app: f"Konduktor-{version}-app-updater.tar.gz",
}
# Tauri's platform keys -> the file that platform's updater installs.
manifest = {
"version": version,
"pub_date": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
"platforms": {
"darwin-aarch64": {"signature": signature(app), "url": url(names[app])},
"windows-x86_64": {"signature": signature(setup), "url": url(names[setup])},
},
}
out.mkdir(parents=True, exist_ok=True)
for src, name in names.items():
shutil.copy2(src, out / name)
(out / "latest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
(out / "download.md").write_text(
"## Download\n"
f"- **macOS** (Apple Silicon): [{names[dmg]}]({url(names[dmg])})\n"
f"- **Windows**: [{names[setup]}]({url(names[setup])})\n",
encoding="utf-8",
)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("artifacts", type=Path)
ap.add_argument("out", type=Path)
ap.add_argument("--version", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--repo", required=True)
args = ap.parse_args()
lay_out(args.artifacts, args.out, args.version, args.tag, args.repo)
for p in sorted(args.out.iterdir()):
print(p.name)
if __name__ == "__main__":
main()
+125 -6
View File
@@ -55,10 +55,11 @@ jobs:
with:
python-version: "3.12"
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
# --- Step 1: freeze the FastAPI backend into a onedir sidecar folder ---
# build_sidecar.* stages it as
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
# which tauri.conf.json's externalBin bundles into the app.
# frontend/src-tauri/binaries/konduktor-sidecar/
# which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) /
# tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`.
- name: Install backend deps
working-directory: backend
run: |
@@ -85,20 +86,31 @@ jobs:
working-directory: frontend
run: npm ci
# createUpdaterArtifacts also signs the in-app update packages
# (Konduktor.app.tar.gz / the NSIS setup.exe) with the updater key, whose
# public half is plugins.updater.pubkey in tauri.conf.json. Losing the
# private key means installed copies can never update themselves again.
- name: Build Tauri app
working-directory: frontend
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: npx tauri build
# Stage the single installer per OS into a flat folder. Uploading one
# directory (not multiple bundle subpaths) keeps the artifact root at
# ./installer, so the zip holds the bare file — no nested dmg/ or nsis/
# folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows
# (the .msi is intentionally left out).
# (the .msi is intentionally left out), plus what the in-app updater
# installs: the .app.tar.gz on macOS (the setup.exe on Windows) and the
# .sig files the release job folds into latest.json.
- name: Stage installer (macOS)
if: runner.os == 'macOS'
run: |
mkdir -p installer
cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz.sig installer/
- name: Stage installer (Windows)
if: runner.os == 'Windows'
@@ -106,6 +118,7 @@ jobs:
run: |
New-Item -ItemType Directory -Force installer | Out-Null
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe.sig installer/
- name: Upload installer
uses: actions/upload-artifact@v4
@@ -114,6 +127,52 @@ jobs:
if-no-files-found: error
path: installer/*
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
# can name the tag that matches the app it is opened from.
server-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # push to ghcr.io
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and image name
id: meta
run: |
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
# GHCR names must be lower-case; the owner may not be.
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
env:
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
with:
context: .
file: server/Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
${{ steps.meta.outputs.image }}:latest
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
# Gather both platforms' installers and publish them as a single new Release.
# Runs once, after both builds succeed, so the two matrix jobs never race to
# create the same tag/release.
@@ -122,6 +181,7 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write # required to create the tag + release
pull-requests: read # to read the merged PR's patch notes
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -136,14 +196,73 @@ jobs:
- name: Download installers from both builds
uses: actions/download-artifact@v4
with:
# Only the installers: the run also holds server-image's Docker build
# record, which is not a release asset (and once failed to download).
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
# The release's files under user-facing names, the in-app updater's
# latest.json (the app reads releases/download/<tag>/latest.json) and the
# notes' Download section. The .sig files are folded into latest.json and
# not uploaded themselves.
- name: Release assets
run: |
python3 .github/scripts/release_assets.py artifacts release \
--version "${{ steps.version.outputs.version }}" \
--tag "v${{ steps.version.outputs.version }}-b${{ github.run_number }}" \
--repo "${{ github.repository }}"
# Release notes from the "Patch notes" section of the PR that merged this
# commit into main (dev → main merges carry many features in one PR, so
# its title alone says little). Written under "What's Changed", the
# heading the app's update dialog reads. No PR (a manual run, a direct
# push) or no such section → GitHub's generated notes, as before. The
# Download section always comes first (the action puts the body above
# generated notes); the dialog reads only "What's Changed".
- name: Patch notes from the merged PR
id: notes
env:
GH_TOKEN: ${{ github.token }}
run: |
gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \
--jq '[.[] | select(.base.ref == "main" and .merged_at != null)][0].body // ""' \
> pr-body.md || : > pr-body.md
python3 - <<'EOF'
import os, re
body = open("pr-body.md", encoding="utf-8").read().replace("\r\n", "\n")
body = re.sub(r"<!--.*?-->", "", body, flags=re.S)
section, level = [], None
for line in body.split("\n"):
m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line)
if level is None:
if m and re.fullmatch(r"patch[\s-]?notes:?", m.group(2), re.I):
level = len(m.group(1))
elif m and len(m.group(1)) <= level:
break
else:
section.append(line)
notes = "\n".join(section).strip()
found = bool(notes)
with open("release-notes.md", "w", encoding="utf-8") as f:
f.write(open("release/download.md", encoding="utf-8").read())
if found:
f.write("\n## What's Changed\n\n" + notes + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as out:
out.write(f"found={'true' if found else 'false'}\n")
print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.")
EOF
- name: Publish release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
target_commitish: ${{ github.sha }}
generate_release_notes: true # auto changelog from commits/PRs since last release
body_path: release-notes.md
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
fail_on_unmatched_files: true
files: artifacts/**/*
files: |
release/*.dmg
release/*.exe
release/*.tar.gz
release/latest.json
+142
View File
@@ -0,0 +1,142 @@
# The stem engine: a frozen torch + Demucs program, built per target and
# published on its OWN release channel (`engine-v<version>`), separate from the
# app's `v<version>-b<N>` releases. The app downloads the one it needs on first
# use (see backend/konduktor/stems/engine_manager.py).
#
# * A tag `engine-v1.2.3` builds, tests and publishes — the tag must match
# `konduktor_engine.VERSION`.
# * A manual run builds and tests only (artifacts, no release).
#
# Releases are `prerelease: true` and `make_latest: false`: GitHub's "latest"
# is what an app would take for itself, and the app's update check reads the
# release list (UpdateDialog.tsx) — an engine release must never look like one.
#
# The weights are NOT in the engine (their licence is ambiguous): CI fetches the
# pinned files from Hugging Face only to run the golden test.
name: Engine
on:
push:
tags: ["engine-v*"]
workflow_dispatch:
concurrency:
group: engine-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- target: macos-arm64
os: macos-latest
torch_index: ""
- target: windows-x64-cpu
os: windows-latest
torch_index: "" # PyPI's Windows torch is the CPU build
- target: windows-x64-cuda
os: windows-latest
# CUDA 13: Turing (RTX 20) through Blackwell (RTX 50); needs an
# NVIDIA driver from r580. Older cards get the CPU engine — the
# manager checks `engine info`'s arch list before offering this.
torch_index: "https://download.pytorch.org/whl/cu130"
runs-on: ${{ matrix.os }}
name: ${{ matrix.target }}
defaults:
run:
shell: bash
working-directory: engine
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Check the tag matches the engine version
if: startsWith(github.ref, 'refs/tags/engine-v')
run: |
want="$(python -c 'import konduktor_engine as e; print(e.VERSION)')"
[ "${GITHUB_REF_NAME#engine-v}" = "$want" ] || { echo "tag ${GITHUB_REF_NAME} != engine $want"; exit 1; }
- name: Install
run: |
python -m pip install --upgrade pip uv
uv venv .venv --python 3.12
PY=.venv/bin/python; [ -f .venv/Scripts/python.exe ] && PY=.venv/Scripts/python.exe
echo "PY=$PY" >> "$GITHUB_ENV"
if [ -n "${{ matrix.torch_index }}" ]; then
uv pip install --python "$PY" "torch==2.14.0" --index-url "${{ matrix.torch_index }}"
fi
uv pip install --python "$PY" -r requirements.txt "pyinstaller==6.21.0"
- name: Weights (for the golden test only)
uses: actions/cache@v4
with:
path: engine/weights
key: htdemucs-ft-d74ac89c3a1e874fc78f152555cf4d8533f06cd4
- run: $PY fetch_weights.py weights
- name: Freeze
run: $PY -m PyInstaller --noconfirm --clean konduktor-engine.spec
- name: Golden test (frozen vs unfrozen, CPU)
run: |
EXE=dist/konduktor-engine/konduktor-engine; [ -f "$EXE.exe" ] && EXE="$EXE.exe"
$PY test_engine.py --weights weights --frozen "$EXE"
- name: Package
run: $PY package.py ${{ matrix.target }} dist out
- name: Paths fit Windows' limit once installed
run: |
# Installed under e.g. %LOCALAPPDATA%\Konduktor\engine\<ver>\<target>\
# (~70 characters on a typical user name): the tree must stay short.
$PY -c "import json,sys; n=json.load(open('out/${{ matrix.target }}.json'))['longest_path']; print('longest', n); sys.exit(n > 180)"
- uses: actions/upload-artifact@v4
with:
name: engine-${{ matrix.target }}
path: engine/out/*
if-no-files-found: error
release:
needs: build
if: startsWith(github.ref, 'refs/tags/engine-v')
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
path: artifacts
merge-multiple: true
- name: Manifest
run: |
python - <<'PY'
import json, glob, os
targets = {}
for f in glob.glob("artifacts/*.json"):
info = json.load(open(f))
targets[info["target"]] = info
version = os.environ["GITHUB_REF_NAME"].removeprefix("engine-v")
weights = json.load(open("engine/weights.json"))
json.dump({"version": version, "targets": targets, "weights": weights},
open("artifacts/engine-manifest.json", "w"), indent=1)
PY
- uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: Konduktor stem engine ${{ github.ref_name }}
prerelease: true
make_latest: false
fail_on_unmatched_files: true
files: |
artifacts/*.tar.gz*
artifacts/engine-manifest.json
body: |
The stem engine Konduktor downloads for **Convert to Stems** — not an app release.
Konduktor fetches the right file for your computer itself; there is nothing to install by hand.
+4
View File
@@ -47,3 +47,7 @@ backend/userprefs.json
# build_sidecar.sh are source and ARE tracked.
backend/build/
backend/dist/
# ---- Stem engine (PyInstaller onedir build) ----
engine/build/
engine/dist/
+107 -30
View File
@@ -1,21 +1,27 @@
# Building Konduktor for Windows
The desktop app can't be cross-compiled — a Windows build must be produced **on
Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
The desktop app can't be cross-compiled. A Windows build must be produced **on
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately
on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)).
This mirrors the macOS build exactly; only the toolchain install and the
sidecar-build command differ.
The recipe is the same as on macOS. Only the toolchain install and the
sidecar-build command differ. CI does exactly this on `windows-latest`
([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build
disagrees with CI, check that workflow first.
## One-time setup
1. **Rust** — install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
1. **Rust**: install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
development with C++" from the Visual Studio Build Tools installer.
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
4. **Node 18+** — <https://nodejs.org>.
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
get the Evergreen runtime from Microsoft (Tauri's installer can also
bootstrap it).
3. **Python 3.11–3.14**: <https://python.org> (tick "Add to PATH"). CI builds
with **3.12**, the safest choice.
4. **Node 20.19+ or 22.12+**: <https://nodejs.org>. Vite 8 refuses older
versions, so Node 18 no longer works. CI uses Node 20.
Then, from the repo root:
@@ -33,49 +39,120 @@ npm install
cd ..
```
## Build
If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is
disabled on this system"), either allow local scripts once with
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with
`powershell -ExecutionPolicy Bypass -File .\dev.ps1`.
## Develop (no build)
```powershell
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
```
Then open <http://localhost:5173> in a browser. `dev.ps1` is the Windows
counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules`
from the setup above. It runs the Python source, not the frozen sidecar, so it
can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file
drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this
still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend
changes need `build_sidecar.ps1` first.
### Tests
`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't
run as-is on Windows. Run a suite directly with the venv's Python instead:
```powershell
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
cd backend
.\.venv\Scripts\Activate.ps1 # if not already active
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
.\.venv\Scripts\python.exe test_save_fidelity.py
```
## Build
One command does both steps and lists the installers it produced:
```powershell
.\build.ps1 # sidecar + app
.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
.\build.ps1 --debug # any other argument is passed on to `tauri build`
```
By hand, that is:
```powershell
# 1) Freeze + stage the backend sidecar
cd backend
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
cd ..
# 2) Build the app
# 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend
npx tauri build
npx tauri build --config src-tauri/tauri.unsigned.conf.json
```
The `--config` override skips the in-app updater packages, which are signed
with the release key that only CI holds (`TAURI_SIGNING_PRIVATE_KEY`). With
that key set in the environment, plain `npx tauri build` makes them too.
`build.ps1` picks the right one by itself.
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
gotcha 4 in [CLAUDE.md](CLAUDE.md).
## Output
Installers land in:
```
frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
frontend\src-tauri\target\release\bundle\nsis\Konduktor_<version>_x64-setup.exe
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
```
Either one installs the app (bundling the sidecar `.exe` alongside it).
`<version>` is the `version` in [frontend/package.json](frontend/package.json),
the app's only version source. Either installer works. Releases ship only the
NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource
folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
`sidecar\konduktor-sidecar.exe`.
## Rebuilding after changes
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
(its `beforeBuildCommand` rebuilds the web app).
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build` as above). Frontend-only changes just need
`.\build.ps1 -SkipSidecar`.
## Not part of this build: the stem engine
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
released on its own channel by
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
and `windows-x64-cuda`). The app downloads it at runtime into a short
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
limit. You don't need it to build or run the app.
## Known Windows caveats
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
(Signing is a future step.)
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
launch shows a "Windows protected your PC" prompt. Click **More info → Run
anyway**.
- **Mixed content is already handled.** The webview is forced to the `http`
custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
Leave that setting as-is.
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
without a visible window; if a console flashes on launch, tell me and we'll add
the `CREATE_NO_WINDOW` spawn flag.
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
- **The sidecar is a console app, but no console appears.** It's frozen with
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
flashes.
- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its
stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS
DLL, which hung the first analysis, so it waits on the parent process instead
(`backend/sidecar.py`). Keep this in mind before touching that watcher.
- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads
AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` /
`.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg.
- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run.
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
+1752 -84
View File
File diff suppressed because it is too large. Load diff
+125 -197
View File
@@ -1,213 +1,141 @@
# Konduktor
<p align="center">
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
</p>
**A fast, modern home for your Traktor collection.**
<h1 align="center">Konduktor</h1>
Konduktor is a lightweight desktop-style app for DJs who run **Native
Instruments Traktor** (Pro 4 / NML v20). It opens your existing
`collection.nml`, gives you a beautiful dark library to explore, and lets you
build playlists and prep tracks — without launching the whole heavyweight
Traktor app just to tidy up your tags or drop a few cue points.
<p align="center">
<b>Prep your tracks and run your DJ libraries in one fast app.</b><br>
Traktor, Rekordbox, or the USB stick in your pocket.
</p>
Your collection stays exactly where it is. Konduktor reads and writes the same
file Traktor uses, so everything you do shows up next time you open Traktor.
<p align="center">
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
</p>
![Konduktor: 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.
---
## Why you'll like it
## One app for every library
- **Instant, searchable library.** Your whole collection loads into a snappy,
virtualized grid. Search, filter by genre / key / BPM / rating, and sort by
any column — all instant, no waiting.
- **Make it yours.** Show only the columns you care about, drag them into the
order you like, and resize them to fit. Your layout is remembered.
- **Edit tags without the ceremony.** Double-click any field to fix a title or
genre on the spot, click the stars to rate a track, or right-click for a full
tag + cover-art editor. Great for quick one-off fixes.
- **Playlists, the easy way.** Create, rename, and delete playlists, then
drag-and-drop to reorder or add tracks.
- **A real prep deck.** Load any track into the deck at the top and:
- play it with a **frequency-colored waveform** (Traktor-style Spectrum look),
scrolling under a fixed playhead with zoom in/out
- scratch it by dragging the waveform
- see and adjust the **beatgrid** and BPM
- set, jump to, and delete **hotcues** (with a color-coded 8-slot bar)
- build **loops** in fixed beat sizes, tied into the hotcue system
- use keyboard shortcuts: **Space** to play/pause, **1–8** to fire hotcues,
**Shift+1–8** to clear them
- **Your data is safe.** Every save makes a timestamped backup first, and only
ever touches the parts you changed — the rest of the file stays byte-for-byte
identical.
<img src="docs/screenshots/platforms.png" align="right" width="420" alt="Choosing a platform: Rekordbox, Traktor, OneLibrary or Remote">
- **Traktor** collections.
- **Rekordbox** libraries.
- **OneLibrary** USB sticks, the format CDJs read. Plug one in to browse it,
preview tracks off it, import them, or edit the stick directly.
- **Remote** libraries: keep your whole library and music on a home server and
open it from any laptop ([set up a server](docs/REMOTE-SERVER.md)).
- **Any folder or drive**: browse loose audio files, preview them, and add
them to your library.
Your library is never converted into a Konduktor database. Saves write back to
the original file and change only what you edited.
<br clear="right">
## A real prep deck
![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.
---
## Getting started
## Get Konduktor
Konduktor runs as two small local servers (a Python backend and a web
frontend). Do the one-time setup, then start them — the same steps work on
macOS, Linux, and Windows.
Download the latest build from
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows.
### 1. Install (once)
> **First launch:** builds aren't notarised yet, so your OS will warn you the
> first time.
> **macOS:** right-click the app, choose **Open**, then **Open** again. If it
> still refuses, run `xattr -cr /Applications/Konduktor.app` once.
> **Windows:** click **More info → Run anyway**.
**Backend** — needs Python 3.11+. Create a virtual environment and install the
dependencies:
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
> `collection.nml` when it quits, which would overwrite your changes.
```bash
cd backend
python3 -m venv .venv # Windows: python -m venv .venv
```
Want to run it from source or build it yourself? See
[docs/BUILDING.md](docs/BUILDING.md).
Activate it, then install:
## License
```bash
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
cd ..
```
**Frontend** — needs Node 18+ (same on every platform):
```bash
cd frontend
npm install
cd ..
```
### 2. Run it (development)
Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`).
**macOS / Linux** — one command starts both:
```bash
./dev.sh
```
**Windows** — start each server in its own terminal:
```powershell
# Terminal 1 — backend
cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000
# Terminal 2 — frontend
cd frontend; npm run dev
```
Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a
server). This is the fastest way to try Konduktor or hack on it — the frontend
hot-reloads as you edit. To package a real double-clickable app instead, see
[Build a standalone app](#build-a-standalone-app-production) below.
### 3. Open your collection
On launch, Konduktor offers to:
- **Automatically** open the collection from your latest installed Traktor,
- reopen the **last collection** you used, or
- **browse** for a `collection.nml` yourself.
That's it — you're in.
---
## Build a standalone app (production)
Prefer a real double-clickable app over running the dev servers? Konduktor
packages into a native desktop app (via **Tauri**) that bundles the Python
backend as a sidecar — no terminal, no servers to start by hand.
### Extra prerequisites
On top of the Python 3.11+ and Node 18+ from above:
- **Rust** — install from <https://rustup.rs> (the app shell is Tauri/Rust).
- **PyInstaller** — into the backend venv:
`pip install -r backend/requirements-build.txt`
- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see
[BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup.
The build is a two-step recipe on both platforms: **freeze the backend into a
sidecar binary**, then **build the app**. The only difference is which sidecar
script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its
own OS (the app can't be cross-compiled).
### macOS / Linux
```bash
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd ..
# 2) Build the app
cd frontend && npx tauri build
```
The installer lands at
`frontend/src-tauri/target/release/bundle/dmg/Konduktor_<version>_aarch64.dmg`
(with the `.app` beside it).
### Windows
```powershell
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd ..
# 2) Build the app
cd frontend; npx tauri build
```
The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
walkthrough and Windows-specific notes.
> **First launch — getting past the OS security prompt.** Builds are
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
> the OS flags them the first time. This is expected — the app isn't damaged.
>
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
> quarantines — clear the quarantine flag once from Terminal:
> ```bash
> xattr -cr /Applications/Konduktor.app
> ```
> - **Windows:** click **More info → Run anyway** past SmartScreen.
>
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
> optimizer and the installer, giving you a runnable app in seconds — handy while
> iterating.
### Rebuilding after changes
Changed **backend** Python? Re-run the sidecar script for your OS
(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`.
Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you.
---
## Saving back to Traktor
Playlist edits, tag changes, and prep tweaks all apply live in the app. When
you're happy, hit **Save to Traktor** to write them to `collection.nml`.
> ⚠️ **Close Traktor before saving.** Traktor rewrites `collection.nml` when it
> quits, so if it's open it will overwrite your changes. Konduktor always writes
> a backup first (into a `backups/` folder next to your collection), but closing
> Traktor first is the safe habit.
Want to experiment risk-free? Point Konduktor at a *copy* of your collection and
play around.
---
## Good to know
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
and speaks Traktor's real file format — no import/export, no separate database.
- Run it in your browser from source, or package it into a native desktop app
(macOS `.dmg` / Windows `.msi`) that bundles the backend — see
[Build a standalone app](#build-a-standalone-app-production). A mobile version
is on the horizon.
- Under the hood: **FastAPI** (Python) backend + **React / TypeScript / Vite**
frontend. Curious about internals or contributing? See
[CLAUDE.md](CLAUDE.md) for the architecture and conventions.
[AGPL-3.0](LICENSE)
+7 -1
View File
@@ -6,6 +6,8 @@ compare rather than a pass/fail. Every open is read-only — nothing is saved.
python bench_grid_detect.py # the local Rekordbox library
python bench_grid_detect.py path/to/collection.nml path/to/master.db
python bench_grid_detect.py --legacy # score the old librosa beat_track
python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM
python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor
The reference is each track's own grid, and only single-marker grids are used:
a multi-marker grid is either a real tempo change (which a constant-tempo
@@ -102,6 +104,9 @@ def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("libraries", nargs="*", type=Path)
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
ap.add_argument("--hold", choices=("bpm", "anchor"),
help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's "
"'Grid' tick — phase is all that is scored) or its anchor ('BPM')")
args = ap.parse_args()
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
@@ -119,7 +124,8 @@ def main() -> int:
for name, audio, r0, rb in refs:
t0 = time.perf_counter()
try:
res = detect(str(audio))
hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
res = detect(str(audio), **hold)
except Exception as ex: # a failure is a data point, not a crash
print(f" FAIL {name[:48]:48} {ex}")
rows.append(None)
+172
View File
@@ -0,0 +1,172 @@
"""Benchmark key detection (`core/key_detect.py`).
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
compare rather than a pass/fail.
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
python bench_key_detect.py ~/Music # files with a key TAG
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
and the number to quote; the model never trained on it (see
`train_key_model.py`). A folder's key tags were written by some other
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
source) count once, by title.
Errors are classed the MIREX way, because they are not equally wrong for a
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
"""
from __future__ import annotations
import argparse
import os
import re
import sys
import warnings
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
warnings.filterwarnings("ignore")
from konduktor.core import key_detect, musical_key # noqa: E402
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
"""How a detected (wheel, mode) relates to the reference."""
(dw, dm), (rw, rm) = det, ref
if (dw, dm) == (rw, rm):
return "exact"
if dw == rw:
return "relative"
if dm == rm and (dw - rw) % 12 in (1, 11):
return "fifth"
if dm != rm:
major, minor = (dw, rw) if dm == "major" else (rw, dw)
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
return "parallel"
return "other"
def parse_any(text: str) -> tuple[int, str] | None:
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
w, m = musical_key.parse(text)
return (w, m) if w else None
def _tag_key(path: Path) -> tuple[str, str] | None:
import mutagen
try:
f = mutagen.File(path)
except Exception:
return None
if not f or not f.tags:
return None
t = f.tags
def has(name: str) -> bool:
try:
return name in t
except ValueError: # a Vorbis comment refuses an MP4-style atom name
return False
key = title = None
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
if has(name):
v = t[name]
v = v.text[0] if hasattr(v, "text") else v[0]
key = v.decode() if isinstance(v, bytes) else str(v)
break
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
if has(name):
v = t[name]
title = str(v.text[0] if hasattr(v, "text") else v[0])
break
return (key, title or path.stem) if key else None
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
seen, out = set(), []
for root in roots:
for dp, dirs, files in os.walk(root):
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
for name in sorted(files):
p = Path(dp) / name
if p.suffix.lower() not in AUDIO or name.startswith("."):
continue
tagged = _tag_key(p)
if not tagged or not (ref := parse_any(tagged[0])):
continue
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
if title not in seen:
seen.add(title)
out.append((p, ref, tagged[1]))
return out
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
out = []
for f in sorted((gs / "annotations/key").glob("*.key")):
audio = gs / "audio" / f"{f.stem}.mp3"
ref = parse_any(f.read_text()) # "C minor"
if audio.exists() and ref:
out.append((audio, ref, f.stem))
return out
def _detect(path: Path):
warnings.filterwarnings("ignore")
try:
r = key_detect.detect_key(str(path))
except Exception as ex: # an undecodable file is reported, not fatal
return None, str(ex)
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
def run(refs, label: str, verbose: bool) -> None:
with ProcessPoolExecutor() as ex:
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
rels, misses = [], []
for (path, ref, title), (det, err) in zip(refs, results):
if det is None:
print(f" could not analyse {title}: {err or 'silent / too short'}")
continue
rel = relation(det[:2], ref)
rels.append(rel)
if rel != "exact":
misses.append((title, ref, det, rel))
n = len(rels)
if not n:
print(f"{label}: nothing to score")
return
c = Counter(rels)
print(f"\n{label}: {n} tracks")
for k in WEIGHT:
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
if verbose:
for title, ref, det, rel in misses:
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
if __name__ == "__main__":
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
a = ap.parse_args()
if not a.folders and not a.giantsteps:
ap.error("give --giantsteps and/or folders")
if a.giantsteps:
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
if a.folders:
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
sys.exit(0)
+156
View File
@@ -0,0 +1,156 @@
"""How Traktor's auto-gain relates to Konduktor's loudness measures.
Traktor stores its gain per ENTRY as `<LOUDNESS ANALYZED_DB>` (its own
measurement) and `PERCEIVED_DB` (the gain the deck applies; equal to
ANALYZED after Traktor's own analysis — kit G1, 2026-10-19). If Traktor
levels toward a fixed reference, `ANALYZED_DB = reference − loudness`, so
`ANALYZED_DB + LUFS` is that reference, and its spread is how far Konduktor's
measure is from Traktor's.
python bench_traktor_gain.py FOLDER [--nml collection.nml]
FOLDER's audio must be in the collection and analysed by Traktor (Gain).
A stem file is measured as its four stems SUMMED, as Traktor measures it.
Result (2026-10-19, 80 MP3 + 40 commercial stem files, Traktor 4.5):
ANALYZED_DB = -9.2 - LUFS (free slope 0.99), sd 0.80 dB, |miss| p50 0.56 /
p90 1.35; RMS fits worse (sd 1.17); the miss follows nothing measured here
(LRA, PLR, true peak, bass weight: |r| < 0.2) — it is Traktor's own measure.
Fits LUFS and RMS (slope and fixed-slope), then asks whether what is left
over follows something about the music (LRA, PLR, bass weight, format, genre).
"""
from __future__ import annotations
import argparse
import html
import re
import sys
import unicodedata
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
DEFAULT_NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
def _key(path: str) -> str:
return unicodedata.normalize("NFC", path).casefold()
def traktor_values(nml: Path) -> dict[str, dict]:
"""Absolute path (normalised) -> Traktor's LOUDNESS + genre, for analysed entries."""
out = {}
text = nml.read_text(encoding="utf-8")
for e in re.findall(r"<ENTRY .*?</ENTRY>", text, re.S):
loc = re.search(r'<LOCATION DIR="([^"]*)" FILE="([^"]*)"', e)
loud = re.search(r'<LOUDNESS PEAK_DB="([-\d.]+)" PERCEIVED_DB="([-\d.]+)" ANALYZED_DB="([-\d.]+)"', e)
if not (loc and loud):
continue
path = html.unescape(loc.group(1)).replace("/:", "/") + html.unescape(loc.group(2))
genre = re.search(r'<INFO [^>]*GENRE="([^"]*)"', e)
out[_key(path)] = {
"peak": float(loud.group(1)),
"perceived": float(loud.group(2)),
"analyzed": float(loud.group(3)),
"genre": html.unescape(genre.group(1)) if genre else "",
}
return out
def _measure(path: str):
"""`loudness.measure_file` — which measures a stem file as its four stems
summed, as Traktor does (found by this bench: against the mix stream the
reference was -6.6, sd 1.18; against the sum -9.3, sd 0.68)."""
from konduktor.core import loudness
try:
return path, loudness.measure_file(path)
except Exception as e: # an undecodable file is reported, not fatal
return path, e
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("folder", type=Path)
ap.add_argument("--nml", type=Path, default=DEFAULT_NML)
args = ap.parse_args()
tk = traktor_values(args.nml)
files = sorted(p for p in args.folder.rglob("*") if p.is_file() and not p.name.startswith("."))
held = [p for p in files if _key(str(p)) in tk]
print(f"{len(files)} files, {len(held)} analysed by Traktor")
for p in files:
if _key(str(p)) not in tk:
print(f" not in the collection / not analysed: {p.name}")
rows = []
with ProcessPoolExecutor(4) as pool: # a stem file holds 4 decoded streams
for path, m in pool.map(_measure, [str(p) for p in held]):
if m is None or isinstance(m, Exception):
print(f" not measured: {Path(path).name}: {m}")
continue
t = tk[_key(path)]
rows.append((Path(path), m, t))
name = np.array([r[0].name for r in rows])
lufs = np.array([r[1].lufs for r in rows])
rms = np.array([r[1].rms for r in rows])
tp = np.array([r[1].true_peak for r in rows])
lra = np.array([r[1].lra for r in rows])
plr = np.array([r[1].plr for r in rows])
an = np.array([r[2]["analyzed"] for r in rows])
pc = np.array([r[2]["perceived"] for r in rows])
pk = np.array([r[2]["peak"] for r in rows])
fmt = np.array([r[0].suffix.lower() for r in rows])
genre = np.array([r[2]["genre"] or "(none)" for r in rows])
n = len(rows)
print(f"\n{n} tracks; LUFS {lufs.min():.1f} .. {lufs.max():.1f}, "
f"PERCEIVED == ANALYZED on {int(np.sum(np.isclose(pc, an)))}")
print("\n== reference = ANALYZED_DB + measure (slope fixed at 1)")
for label, v in (("LUFS", lufs), ("RMS", rms)):
ref = an + v
k, b = np.polyfit(-v, an, 1)
free = an - (k * -v + b)
q = np.percentile(np.abs(ref - np.median(ref)), [50, 90])
print(f" {label:4s}: mean {ref.mean():6.2f} median {np.median(ref):6.2f} sd {ref.std():.2f} "
f"|miss| p50 {q[0]:.2f} p90 {q[1]:.2f} (free slope {k:.3f}, sd {free.std():.2f})")
print("\n== PEAK_DB + true peak (Traktor's peak gain vs our true peak)")
d = pk + tp
print(f" mean {d.mean():+.2f} sd {d.std():.2f} min {d.min():+.2f} max {d.max():+.2f}")
ref = an + lufs
resid = ref - ref.mean()
print("\n== does the LUFS miss follow the music? (correlation with the residual)")
bass = rms - lufs # unweighted vs K-weighted: higher = more low end
for label, v in (("LRA", lra), ("PLR", plr), ("true peak", tp), ("bass weight (RMS-LUFS)", bass), ("LUFS", lufs)):
r = np.corrcoef(v, resid)[0, 1]
k = np.polyfit(v, resid, 1)[0]
print(f" {label:24s} r = {r:+.2f} slope {k:+.3f} dB per unit")
X = np.column_stack([bass, lra, np.ones(n)])
coef, *_ = np.linalg.lstsq(X, resid, rcond=None)
print(f" bass + LRA together: sd {resid.std():.2f} -> {(resid - X @ coef).std():.2f}")
print("\n== by format")
for f in sorted(set(fmt)):
s = fmt == f
print(f" {f:5s} n={s.sum():3d} reference mean {ref[s].mean():6.2f} sd {ref[s].std():.2f}")
print("\n== by genre (n >= 3)")
for g in sorted(set(genre), key=lambda g: -np.sum(genre == g)):
s = genre == g
if s.sum() >= 3:
print(f" {g[:24]:24s} n={s.sum():3d} reference mean {ref[s].mean():6.2f} sd {ref[s].std():.2f}")
print("\n== largest misses (LUFS)")
for i in np.argsort(-np.abs(resid))[:8]:
print(f" {resid[i]:+5.2f} LUFS {lufs[i]:6.2f} LRA {lra[i]:4.1f} bass {bass[i]:+5.2f} {genre[i][:14]:14s} {name[i][:50]}")
if __name__ == "__main__":
main()
+17 -10
View File
@@ -1,6 +1,7 @@
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
# tauri.conf.json bundles as a resource folder (`sidecar\` in the app).
# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\
#
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
# cd backend
@@ -15,13 +16,19 @@ Set-Location $Root
$Py = Join-Path $Root ".venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { $Py = "python" }
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
# native command's stderr into an error record, which "Stop" makes fatal on the
# first INFO line — so relax it for this call and judge by the exit code.
$ErrorActionPreference = "Continue"
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
$ErrorActionPreference = "Stop"
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
Write-Host "Built: $Root\dist\konduktor-sidecar\"
# Stage for Tauri: name with the host target triple + .exe so the shell plugin
# resolves it. (rustc must be on PATH.)
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
$Staged = Join-Path $Dest "konduktor-sidecar"
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
Write-Host "Staged: $Staged\"
+19 -23
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Build the frozen backend sidecar (single-file binary) with PyInstaller and
# stage it for Tauri as binaries/konduktor-sidecar-<target-triple>.
# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/…
# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage
# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which
# tauri.conf.json bundles as a resource folder (`sidecar/` in the app).
# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/
#
# One-time: pip install -r requirements-build.txt (into the backend venv).
set -euo pipefail
@@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
PY="${PY:-.venv/bin/python}"
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
echo "Built: $ROOT/dist/konduktor-sidecar"
echo "Built: $ROOT/dist/konduktor-sidecar/"
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
# fails with "different Team IDs" and the sidecar dies on launch (which makes
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this binary without re-signing it.
# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc
# signs the executable AND its collected libraries (Python, the .so/.dylib
# files) with a matching identity. Re-signing only some of them desyncs the
# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on
# launch (the app then shows "Konduktor couldn't start"). The app bundle is
# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this folder as a resource without re-signing it.
# Stage for Tauri: the sidecar must be named with the host target triple so the
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
if command -v rustc >/dev/null 2>&1; then
TRIPLE="$(rustc -vV | sed -n 's/host: //p')"
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE"
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
else
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
fi
# Stage for Tauri. Replace the whole folder so no file from an older build
# survives; `cp -R` keeps PyInstaller's symlinks as symlinks.
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
rm -rf "$DEST/konduktor-sidecar"
cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
echo "Staged: $DEST/konduktor-sidecar/"
+321
View File
@@ -0,0 +1,321 @@
"""Kit G1 — what Traktor 4.5 does with gain (dev only, like dev_stems.py).
Answers, by measuring in Traktor itself (see
.claude/discussions/discuss-gain-normalization-2026-10-19.md, "Kit G1"):
1. Does a LEVEL change to a file make Traktor re-analyse it (LOUDNESS,
BPM/grid, AUDIO_ID)? MP3 by lossless frame gain (same size; + an APE undo
tag; + the mtime put back), FLAC re-written exactly, and a control whose
mtime alone changes.
2. Does Traktor KEEP a LOUDNESS Konduktor writes — on an entry it analysed
(AUDIO_ID kept), and on one Konduktor added (AUDIO_ID empty)?
3. Which LOUDNESS attribute drives the deck's auto-gain (the three are set
to values that cannot be confused)?
python dev_gain_kit.py prepare # build the kit folder
# -> in Traktor: import the folder, analyse, quit
python dev_gain_kit.py apply # change the files + write LOUDNESS
# -> in Traktor: load each G1 track, note the gain knob, quit
python dev_gain_kit.py report # what Traktor changed
Traktor must be closed for `apply`. The collection is saved through
TraktorStore (backup-first, byte-exact render).
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
import numpy as np
NML = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
KITS = Path.home() / "Music/Konduktor Stem Test"
KIT = KITS / "Kit G1"
STEPS = -2 # global_gain steps of 2^(1/4): -2 = -3.01 dB
# name -> (source, what happens at `apply`)
FILES = {
"G1-A0 control touch.mp3": (KITS / "Kit 2/K2 01 All I Need.mp3", "mtime only"),
"G1-A1 mp3 framegain.mp3": (KITS / "Kit 2/K1 01 Abyss of Love - Franky Rizardo Remix.mp3", "frame gain"),
"G1-A2 mp3 framegain ape.mp3": (KITS / "Kit 2/K4 Ragga Bomb with Ragga Twins.mp3", "frame gain + APE undo tag"),
"G1-A3 flac exact.flac": (KITS / "Kit 4/K4-3 flac.flac", "exact gain, re-written"),
"G1-A4 mp3 framegain same mtime.mp3": (KITS / "Kit 4/K4-5 mp3 cbr noxing.mp3", "frame gain, mtime restored"),
"G1-B1 loudness written.mp3": (KITS / "Kit 2/K3 01 Motorola.mp3", "LOUDNESS written, AUDIO_ID kept"),
}
# Added by Konduktor at `apply` (so Traktor never analysed it): AUDIO_ID empty.
B2 = ("G1-B2 konduktor added.mp3", KITS / "Kit 4/K4-4 mp3 cbr xing.mp3")
# Values no real analysis would give, so the deck's knob says which one it read.
B1_LOUDNESS = (2.5, -6.0, 6.0) # PEAK_DB, PERCEIVED_DB, ANALYZED_DB
B2_LOUDNESS = (2.5, -4.0, 4.0)
# ── MP3 frame gain (mp3gain's edit) ──────────────────────────────────────────
_BITRATE = {
True: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
False: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
}
_RATE = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]}
def _get(buf: bytearray, bit: int, n: int) -> int:
v = 0
for i in range(n):
v = (v << 1) | ((buf[(bit + i) >> 3] >> (7 - ((bit + i) & 7))) & 1)
return v
def _put(buf: bytearray, bit: int, n: int, v: int) -> None:
for i in range(n):
b = (v >> (n - 1 - i)) & 1
byte, shift = (bit + i) >> 3, 7 - ((bit + i) & 7)
buf[byte] = (buf[byte] & ~(1 << shift) & 0xFF) | (b << shift)
def _header(buf: bytearray, pos: int):
if pos + 4 > len(buf) or buf[pos] != 0xFF or (buf[pos + 1] & 0xE0) != 0xE0:
return None
ver, layer = (buf[pos + 1] >> 3) & 3, (buf[pos + 1] >> 1) & 3
br_i, sr_i = buf[pos + 2] >> 4, (buf[pos + 2] >> 2) & 3
if ver == 1 or layer != 1 or br_i in (0, 15) or sr_i == 3:
return None
mpeg1 = ver == 3
br, sr = _BITRATE[mpeg1][br_i], _RATE[ver][sr_i]
pad = (buf[pos + 2] >> 1) & 1
length = (144000 if mpeg1 else 72000) * br // sr + pad
return {
"mpeg1": mpeg1,
"crc": (buf[pos + 1] & 1) == 0,
"nch": 1 if (buf[pos + 3] >> 6) == 3 else 2,
"len": length,
}
def _gain_bits(h: dict) -> list[int]:
"""Bit offsets (from the side info's start) of every granule's global_gain."""
nch = h["nch"]
if h["mpeg1"]:
start, block, granules = 9 + (5 if nch == 1 else 3) + 4 * nch, 59, 2
else:
start, block, granules = 8 + (1 if nch == 1 else 2), 63, 1
return [start + (g * nch + c) * block + 21 for g in range(granules) for c in range(nch)]
def mp3_frame_gain(path: Path, steps: int) -> int:
"""Add `steps` to every audio granule's global_gain in place; returns frames edited."""
buf = bytearray(path.read_bytes())
pos = 0
if buf[:3] == b"ID3":
size = (buf[6] << 21) | (buf[7] << 14) | (buf[8] << 7) | buf[9]
pos = 10 + size + (10 if buf[5] & 0x10 else 0)
frames = 0
first = True
while (h := _header(buf, pos)) is not None:
side = pos + 4 + (2 if h["crc"] else 0)
if h["crc"]:
raise SystemExit(f"{path.name}: CRC-protected frames are not handled by the kit")
side_len = (17 if h["nch"] == 1 else 32) if h["mpeg1"] else (9 if h["nch"] == 1 else 17)
tag = bytes(buf[side + side_len : side + side_len + 4])
if first and (tag in (b"Xing", b"Info") or bytes(buf[pos + 36 : pos + 40]) == b"VBRI"):
pass # the header frame is not audio (Traktor decodes it anyway — leave it as it is)
else:
for off in _gain_bits(h):
g = _get(buf, side * 8 + off, 8) + steps
if not 0 <= g <= 255:
raise SystemExit(f"{path.name}: global_gain would leave 0..255")
_put(buf, side * 8 + off, 8, g)
frames += 1
first = False
pos += h["len"]
rest = bytes(buf[pos : pos + 8])
if pos < len(buf) - 128 and not rest.startswith((b"TAG", b"APETAGEX", b"LYRICS")):
raise SystemExit(f"{path.name}: lost frame sync at {pos} of {len(buf)}")
path.write_bytes(buf)
return frames
def _decode(path: Path) -> np.ndarray:
from konduktor.core import pyav
out = []
with pyav.open_input(path) as c:
for frame in c.decode(audio=0):
a = frame.to_ndarray()
out.append(a if a.ndim == 2 and a.shape[0] <= 2 else a.reshape(1, -1))
return np.concatenate(out, axis=1).astype(np.float64)
def _check_gain(before: np.ndarray, after: Path, db: float, what: str) -> None:
b = before
a = _decode(after)
n = min(b.shape[1], a.shape[1])
want = 10 ** (db / 20)
err = np.max(np.abs(a[:, :n] - b[:, :n] * want)) / max(np.max(np.abs(b)), 1e-9)
print(f" {what}: decoded = original x {want:.4f} ({db:+.2f} dB), max error {err:.1e} of peak")
if err > 1e-3:
raise SystemExit(" gain check FAILED")
def flac_exact_gain(path: Path, db: float) -> None:
import soundfile as sf
from mutagen.flac import FLAC
info = sf.info(str(path))
data, rate = sf.read(str(path), dtype="float64", always_2d=True)
old = FLAC(str(path))
tags, pictures = list(old.tags.items()) if old.tags else [], list(old.pictures)
tmp = path.with_suffix(".tmp.flac")
sf.write(str(tmp), data * 10 ** (db / 20), rate, subtype=info.subtype, format="FLAC")
new = FLAC(str(tmp))
for k, v in tags:
new[k] = v
for p in pictures:
new.add_picture(p)
new.save()
tmp.replace(path)
# ── steps ────────────────────────────────────────────────────────────────────
def _traktor_running() -> bool:
# The executable is "Traktor Pro 4" (an exact "Traktor" never matches).
return subprocess.run(["pgrep", "-f", r"Traktor Pro 4\.app/Contents/MacOS/"], capture_output=True).returncode == 0
def prepare() -> None:
KIT.mkdir(parents=True, exist_ok=True)
for name, (src, what) in FILES.items():
shutil.copy2(src, KIT / name)
print(f" {name:38s} <- {src.name} [{what} at apply]")
print(f"\nKit at {KIT}\n"
"Next, in Traktor 4.5:\n"
" 1. Preferences > Mixer: note the Autogain setting, and turn ON\n"
" 'Set Autogain when Loading Track' (or the nearest wording).\n"
" 2. Import the Kit G1 folder; select its 6 tracks; Analyze (Async) > All.\n"
" 3. Quit Traktor (it writes the collection on exit).\n"
"Then: python dev_gain_kit.py apply")
def _entries(nml_text: str) -> dict[str, str]:
out = {}
for e in re.findall(r"<ENTRY .*?</ENTRY>", nml_text, re.S):
m = re.search(r'<LOCATION [^>]*FILE="(G1-[^"]+)"', e)
if m:
out[m.group(1)] = e
return out
def apply() -> None:
if _traktor_running():
raise SystemExit("Quit Traktor first.")
text = NML.read_text(encoding="utf-8")
have = _entries(text)
missing = [n for n in FILES if n not in have]
if missing:
raise SystemExit(f"Not in the collection yet (import + analyse in Traktor): {missing}")
unanalysed = [n for n in FILES if "<LOUDNESS" not in have[n] or 'AUDIO_ID=""' in have[n] or "AUDIO_ID" not in have[n]]
if unanalysed:
raise SystemExit(f"Not analysed by Traktor yet: {unanalysed}")
shutil.copy2(NML, KIT / "1-after-traktor-analysed.nml")
print("Changing files:")
for name, (_, what) in FILES.items():
p = KIT / name
st = p.stat()
if what == "mtime only":
os.utime(p)
print(f" {name}: mtime touched")
elif what.startswith("frame gain"):
before = _decode(p)
n = mp3_frame_gain(p, STEPS)
print(f" {name}: {n} frames, {STEPS:+d} steps")
_check_gain(before, p, STEPS * 20 * np.log10(2 ** 0.25), "check")
if "APE" in what:
from mutagen.apev2 import APEv2
tag = APEv2()
tag["MP3GAIN_UNDO"] = f"{-STEPS:+04d},{-STEPS:+04d},N"
tag.save(str(p))
print(" + APEv2 MP3GAIN_UNDO tag")
if "restored" in what:
os.utime(p, ns=(st.st_atime_ns, st.st_mtime_ns))
print(f" mtime restored, size {'same' if p.stat().st_size == st.st_size else 'CHANGED'}")
elif what.startswith("exact"):
before = _decode(p)
db = STEPS * 20 * np.log10(2 ** 0.25)
flac_exact_gain(p, db)
print(f" {name}: {db:+.2f} dB, size {st.st_size} -> {p.stat().st_size}")
_check_gain(before, p, db, "check")
from konduktor.adapters.traktor.store import TraktorStore
from konduktor.core import folder
from traktor_nml_utils.models.collection import Loudnesstype
shutil.copy2(B2[1], KIT / B2[0])
store = TraktorStore(NML)
store.add_entry(folder.read_track(KIT / B2[0]), KIT / B2[0])
def set_loudness(file: str, vals) -> None:
for e in store._nml.collection.entry:
if e.location is not None and e.location.file == file:
e.loudness = Loudnesstype(peak_db=vals[0], perceived_db=vals[1], analyzed_db=vals[2])
return
raise SystemExit(f"entry {file} not found")
set_loudness("G1-B1 loudness written.mp3", B1_LOUDNESS)
set_loudness(B2[0], B2_LOUDNESS)
store.save()
shutil.copy2(NML, KIT / "2-after-konduktor-apply.nml")
print(f"\nLOUDNESS written: B1 {B1_LOUDNESS}, B2 (added, AUDIO_ID empty) {B2_LOUDNESS}\n"
"Next, in Traktor 4.5 (do NOT run Analyze):\n"
" 1. Load EACH G1 track into deck A in turn (B1 and B2 first).\n"
" For each, note the GAIN knob's value (hover / the readout) and\n"
" whether Traktor shows it analysing.\n"
" 2. Quit Traktor.\n"
"Then: python dev_gain_kit.py report")
_FIELDS = {
"AUDIO_ID": r'AUDIO_ID="([^"]*)"',
"LOUDNESS": r"<LOUDNESS ([^>]*)>",
"TEMPO": r'<TEMPO BPM="([^"]*)"',
"GRID": r'<CUE_V2 [^>]*TYPE="4"[^>]*START="([^"]*)"',
"MODIFIED": r'MODIFIED_DATE="([^"]*)" MODIFIED_TIME="([^"]*)"',
"FILESIZE": r'FILESIZE="([^"]*)"',
"LAST_PLAYED": r'LAST_PLAYED="([^"]*)"',
}
def report() -> None:
if _traktor_running():
raise SystemExit("Quit Traktor first (it writes the collection on exit).")
shutil.copy2(NML, KIT / "3-after-traktor-load.nml")
stages = [
("analysed", _entries((KIT / "1-after-traktor-analysed.nml").read_text(encoding="utf-8"))),
("applied", _entries((KIT / "2-after-konduktor-apply.nml").read_text(encoding="utf-8"))),
("loaded", _entries(NML.read_text(encoding="utf-8"))),
]
for name in [*FILES, B2[0]]:
print(f"\n== {name} [{FILES.get(name, (None, 'added by Konduktor'))[1]}]")
for field, rx in _FIELDS.items():
vals = []
for _, ents in stages:
e = ents.get(name)
m = re.search(rx, e) if e else None
vals.append(" ".join(m.groups()) if m else ("-" if e else "(no entry)"))
flag = "" if vals[1] == vals[2] else " <-- CHANGED by Traktor"
print(f" {field:11s} analysed: {vals[0][:60]}\n"
f" {'':11s} applied: {vals[1][:60]}\n"
f" {'':11s} loaded: {vals[2][:60]}{flag}")
if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).resolve().parent))
{"prepare": prepare, "apply": apply, "report": report}[sys.argv[1] if len(sys.argv) > 1 else "prepare"]()
+336
View File
@@ -0,0 +1,336 @@
"""Kit G2 — what rekordbox 7 does with auto gain, and whether a stick carries it
(dev only; see .claude/discussions/discuss-gain-normalization-2026-10-19.md).
Already measured without rekordbox open (2026-10-19, 19 local tracks):
`djmdMixerParam.Gain{High,Low}` are the halves of a big-endian float32, LINEAR,
= 10^((-10 - LUFS)/20) to 0.13 dB — rekordbox levels integrated BS.1770
loudness to -10 LUFS. `Peak{High,Low}` = the linear SAMPLE peak.
Every SONG in the local library was added by Konduktor (2026-10-01), whose
rekordbox add writes no MixerParam row — so the fit above is rekordbox's
sample pack only. This kit asks rekordbox itself:
A. A track with NO row: does loading it create one (R2, R3)?
B. After rekordbox analyses the songs: is the gain -10 - LUFS on music too?
C. Is a gain Konduktor writes KEPT (R1 at -20 dB)?
D. Does a USB export carry the gain anywhere a CDJ reads (OneLibrary
exportLibrary.db, export.pdb, the ANLZ files)? R1-R3 are exported twice
with different gains and the two exports diffed.
python dev_gain_kit_g2.py prepare # records state; writes nothing
# A -> rekordbox: Auto Gain on, load R2 + R3, quit
python dev_gain_kit_g2.py status
# B -> rekordbox: Analyze the 7 songs, quit
python dev_gain_kit_g2.py status
python dev_gain_kit_g2.py write # R1 -> -20 dB
# C -> rekordbox: load R1, export R1-R3 to a stick, quit
python dev_gain_kit_g2.py check1 /Volumes/STICK
python dev_gain_kit_g2.py flip
# D -> rekordbox: remove R1-R3 from the stick, export again, quit
python dev_gain_kit_g2.py check2 /Volumes/STICK
python dev_gain_kit_g2.py restore # R1-R3 back to rekordbox's own gains
rekordbox must be closed whenever this script runs. The local master.db is written directly (it is disposable — but `prepare`
records every row it touches and `restore` puts them back).
"""
from __future__ import annotations
import json
import math
import shutil
import sqlite3
import struct
import sys
import uuid
from datetime import datetime
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
KIT = Path.home() / "Music/Konduktor Stem Test/Kit G2"
STATE = KIT / "state.json"
FLIP = {"R1": -8.0, "R2": +6.0, "R3": -14.0} # export 2's gains
def _halves(x: float) -> tuple[int, int]:
bits = struct.unpack(">I", struct.pack(">f", x))[0]
return bits >> 16, bits & 0xFFFF
def _value(hi, lo) -> float | None:
if hi is None or lo is None:
return None
return struct.unpack(">f", struct.pack(">I", ((hi & 0xFFFF) << 16) | (lo & 0xFFFF)))[0]
def _db_str(lin: float | None) -> str:
return "—" if lin is None else ("-inf" if lin <= 0 else f"{20 * math.log10(lin):+.2f} dB")
def _db():
from pyrekordbox import masterdb
from konduktor.adapters.rekordbox.store import rekordbox_probe_suppressed
from pyrekordbox.masterdb import database as rb_database
if rb_database.get_rekordbox_pid():
raise SystemExit("Quit rekordbox first.")
return masterdb.MasterDatabase(), rekordbox_probe_suppressed
def _row(db, content_id):
from pyrekordbox.masterdb import models
return db.query(models.DjmdMixerParam).filter_by(ContentID=content_id).one_or_none()
def _snapshot_row(r) -> dict | None:
if r is None:
return None
return {c: getattr(r, c) for c in ("ID", "ContentID", "GainHigh", "GainLow", "PeakHigh", "PeakLow", "UUID")} | {
"created_at": str(r.created_at), "updated_at": str(r.updated_at)}
def _set_gain(db, content_id: str, db_gain: float) -> None:
r = _row(db, content_id)
r.GainHigh, r.GainLow = _halves(10 ** (db_gain / 20))
SONGS = {"R1": "Faith in You - AC Slater Remix", "R2": "Low Frequency", "R3": "Never Let You Go"} # unlocked: a locked track cannot be analysed
def prepare() -> None:
"""Record the kit's songs, their LUFS and their MixerParam rows. Writes nothing:
every song in this library was added by Konduktor and has NO MixerParam row."""
from konduktor.core import loudness
db, _ = _db()
state = {"tracks": {}, "songs": {}, "created": datetime.now().isoformat()}
KIT.mkdir(parents=True, exist_ok=True)
for c in db.get_content().all():
if (c.Length or 0) < 120 or not Path(c.FolderPath or "").is_file():
continue
m = loudness.measure_file(c.FolderPath)
entry = {"content_id": c.ID, "title": c.Title, "artist": c.Artist.Name if c.Artist else "",
"path": c.FolderPath, "lufs": m.lufs if m else None, "true_peak": m.true_peak if m else None,
"original": _snapshot_row(_row(db, c.ID))}
state["songs"][c.Title] = entry
for name, title in SONGS.items():
if title == c.Title:
state["tracks"][name] = entry
STATE.write_text(json.dumps(state, indent=2))
status()
print("\nNext, in rekordbox 7 (step A — a track with NO MixerParam row):\n"
" 1. Preferences > Controller > Mixer tab > Auto Gain: Enable.\n"
f" 2. PERFORMANCE mode: load '{SONGS['R2']}', open the deck's GRID EDIT panel and\n"
f" note its Auto Gain value (or that it is blank); then '{SONGS['R3']}'.\n"
" (No Performance mode: EXPORT mode, DUAL PLAYER layout, the AUTO GAIN knob.)\n"
" Do NOT run Analyze and do NOT turn the knob (a manual change is saved).\n"
" 3. Quit rekordbox.\n"
"Then: python dev_gain_kit_g2.py status")
def status() -> None:
"""Every song's MixerParam row now, against -10 - LUFS."""
db, _ = _db()
state = json.loads(STATE.read_text())
print("== songs: MixerParam now (expected if rekordbox levels to -10 LUFS)")
for title, t in state["songs"].items():
r = _row(db, t["content_id"])
want = f"{-10 - t['lufs']:+.2f} dB" if t["lufs"] is not None else "?"
if r is None:
print(f" {title[:34]:34s} no row (expect {want})")
else:
g, pk = _value(r.GainHigh, r.GainLow), _value(r.PeakHigh, r.PeakLow)
print(f" {title[:34]:34s} gain {_db_str(g):>10s} peak {_db_str(pk):>10s} (expect {want}; "
f"true peak {t['true_peak']:+.2f}; updated {r.updated_at})")
def write() -> None:
"""Step C: R1's gain set to -20 dB (it must have a row: run after rekordbox analysed it)."""
db, suppressed = _db()
state = json.loads(STATE.read_text())
for name, t in state["tracks"].items():
t["before_write"] = _snapshot_row(_row(db, t["content_id"]))
if state["tracks"]["R1"]["before_write"] is None:
raise SystemExit("R1 has no MixerParam row yet — analyse it in rekordbox first.")
_set_gain(db, state["tracks"]["R1"]["content_id"], -20.0)
with suppressed():
db.commit(autoinc=True)
STATE.write_text(json.dumps(state, indent=2))
print(f"R1 '{SONGS['R1']}' gain written -20.0 dB.\n"
"Next, in rekordbox 7 (step C):\n"
" 1. Load R1 and read GRID EDIT > Auto Gain (or the DUAL PLAYER AUTO GAIN\n"
" knob): -20 dB = kept, ~+4.5 dB = recomputed. Do NOT run Analyze.\n"
f" 2. Export R1, R2, R3 ('{SONGS['R1']}', '{SONGS['R2']}', '{SONGS['R3']}') to a USB stick.\n"
" 3. Quit rekordbox.\n"
"Then: python dev_gain_kit_g2.py check1 /Volumes/<STICK>")
def _rows_now(db, state) -> dict:
return {name: _snapshot_row(_row(db, t["content_id"])) for name, t in state["tracks"].items()}
def _snapshot_stick(stick: Path, dest: Path) -> None:
rb = stick / "PIONEER/rekordbox"
if not rb.is_dir():
raise SystemExit(f"No PIONEER/rekordbox on {stick}")
if dest.exists():
shutil.rmtree(dest)
shutil.copytree(rb, dest / "rekordbox", ignore=shutil.ignore_patterns("*-shm", "*-wal"))
shutil.copytree(stick / "PIONEER/USBANLZ", dest / "USBANLZ")
def _report_rows(label: str, rows: dict, state: dict) -> None:
print(f"\n== master.db MixerParam {label}")
for name, r in rows.items():
t = state["tracks"][name]
orig = t.get("before_write") or t["original"] or {}
if r is None:
print(f" {name}: no row")
continue
g, pk = _value(r["GainHigh"], r["GainLow"]), _value(r["PeakHigh"], r["PeakLow"])
same_id = "same row" if r["ID"] == orig.get("ID") else "NEW row"
print(f" {name}: gain {_db_str(g)}, peak {_db_str(pk)} ({same_id}, updated {r['updated_at']})")
def check1(stick: str) -> None:
db, _ = _db()
state = json.loads(STATE.read_text())
rows = _rows_now(db, state)
state["after_load"] = rows
STATE.write_text(json.dumps(state, indent=2))
_report_rows("after rekordbox loaded + exported (R1 written -20 dB)", rows, state)
_snapshot_stick(Path(stick), KIT / "stick-1")
print(f"\nStick snapshot: {KIT / 'stick-1'}\nThen: python dev_gain_kit_g2.py flip")
def flip() -> None:
db, suppressed = _db()
state = json.loads(STATE.read_text())
for name, g in FLIP.items():
_set_gain(db, state["tracks"][name]["content_id"], g)
with suppressed():
db.commit(autoinc=True)
print("Gains for export 2: " + ", ".join(f"{n} {g:+.1f} dB" for n, g in FLIP.items()) +
"\n"
"Next, in rekordbox 7:\n"
" 1. In the stick's browser, remove R1, R2, R3 from the device.\n"
" 2. Export R1, R2, R3 to the stick again.\n"
" 3. Quit rekordbox.\n"
"Then: python dev_gain_kit_g2.py check2 /Volumes/<STICK>")
def _onelibrary_rows(snap: Path, titles: list[str]) -> dict:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
db = snap / "rekordbox/exportLibrary.db"
if not db.is_file():
return {}
con = sqlcipher.connect(str(db))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
cols = [r[1] for r in con.execute("PRAGMA table_info(content)")]
out = {}
for row in con.execute("SELECT * FROM content"):
d = dict(zip(cols, row))
if d.get("title") in titles:
out[d["title"]] = d
con.close()
return out
def _pdb_rows(snap: Path, titles: list[str]) -> dict:
from konduktor.adapters.rekordbox import pdb
f = snap / "rekordbox/export.pdb"
if not f.is_file():
return {}
buf = f.read_bytes()
out = {}
for row in pdb.table_rows(buf, pdb.TRACKS):
fields, strings = pdb.track_fields(row)
if strings.get("title") in titles:
out[strings["title"]] = (row[: pdb.track_extent(row)], fields, strings)
return out
def _anlz(snap: Path, rel: str | None) -> dict:
from konduktor.adapters.rekordbox import anlz_file
out = {}
if not rel:
return out
base = snap / "USBANLZ" / Path(rel.lstrip("/")).relative_to("PIONEER/USBANLZ")
for ext in (".DAT", ".EXT", ".2EX"):
p = base.with_suffix(ext)
if p.is_file():
tags, seen = {}, {}
for t in anlz_file.parse_file(p).tags: # PCOB / PCO2 come twice (hot, memory)
seen[t.type] = seen.get(t.type, 0) + 1
tags[f"{t.type}#{seen[t.type]}"] = t.data
out[ext] = tags
return out
def check2(stick: str) -> None:
db, _ = _db()
state = json.loads(STATE.read_text())
rows = _rows_now(db, state)
_report_rows("before export 2 (flip), as rekordbox left it", rows, state)
_snapshot_stick(Path(stick), KIT / "stick-2")
titles = [t["title"] for t in state["tracks"].values()]
s1, s2 = KIT / "stick-1", KIT / "stick-2"
print("\n== OneLibrary content rows: columns that differ between export 1 and 2")
a, b = _onelibrary_rows(s1, titles), _onelibrary_rows(s2, titles)
ids = {"content_id", "analysisDataFilePath", "image_id", "path", "dateAdded"}
for title in titles:
if title not in a or title not in b:
print(f" {title}: missing in an export ({title in a}, {title in b})")
continue
diff = {k: (a[title][k], b[title][k]) for k in a[title] if a[title][k] != b[title].get(k)}
print(f" {title[:40]}: {diff or 'identical'}")
print("\n== export.pdb track rows: fields / bytes that differ")
a, b = _pdb_rows(s1, titles), _pdb_rows(s2, titles)
for title in titles:
if title not in a or title not in b:
print(f" {title}: missing in a pdb ({title in a}, {title in b})")
continue
fa, fb = a[title][1], b[title][1]
diff = {k: (fa[k], fb[k]) for k in fa if fa[k] != fb.get(k)}
sdiff = {k: (a[title][2][k], b[title][2][k]) for k in a[title][2] if a[title][2][k] != b[title][2].get(k)}
print(f" {title[:40]}: fields {diff or 'identical'}; strings {sdiff or 'identical'}")
print("\n== ANLZ tags that differ")
oa, ob = _onelibrary_rows(s1, titles), _onelibrary_rows(s2, titles)
for title in titles:
ta = _anlz(s1, (oa.get(title) or {}).get("analysisDataFilePath"))
tb = _anlz(s2, (ob.get(title) or {}).get("analysisDataFilePath"))
changed = [f"{ext}:{k}" for ext in ta for k in ta[ext] if ta[ext][k] != tb.get(ext, {}).get(k)]
missing = [f"{ext}:{k}" for ext in tb for k in tb[ext] if k not in ta.get(ext, {})]
print(f" {title[:40]}: changed {changed or 'none'}; new {missing or 'none'}")
print("\nThen: python dev_gain_kit_g2.py restore")
def restore() -> None:
"""R1 and R3 back to the gain rekordbox computed (their rows before `write`)."""
db, suppressed = _db()
state = json.loads(STATE.read_text())
for name, t in state["tracks"].items():
o, r = t.get("before_write"), _row(db, t["content_id"])
if o and r is not None:
r.GainHigh, r.GainLow, r.PeakHigh, r.PeakLow = o["GainHigh"], o["GainLow"], o["PeakHigh"], o["PeakLow"]
with suppressed():
db.commit(autoinc=True)
print("R1-R3 gains restored to rekordbox's own values.")
if __name__ == "__main__":
cmd = sys.argv[1] if len(sys.argv) > 1 else "prepare"
fn = {"prepare": prepare, "status": status, "write": write, "check1": check1, "flip": flip,
"check2": check2, "restore": restore}[cmd]
fn(*sys.argv[2:])
+129
View File
@@ -0,0 +1,129 @@
"""DEV ONLY — convert audio files to stem files with an UNFROZEN engine.
Not shipped, not in run_tests.sh. It exists so real stem files can be made (and
checked in Traktor) before the frozen engine and its download exist: the stem
writer (`core/stem_file.py`) runs here in the backend venv, and the separation
runs in any Python that has torch + demucs, through the engine's own one-shot
CLI — the same raw-f32 exchange the batch will use.
python dev_stems.py --engine-python ~/demucs-venv/bin/python \\
--weights ~/.cache/huggingface/hub/models--adefossez--HTDemucs-ft/snapshots/<rev> \\
[--out-dir DIR] [--device auto] FILE...
Each FILE becomes `<name>.stem.m4a` beside it (or in --out-dir); an existing
target is skipped, never overwritten.
With `--collection NML` it also does what the batch will do at its end: park
each original (`.<name>.konduktor-parked`, beside it), repoint the collection
entry that names it at the stem file (`apply_stem_swaps`), and SAVE — after
copying the collection into its `backups/` folder. Traktor must be closed.
`--keep-audio-id` keeps Traktor's analysis fingerprint on the swapped entries
(the milestone-2 check compares kept vs cleared).
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import tempfile
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
import numpy as np # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
ENGINE_DIR = Path(__file__).resolve().parents[1] / "engine"
def engine_separator(python: str, weights: str, device: str):
def separate(pcm: np.ndarray) -> list[np.ndarray]:
with tempfile.TemporaryDirectory(prefix="konduktor-dev-stems-") as d:
mix = Path(d) / "mix.f32"
np.ascontiguousarray(pcm, dtype=np.float32).tofile(mix)
cmd = [python, "-m", "konduktor_engine", "separate", "--input", str(mix),
"--samples", str(pcm.shape[1]), "--output-dir", str(Path(d) / "out"),
"--weights", weights, "--device", device]
proc = subprocess.Popen(cmd, cwd=ENGINE_DIR, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True)
last = None
for line in proc.stdout:
msg = json.loads(line)
if msg["event"] == "progress":
print(f"\r separating {msg['fraction'] * 100:5.1f} %", end="", flush=True)
last = msg
proc.wait()
print()
if not last or last["event"] != "done":
raise sf.StemFileError(f"engine failed: {last}")
return [np.fromfile(Path(d) / "out" / f"{name}.f32", dtype=np.float32).reshape(2, -1)
for name in sf.DEMUCS_ORDER]
return separate
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--engine-python", required=True)
ap.add_argument("--weights", required=True)
ap.add_argument("--out-dir")
ap.add_argument("--device", default="auto")
ap.add_argument("--collection")
ap.add_argument("--keep-audio-id", action="store_true")
ap.add_argument("files", nargs="+")
args = ap.parse_args()
separate = engine_separator(args.engine_python, args.weights, args.device)
adapter = None
swaps = []
if args.collection:
if subprocess.run(["pgrep", "-x", "Traktor"], capture_output=True).returncode == 0:
print("Traktor is running — close it first (it rewrites the collection on exit).")
return 1
from konduktor.adapters.traktor.adapter import TraktorAdapter
adapter = TraktorAdapter(Path(args.collection))
adapter.store._KEEP_AUDIO_ID_ON_STEM = args.keep_audio_id
by_path = {str(adapter.audio_path(t.id)): t.id for t in adapter.tracks}
for f in (Path(x).expanduser().absolute() for x in args.files):
target = (Path(args.out_dir) if args.out_dir else f.parent) / sf.stem_target_name(f.name)
if target.exists():
print(f"skip (exists): {target}")
continue
partial = target.with_name(target.name + ".konduktor-partial")
t0 = time.time()
print(f"{f.name}")
try:
written = sf.build(f, partial, separate)
except Exception:
partial.unlink(missing_ok=True)
raise
os.replace(partial, target)
print(f" -> {target.name} {written.duration:.0f} s, {written.bit_rate // 1000} kbps x5, "
f"{written.size / 1e6:.1f} MB, {time.time() - t0:.0f} s")
if adapter is not None:
from konduktor.core.adapter import StemSwap
tid = by_path.get(str(f))
if tid is None:
print(f" (not in the collection: {f})")
continue
parked = f.with_name(f".{f.name}.konduktor-parked")
os.replace(f, parked)
swaps.append(StemSwap(tid, target, "repoint", parked, written.bit_rate,
written.duration, written.size))
if adapter is not None and swaps:
import shutil
nml = Path(args.collection)
backups = nml.parent / "backups"
backups.mkdir(exist_ok=True)
shutil.copy2(nml, backups / f"{nml.name}.{time.strftime('%Y%m%d-%H%M%S')}.dev-stems.bak")
res = adapter.apply_stem_swaps(swaps)
adapter.save()
print(f"swapped {len(res.renamed)} entries; clamped: {res.clamped or 'none'}; saved {nml}")
return 0
if __name__ == "__main__":
sys.exit(main())
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,32 @@
# 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`.
@@ -0,0 +1,38 @@
# Memory-cue edits rekordbox 7 made on a stick
Analysis files of six tracks on a OneLibrary test stick written by
rekordbox, before and after **rekordbox 7 itself** edited their MEMORY cues
(kit M2, 2026-10-16; the stick was backed up first and restored afterwards).
`test_onelibrary_anlz.py` replays each edit with Konduktor's helpers on
`before/` and compares the memory lists with `after/` byte for byte.
Only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for byte — the
waveforms were dropped, as in `onelibrary-goober/`. There is no database and
no audio: `exportLibrary.db` and both pdbs had NO row change for any of these
edits (memory cues on a stick live only in the analysis files).
| File | Track | Edit (one per track) |
|---|---|---|
| `black-bloc` | Justin Hawkes – Black Bloc (VIP) | memory cue ADDED at 2:11.206 |
| `formula` | RL Grime & Juelz – Formula (IMANU Remix) | 4-beat memory LOOP added at 1:20.378 |
| `lift-it` | Tian – Lift It (Hexa Remix) | 8 memory cues added (2 → 10, the cap) |
| `wtf` | Result – WTF (Phace Remix) | the memory loop at 1:53 recoloured Blue |
| `sell-my-soul` | Bensley, Justin Hawkes & Kumarion – Sell My Soul | comment "Loopy" on the memory loop at 1:18 |
| `doomed` | Nemean – Doomed | the memory loop at 2:01 DELETED |
What they show (the full write-up is in
`.claude/discussions/discuss-memory-cues-2026-10-16.md`, kit M2):
- `.DAT` `PCOB` memory list: a new entry is PREPENDED; every entry has status 0
and bytes 24–27 = previous / next index in the list (`ffff` at the ends), so
any add or delete relinks the whole list; the header i32 at offset 20 is
count − 1.
- `.EXT` `PCO2` memory list: a new entry is APPENDED in rekordbox's compact
44-byte form; the others stay byte-identical. The `.EXT`'s `PCOB` memory list
stays empty.
- When rekordbox rewrites a `.DAT` (any memory add or delete), it ALSO
re-sorts the untouched hot-cue `PCOB` into ascending pad order (an export
writes it highest pad first); the entries themselves are unchanged.
Konduktor changes only the list it edits, so the test compares that tag's
entries regardless of order.
- Colour: `PCP2` byte 28, 1-based (Blue = 7), 0 = none. Comment: UTF-16BE + NUL
at byte 44, `len_comment` at 40. Neither touches the `.DAT`.
+13
View File
@@ -56,3 +56,16 @@ 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`.
+81
View File
@@ -0,0 +1,81 @@
-- rekordbox's own scaffolding rows for a OneLibrary drive: the browse menu
-- items, the categories and sort columns a player offers, and the colour
-- palette. Extracted verbatim from fixtures/onelibrary/PIONEER/rekordbox/
-- exportLibrary.db (a real rekordbox 7.2.18 export). No user data, no
-- machine identity. rekordbox writes these on every export, so a drive without
-- them is not a shape any player has been tested against.
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (1, 128, 'GENRE');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (2, 129, 'ARTIST');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (3, 130, 'ALBUM');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (4, 131, 'TRACK');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (5, 133, 'BPM');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (6, 134, 'RATING');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (7, 135, 'YEAR');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (8, 136, 'REMIXER');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (9, 137, 'LABEL');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (10, 138, 'ORIGINAL ARTIST');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (11, 139, 'KEY');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (12, 141, 'CUE');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (13, 142, 'COLOR');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (14, 146, 'TIME');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (15, 147, 'BITRATE');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (16, 148, 'FILE NAME');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (17, 132, 'PLAYLIST');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (18, 152, 'HOT CUE BANK');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (19, 149, 'HISTORY');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (20, 145, 'SEARCH');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (21, 150, 'COMMENTS');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (22, 140, 'DATE ADDED');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (23, 151, 'DJ PLAY COUNT');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (24, 144, 'FOLDER');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (25, 161, 'DEFAULT');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (26, 162, 'ALPHABET');
INSERT INTO "menuItem" ("menuItem_id", "kind", "name") VALUES (27, 170, 'MATCHING');
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (1, 1, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (2, 2, 1, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (3, 3, 2, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (4, 4, 3, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (5, 17, 5, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (6, 5, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (7, 6, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (8, 7, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (9, 8, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (10, 9, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (11, 10, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (12, 11, 4, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (15, 13, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (17, 24, 9, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (18, 20, 7, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (19, 14, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (20, 15, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (21, 16, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (22, 19, 6, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (23, 18, 0, 0);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (26, 27, 8, 1);
INSERT INTO "category" ("category_id", "menuItem_id", "sequenceNo", "isVisible") VALUES (27, 22, 10, 1);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (0, 25, 1, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (1, 26, 2, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (2, 2, 3, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (3, 3, 4, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (4, 5, 5, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (5, 6, 6, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (6, 1, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (7, 21, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (8, 14, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (9, 8, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (10, 9, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (11, 10, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (12, 11, 7, 1, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (13, 15, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (15, 13, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (16, 23, 0, 0, 0);
INSERT INTO "sort" ("sort_id", "menuItem_id", "sequenceNo", "isVisible", "isSelectedAsSubColumn") VALUES (17, 22, 0, 0, 0);
INSERT INTO "color" ("color_id", "name") VALUES (1, 'Pink');
INSERT INTO "color" ("color_id", "name") VALUES (2, 'Red');
INSERT INTO "color" ("color_id", "name") VALUES (3, 'Orange');
INSERT INTO "color" ("color_id", "name") VALUES (4, 'Yellow');
INSERT INTO "color" ("color_id", "name") VALUES (5, 'Green');
INSERT INTO "color" ("color_id", "name") VALUES (6, 'Aqua');
INSERT INTO "color" ("color_id", "name") VALUES (7, 'Blue');
INSERT INTO "color" ("color_id", "name") VALUES (8, 'Purple');
@@ -0,0 +1,20 @@
# Empty rekordbox device library (`export.pdb`, `exportExt.pdb`)
The legacy "Device Library" a Pioneer USB stick carries — the one Rekordbox
lists as **Device Library** and older players (CDJ-2000NXS2, many XDJs) read —
exactly as **Rekordbox 7.2.18 wrote it for an empty stick**: it creates both
files the first time it mounts a drive that has none.
They are the starting point of the "Rekordbox Export" target
(`adapters/rekordbox/device_export.py`), for the same reason `seed.sql` exists:
the format has fixed tables that are the same on every stick and cannot be
derived — the colour list (table 6), the browse columns (16), two menu tables
(17, 18) and a history header (19) in `export.pdb`; rekordbox's default MyTag
names in `exportExt.pdb`. Every data table (tracks, artists, albums, genres,
labels, keys, playlists, artwork) holds only its header page, with a blank page
reserved after it for its first rows — the allocation rule the writer follows.
**No user data**: the only strings are colour names, column names, the default
MyTag names, the creation date (`2026-09-27`, rewritten on every export) and the
database version `1000`. Pages 13-14 and 33-38 are byte-identical to the same
pages of a real rekordbox device export of eight tracks.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,62 @@
{
"note": "Rows from a real rekordbox 7.2.18 device export (export.pdb), for byte-level tests. Only the Loopmasters demo tracks and generic key names; see README.md. The track row's u3/u4 (the exporting computer's rekordbox masterDbId) are zeroed.",
"track_row_demo_track_2": "2400200000070c0044ac000000000000f6304e0011a8a6040000000000000000000000000000000001000000000000004001000000000000e02e000000000000000000000100000002000000000000000000100080002900000001000300880089008a008c008e00910092009500980099009a00a500a600a700a800d400df00fd000a010b011c0103030531053107313103074f4e074f4e030317323031382d30352d3235030303592f50494f4e4545522f555342414e4c5a2f503035332f30303031443231462f414e4c5a303030302e44415417323032362d30392d31373d547261636b73206279207777772e6c6f6f706d6173746572732e636f6d1b44656d6f20547261636b2032032344656d6f20547261636b20322e6d7033692f436f6e74656e74732f4c6f6f706d6173746572732f556e6b6e6f776e416c62756d2f44656d6f20547261636b20322e6d7033",
"track_row_demo_track_2_fields": {
"subtype": 36,
"index_shift": 32,
"bitmask": 788224,
"sample_rate": 44100,
"composer_id": 0,
"file_size": 5124342,
"u2": 78030865,
"u3": 0,
"u4": 0,
"artwork_id": 0,
"key_id": 0,
"original_artist_id": 0,
"label_id": 1,
"remixer_id": 0,
"bitrate": 320,
"track_number": 0,
"tempo": 12000,
"genre_id": 0,
"album_id": 0,
"artist_id": 1,
"id": 2,
"disc_number": 0,
"play_count": 0,
"year": 0,
"sample_depth": 16,
"duration": 128,
"u5": 41,
"color_id": 0,
"rating": 0,
"u6": 1,
"u7": 3,
"isrc": "",
"texter": "",
"unknown_string_2": "1",
"unknown_string_3": "1",
"unknown_string_4": "11",
"message": "",
"kuvo_public": "ON",
"autoload_hotcues": "ON",
"unknown_string_5": "",
"unknown_string_6": "",
"date_added": "2018-05-25",
"release_date": "",
"mix_name": "",
"unknown_string_7": "",
"analyze_path": "/PIONEER/USBANLZ/P053/0001D21F/ANLZ0000.DAT",
"analyze_date": "2026-09-17",
"comment": "Tracks by www.loopmasters.com",
"title": "Demo Track 2",
"unknown_string_8": "",
"filename": "Demo Track 2.mp3",
"file_path": "/Contents/Loopmasters/UnknownAlbum/Demo Track 2.mp3"
},
"artist_row_loopmasters": "6000000001000000030a194c6f6f706d617374657273000000000000",
"playlist_row_demos": "00000000000000000100000001000000000000000d64656d6f730000",
"keys_page_index": 12,
"keys_page": "000000000c0000000500000034000000140000000000000002400024b80f1800010001000000000001000000010000000941626d020000000200000007456d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000Line truncated
}
+51 -7
View File
@@ -1,6 +1,14 @@
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
# build). Produces a single-file binary that serves the FastAPI API on a free
# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the
# executable plus `_internal/` — that serves the FastAPI API on a free loopback
# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
#
# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390
# native libraries) into a NEW temp folder on every launch, and macOS checks
# every library it has not seen before (XProtect / syspolicyd) as it is
# dlopen()ed, keyed per file — so every launch paid ~10 s before the window
# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once
# seen). Installed as a folder inside the app, they are checked once.
#
# The tricky bits this handles:
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
@@ -10,7 +18,7 @@
# - python-multipart is imported as `multipart` by starlette → hidden import
# - dulwich (version-history backups) imports git backends dynamically →
# collect_submodules('dulwich')
from PyInstaller.utils.hooks import collect_submodules, collect_all
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
hiddenimports = []
datas = []
@@ -20,8 +28,9 @@ binaries = []
for pkg in ("uvicorn", "xsdata", "dulwich"):
hiddenimports += collect_submodules(pkg)
# Native standard extras — grab modules + shared libs + any data.
for pkg in ("uvloop", "httptools", "websockets"):
# Native standard extras — grab modules + shared libs + any data. PyAV (`av`)
# carries FFmpeg's shared libraries, which the export's waveform analysis needs.
for pkg in ("uvloop", "httptools", "websockets", "av"):
d, b, h = collect_all(pkg)
datas += d
binaries += b
@@ -30,11 +39,38 @@ for pkg in ("uvloop", "httptools", "websockets"):
# 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.
datas += [("../frontend/package.json", ".")]
# The Rekordbox and OneLibrary exporters build their databases from the real
# DDL + scaffolding rows under fixtures/, found at `parents[3] / "fixtures"` —
# i.e. the bundle root. Without these a packaged app cannot export to either.
datas += [
("fixtures/rekordbox/schema.sql", "fixtures/rekordbox"),
("fixtures/rekordbox/seed.sql", "fixtures/rekordbox"),
("fixtures/onelibrary/schema.sql", "fixtures/onelibrary"),
("fixtures/onelibrary/seed.sql", "fixtures/onelibrary"),
# The "Rekordbox Export" target starts from rekordbox's own empty device library.
("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"],
pathex=[],
@@ -54,9 +90,8 @@ pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
exclude_binaries=True,
name="konduktor-sidecar",
debug=False,
bootloader_ignore_signals=False,
@@ -69,3 +104,12 @@ exe = EXE(
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=False,
name="konduktor-sidecar",
)
+358 -54
View File
@@ -5,28 +5,30 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
* a ``TrackIndex`` — the generic READ projection built from it.
**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.
**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.
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.
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.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from ..rekordbox import 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
@@ -42,23 +44,28 @@ ATTRIBUTE_SMART = 4
class OneLibraryAdapter:
platform = "onelibrary"
def __init__(self, path: Path):
def __init__(self, path: Path, *, read_only: bool = False):
self.path = Path(path)
self._store = OneLibraryStore(self.path)
self.read_only = read_only
self._store = OneLibraryStore(self.path, read_only=read_only)
self._index = TrackIndex()
self._rebuild()
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
self._index.rebuild(
[
projection.to_track(row, self._drive_path(row))
for row in self._store.iter_content()
]
)
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)
def _drive_path(self, row) -> str | None:
resolved = self._store.layout.resolve(getattr(row, "path", 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))
return str(resolved) if resolved is not None else None
def close(self) -> None:
@@ -70,14 +77,27 @@ class OneLibraryAdapter:
self._store.close()
def reload(self) -> None:
self._store._load()
"""Re-read the drive, DISCARDING unsaved edits."""
self._store.discard()
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 ------------------------------------------------------------
@@ -144,7 +164,9 @@ class OneLibraryAdapter:
rather than an absence, and treating 0 as a real id would orphan every
top-level playlist.
"""
rows = self._store.playlists()
rows = sorted(self._store.playlists(),
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
writable = not self.read_only
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
@@ -164,13 +186,14 @@ class OneLibraryAdapter:
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
selectable=kind == "playlist",
# Read-only: every per-node flag is False, and
# Opened read-only, every flag is False and
# `capabilities.writable` tells the UI why, once.
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
can_add_tracks=writable and kind == "playlist",
can_reorder=writable and kind == "playlist",
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
parents[node_id] = "root" if parent in ("0", "", "None") else parent
@@ -201,6 +224,9 @@ class OneLibraryAdapter:
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
"""Ignored: a drive's paths are relative to wherever it is mounted.
@@ -211,6 +237,13 @@ class OneLibraryAdapter:
"""
return None
def unresolved_path_groups(self) -> list:
"""None, ever: a drive's paths are relative to its own mount point."""
return []
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
@@ -229,83 +262,354 @@ class OneLibraryAdapter:
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return False
return self._store.dirty
def save(self):
raise Unsupported(self._readonly_reason("Saving"))
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
def snapshot(self) -> bytes:
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
# ---- commands: all refused -------------------------------------------
# ---- commands -----------------------------------------------------------
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 add_tracks(self, items: list) -> list[str]:
self._refuse("Adding tracks")
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 remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks")
"""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
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._refuse("Editing track metadata")
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")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return None
return self._store.cover_art(track_id)
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists")
self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
def create_folder(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlist folders")
self._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists")
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists")
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._refuse("Editing playlists")
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
def set_cue(self, track_id: str, **kw) -> TrackCues:
self._refuse("Editing cues")
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_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._refuse("Editing cues")
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)
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._refuse("Deleting cues")
self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._refuse("Placing cues")
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]
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.add_grid_marker(track_id, start_sec, bpm)
return self._refresh_cues(track_id)
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.move_grid_marker(track_id, index, start_sec)
return self._refresh_cues(track_id)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.set_grid_marker_bpm(track_id, index, bpm)
return self._refresh_cues(track_id)
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.delete_grid_marker(track_id, index)
return self._refresh_cues(track_id)
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.replace_grid(track_id, self._markers_from(markers))
return self._refresh_cues(track_id)
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
"""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)
def delete_grid(self, track_id: str) -> TrackCues:
self._refuse("Deleting the beatgrid")
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
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")
@@ -27,8 +27,9 @@ from ..rekordbox.beatgrid import BPM_EPSILON, markers_from_beats # noqa: F401
__all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"]
def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None:
"""Per-beat ``(times_sec, bpms)`` from a parsed ANLZ file's `PQTZ` tag.
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`).
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
@@ -39,18 +40,21 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None:
for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ":
continue
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
entries = tag.entries
if not entries:
return None
times: list[float] = []
bpms: list[float] = []
beats: list[int] = []
for e in entries:
try:
times.append(int(e.time) / 1000.0)
bpms.append(int(e.tempo) / 100.0)
time, tempo, beat = int(e.time) / 1000.0, int(e.tempo) / 100.0, int(e.beat)
except (AttributeError, TypeError, ValueError):
continue
return (times, bpms) if times else None
times.append(time)
bpms.append(tempo)
beats.append(beat)
return (times, bpms, beats) if times else None
return None
@@ -1,25 +1,27 @@
"""What a OneLibrary drive can persist: nothing, for now.
"""What a OneLibrary drive can persist.
`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.
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.
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.
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.
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 **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.
* 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.)
* 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.
@@ -34,44 +36,66 @@ 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) -> Capabilities:
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:
return Capabilities(
platform="onelibrary",
version=version,
# 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",
writable=not read_only,
readonly_cause="browsing" if read_only else None,
cues=CueCapabilities(
editable=False,
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does. They are
# projected and preserved; nothing here is editable anyway.
# Memory cues, editable as in Rekordbox — in the ANLZ files, the
# way rekordbox 7 edits them on a stick (measured, kit M2).
memory_cues=True,
max_memory_cues=None,
types=["cue", "loop"],
color="free", # PCO2 stores RGB per cue, not a palette index
palette=[],
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],
named=True, # PCO2 carries a per-cue comment
loops="cue_type",
),
# 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),
# 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),
tracks=TrackCapabilities(
rating_max=5, # stored 0-5 directly, as in master.db
editable_fields=[],
media_kinds=["audio"],
# The drive has an `image` table and an Artwork folder, but nothing
# is wired up to read them yet.
# 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`.
artwork=False,
artwork_note=None,
),
@@ -80,13 +104,18 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
# A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules.
smart="none",
reorder=False,
reorder=True,
),
save=SaveCapabilities(
app_name="OneLibrary",
library_label=device_name or "exportLibrary.db",
# Nothing is written, so nothing can be overwritten by another app.
# 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.
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.
+54 -24
View File
@@ -37,6 +37,7 @@ from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import memory_palette, palette
log = logging.getLogger(__name__)
@@ -47,14 +48,13 @@ 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; PCOB exposes it as
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
# PCO2/PCOB entry kinds. The value is the same in both tags.
ENTRY_CUE = 1
ENTRY_LOOP = 2
def _entry_kind(value) -> int:
"""PCOB gives an enum, PCO2 an int — one number out of either."""
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
try:
return int(value)
except (TypeError, ValueError):
@@ -68,8 +68,17 @@ 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
@@ -78,7 +87,7 @@ def _color(entry) -> str | None:
return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try:
hot_cue = int(entry.hot_cue)
@@ -103,6 +112,13 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
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",
@@ -110,16 +126,26 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
start=start_ms / 1000.0,
length=length,
slot=slot,
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",
color=color,
# Editable on a drive opened for editing (the caller says so), memory
# cues included; browsing a device is read-only.
editable=editable,
readonly_reason=None if editable else "platform_managed",
grid_marker=None,
id=memory_cue_id(entry) if role == "memory" else None,
)
def memory_cue_id(entry) -> str:
"""A memory cue's `CuePoint.id`: its STORED position, kind and loop end.
Content-derived, so it is the same on every read and in both lists (`PCOB`
in the .DAT, `PCO2` in the .EXT, which order the same cues differently);
an index would not be. Two memory cues identical in all three are one cue
to `_dedupe` already, so the first match is the one meant."""
return f"m:{int(entry.time)}:{_entry_kind(getattr(entry, 'type', ENTRY_CUE))}:{int(getattr(entry, 'loop_time', NO_LOOP))}"
def _entries(anlz, tag_type: str) -> list:
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
@@ -130,15 +156,14 @@ def _entries(anlz, tag_type: str) -> list:
"""
out: list = []
for tag in getattr(anlz, "tags", []):
if tag.type != tag_type:
continue
content = getattr(tag.struct, "content", None)
out.extend(getattr(content, "entries", None) or [])
if tag.type == tag_type:
out.extend(tag.entries)
return out
def cues_from_anlz(dat, ext) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
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).
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.
@@ -153,14 +178,14 @@ def cues_from_anlz(dat, ext) -> 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)) is not None]
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) 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)) is not None]
cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
return _dedupe(cues)
@@ -168,18 +193,23 @@ def cues_from_anlz(dat, ext) -> 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) 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.
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.
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[str, int | None, int]] = set()
seen: set[tuple] = set()
out: list[CuePoint] = []
for c in cues:
key = (c.role, c.slot, round(c.start * 1000))
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
if key in seen:
continue
seen.add(key)
@@ -0,0 +1,209 @@
"""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.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
@@ -73,8 +73,8 @@ class OneLibraryDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path) -> OneLibraryAdapter:
return OneLibraryAdapter(path)
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
return OneLibraryAdapter(path, read_only=read_only)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
+227 -43
View File
@@ -42,7 +42,10 @@ from datetime import date
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.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key
from .capabilities import capabilities_for
@@ -51,11 +54,21 @@ from .layout import DB_SUBPATH
log = logging.getLogger(__name__)
SCHEMA = Path(__file__).resolve().parents[3] / "fixtures" / "onelibrary" / "schema.sql"
#: rekordbox's scaffolding rows — browse menu items, categories, sort columns,
#: the colour palette — copied from a real export. See the file's header.
SEED = SCHEMA.with_name("seed.sql")
#: rekordbox writes this in `property.dbVersion` on a real export.
DB_VERSION = "1000"
#: Seen on every track of a real export; semantics undocumented, copied as-is.
ANALYSED_BITS = 41
#: `content.contentLink`, as rekordbox 7 writes it beside `analysedBits` 41 (a
#: re-analysed track carried 1902336 beside 105; what the bits mean is unknown).
#: NOT optional: measured by blanking it on one track of a rekordbox-written
#: stick — that row's song-list preview fell back to plain blue and gained a "?"
#: beside CUE, exactly as every row of Konduktor's exports did while it was NULL.
#: `masterDbId`/`masterContentId` were cleared the same way and changed nothing.
CONTENT_LINK = 788224
OTHER_PLAYLIST = "Other"
@@ -84,8 +97,11 @@ def _anlz_dir(drive_relative: str) -> str:
class OneLibraryExporter:
platform = "onelibrary"
menu_order = 10
#: Relative to the drive root, which is what the destination folder is.
library_filename = str(Path("PIONEER") / DB_SUBPATH)
#: A CDJ looks for `PIONEER/` at the root of the stick and nowhere else.
drive_root = True
def capabilities(self):
"""What a drive can hold — no device, no path, no library to read.
@@ -96,20 +112,30 @@ class OneLibraryExporter:
yes to. Leaving the adapter's answer here would have the UI report that
the thing it just wrote cannot be written.
"""
return capabilities_for().model_copy(
update={"writable": True, "readonly_cause": None}
)
caps = capabilities_for()
# An exported drive CARRIES artwork (`_write_art`); the adapter's False
# means "cannot edit a plugged-in drive's art", a different question.
return caps.model_copy(update={
"writable": True, "readonly_cause": None,
"tracks": caps.tracks.model_copy(update={"artwork": True}),
})
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
library = root / "PIONEER" / DB_SUBPATH
library.parent.mkdir(parents=True, exist_ok=True)
if library.exists():
library.unlink() # SQLCipher will not re-key an existing file
# SQLCipher will not re-key an existing file — and the WAL and shared
# memory files beside it must go too. rekordbox leaves both on a stick
# it has mounted, and SQLite REPLAYS a leftover WAL into whatever
# database it finds, so a fresh library would open with the old one's
# pages written over it.
for stale in (library, *(library.with_name(library.name + s) for s in ("-wal", "-shm"))):
if stale.exists():
stale.unlink()
extra: list[Path] = []
con = sqlcipher.connect(str(library))
@@ -118,6 +144,7 @@ class OneLibraryExporter:
# stick is readable by any of them, which is the point of it.
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
con.executescript(SCHEMA.read_text())
con.executescript(SEED.read_text(encoding="utf-8"))
extra += self._fill(con, payload, root)
con.commit()
finally:
@@ -128,10 +155,17 @@ class OneLibraryExporter:
def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]:
lookups = {name: {} for name in ("artist", "album", "genre", "label", "key")}
# Image ids are handed out in track order, one per track that HAS art —
# rekordbox does not share an image between tracks, even identical ones.
lookups["image"] = {"next": 0}
written: list[Path] = []
by_source: dict[str, int] = {}
total = len(payload.tracks)
for n, item in enumerate(payload.tracks, start=1):
# Each track is DECODED for its waveform, so this loop is the slow
# part of the write — report it, and let a cancel land between tracks.
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
by_source[item.source_id] = n
written += self._write_track(con, n, item, root, lookups)
@@ -170,16 +204,18 @@ class OneLibraryExporter:
size = item.destination.stat().st_size
except OSError:
size = 0
sample_rate, bit_depth = _audio_format(item.destination)
image_id, art_files = self._write_art(con, item, root, lookups["image"])
con.execute(
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, color_id, image_id, "
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, samplingRate, isHotCueAutoLoadOn, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, hasModified, cueUpdateCount, "
"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,
@@ -193,40 +229,113 @@ 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,
1, track.bitrate, None, 1, 1, 0, content_id,
anlz_rel, ANALYSED_BITS, 0, 0, 0, 0,
# kbps, as every Pioneer library stores it; the generic model
# carries bits per second.
_file_type(item.destination), _kbps(track.bitrate),
bit_depth, sample_rate, 1, 1, 0, content_id,
anlz_rel, ANALYSED_BITS, CONTENT_LINK, 0, 0, 0, 0,
),
)
return self._write_anlz(item, rel, root / anlz_rel.lstrip("/"))
return art_files + self._write_anlz(item, rel, root / anlz_rel.lstrip("/"))
# ---- artwork -------------------------------------------------------------
@staticmethod
def _write_art(con, item: ExportTrack, root: Path, counter: dict) -> tuple[int | None, list[Path]]:
"""One track's cover: four JPEGs and an `image` row, as rekordbox 7 writes.
`PIONEER/Artwork/00001/` holds `a<n>.jpg` / `a<n>_m.jpg` and a byte-
identical `b<n>.jpg` / `b<n>_m.jpg` (80 and 240 px); `image.path` names the
`b` file and `content.image_id` points at the row. rekordbox's own export
writes both letters — the `a` pair presumably for the legacy `export.pdb`
readers — so both are written here too.
Everything goes in folder `00001`. How rekordbox splits a large library
across folders is not known (the reference export has 6 images); a single
folder is what it demonstrably reads.
"""
if not item.art:
return None, []
jpegs = artwork.pioneer_jpegs(item.art[0])
if jpegs is None:
return None, []
counter["next"] += 1
n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True)
files = []
for rel, data in art_files(n, jpegs):
path = root / rel.lstrip("/")
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 _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""The `.DAT` and, when there are cues beyond pad C, the `.EXT`.
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`).
Always both when there are any cues: `PCO2` lives only in the `.EXT` and
is the complete list, which is what the reader prefers.
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,
which readers prefer — lives only in the `.EXT`.
**The `.DAT` must carry `PVBR` and the preview waveforms**, or rekordbox
shows neither the grid nor the cues (see `anlz_writer`). The `.EXT` and
`.2EX` waveforms only affect drawing: the song-list preview and the
deck's scrolling waveform. Tag order is rekordbox's in each file:
.DAT PPTH PVBR PQTZ PWAV PWV2 PCOB PCOB
.EXT PPTH PWV3 PCOB PCOB PCO2 PCO2 PWV5 PWV4
.2EX PPTH PWV7 PWV6 PWVC
An undecodable file still gets the `.DAT` (with a flat preview) and the
`.EXT` cue lists — its grid and cues must show — but no drawn waveforms.
"""
cues = self._cue_dicts(item)
beats = self._beats(item)
# rekordbox's clock runs ~25 ms behind the decoded audio on MP3/AAC (see
# `timebase`): beats and cues are computed in the decoded time base and
# shifted as they are packed, and the waveform frames are measured with
# the same lead so they line up with the beats.
off = timebase.offset(item.destination)
measured = item.waveform(lead=off)
# The DECODED length where there is one: `Track.length` is whole seconds
# rounded down, and a grid expanded to it loses the track's last beat.
beats = self._beats(item, measured.duration if measured else None)
cues = self._cue_dicts(item, beats, off)
if measured:
previews = W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
previews, ext_waves, two_ex = W.flat_preview_tags(), [], []
tags = [W.path_tag(rel)]
tags = [W.path_tag(rel), W.vbr_tag(W.mp3_samples(item.destination))]
if beats:
tags.append(W.beatgrid_tag(beats))
tags.append(W.beatgrid_tag([(n, bpm, timebase.to_pioneer(t, off))
for n, bpm, t in beats]))
tags += previews
tags += W.cue_tags(cues, extended=False)
written = [W.write_anlz(dat, tags)]
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))]
if two_ex:
files.append((".2EX", W.anlz_bytes([W.path_tag(rel), *two_ex])))
return files
if cues:
written.append(
W.write_anlz(dat.with_suffix(".EXT"),
[W.path_tag(rel), *W.cue_tags(cues, extended=True)])
)
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)
return written
@staticmethod
def _beats(item: ExportTrack) -> list[tuple[int, float, float]]:
def _beats(item: ExportTrack, duration: float | None = None) -> list[tuple[int, float, float]]:
"""Every beat, expanded from the generic marker list.
A Pioneer grid has no tempo markers — it is a flat list of beats — so a
@@ -237,12 +346,13 @@ class OneLibraryExporter:
cues = item.cues
if not cues or not cues.grid_markers:
return []
duration = float(item.track.length or 0) or (cues.grid_markers[-1].start + 60.0)
duration = (duration or float(item.track.length or 0)
or (cues.grid_markers[-1].start + 60.0))
nums, bpms, times = beats_from_markers(cues.grid_markers, duration)
return list(zip(nums, bpms, times))
@staticmethod
def _cue_dicts(item: ExportTrack) -> list[dict]:
def _cue_dicts(item: ExportTrack, beats: list | None = None, off: float = 0.0) -> list[dict]:
"""Generic cues in the shape `anlz_writer` packs.
Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue.
@@ -251,22 +361,44 @@ class OneLibraryExporter:
too far along.
"""
out: list[dict] = []
for cue in (item.cues.cues if item.cues else []):
memory = 0
for cue in sorted(item.cues.cues if item.cues else [], key=lambda c: c.start):
is_loop = cue.type == "loop" or cue.length > 0
is_memory = cue.role == "memory" or cue.slot is None
if is_memory:
# rekordbox keeps 10 (earliest first; the rest are dropped, per
# the lossiness rule). A memory cue's colour is PCP2 byte 28 from
# its own 8-colour palette — what Konduktor SHOWS (stored, else
# the type's), as for a hot cue; the hot-cue code + RGB stay zero.
if memory >= MAX_MEMORY_CUES:
continue
memory += 1
code, rgb = 0, (0, 0, 0)
color_id = memory_palette.anlz_byte(memory_palette.nearest_code(effective_color(cue)))
else:
# What Konduktor SHOWS — stored colour, else the type's (blue cue,
# green loop) — as a rekordbox palette CODE, which is what
# rekordbox draws from; "unset" draws its own defaults.
code, rgb = palette.code_for(effective_color(cue))
color_id = 0
out.append({
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1,
"color_id": color_id,
"hot_cue": 0 if is_memory else cue.slot + 1,
"kind": 2 if is_loop else 1,
"time_ms": int(round(cue.start * 1000)),
"loop_ms": int(round((cue.start + cue.length) * 1000)) if is_loop else None,
"rgb": _rgb(cue.color),
"beats": None,
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
if is_loop else None),
"rgb": rgb,
"code": code,
"beats": _loop_beats(cue.start, cue.length, beats or []) if is_loop else None,
})
return out
# ---- playlists -----------------------------------------------------------
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
"""One folder named after the export, with the tree preserved under it.
"""The tree preserved — at the top level (parent NULL), or with
`payload.root_folder` under one folder named after the export.
`playlist` is a flat table with `playlist_id_parent`, so folders and
playlists are the same row kind told apart by `attribute` (1 = folder).
@@ -282,8 +414,8 @@ class OneLibraryExporter:
)
return next_id[0]
root = add(payload.name, None, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
root = add(payload.name, None, folder=True) if payload.root_folder else None
folders: dict[tuple[str, ...], int | None] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -312,10 +444,62 @@ class OneLibraryExporter:
)
def _rgb(color: str | None) -> tuple[int, int, int] | None:
if not color or not color.startswith("#") or len(color) != 7:
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
#: both still write 4.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12}
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)
def _kbps(bitrate: int | None) -> int | None:
"""Generic bits per second → Pioneer's kbps."""
if not bitrate:
return None
return int(round(bitrate / 1000))
def _audio_format(path: Path) -> tuple[int | None, int | None]:
"""(sample rate, bit depth) read from the COPIED file, or Nones.
Not in the generic model, and not worth adding for one target: the file is
right here, and reading its header costs a millisecond.
"""
try:
return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
except ValueError:
import mutagen
info = getattr(mutagen.File(str(path)), "info", None)
except Exception: # an unreadable file still exports; these stay empty
return None, None
rate = getattr(info, "sample_rate", None)
depth = getattr(info, "bits_per_sample", None)
return (int(rate) if rate else None), (int(depth) if depth else None)
def _loop_beats(start: float, length: float, beats: list[tuple[int, float, float]]) -> int | None:
"""A loop's length in whole beats at the tempo governing its start.
rekordbox stores it (`loop_num`/`loop_den`, e.g. 4/1). A loop that is not a
whole number of beats — or a track with no grid — gets none, as rekordbox
itself writes for a loop set by hand.
"""
bpm = next((b for _, b, t in reversed(beats) if t <= start + 1e-3), None)
if not bpm or length <= 0:
return None
count = length * bpm / 60.0
whole = round(count)
return whole if whole >= 1 and abs(count - whole) < 0.05 else None
@@ -0,0 +1,102 @@
"""Memory-cue edits on a track's two analysis files, the way rekordbox 7 makes them.
Pure functions over parsed `AnlzFile`s, so they are pinned byte for byte
against rekordbox's own edits (`fixtures/onelibrary-memory-edits`, kit M2,
2026-10-16) without a drive; the store adds the drive, the time base and Save.
A stick keeps memory cues ONLY in the analysis files — the database and both
pdbs keep every row — in two lists kept in OPPOSITE orders:
* `.DAT` `PCOB` memory: a new cue is PREPENDED, and the whole list is
relinked (`anlz_writer.relinked_memory_pcpts`: status 0, prev/next
indexes) on any add or delete; header field = count − 1.
* `.EXT` `PCO2` memory: a new cue is APPENDED in the compact 44-byte form;
every other entry keeps its bytes. The `.EXT`'s own `PCOB` memory list
stays empty.
A colour is `PCP2` byte 28 and a name the `PCP2` comment; neither touches the
`.DAT`. A cue is addressed by `cues.memory_cue_id` (stored time, kind, loop
end), which is the same in both lists.
"""
from __future__ import annotations
from ..rekordbox import anlz_file
from ..rekordbox import anlz_writer as W
from .cues import memory_cue_id
DAT_ORDER = ("PPTH", "PVBR", "PQTZ", "PWAV", "PWV2", "PCOB")
EXT_ORDER = ("PPTH", "PWV3", "PCOB", "PCO2")
def entries(f: anlz_file.AnlzFile, kind: str) -> list[bytes]:
"""The raw entries of a file's `kind` (PCOB / PCO2) MEMORY list."""
i = f.find(kind, anlz_file.LIST_MEMORY)
return anlz_file.raw_entries(f.tags[i]) if i is not None else []
def count(ext: anlz_file.AnlzFile) -> int:
return len(entries(ext, "PCO2"))
def _matches(entry: bytes, cue_id: str) -> bool:
return memory_cue_id(anlz_file.decode_entry(entry)) == cue_id
def _put(dat, ext, pcob: list[bytes] | None, pco2: list[bytes] | None) -> None:
if pcob is not None:
dat.put("PCOB", W.pcob_tag(anlz_file.LIST_MEMORY, W.relinked_memory_pcpts(pcob)),
list_kind=anlz_file.LIST_MEMORY, after=DAT_ORDER)
if pco2 is not None:
ext.put("PCO2", W.pco2_tag(anlz_file.LIST_MEMORY, pco2),
list_kind=anlz_file.LIST_MEMORY, after=EXT_ORDER)
def add(dat, ext, *, kind: int, time_ms: int, loop_ms: int | None, beats: int | None,
name: str | None = None, color_id: int = 0) -> None:
"""Add one memory cue (kind 1 cue, 2 loop): prepended to the `.DAT`'s list,
appended — compact unless named — to the `.EXT`'s."""
pcp2 = W.pcp2_compact_entry(kind=kind, time_ms=time_ms, loop_ms=loop_ms,
beats=beats, color_id=color_id)
if name:
pcp2 = anlz_file.entry_with_comment(pcp2, name)
pcpt = W.pcpt_entry(hot_cue=0, kind=kind, time_ms=time_ms, loop_ms=loop_ms)
_put(dat, ext, [pcpt] + entries(dat, "PCOB"), entries(ext, "PCO2") + [pcp2])
def _index(ext, cue_id: str) -> tuple[list[bytes], int | None]:
pco2 = entries(ext, "PCO2")
return pco2, next((n for n, e in enumerate(pco2) if _matches(e, cue_id)), None)
def rename(ext, cue_id: str, name: str | None) -> bool:
"""Rename in the `.EXT` only; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_comment(pco2[i], name)
_put(None, ext, None, pco2)
return True
def recolour(ext, cue_id: str, color_id: int) -> bool:
"""Byte 28 of the cue's `PCP2` entry, nothing else; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_color_id(pco2[i], color_id)
_put(None, ext, None, pco2)
return True
def delete(dat, ext, cue_id: str) -> bool:
"""Out of both lists (the `.DAT`'s relinked); False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
del pco2[i]
pcob = entries(dat, "PCOB")
j = next((n for n, e in enumerate(pcob) if _matches(e, cue_id)), None)
if j is not None:
del pcob[j]
_put(dat, ext, pcob if j is not None else None, pco2)
return True
@@ -1,6 +1,6 @@
"""OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed:
@@ -16,6 +16,7 @@ Field conventions are read off a real rekordbox 7 export rather than guessed:
from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox import track_palette
from ..rekordbox.projection import parse_key
@@ -54,7 +55,7 @@ def _bpm(row) -> float | None:
return round(int(raw) / 100.0, 2)
def to_track(row, drive_path: str | None = None) -> Track:
def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
"""Project one ``Content`` row.
**The three count fields are approximations here**, and deliberately so. Cues
@@ -93,7 +94,8 @@ def to_track(row, drive_path: str | None = None) -> Track:
rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))),
playcount=getattr(row, "djPlayCount", None),
length=getattr(row, "length", None),
bitrate=getattr(row, "bitrate", None),
# kbps here; the generic model (and the table) carry bits per second.
bitrate=(getattr(row, "bitrate", None) or 0) * 1000 or None,
import_date=_iso_date(getattr(row, "dateAdded", None)),
last_played=None, # the drive records history as playlists, not per track
release_date=_iso_date(getattr(row, "releaseDate", None))
@@ -103,7 +105,10 @@ def to_track(row, drive_path: str | None = None) -> Track:
hotcue_count=0,
grid_marker_count=1 if (bpm and has_analysis) else 0,
grid_locked=False, # OneLibrary has no grid lock
media_kind="audio",
# 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)),
)
@@ -112,7 +117,7 @@ def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
`cues` are already generic — see `store.cues` for why that boundary sits
where it does — so this is the assembly point rather than a translation.
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
`capabilities.writable` says so at the library level.
Each cue already says whether it is editable (the store knows whether the
drive was opened for editing or is only being browsed).
"""
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
File diff suppressed because it is too large. Load diff
@@ -8,6 +8,7 @@ capabilities.
from ...core import export as core_export
from ...core import registry
from .driver import RekordboxDriver
from .device_export import RekordboxDeviceExporter
from .export import RekordboxExporter
REKORDBOX = RekordboxDriver()
@@ -15,3 +16,8 @@ registry.register(REKORDBOX)
REKORDBOX_EXPORTER = RekordboxExporter()
core_export.register(REKORDBOX_EXPORTER)
# The stick's legacy Device Library (`export.pdb`): a separate TARGET with no
# reader of its own — Konduktor reads a stick through its OneLibrary database.
REKORDBOX_DEVICE_EXPORTER = RekordboxDeviceExporter()
core_export.register(REKORDBOX_DEVICE_EXPORTER)
+272 -23
View File
@@ -21,13 +21,14 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import projection
from . import memory_palette, palette, projection, timebase
from ...core import add_analysis
from .store import RekordboxStore
@@ -44,9 +45,12 @@ class RekordboxAdapter:
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
kinds = self._store.cue_kinds()
gains = self._store.mixer_gains()
self._index.rebuild(
[
projection.to_track(row, kinds.get(str(row.ID), ()))
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)))
for row in self._store.iter_content()
]
)
@@ -68,7 +72,9 @@ 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), ())))
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))))
def close(self) -> None:
"""Release the database connection.
@@ -80,7 +86,9 @@ class RekordboxAdapter:
self._store.close()
def reload(self) -> None:
self._store._load()
"""Re-read the library from disk, DISCARDING unsaved edits (see
`RekordboxStore.discard` for why a plain re-open is not enough)."""
self._store.discard()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
@@ -124,7 +132,8 @@ class RekordboxAdapter:
if self._index.get(track_id) is None:
return None
cues = projection.to_track_cues(
self._store.cues(track_id), self._store.anlz_grid(track_id)
self._store.cues(track_id), self._store.anlz_grid(track_id),
self._store.time_offset(track_id),
)
# The track projection carries an APPROXIMATE grid_marker_count until the
# grid is actually read (see projection.to_track). This is that moment —
@@ -166,6 +175,7 @@ class RekordboxAdapter:
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
@@ -197,8 +207,25 @@ 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
for now. Rekordbox's `FolderPath` is absolute too, so it will qualify."""
return []
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()
@@ -230,6 +257,30 @@ class RekordboxAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
def audio_changed(self, track_id: str, change) -> Track | None:
self._require_writable("Changing a track's level")
self._store.audio_changed(track_id, change)
self._refresh(track_id)
return self._index.get(track_id)
def set_auto_gain(self, track_id: str, loudness) -> Track | None:
self._require_writable("Setting the auto gain")
self._store.set_auto_gain(track_id, loudness)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
@@ -247,6 +298,10 @@ class RekordboxAdapter:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
@@ -269,12 +324,8 @@ class RekordboxAdapter:
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# Rekordbox is the ONLY platform with memory cues, so under the
# two-platform promotion rule they stay preserved-but-uneditable:
# they are projected and shown, never written.
raise Unsupported(
"Memory cues are shown but cannot be edited — only hot cues are writable"
)
# A memory cue has no slot to set; it has its own commands.
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
self._check_cue_type(cue_type)
self._store.set_cue(
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
@@ -288,11 +339,70 @@ 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:
@@ -350,11 +460,41 @@ class RekordboxAdapter:
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
def replace_cues(self, track_id: str, cues: TrackCues) -> TrackCues:
"""Clear the track's cues and grid, then place `cues` as `add_tracks`
does (`_place_imported_cues`). Rekordbox has no grid lock, so
`grid_locked` is not carried; a cue on the reserved `Kind=4` (shown,
not editable) is left where it is."""
self._require_writable("Replacing cues")
current = self.track_cues(track_id)
if current is None:
raise NotFound(f"Track not found: {track_id}")
for cue in current.cues:
if not cue.editable:
continue
if cue.role == "hotcue" and cue.slot is not None:
self._store.delete_cue(track_id, cue.slot)
elif cue.id:
self._store.delete_memory_cue(track_id, cue.id)
markers = list(cues.grid_markers or [])
if markers:
self._store.replace_grid(track_id, self._markers_from(markers))
elif current.grid_markers:
self._store.delete_grid(track_id)
self._place_imported_cues(track_id, cues)
return self._refresh_cues(track_id)
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._journal.summary()
def save(self):
self._require_writable("Saving")
return self._store.save()
@@ -389,19 +529,128 @@ class RekordboxAdapter:
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
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 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 remove_tracks(self, track_ids: list[str]) -> int:
# 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")
# 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
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
# Rekordbox does not play native-instruments stem files as stems.
self._refuse("Converting tracks to stems")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -0,0 +1,324 @@
"""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",
]
@@ -18,12 +18,27 @@ silently overwrites the first in the result; BUILDING is impossible, because
satisfy a string `Const` and an integer field. So cue entries are packed here by
hand, to the layout `pyrekordbox`'s own structs document:
PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · 3x
I time · I loop_time · B color_id · 7x · H loop_num · H loop_den
I len_comment · {n}s comment(utf-16-be) · 4B colour · {pad}x
PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · x
H 1000 · I time · I loop_time · B color_id · B 1 · 6x
H loop_num · H loop_den · I len_comment · {n}s comment(utf-16-be)
4B colour · {pad}x
Everything is verified by parsing the result back through `pyrekordbox`, which is
the only check that matters: the reader is the thing that has to accept it.
**`pyrekordbox` accepting the result is NOT enough.** Its parser ignores
`len_header` and the constants, so an early version with a 12-byte `PCPT`
header round-tripped through Konduktor's own reader perfectly. The cue layout is
therefore pinned to a real rekordbox 7 export byte-for-byte
(`test_export_pioneer.py`).
**Which tags a file needs was measured, not assumed** — by stripping tags from a
rekordbox-written stick one at a time and loading each track in rekordbox 7:
* `.DAT` needs `PVBR` AND the preview waveform (`PWAV`/`PWV2`) before rekordbox
shows the grid OR the hot cues. The grid and cue tags alone — rekordbox's
own bytes — show nothing. (This, not the cue bytes, was why an early
Konduktor export had no grid.)
* rekordbox follows the database's analysis-path column; the folder names
need not match its own path hash.
* `.EXT` extras (`PWV3`-`PWV5`, `PQT2`, `PSSI`) and the whole `.2EX` affect
only the drawn waveforms.
Slot numbering here is ANLZ's own — a **dense 1-based** `hot_cue` where 0 means a
memory cue. That is NOT `master.db`'s sparse `Kind` bank, which skips 4.
@@ -37,6 +52,8 @@ from pathlib import Path
from construct import Container, ListContainer
from pyrekordbox.anlz import structs
from ...core.waveform import even_slices
log = logging.getLogger(__name__)
NO_LOOP = 0xFFFFFFFF
@@ -54,7 +71,9 @@ _TAG_PREFIX = 12
#: Each tag counts a different number of its leading CONTENT fields as part of
#: its header. Read off `pyrekordbox`'s own tag classes rather than guessed.
_LEN_HEADER = {"PPTH": 16, "PQTZ": 24, "PCOB": 24, "PCO2": 20}
_LEN_HEADER = {"PPTH": 16, "PQTZ": 24, "PCOB": 24, "PCO2": 20,
"PVBR": 16, "PWAV": 20, "PWV2": 20,
"PWV3": 24, "PWV5": 24, "PWV4": 24, "PWV7": 24, "PWV6": 20, "PWVC": 14}
def _wrap(kind: str, body: bytes) -> bytes:
@@ -92,85 +111,390 @@ def beatgrid_tag(beats: list[tuple[int, float, float]]) -> bytes:
return _wrap("PQTZ", body)
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None) -> bytes:
comment = b""
# ---- what rekordbox needs before it will show a grid or cues ------------------
#
# Measured on a rekordbox-written stick by removing tags one at a time: with
# only PPTH + PQTZ + PCOB in the `.DAT` — the grid and cue tags byte-for-byte
# rekordbox's own — rekordbox shows NO grid and NO hot cues. Adding PVBR alone
# is not enough, nor PWAV + PWV2 alone; the full `.DAT` is. So every `.DAT`
# carries all three. (The `.EXT` and `.2EX` waveforms only affect drawing.)
#: PVBR's entry count: 400 seek points plus one trailing value.
_PVBR_ENTRIES = 401
def vbr_tag(total_samples: int = 0) -> bytes:
"""`PVBR` as rekordbox writes it for a constant-rate file.
400 zero seek offsets, then the track's length in SAMPLES — for an MP3,
frames x 1152 (Demo Track 1: 6601 x 1152 = 7604352). An `.m4a` gets zero
there too. A VBR MP3 presumably gets real offsets; none of the reference
tracks is VBR, so that is unmeasured, and a zero index is what an `.m4a`
carries and rekordbox accepts.
"""
body = struct.pack(">I", 0) + bytes(4 * (_PVBR_ENTRIES - 1)) + struct.pack(
">I", max(0, int(total_samples)))
return _wrap("PVBR", body)
def mp3_samples(path: Path) -> int:
"""An MP3's length in samples — frames x 1152 — for `PVBR`; 0 otherwise.
rekordbox writes this value only for MP3s (every `.m4a` carries 0).
"""
if path.suffix.lower() != ".mp3":
return 0
try:
import mutagen
info = mutagen.File(str(path)).info
return int(round(info.length * info.sample_rate / 1152)) * 1152
except Exception: # an unreadable header costs the seek hint, not the export
return 0
#: PWAV height = K * sqrt(rms) + B, fitted against rekordbox's own previews of
#: eight tracks (mean error 3.4 on the 0-31 scale, correlation 0.8). An absolute
#: scale, not normalised per track — a quiet master draws smaller, as in rekordbox.
_PWAV_K, _PWAV_B = 37.6, -5.2
def preview_tags(rms, brightness) -> list[bytes]:
"""`PWAV` (400 columns) and `PWV2` (100) from per-column RMS and brightness.
`PWAV`: one byte per column — whiteness (3 bits) << 5 | height (5 bits).
`PWV2`: a 4-bit height per group of four `PWAV` columns, scaled so the
track's tallest column is 15; that reproduces rekordbox's own to a mean
error of 1.7. Whiteness loosely follows brightness in rekordbox's output
(it is cosmetic: the colour of the blue-to-white preview).
"""
import numpy as np
rms = np.asarray(rms, dtype=float)
heights = np.clip(np.round(_PWAV_K * np.sqrt(rms) + _PWAV_B), 0, 31).astype(int)
white = np.clip(np.round(2.5 + 10.0 * np.asarray(brightness, dtype=float)), 0, 5).astype(int)
pwav = bytes(int((w << 5) | h) for w, h in zip(white, heights))
tallest = max(int(heights.max()), 1)
grouped = heights.reshape(100, 4).max(axis=1)
pwv2 = bytes(int(v) for v in np.clip(np.round(grouped * 15 / tallest), 0, 15))
return [
_wrap("PWAV", struct.pack(">II", len(pwav), 0x10000) + pwav),
_wrap("PWV2", struct.pack(">II", len(pwv2), 0x10000) + pwv2),
]
# ---- the detail and 3-band waveforms (`.EXT` / `.2EX`) -------------------------
#
# These only affect DRAWING — rekordbox shows the grid and cues without them — but
# without them its song list has no preview and its deck draws a flat blue line,
# and it warns the device was "analyzed by an older version". All constants are
# fitted against rekordbox 7's own files for 12 local tracks, measured through
# `core.waveform` exactly as the exporter measures (per-band mean error ~8 on the
# 0-127 scale). rekordbox 7's song list draws `PWV6` — but ONLY for a track
# whose `content.contentLink` is set (see the OneLibrary exporter); with it NULL
# the row is plain blue whatever the files hold. `PWV4` is written by
# distribution matching, not per-column fitting (see `_PWV4_MAPS`).
#: PWV7 byte per band = top * (energy / its 99.5th percentile) ** gamma.
_PWV7 = ((88, 0.6), (92, 0.9), (68, 1.7)) # low, mid, high
#: PWV6: the same, over 1200 overview columns (column = mean of its frames).
_PWV6 = ((40, 0.5), (34, 0.5), (34, 0.5))
#: PWVC: a per-band gain, = C / (the band's 99.5th percentile), floored at 80 —
#: rekordbox's own values follow this to about +/-20%. What rekordbox does with
#: it is not known; it is reproduced rather than invented.
_PWVC_C, _PWVC_FLOOR = (20763.0, 15220.0, 12571.0), 80
#: PWV3/PWV5 height (5 bits) from overall energy: 28 * x ** 1.5.
_HEIGHT = (28, 1.5)
#: PWV5 colour (3 bits each) from each band's SHARE of the frame's energy.
_RGB = ((8.47, 0.54), (7.60, 0.47), (13.78, 1.83)) # red<-low, green<-mid, blue<-high
_OVERVIEW_COLUMNS = 1200
#: PWV4 — the 6-byte colour overview. NOT what rekordbox 7's song list draws
#: (that is PWV6: removing PWV6 from a rekordbox-written track left its row
#: empty, removing PWV4 changed nothing); written because every rekordbox file
#: carries it and its RGB mode and older players may read it. Per column: b0 overall level, b1 a
#: companion of b0, b2 the height, b3/b4/b5 the low/mid/high (red/green/blue)
#: levels. Two measured facts shape it: b4 and b5 are sampled at ONE instant per
#: column (their column-to-column correlation is 0.05 and 0.16, against ~0.6 for
#: the rest), and rekordbox's per-column bytes are too jumpy to reproduce one by
#: one — so each byte is a QUANTILE MAP, (normalised measurement knots, byte
#: knots), fitted on 12 tracks so the distribution matches rekordbox's (held-out
#: medians within a few levels, the same spiky top end). b2 and b1 follow from
#: the others by linear fits on rekordbox's own bytes (mean error 10 and 12).
_PWV4_MAPS = {
"b0": ((0.0, 0.1027, 0.1843, 0.3094, 0.3971, 0.4832, 0.5759, 0.6569, 0.731, 0.8102, 0.8973, 0.9419, 0.971, 1.1784),
(0, 17, 28, 45, 56, 62, 65, 69, 74, 115, 127, 127, 127, 127)),
"b3": ((0.0, 0.0135, 0.0473, 0.1407, 0.26, 0.3841, 0.5027, 0.5911, 0.6686, 0.7617, 0.8646, 0.9209, 0.9645, 1.1825),
(0, 1, 4, 15, 24.7, 37, 44, 54, 62, 68, 89, 107, 120, 127)),
"b4": ((0.0, 0.0305, 0.0654, 0.1307, 0.1855, 0.2325, 0.2819, 0.3342, 0.3977, 0.4809, 0.6036, 0.708, 0.8719, 1.2804),
(0, 2, 7, 12, 17, 21, 25, 30, 35, 43, 62, 109, 127, 127)),
"b5": ((0.0, 0.0077, 0.0223, 0.0511, 0.09, 0.1298, 0.1809, 0.2427, 0.3167, 0.4143, 0.5749, 0.7209, 0.863, 1.4313),
(0, 1, 4, 7, 10, 12, 16, 20, 24, 31, 60, 127, 127, 127)),
}
def _pwv4(bands) -> bytes:
import numpy as np
full = np.sqrt((bands ** 2).sum(axis=1))
x = np.column_stack([bands, full]) # low, mid, high, full
cols = [np.arange(len(x))[s] for s in even_slices(len(x), _OVERVIEW_COLUMNS)]
mean = np.array([x[i].mean(axis=0) if len(i) else np.zeros(4) for i in cols])
instant = np.array([x[i[len(i) // 2]] if len(i) else np.zeros(4) for i in cols])
def mapped(values, key):
ref = float(np.percentile(values, 99.5)) or 1.0
knots_x, knots_y = _PWV4_MAPS[key]
return np.clip(np.round(np.interp(values / ref, knots_x, knots_y)), 0, 127).astype(int)
b0, b3 = mapped(mean[:, 3], "b0"), mapped(mean[:, 0], "b3")
b4, b5 = mapped(instant[:, 1], "b4"), mapped(instant[:, 2], "b5")
b2 = np.clip(np.round(0.83 * np.maximum(b3, np.maximum(b4, b5)) + 11.6), 0, 127).astype(int)
b1 = np.clip(np.round(235.2 - 0.77 * b0), 0, 255).astype(int)
return np.column_stack([b0, b1, b2, b3, b4, b5]).astype(np.uint8).tobytes()
def _norm(x, top: float, gamma: float, cap: int):
import numpy as np
ref = float(np.percentile(x, 99.5)) or 1.0
return np.clip(np.round(top * np.clip(x / ref, 0, None) ** gamma), 0, cap).astype(int)
def waveform_tags(bands) -> tuple[list[bytes], list[bytes]]:
"""(`.EXT` tags, `.2EX` tags) from 150-per-second low/mid/high band energy.
`.EXT`: `PWV3` (detail, 1 byte: whiteness << 5 | height), `PWV5` (detail
colour, 2 bytes: rrr ggg bbb hhhhh 00) and `PWV4` (the RGB-mode colour
overview, 1200 x 6 bytes — see `_PWV4_MAPS`). `.2EX`: `PWV7` (3-band detail, one
byte per band), `PWV6` (3-band overview, 1200 columns) and `PWVC`. The frames
must already be on rekordbox's clock (`waveform.analyse(lead=offset)`).
"""
import numpy as np
bands = np.asarray(bands, dtype=float)
n = len(bands)
full = np.sqrt((bands ** 2).sum(axis=1))
share = bands / (bands.sum(axis=1, keepdims=True) + 1e-12)
height = _norm(full, *_HEIGHT, 31)
white = np.clip(np.round(2.5 + 10.0 * share[:, 2]), 0, 7).astype(int)
pwv3 = bytes(int((w << 5) | h) for w, h in zip(white, height))
rgb = [np.clip(np.round(k * share[:, i] + c), 0, 7).astype(int)
for i, (k, c) in enumerate(_RGB)]
pwv5 = b"".join(struct.pack(">H", (int(r) << 13) | (int(g) << 10) | (int(b) << 7) | (int(h) << 2))
for r, g, b, h in zip(*rgb, height))
pwv7 = np.stack([_norm(bands[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV7)], axis=1)
cols = np.array([bands[s].mean(axis=0) if n else np.zeros(3)
for s in even_slices(n, _OVERVIEW_COLUMNS)])
pwv6 = np.stack([_norm(cols[:, i], top, g, 127) for i, (top, g) in enumerate(_PWV6)], axis=1)
gains = [max(_PWVC_FLOOR, int(round(c / (float(np.percentile(bands[:, i], 99.5)) or 1.0))))
for i, c in enumerate(_PWVC_C)]
ext = [
_wrap("PWV3", struct.pack(">III", 1, n, 0x00960000) + pwv3),
_wrap("PWV5", struct.pack(">III", 2, n, 0x00960305) + pwv5),
_wrap("PWV4", struct.pack(">III", 6, _OVERVIEW_COLUMNS, 0) + _pwv4(bands)),
]
two_ex = [
_wrap("PWV7", struct.pack(">III", 3, n, 0x00960000) + pwv7.astype(np.uint8).tobytes()),
_wrap("PWV6", struct.pack(">II", 3, _OVERVIEW_COLUMNS) + pwv6.astype(np.uint8).tobytes()),
_wrap("PWVC", struct.pack(">H", 0) + struct.pack(">HHH", *[min(g, 0xFFFF) for g in gains])),
]
return ext, two_ex
def flat_preview_tags() -> list[bytes]:
"""Empty previews, for a file nothing could decode, so the grid and cues can
still show. That an all-zero preview satisfies rekordbox is an assumption,
by analogy with the all-zero PVBR every `.m4a` carries — not measured."""
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:
"""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""
red, green, blue = rgb or (0, 0, 0)
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
return struct.pack(
">4sIIIB3xIIB7xHHI",
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind,
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, length, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
0, beats or 0, 1 if beats else 0, len(comment),
) + comment + struct.pack(">4B", 0, red, green, blue) + bytes(
PCP2_ENTRY_LEN - 48 - len(comment)
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
# The colour is the palette CODE, then RGB: rekordbox draws from the code
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
length - 48 - len(comment_bytes)
)
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
first: int, last: int) -> bytes:
#: rekordbox's COMPACT `PCP2` entry: the first 44 bytes of a full one — no
#: comment and no colour tail. What rekordbox 7 appends when it ADDS a memory cue
#: on a stick (measured 2026-10-16, `fixtures/onelibrary-memory-edits`).
PCP2_COMPACT_LEN = 44
def pcp2_compact_entry(*, kind: int, time_ms: int, loop_ms: int | None,
beats: int | None, color_id: int = 0, hot_cue: int = 0) -> bytes:
"""A compact 44-byte `PCP2` entry, byte for byte as rekordbox 7 writes one
for a memory cue it adds: the same fields as `pcp2_entry` up to
`len_comment` (0), including the `1000` and the `1` after byte 28."""
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, PCP2_COMPACT_LEN, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, 0,
)
def relinked_memory_pcpts(entries: list[bytes]) -> list[bytes]:
"""A `PCOB` MEMORY list's entries with their link fields rewritten, as
rekordbox 7 leaves them after ANY add or delete (measured 2026-10-16,
`fixtures/onelibrary-memory-edits`): status (bytes 16-19) 0, and bytes 24-27 the
previous / next entry's INDEX IN THE LIST, 0xFFFF at either end — so every
entry changes when one is added or removed. rekordbox's exports agree on any
list of two or more; a lone exported entry is status 4, 0xFFFF/0xFFFF."""
n = len(entries)
out = []
for i, e in enumerate(entries):
prev = i - 1 if i > 0 else 0xFFFF
nxt = i + 1 if i < n - 1 else 0xFFFF
out.append(e[:16] + struct.pack(">I", 0) + e[20:24] + struct.pack(">HH", prev, nxt) + e[28:])
return out
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
bytes early.
Status is 0 on a hot cue and 4 on a memory cue, and rekordbox leaves the
linked-list order fields at 0xFFFF rather than linking the entries.
"""
return struct.pack(
">4sIIIIIHHBxHII",
b"PCPT", 12, PCPT_ENTRY_LEN, hot_cue,
4 if loop_ms is not None else 4, # status: 4 = active, as rekordbox writes
0x10000, first, last, kind, 1000,
b"PCPT", 28, PCPT_ENTRY_LEN, hot_cue,
0 if hot_cue else 4,
0x10000, 0xFFFF, 0xFFFF, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
) + bytes(16)
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
"""`PCOB` (+ `PCO2` in the .EXT) for one track's cues.
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`)."""
# 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))
`PCOB` is **split by pad**: the `.DAT` carries hot cues 1-3 and the `.EXT`
carries 4 and up, which is why the reader merges across both files. Memory
cues go in their own `PCOB` with `cue_type` 0. `PCO2` is the complete list
and only exists in the `.EXT`.
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)
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))
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.
"""
hot = [c for c in cues if c["hot_cue"]]
memory = [c for c in cues if not c["hot_cue"]]
tags: list[bytes] = []
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
# PCOB, one per kind, filtered to the pads this file is responsible for.
for cue_type, group in ((0, memory), (1, hot)):
chosen = [
c for c in group
if not c["hot_cue"] or ((c["hot_cue"] > 3) == extended)
] if cue_type == 1 else (group if not extended else [])
if not chosen:
continue
blob = b"".join(
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"],
first=0xFFFF if i == 0 else i,
last=i + 1 if i + 1 < len(chosen) else 0xFFFF)
for i, c in enumerate(chosen)
)
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
# shifts every following field and the reader sees garbage.
header = struct.pack(">IHHi", cue_type, 0, len(chosen), len(chosen))
tags.append(_wrap("PCOB", header + blob))
if extended and cues:
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"))
for c in cues
)
header = struct.pack(">IHH", 1 if hot else 0, len(cues), 0)
tags.append(_wrap("PCO2", header + blob))
return tags
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
"""The cue tags for one file, in the order and shape rekordbox writes them.
`.DAT`: `PCOB` hot (pads 1-3), `PCOB` memory (every memory cue).
`.EXT`: `PCOB` hot (pads 4 and up), `PCOB` memory (EMPTY), then `PCO2` hot
and `PCO2` memory — each the complete list of its kind.
**Every list is written even when empty.** A rekordbox file always carries
all of them, and a file missing one is not a shape rekordbox produces.
Hot cues are ordered by pad, HIGHEST first, which is also what it does.
"""
hot = sorted((c for c in cues if c["hot_cue"]), key=lambda c: -c["hot_cue"])
memory = sorted((c for c in cues if not c["hot_cue"]), key=lambda c: c["time_ms"])
if not extended:
return [_pcob(1, [c for c in hot if c["hot_cue"] <= 3]), _pcob(0, memory)]
return [
_pcob(1, [c for c in hot if c["hot_cue"] > 3]),
_pcob(0, []),
_pco2(1, hot),
_pco2(0, memory),
]
#: `PMAI` + len_header + len_file + four unknowns.
_FILE_HEADER_LEN = 28
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)
def anlz_bytes(tags: list[bytes]) -> bytes:
"""Assemble an ANLZ file from built tag bytes."""
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,
)
path.write_bytes(header + body)
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))
return path
@@ -0,0 +1,85 @@
"""Cover art the way a Pioneer library stores it: two small square JPEGs.
Measured on a rekordbox 7 USB export rather than assumed:
* two sizes per image — **80 x 80** (`<n>.jpg`) and **240 x 240** (`<n>_m.jpg`);
* **baseline JPEG at quality 85, 4:2:0** — its quantisation table is libjpeg's
standard table scaled to exactly 85, with no EXIF and a plain JFIF header;
* a non-square cover is **letterboxed onto black**, aspect kept and centred.
Motorola's 4112 x 1112 art matches rekordbox's own to a mean of 1.8 levels
that way; a centre crop is off by 26, a stretch by 19.5.
Where the files go and how the database points at them is the target's business
(a OneLibrary drive: `PIONEER/Artwork/00001/`, see its exporter).
"""
from __future__ import annotations
import io
import logging
log = logging.getLogger(__name__)
SMALL, MEDIUM = 80, 240
#: A master.db library also keeps a LARGE copy: the cover itself, aspect kept,
#: scaled down to fit 800 px (never up) — Motorola's 4112 x 1112 art is stored
#: 800 x 216, a 640 or 300 px cover unchanged.
LARGE = 800
_QUALITY = 85
def _square(image, size: int):
from PIL import Image
fitted = image.copy()
fitted.thumbnail((size, size), Image.BICUBIC) # the closest of Pillow's filters
canvas = Image.new("RGB", (size, size), (0, 0, 0))
canvas.paste(fitted, ((size - fitted.width) // 2, (size - fitted.height) // 2))
return canvas
def _jpeg(image) -> bytes:
out = io.BytesIO()
# subsampling=2 is 4:2:0; progressive/optimize off = the baseline rekordbox writes.
image.save(out, format="JPEG", quality=_QUALITY, subsampling=2,
progressive=False, optimize=False)
return out.getvalue()
def _open(data: bytes):
from PIL import Image
try:
with Image.open(io.BytesIO(data)) as src:
src.load()
return src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
except Exception as ex: # noqa: BLE001 — any unreadable image
log.warning("could not read cover art (%s); exporting without it", ex)
return None
def library_jpegs(data: bytes) -> tuple[bytes, bytes, bytes] | None:
"""(large, 240 px, 80 px) for a `master.db` library — `artwork.jpg`,
`artwork_m.jpg`, `artwork_s.jpg` — or None when the image cannot be read."""
from PIL import Image
rgb = _open(data)
if rgb is None:
return None
large = rgb.copy()
large.thumbnail((LARGE, LARGE), Image.BICUBIC)
return _jpeg(large), _jpeg(_square(rgb, MEDIUM)), _jpeg(_square(rgb, SMALL))
def pioneer_jpegs(data: bytes) -> tuple[bytes, bytes] | None:
"""(80 px JPEG, 240 px JPEG) from any image the source library holds, or None
when it cannot be read — a bad cover costs the artwork, not the export."""
try:
from PIL import Image
with Image.open(io.BytesIO(data)) as src:
src.load()
rgb = src.convert("RGB") # PNG alpha / palette / CMYK -> RGB
except Exception as ex: # noqa: BLE001 — any unreadable image
log.warning("could not read cover art (%s); exporting without it", ex)
return None
return _jpeg(_square(rgb, SMALL)), _jpeg(_square(rgb, MEDIUM))
@@ -31,8 +31,18 @@ def markers_from_beats(
) -> list[GridMarker]:
"""Collapse a per-beat grid into the generic marker list.
`times` are seconds, `bpms` the tempo in force at each beat. A marker is
emitted for the first beat and wherever the tempo changes.
`times` are seconds, `bpms` the tempo in force at each beat, `beats` the
beat-in-bar (1-4) of each. A marker is emitted for the start of the grid and
wherever the tempo changes.
**The first marker goes on the first DOWNBEAT**, not the first beat. In the
generic model the first marker is bar 1 (Traktor's convention), but a
Pioneer grid often starts mid-bar: Motorola's opens on beat 3 at 0.026 s,
with its first downbeat at 0.986 s. Put the marker on the first beat and
every bar lands two beats early — in Traktor after an import, and on the
CDJ after an export. The beats before it are not lost: a grid extends back
to the start of the track from its first marker, and `beats_from_markers`
writes them back numbered as they were.
"""
if not times or not bpms:
return []
@@ -42,6 +52,12 @@ def markers_from_beats(
if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON:
out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None))
last_bpm = float(bpm)
if beats and out:
# The first tempo run ends where the second marker starts (or never).
run_end = out[1].start if len(out) > 1 else float("inf")
downbeat = next((t for t, b in zip(times, beats) if int(b) == 1 and t < run_end), None)
if downbeat is not None:
out[0] = out[0].model_copy(update={"start": float(downbeat)})
return out
@@ -54,8 +70,10 @@ def beats_from_markers(
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
each marker, which is how Rekordbox numbers bars.
Not used by the read-only adapter, but it is the inverse of
`markers_from_beats` and belongs beside it.
The first marker's tempo also runs BACKWARDS to the start of the track: a
grid covers the whole track in Traktor and in rekordbox alike, and a marker
placed on the first downbeat (see `markers_from_beats`) has beats before it
— numbered 4, 3, … counting back, which reproduces rekordbox's own grid.
"""
beat_nums: list[int] = []
bpms: list[float] = []
@@ -63,6 +81,15 @@ def beats_from_markers(
if not markers:
return beat_nums, bpms, times
ordered = sorted(markers, key=lambda m: m.start)
first = next((m for m in ordered if m.bpm > 0), None)
if first is not None:
step = 60.0 / first.bpm
lead = int((first.start + 1e-9) // step) # whole beats that fit before it
for k in range(lead, 0, -1):
beat_nums.append((-k) % 4 + 1)
bpms.append(first.bpm)
times.append(first.start - k * step)
for i, m in enumerate(ordered):
if m.bpm <= 0:
continue
@@ -72,9 +99,15 @@ def beats_from_markers(
n = 1
# Guard against a zero/negative span producing an endless loop.
while t < end - 1e-9 and step > 0:
beat_nums.append(n)
bpms.append(m.bpm)
times.append(t)
# A beat before the audio starts is skipped but still COUNTED, so the
# next one keeps its place in the bar. The generic model can hold one
# (a Traktor grid anchored inside an MP3's header frame reads
# negative); rekordbox stores no negative times, and clamping it to 0
# would invent a beat there.
if t >= 0.0:
beat_nums.append(n)
bpms.append(m.bpm)
times.append(t)
n = n % 4 + 1
t += step
return beat_nums, bpms, times
@@ -30,7 +30,8 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from .cue_types import WRITABLE_CUE_TYPES
from . import memory_palette, palette, track_palette
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps
@@ -54,22 +55,25 @@ def capabilities_for(
writable=not cloud_synced,
readonly_cause="cloud_synced" if cloud_synced else None,
cues=CueCapabilities(
# Hot cues are writable: djmdCue rows plus the contentCue JSON
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
# Rekordbox is the only platform that has them, and the two-platform
# promotion rule says a one-platform concept does not become an
# editing feature.
# Hot AND memory cues are writable: djmdCue rows plus the
# contentCue JSON mirror, kept in step (memory cues: measured
# 2026-10-16, kit M1).
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# Rekordbox is the only platform with memory cues, so they are
# projected and PRESERVED but not editable (two-platform rule).
memory_cues=True,
max_memory_cues=None, # unlimited
# rekordbox stops storing at 10, silently; the store refuses the 11th.
max_memory_cues=MAX_MEMORY_CUES,
# A memory cue's colour is its own 8-colour palette (`Color`, not
# `ColorTableIndex`) — see `memory_palette`.
memory_color="palette",
memory_palette=list(memory_palette.SWATCHES),
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's 16 swatches (all
# measured, see `palette`), offered in rekordbox's own order.
color="palette",
palette=[], # TODO milestone 2: the built-in cue colour table
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # djmdCue.Comment
loops="cue_type",
),
@@ -83,7 +87,17 @@ 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 []),
media_kinds=["audio"],
# 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,
artwork=False,
artwork_note=None,
),
@@ -36,6 +36,10 @@ has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
from __future__ import annotations
MEMORY_KIND = 0
#: rekordbox stores at most this many memory cues per track — on the computer
#: AND on a stick — and enforces it SILENTLY (measured 2026-10-16: MEMORY simply
#: stops storing), so Konduktor refuses the next one itself, with a reason.
MAX_MEMORY_CUES = 10
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
CUE_TYPES = ["cue", "loop"]
@@ -0,0 +1,239 @@
"""The "Rekordbox Export" target: a USB stick's legacy Device Library (`export.pdb`).
What Rekordbox lists as a stick's **Device Library**, and what pre-OneLibrary
players (CDJ-2000NXS2, many XDJs) read. Not to be confused with the "Rekordbox
Library" target (`export.py`), which writes a COMPUTER library (`master.db`)
that Rekordbox never reads from a stick.
## Shared with the OneLibrary target — deliberately
Rekordbox's own device export writes `export.pdb` AND `exportLibrary.db`, both
pointing at ONE set of audio, analysis files and artwork. This target does the
same: the analysis files are written by the OneLibrary exporter's own
`_write_anlz`, at the same paths (`PIONEER/USBANLZ/P0xx/xxxxxxxx/`), and the
artwork is the `a<n>.jpg` pair the OneLibrary target also writes (rekordbox's
`a` files are the ones `export.pdb` names; OneLibrary's `image` table names the
byte-identical `b` files). When both targets are ticked, whichever runs second
finds the analysis already on the stick — written moments ago by the first, as
the runner clears the previous export before copying — and reuses it rather
than decoding every track again.
## The database
`pdb.PdbWriter` fills rekordbox's own empty device library (a template) with
rows; see `pdb.py` for the format and why a template. Values follow a real
rekordbox 7 device export:
* `bitmask` 0xC0700 — the same value as OneLibrary's `content.contentLink`,
which is what makes rekordbox draw a track's song-list preview there;
* `u2` = the track id + 0x600 (rekordbox: masterContentId + 0x600);
* `u3`/`u4` = 0: they are the halves of rekordbox's `masterDbId`, the link to a
computer's collection, which a Konduktor export does not claim;
* `u5` 0x29 (= `analysedBits` 41), `u6` the file type, `u7` 3;
* strings "ON" for kuvo_public / autoload_hotcues; the three unnamed strings
rekordbox fills from its phrase analysis are left EMPTY — this exporter
writes no phrases, and whether players care is what the device test checks.
"""
from __future__ import annotations
import logging
from datetime import date
from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from . import artwork, pdb, track_palette
from .projection import render_key
log = logging.getLogger(__name__)
PDB_DIR = Path("PIONEER") / "rekordbox"
OTHER_PLAYLIST = "Other"
BITMASK = 0xC0700
ANALYSED = 0x29
class RekordboxDeviceExporter:
platform = "rekordbox_export"
menu_order = 30
display_name = "Rekordbox Export"
library_filename = str(PDB_DIR / "export.pdb")
#: A player looks for `PIONEER/` at the root of the stick.
drive_root = True
def capabilities(self):
"""What a stick's device library can hold — the OneLibrary target's
answer, since both describe the same drive and its analysis files."""
from ..onelibrary.export import OneLibraryExporter
return OneLibraryExporter().capabilities()
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# Imported here, not at module level: the OneLibrary package imports this
# package's modules, and a module-level import would be circular.
from ..onelibrary.export import (
OneLibraryExporter, _anlz_dir, _audio_format, _drive_relative, _file_type, _kbps,
)
root = Path(destination)
(root / PDB_DIR).mkdir(parents=True, exist_ok=True)
today = date.today().isoformat()
drive = OneLibraryExporter()
extra: list[Path] = []
ids = {name: {} for name in ("artist", "album", "genre", "label", "key")}
rows = {t: [] for t in (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES,
pdb.LABELS, pdb.KEYS, pdb.ARTWORK)}
builders = {"artist": (pdb.ARTISTS, pdb.artist_row), "album": (pdb.ALBUMS, pdb.album_row),
"genre": (pdb.GENRES, pdb.id_string_row), "label": (pdb.LABELS, pdb.id_string_row),
"key": (pdb.KEYS, pdb.key_row)}
def lookup(kind: str, name: str | None) -> int:
if not name:
return 0
table = ids[kind]
if name not in table:
table[name] = len(table) + 1
t, build = builders[kind]
rows[t].append(build(table[name], name))
return table[name]
by_source: dict[str, int] = {}
art_n = 0
total = len(payload.tracks)
for n, item in enumerate(payload.tracks, start=1):
payload.checkpoint(f"Writing the device library: {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
track = item.track
by_source[item.source_id] = n
rel = _drive_relative(item.destination, root)
anlz_rel = f"{_anlz_dir(rel)}/ANLZ0000.DAT"
dat = root / anlz_rel.lstrip("/")
extra += self._analysis(drive, item, rel, dat)
artwork_id = 0
art = self._art(item, root, art_n + 1)
if art:
art_n += 1
artwork_id = art_n
extra += art
rows[pdb.ARTWORK].append(pdb.id_string_row(art_n, f"/PIONEER/Artwork/00001/a{art_n}.jpg"))
sample_rate, bit_depth = _audio_format(item.destination)
try:
size = item.destination.stat().st_size
except OSError:
size = 0
year = int(track.release_date[:4]) if (track.release_date or "")[:4].isdigit() else 0
rows[pdb.TRACKS].append(pdb.track_row(
{
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": sample_rate or 0,
"file_size": size, "u2": n + 0x600,
"artwork_id": artwork_id,
"key_id": lookup("key", render_key(track.key_wheel, track.key_mode)),
"label_id": lookup("label", track.label),
"bitrate": _kbps(track.bitrate) or 0,
"tempo": int(round((track.bpm or 0) * 100)),
"genre_id": lookup("genre", track.genre),
"album_id": lookup("album", track.album),
"artist_id": lookup("artist", track.artist),
"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,
},
{
"kuvo_public": "ON", "autoload_hotcues": "ON",
"date_added": today, "release_date": track.release_date or "",
"mix_name": track.mix or "", "analyze_path": anlz_rel,
"analyze_date": today, "comment": track.comment or "",
"title": track.title or item.destination.stem,
"filename": item.destination.name, "file_path": rel,
},
))
tree, entries = self._playlists(payload, by_source)
writer = pdb.PdbWriter(pdb.template("export.pdb"))
for table in (pdb.TRACKS, pdb.GENRES, pdb.ARTISTS, pdb.ALBUMS, pdb.LABELS, pdb.KEYS, pdb.ARTWORK):
writer.fill(table, rows[table])
writer.fill(pdb.PLAYLIST_TREE, tree)
writer.fill(pdb.PLAYLIST_ENTRIES, entries)
writer.stamp_history_date(date.today())
writer.stamp_track_count(len(rows[pdb.TRACKS]))
library = root / self.library_filename
library.write_bytes(writer.render())
ext = root / PDB_DIR / "exportExt.pdb"
ext.write_bytes(pdb.template("exportExt.pdb"))
return WrittenLibrary(library=library, extra=[ext, *extra])
# ---- shared drive files ---------------------------------------------------
@staticmethod
def _analysis(drive, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""This track's analysis files — reused when the OneLibrary target has
just written them in this same export, else written the same way."""
existing = [dat.with_suffix(s) for s in (".DAT", ".EXT", ".2EX") if dat.with_suffix(s).exists()]
if dat.exists() and dat.with_suffix(".EXT").exists():
return existing
return drive._write_anlz(item, rel, dat)
@staticmethod
def _art(item: ExportTrack, root: Path, n: int) -> list[Path]:
"""`a<n>.jpg` / `a<n>_m.jpg` — the pair export.pdb's artwork table names,
numbered in track order exactly as the OneLibrary target numbers them."""
if not item.art:
return []
folder = root / "PIONEER" / "Artwork" / "00001"
small, medium = folder / f"a{n}.jpg", folder / f"a{n}_m.jpg"
if small.exists() and medium.exists():
return [small, medium]
jpegs = artwork.pioneer_jpegs(item.art[0])
if jpegs is None:
return []
folder.mkdir(parents=True, exist_ok=True)
small.write_bytes(jpegs[0])
medium.write_bytes(jpegs[1])
return [small, medium]
# ---- playlists ------------------------------------------------------------
@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."""
tree: list[bytes] = []
entries: list[bytes] = []
next_id = [0]
siblings: dict[int, int] = {}
def add(name: str, parent: int, *, folder: bool) -> int:
next_id[0] += 1
order = siblings.get(parent, 0)
siblings[parent] = order + 1
tree.append(pdb.playlist_tree_row(next_id[0], parent, order, name, folder=folder))
return next_id[0]
def fill(playlist_id: int, source_ids: list[str]) -> None:
index = 0
for source_id in source_ids:
track_id = by_source.get(source_id)
if track_id is not None:
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
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
for depth in range(1, len(playlist.folders) + 1):
branch = tuple(playlist.folders[:depth])
if branch not in folders:
folders[branch] = add(branch[-1], folders[branch[:-1]], folder=True)
parent = folders[branch]
fill(add(playlist.name, parent, folder=False), playlist.track_ids)
claimed = {t for p in payload.playlists for t in p.track_ids}
loose = [t.source_id for t in payload.tracks if t.source_id not in claimed]
if loose:
fill(add(OTHER_PLAYLIST, root, folder=False), loose)
return tree, entries
Loaded 100 of 413 files, more files were not shown because too many files have changed in this diff. Show more