mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Compare commits
100
Commits
reskin
...
v0.2.9-b19
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
422297d890 | ||
|
|
ee48e80440 | ||
|
|
0aeb5019ad | ||
|
|
1f2ca18e8a | ||
|
|
19a604f730 | ||
|
|
83b0978b14 | ||
|
|
0ced274f73 | ||
|
|
fc4e7804b3 | ||
|
|
77b063ba0e | ||
|
|
16c3552be6 | ||
|
|
32cfb034e2 | ||
|
|
b70798a0fe | ||
|
|
4c51f57fe9 | ||
|
|
7b2d6de411 | ||
|
|
8230722105 | ||
|
|
1464b1e211 | ||
|
|
10f175b206 | ||
|
|
a65ef959b2 | ||
|
|
87cbd3720e | ||
|
|
591f2bc791 | ||
|
|
ebe30c1128 | ||
|
|
cd1914216f | ||
|
|
d10b11f8eb | ||
|
|
79a8a843c5 | ||
|
|
0204a322ff | ||
|
|
05051e7056 | ||
|
|
b5dabbc8a0 | ||
|
|
86bbb7b961 | ||
|
|
d474c662db | ||
|
|
a0df683fee | ||
|
|
3385b794e9 | ||
|
|
2c352b76a1 | ||
|
|
40630ff78e | ||
|
|
966f3fe8c5 | ||
|
|
a03b9056a9 | ||
|
|
26b556d975 | ||
|
|
c87444bda5 | ||
|
|
7ba71981c8 | ||
|
|
89c7dade25 | ||
|
|
b154df430a | ||
|
|
e5c7b67626 | ||
|
|
9f79f5a849 | ||
|
|
c8b86100f0 | ||
|
|
0fac84cb73 | ||
|
|
71ee877784 | ||
|
|
920146f2c0 | ||
|
|
ba7b662b93 | ||
|
|
e5fb0f0dbb | ||
|
|
e8a53eee07 | ||
|
|
36a6df4d3b | ||
|
|
72a52d3291 | ||
|
|
c3571fd054 | ||
|
|
b5b3dd04c3 | ||
|
|
4e9472c14a | ||
|
|
957525393b | ||
|
|
bdc62f2c1b | ||
|
|
7960a5a68f | ||
|
|
c5280a95f2 | ||
|
|
e73fa05e1f | ||
|
|
775e94168c | ||
|
|
2784879872 | ||
|
|
702e5d86a6 | ||
|
|
d7f8768d4c | ||
|
|
5c193e0ab7 | ||
|
|
badf12b991 | ||
|
|
ecc0e4c8df | ||
|
|
ae03a93f98 | ||
|
|
c560876c02 | ||
|
|
e805635383 | ||
|
|
27471a82cd | ||
|
|
28b705173e | ||
|
|
681add852a | ||
|
|
376569ec75 | ||
|
|
b5b0fa91fe | ||
|
|
34b18893ef | ||
|
|
2c02019bb2 | ||
|
|
08c53e1150 | ||
|
|
9be2c029b2 | ||
|
|
a6f96d5943 | ||
|
|
bd35418a89 | ||
|
|
86b26e3229 | ||
|
|
bb9f6e2bd3 | ||
|
|
3a9dc90344 | ||
|
|
4b9716d47a | ||
|
|
0b909a84f4 | ||
|
|
157c2c0a04 | ||
|
|
4878d82671 | ||
|
|
c2f5191962 | ||
|
|
99d590a051 | ||
|
|
eccd352ae5 | ||
|
|
90beeef226 | ||
|
|
84947bb0bb | ||
|
|
08884ca6bd | ||
|
|
9851c3c056 | ||
|
|
17b68c40bb | ||
|
|
cb76277016 | ||
|
|
24b9dfe49f | ||
|
|
513808a6d2 | ||
|
|
85f01f6723 | ||
|
|
2e04bcb9f6 |
No files matched your search
@@ -55,10 +55,11 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
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
|
# build_sidecar.* stages it as
|
||||||
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
|
# frontend/src-tauri/binaries/konduktor-sidecar/
|
||||||
# which tauri.conf.json's externalBin bundles into the app.
|
# 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
|
- name: Install backend deps
|
||||||
working-directory: backend
|
working-directory: backend
|
||||||
run: |
|
run: |
|
||||||
@@ -114,6 +115,52 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
path: installer/*
|
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.
|
# 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
|
# Runs once, after both builds succeed, so the two matrix jobs never race to
|
||||||
# create the same tag/release.
|
# create the same tag/release.
|
||||||
@@ -122,6 +169,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: write # required to create the tag + release
|
contents: write # required to create the tag + release
|
||||||
|
pull-requests: read # to read the merged PR's patch notes
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -136,14 +184,55 @@ jobs:
|
|||||||
- name: Download installers from both builds
|
- name: Download installers from both builds
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/download-artifact@v4
|
||||||
with:
|
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/…
|
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
|
||||||
|
|
||||||
|
# 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.
|
||||||
|
- 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)
|
||||||
|
if found:
|
||||||
|
with open("release-notes.md", "w", encoding="utf-8") as f:
|
||||||
|
f.write("## 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
|
- name: Publish release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
||||||
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
||||||
target_commitish: ${{ github.sha }}
|
target_commitish: ${{ github.sha }}
|
||||||
generate_release_notes: true # auto changelog from commits/PRs since last release
|
body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }}
|
||||||
|
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
|
||||||
fail_on_unmatched_files: true
|
fail_on_unmatched_files: true
|
||||||
files: artifacts/**/*
|
files: artifacts/**/*
|
||||||
@@ -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.
|
||||||
@@ -47,3 +47,7 @@ backend/userprefs.json
|
|||||||
# build_sidecar.sh are source and ARE tracked.
|
# build_sidecar.sh are source and ARE tracked.
|
||||||
backend/build/
|
backend/build/
|
||||||
backend/dist/
|
backend/dist/
|
||||||
|
|
||||||
|
# ---- Stem engine (PyInstaller onedir build) ----
|
||||||
|
engine/build/
|
||||||
|
engine/dist/
|
||||||
+101
-29
@@ -1,21 +1,27 @@
|
|||||||
# Building Konduktor for Windows
|
# Building Konduktor for Windows
|
||||||
|
|
||||||
The desktop app can't be cross-compiled — a Windows build must be produced **on
|
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
|
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
|
||||||
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
|
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
|
The recipe is the same as on macOS. Only the toolchain install and the
|
||||||
sidecar-build command differ.
|
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
|
## 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
|
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
|
||||||
development with C++" from the Visual Studio Build Tools installer.
|
development with C++" from the Visual Studio Build Tools installer.
|
||||||
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
|
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
|
||||||
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
|
get the Evergreen runtime from Microsoft (Tauri's installer can also
|
||||||
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
|
bootstrap it).
|
||||||
4. **Node 18+** — <https://nodejs.org>.
|
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:
|
Then, from the repo root:
|
||||||
|
|
||||||
@@ -33,49 +39,115 @@ npm install
|
|||||||
cd ..
|
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
|
```powershell
|
||||||
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
|
|
||||||
cd backend
|
cd backend
|
||||||
.\.venv\Scripts\Activate.ps1 # if not already active
|
.\.venv\Scripts\python.exe test_save_fidelity.py
|
||||||
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
|
```
|
||||||
|
|
||||||
|
## 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 ..
|
cd ..
|
||||||
|
|
||||||
# 2) Build the app
|
# 2) Build the app (its beforeBuildCommand runs the Vite build)
|
||||||
cd frontend
|
cd frontend
|
||||||
npx tauri build
|
npx tauri build
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`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
|
## Output
|
||||||
|
|
||||||
Installers land in:
|
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_<version>_x64-setup.exe
|
||||||
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_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
|
## Rebuilding after changes
|
||||||
|
|
||||||
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
|
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
|
||||||
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
|
then `npx tauri build`). Frontend-only changes just need
|
||||||
(its `beforeBuildCommand` rebuilds the web app).
|
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
|
||||||
|
|
||||||
|
## 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
|
## Known Windows caveats
|
||||||
|
|
||||||
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
|
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
|
||||||
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
|
launch shows a "Windows protected your PC" prompt. Click **More info → Run
|
||||||
(Signing is a future step.)
|
anyway**.
|
||||||
- **Mixed content is already handled.** The webview is forced to the `http`
|
- **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
|
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.
|
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
|
||||||
Leave that setting as-is.
|
Leave that setting as-is.
|
||||||
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
|
- **The sidecar is a console app, but no console appears.** It's frozen with
|
||||||
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
|
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
|
||||||
without a visible window; if a console flashes on launch, tell me and we'll add
|
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
|
||||||
the `CREATE_NO_WINDOW` spawn flag.
|
flashes.
|
||||||
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
|
- **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.
|
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
|
||||||
@@ -1,213 +1,141 @@
|
|||||||
# Konduktor
|
<p align="center">
|
||||||
|
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
|
||||||
|
</p>
|
||||||
|
|
||||||
**A fast, modern home for your Traktor collection.**
|
<h1 align="center">Konduktor</h1>
|
||||||
|
|
||||||
Konduktor is a lightweight desktop-style app for DJs who run **Native
|
<p align="center">
|
||||||
Instruments Traktor** (Pro 4 / NML v20). It opens your existing
|
<b>Prep your tracks and run your DJ libraries in one fast app.</b><br>
|
||||||
`collection.nml`, gives you a beautiful dark library to explore, and lets you
|
Traktor, Rekordbox, or the USB stick in your pocket.
|
||||||
build playlists and prep tracks — without launching the whole heavyweight
|
</p>
|
||||||
Traktor app just to tidy up your tags or drop a few cue points.
|
|
||||||
|
|
||||||
Your collection stays exactly where it is. Konduktor reads and writes the same
|
<p align="center">
|
||||||
file Traktor uses, so everything you do shows up next time you open Traktor.
|
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|

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

|
||||||
|
|
||||||
|
**Play stem files as stems.** Load a stem file and the deck splits into
|
||||||
|
drums, bass, synths and vocals, each drawn in its own lane. Click a lane's
|
||||||
|
button to mute it, Alt/Option-click to solo it, or use Q W E R.
|
||||||
|
|
||||||
|
**Convert to Stems.** In a Traktor collection, right-click any tracks and
|
||||||
|
choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and
|
||||||
|
beatgrid intact.
|
||||||
|
|
||||||
|
- The separation runs on your own computer, so your music isn't sent to an
|
||||||
|
online service.
|
||||||
|
- Replace the originals, or save the stems to a folder and add them as new
|
||||||
|
tracks.
|
||||||
|
- Convert a whole playlist in one go.
|
||||||
|
|
||||||
|
## Let it do the boring parts
|
||||||
|
|
||||||
|
| Auto Hotcues | Analyze |
|
||||||
|
|:---:|:---:|
|
||||||
|
|  |  |
|
||||||
|
| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. |
|
||||||
|
|
||||||
|
## Export to USB for CDJs, or other platforms
|
||||||
|
|
||||||
|
<img src="docs/screenshots/export.png" align="right" width="380" alt="An export set for OneLibrary, Traktor and Rekordbox">
|
||||||
|
|
||||||
|
Make an **export** in the sidebar, drag playlists onto it, and press Export.
|
||||||
|
One stick can carry a Traktor collection, a OneLibrary library for current
|
||||||
|
CDJs and a Rekordbox Device Library for older players, all sharing **one copy
|
||||||
|
of the audio**.
|
||||||
|
|
||||||
|
- Hotcues, memory cues, loops, grids, keys and cover art are converted for
|
||||||
|
each platform.
|
||||||
|
- Playlists stay linked: edit a playlist, re-export, and the stick catches up.
|
||||||
|
- Re-exports copy only what changed, so updating a stick is quick.
|
||||||
|
- Konduktor only ever clears a folder that it wrote itself.
|
||||||
|
|
||||||
|
<br clear="right">
|
||||||
|
|
||||||
|
## Your library is safe
|
||||||
|
|
||||||
|
- **Saves are surgical.** A Traktor save changes only the entries you edited.
|
||||||
|
The rest of the file stays byte-for-byte identical.
|
||||||
|
- **Backups and history.** Every Traktor save makes a backup first and is kept
|
||||||
|
in a version history that you can restore from in the app.
|
||||||
|
- **Nothing is written until you press Save.** Discard changes throws away
|
||||||
|
everything you did since your last save.
|
||||||
|
- Tag edits are also written into the audio files themselves, so other apps
|
||||||
|
see them too.
|
||||||
|
|
||||||
|
## And also
|
||||||
|
|
||||||
|
- A fast library with search, filters, sorting and columns you can rearrange,
|
||||||
|
even with thousands of tracks.
|
||||||
|
- Edit tags inline or in a full tag and cover-art editor.
|
||||||
|
- Drag and drop tracks onto playlists, exports or the deck, and drag playlists
|
||||||
|
to reorganise them.
|
||||||
|
- If you open a Traktor collection on a different computer or drive,
|
||||||
|
Konduktor finds the missing files for you.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Getting started
|
## Get Konduktor
|
||||||
|
|
||||||
Konduktor runs as two small local servers (a Python backend and a web
|
Download the latest build from
|
||||||
frontend). Do the one-time setup, then start them — the same steps work on
|
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
|
||||||
macOS, Linux, and Windows.
|
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
|
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
|
||||||
dependencies:
|
> `collection.nml` when it quits, which would overwrite your changes.
|
||||||
|
|
||||||
```bash
|
Want to run it from source or build it yourself? See
|
||||||
cd backend
|
[docs/BUILDING.md](docs/BUILDING.md).
|
||||||
python3 -m venv .venv # Windows: python -m venv .venv
|
|
||||||
```
|
|
||||||
|
|
||||||
Activate it, then install:
|
## License
|
||||||
|
|
||||||
```bash
|
[AGPL-3.0](LICENSE)
|
||||||
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.
|
|
||||||
@@ -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 # the local Rekordbox library
|
||||||
python bench_grid_detect.py path/to/collection.nml path/to/master.db
|
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 --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:
|
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
|
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 = argparse.ArgumentParser()
|
||||||
ap.add_argument("libraries", nargs="*", type=Path)
|
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("--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()
|
args = ap.parse_args()
|
||||||
|
|
||||||
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
|
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:
|
for name, audio, r0, rb in refs:
|
||||||
t0 = time.perf_counter()
|
t0 = time.perf_counter()
|
||||||
try:
|
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
|
except Exception as ex: # a failure is a data point, not a crash
|
||||||
print(f" FAIL {name[:48]:48} {ex}")
|
print(f" FAIL {name[:48]:48} {ex}")
|
||||||
rows.append(None)
|
rows.append(None)
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
"""Benchmark key detection (`core/key_detect.py`).
|
||||||
|
|
||||||
|
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
|
||||||
|
compare rather than a pass/fail.
|
||||||
|
|
||||||
|
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
|
||||||
|
python bench_key_detect.py ~/Music # files with a key TAG
|
||||||
|
|
||||||
|
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
|
||||||
|
and the number to quote; the model never trained on it (see
|
||||||
|
`train_key_model.py`). A folder's key tags were written by some other
|
||||||
|
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
|
||||||
|
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
|
||||||
|
source) count once, by title.
|
||||||
|
|
||||||
|
Errors are classed the MIREX way, because they are not equally wrong for a
|
||||||
|
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
|
||||||
|
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
|
||||||
|
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import warnings
|
||||||
|
from collections import Counter
|
||||||
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
|
||||||
|
from konduktor.core import key_detect, musical_key # noqa: E402
|
||||||
|
|
||||||
|
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
|
||||||
|
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
|
||||||
|
|
||||||
|
|
||||||
|
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
|
||||||
|
"""How a detected (wheel, mode) relates to the reference."""
|
||||||
|
(dw, dm), (rw, rm) = det, ref
|
||||||
|
if (dw, dm) == (rw, rm):
|
||||||
|
return "exact"
|
||||||
|
if dw == rw:
|
||||||
|
return "relative"
|
||||||
|
if dm == rm and (dw - rw) % 12 in (1, 11):
|
||||||
|
return "fifth"
|
||||||
|
if dm != rm:
|
||||||
|
major, minor = (dw, rw) if dm == "major" else (rw, dw)
|
||||||
|
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
|
||||||
|
return "parallel"
|
||||||
|
return "other"
|
||||||
|
|
||||||
|
|
||||||
|
def parse_any(text: str) -> tuple[int, str] | None:
|
||||||
|
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
|
||||||
|
w, m = musical_key.parse(text)
|
||||||
|
return (w, m) if w else None
|
||||||
|
|
||||||
|
|
||||||
|
def _tag_key(path: Path) -> tuple[str, str] | None:
|
||||||
|
import mutagen
|
||||||
|
|
||||||
|
try:
|
||||||
|
f = mutagen.File(path)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
if not f or not f.tags:
|
||||||
|
return None
|
||||||
|
t = f.tags
|
||||||
|
|
||||||
|
def has(name: str) -> bool:
|
||||||
|
try:
|
||||||
|
return name in t
|
||||||
|
except ValueError: # a Vorbis comment refuses an MP4-style atom name
|
||||||
|
return False
|
||||||
|
|
||||||
|
key = title = None
|
||||||
|
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
|
||||||
|
if has(name):
|
||||||
|
v = t[name]
|
||||||
|
v = v.text[0] if hasattr(v, "text") else v[0]
|
||||||
|
key = v.decode() if isinstance(v, bytes) else str(v)
|
||||||
|
break
|
||||||
|
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
|
||||||
|
if has(name):
|
||||||
|
v = t[name]
|
||||||
|
title = str(v.text[0] if hasattr(v, "text") else v[0])
|
||||||
|
break
|
||||||
|
return (key, title or path.stem) if key else None
|
||||||
|
|
||||||
|
|
||||||
|
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
|
||||||
|
seen, out = set(), []
|
||||||
|
for root in roots:
|
||||||
|
for dp, dirs, files in os.walk(root):
|
||||||
|
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
|
||||||
|
for name in sorted(files):
|
||||||
|
p = Path(dp) / name
|
||||||
|
if p.suffix.lower() not in AUDIO or name.startswith("."):
|
||||||
|
continue
|
||||||
|
tagged = _tag_key(p)
|
||||||
|
if not tagged or not (ref := parse_any(tagged[0])):
|
||||||
|
continue
|
||||||
|
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
|
||||||
|
if title not in seen:
|
||||||
|
seen.add(title)
|
||||||
|
out.append((p, ref, tagged[1]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
|
||||||
|
out = []
|
||||||
|
for f in sorted((gs / "annotations/key").glob("*.key")):
|
||||||
|
audio = gs / "audio" / f"{f.stem}.mp3"
|
||||||
|
ref = parse_any(f.read_text()) # "C minor"
|
||||||
|
if audio.exists() and ref:
|
||||||
|
out.append((audio, ref, f.stem))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _detect(path: Path):
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
try:
|
||||||
|
r = key_detect.detect_key(str(path))
|
||||||
|
except Exception as ex: # an undecodable file is reported, not fatal
|
||||||
|
return None, str(ex)
|
||||||
|
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
|
||||||
|
|
||||||
|
|
||||||
|
def run(refs, label: str, verbose: bool) -> None:
|
||||||
|
with ProcessPoolExecutor() as ex:
|
||||||
|
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
|
||||||
|
rels, misses = [], []
|
||||||
|
for (path, ref, title), (det, err) in zip(refs, results):
|
||||||
|
if det is None:
|
||||||
|
print(f" could not analyse {title}: {err or 'silent / too short'}")
|
||||||
|
continue
|
||||||
|
rel = relation(det[:2], ref)
|
||||||
|
rels.append(rel)
|
||||||
|
if rel != "exact":
|
||||||
|
misses.append((title, ref, det, rel))
|
||||||
|
n = len(rels)
|
||||||
|
if not n:
|
||||||
|
print(f"{label}: nothing to score")
|
||||||
|
return
|
||||||
|
c = Counter(rels)
|
||||||
|
print(f"\n{label}: {n} tracks")
|
||||||
|
for k in WEIGHT:
|
||||||
|
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
|
||||||
|
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
|
||||||
|
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
|
||||||
|
if verbose:
|
||||||
|
for title, ref, det, rel in misses:
|
||||||
|
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
|
||||||
|
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
|
||||||
|
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
|
||||||
|
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
|
||||||
|
a = ap.parse_args()
|
||||||
|
if not a.folders and not a.giantsteps:
|
||||||
|
ap.error("give --giantsteps and/or folders")
|
||||||
|
if a.giantsteps:
|
||||||
|
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
|
||||||
|
if a.folders:
|
||||||
|
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
|
||||||
|
sys.exit(0)
|
||||||
+17
-10
@@ -1,6 +1,7 @@
|
|||||||
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
|
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
|
||||||
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
|
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
|
||||||
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
|
# 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.:
|
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
|
||||||
# cd backend
|
# cd backend
|
||||||
@@ -15,13 +16,19 @@ Set-Location $Root
|
|||||||
$Py = Join-Path $Root ".venv\Scripts\python.exe"
|
$Py = Join-Path $Root ".venv\Scripts\python.exe"
|
||||||
if (-not (Test-Path $Py)) { $Py = "python" }
|
if (-not (Test-Path $Py)) { $Py = "python" }
|
||||||
|
|
||||||
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
|
||||||
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
|
# 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
|
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
|
||||||
# resolves it. (rustc must be on PATH.)
|
|
||||||
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
|
|
||||||
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
|
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
|
||||||
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
|
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
|
||||||
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
|
$Staged = Join-Path $Dest "konduktor-sidecar"
|
||||||
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
|
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
|
||||||
|
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
|
||||||
|
Write-Host "Staged: $Staged\"
|
||||||
+17
-21
@@ -1,7 +1,8 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Build the frozen backend sidecar (single-file binary) with PyInstaller and
|
# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage
|
||||||
# stage it for Tauri as binaries/konduktor-sidecar-<target-triple>.
|
# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which
|
||||||
# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/…
|
# 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).
|
# One-time: pip install -r requirements-build.txt (into the backend venv).
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
|
|||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
PY="${PY:-.venv/bin/python}"
|
PY="${PY:-.venv/bin/python}"
|
||||||
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
"$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
|
# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc
|
||||||
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
|
# signs the executable AND its collected libraries (Python, the .so/.dylib
|
||||||
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
|
# files) with a matching identity. Re-signing only some of them desyncs the
|
||||||
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
|
# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on
|
||||||
# fails with "different Team IDs" and the sidecar dies on launch (which makes
|
# launch (the app then shows "Konduktor couldn't start"). The app bundle is
|
||||||
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
|
# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||||
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
# which seals this folder as a resource without re-signing it.
|
||||||
# which seals this binary without re-signing it.
|
|
||||||
|
|
||||||
# Stage for Tauri: the sidecar must be named with the host target triple so the
|
# Stage for Tauri. Replace the whole folder so no file from an older build
|
||||||
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
|
# survives; `cp -R` keeps PyInstaller's symlinks as symlinks.
|
||||||
if command -v rustc >/dev/null 2>&1; then
|
|
||||||
TRIPLE="$(rustc -vV | sed -n 's/host: //p')"
|
|
||||||
DEST="$ROOT/../frontend/src-tauri/binaries"
|
DEST="$ROOT/../frontend/src-tauri/binaries"
|
||||||
mkdir -p "$DEST"
|
mkdir -p "$DEST"
|
||||||
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE"
|
rm -rf "$DEST/konduktor-sidecar"
|
||||||
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
|
cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
|
||||||
else
|
echo "Staged: $DEST/konduktor-sidecar/"
|
||||||
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
|
|
||||||
fi
|
|
||||||
@@ -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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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`.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,38 @@
|
|||||||
|
# Memory-cue edits rekordbox 7 made on a stick
|
||||||
|
|
||||||
|
Analysis files of six tracks on a OneLibrary test stick written by
|
||||||
|
rekordbox, before and after **rekordbox 7 itself** edited their MEMORY cues
|
||||||
|
(kit M2, 2026-10-16; the stick was backed up first and restored afterwards).
|
||||||
|
`test_onelibrary_anlz.py` replays each edit with Konduktor's helpers on
|
||||||
|
`before/` and compares the memory lists with `after/` byte for byte.
|
||||||
|
|
||||||
|
Only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for byte — the
|
||||||
|
waveforms were dropped, as in `onelibrary-goober/`. There is no database and
|
||||||
|
no audio: `exportLibrary.db` and both pdbs had NO row change for any of these
|
||||||
|
edits (memory cues on a stick live only in the analysis files).
|
||||||
|
|
||||||
|
| File | Track | Edit (one per track) |
|
||||||
|
|---|---|---|
|
||||||
|
| `black-bloc` | Justin Hawkes – Black Bloc (VIP) | memory cue ADDED at 2:11.206 |
|
||||||
|
| `formula` | RL Grime & Juelz – Formula (IMANU Remix) | 4-beat memory LOOP added at 1:20.378 |
|
||||||
|
| `lift-it` | Tian – Lift It (Hexa Remix) | 8 memory cues added (2 → 10, the cap) |
|
||||||
|
| `wtf` | Result – WTF (Phace Remix) | the memory loop at 1:53 recoloured Blue |
|
||||||
|
| `sell-my-soul` | Bensley, Justin Hawkes & Kumarion – Sell My Soul | comment "Loopy" on the memory loop at 1:18 |
|
||||||
|
| `doomed` | Nemean – Doomed | the memory loop at 2:01 DELETED |
|
||||||
|
|
||||||
|
What they show (the full write-up is in
|
||||||
|
`.claude/discussions/discuss-memory-cues-2026-10-16.md`, kit M2):
|
||||||
|
- `.DAT` `PCOB` memory list: a new entry is PREPENDED; every entry has status 0
|
||||||
|
and bytes 24–27 = previous / next index in the list (`ffff` at the ends), so
|
||||||
|
any add or delete relinks the whole list; the header i32 at offset 20 is
|
||||||
|
count − 1.
|
||||||
|
- `.EXT` `PCO2` memory list: a new entry is APPENDED in rekordbox's compact
|
||||||
|
44-byte form; the others stay byte-identical. The `.EXT`'s `PCOB` memory list
|
||||||
|
stays empty.
|
||||||
|
- When rekordbox rewrites a `.DAT` (any memory add or delete), it ALSO
|
||||||
|
re-sorts the untouched hot-cue `PCOB` into ascending pad order (an export
|
||||||
|
writes it highest pad first); the entries themselves are unchanged.
|
||||||
|
Konduktor changes only the list it edits, so the test compares that tag's
|
||||||
|
entries regardless of order.
|
||||||
|
- Colour: `PCP2` byte 28, 1-based (Blue = 7), 0 = none. Comment: UTF-16BE + NUL
|
||||||
|
at byte 44, `len_comment` at 40. Neither touches the `.DAT`.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -56,3 +56,16 @@ implementation — open and write to it.
|
|||||||
|
|
||||||
Not loaded by the tests; kept as documentation, and as the starting point if
|
Not loaded by the tests; kept as documentation, and as the starting point if
|
||||||
Konduktor ever needs to create a drive from nothing.
|
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`.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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.
|
||||||
Executable
BIN
Binary file not shown.
BIN
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
|
||||||
|
}
|
||||||
@@ -1,6 +1,14 @@
|
|||||||
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
|
# 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
|
# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the
|
||||||
# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
|
# 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:
|
# The tricky bits this handles:
|
||||||
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
|
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
|
||||||
@@ -10,7 +18,7 @@
|
|||||||
# - python-multipart is imported as `multipart` by starlette → hidden import
|
# - python-multipart is imported as `multipart` by starlette → hidden import
|
||||||
# - dulwich (version-history backups) imports git backends dynamically →
|
# - dulwich (version-history backups) imports git backends dynamically →
|
||||||
# collect_submodules('dulwich')
|
# collect_submodules('dulwich')
|
||||||
from PyInstaller.utils.hooks import collect_submodules, collect_all
|
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
|
||||||
|
|
||||||
hiddenimports = []
|
hiddenimports = []
|
||||||
datas = []
|
datas = []
|
||||||
@@ -20,8 +28,9 @@ binaries = []
|
|||||||
for pkg in ("uvicorn", "xsdata", "dulwich"):
|
for pkg in ("uvicorn", "xsdata", "dulwich"):
|
||||||
hiddenimports += collect_submodules(pkg)
|
hiddenimports += collect_submodules(pkg)
|
||||||
|
|
||||||
# Native standard extras — grab modules + shared libs + any data.
|
# Native standard extras — grab modules + shared libs + any data. PyAV (`av`)
|
||||||
for pkg in ("uvloop", "httptools", "websockets"):
|
# 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)
|
d, b, h = collect_all(pkg)
|
||||||
datas += d
|
datas += d
|
||||||
binaries += b
|
binaries += b
|
||||||
@@ -30,11 +39,38 @@ for pkg in ("uvloop", "httptools", "websockets"):
|
|||||||
# Imported by name, not statically discoverable.
|
# Imported by name, not statically discoverable.
|
||||||
hiddenimports += ["multipart", "anyio"]
|
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
|
# 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
|
# 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.
|
# app version — see konduktor/__init__.py). Path is relative to this spec.
|
||||||
datas += [("../frontend/package.json", ".")]
|
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(
|
a = Analysis(
|
||||||
["sidecar.py"],
|
["sidecar.py"],
|
||||||
pathex=[],
|
pathex=[],
|
||||||
@@ -54,9 +90,8 @@ pyz = PYZ(a.pure)
|
|||||||
exe = EXE(
|
exe = EXE(
|
||||||
pyz,
|
pyz,
|
||||||
a.scripts,
|
a.scripts,
|
||||||
a.binaries,
|
|
||||||
a.datas,
|
|
||||||
[],
|
[],
|
||||||
|
exclude_binaries=True,
|
||||||
name="konduktor-sidecar",
|
name="konduktor-sidecar",
|
||||||
debug=False,
|
debug=False,
|
||||||
bootloader_ignore_signals=False,
|
bootloader_ignore_signals=False,
|
||||||
@@ -69,3 +104,12 @@ exe = EXE(
|
|||||||
codesign_identity=None,
|
codesign_identity=None,
|
||||||
entitlements_file=None,
|
entitlements_file=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
coll = COLLECT(
|
||||||
|
exe,
|
||||||
|
a.binaries,
|
||||||
|
a.datas,
|
||||||
|
strip=False,
|
||||||
|
upx=False,
|
||||||
|
name="konduktor-sidecar",
|
||||||
|
)
|
||||||
@@ -5,28 +5,30 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
|
|||||||
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
|
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
|
||||||
* a ``TrackIndex`` — the generic READ projection built from it.
|
* a ``TrackIndex`` — the generic READ projection built from it.
|
||||||
|
|
||||||
**Read-only.** Every command is refused and `capabilities.writable` is False with
|
**Editable when opened as THE library**, with parity with the Rekordbox adapter
|
||||||
cause `platform_incomplete`, so the UI never offers an edit in the first place;
|
as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
|
||||||
the raises here are the backstop, not the mechanism.
|
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
|
What a write must look like was MEASURED by diffing a stick before and after
|
||||||
to make a OneLibrary drive a readable SOURCE — the half an import into another
|
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
|
||||||
library needs — and every genuinely unknown part of the format sits on the write
|
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
|
||||||
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
|
playlists, hot cues and the beatgrid so far; adding and removing tracks next —
|
||||||
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
|
and every command not written yet is refused, with its capability flag False so
|
||||||
the update counters a drive uses to reconcile edits made on hardware. None of
|
the UI never offers it.
|
||||||
those has to be guessed at to read a drive, and none of them should be guessed at
|
|
||||||
at all.
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
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.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.pathmap import PathMapping, common_dir_prefix
|
||||||
from ...core.query import TrackIndex
|
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 capabilities as caps
|
||||||
from . import projection
|
from . import projection
|
||||||
from .store import OneLibraryStore
|
from .store import OneLibraryStore
|
||||||
@@ -42,23 +44,28 @@ ATTRIBUTE_SMART = 4
|
|||||||
class OneLibraryAdapter:
|
class OneLibraryAdapter:
|
||||||
platform = "onelibrary"
|
platform = "onelibrary"
|
||||||
|
|
||||||
def __init__(self, path: Path):
|
def __init__(self, path: Path, *, read_only: bool = False):
|
||||||
self.path = Path(path)
|
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._index = TrackIndex()
|
||||||
self._rebuild()
|
self._rebuild()
|
||||||
|
|
||||||
# ---- projection maintenance -----------------------------------------
|
# ---- projection maintenance -----------------------------------------
|
||||||
def _rebuild(self) -> None:
|
def _rebuild(self) -> None:
|
||||||
self._index.rebuild(
|
from ...core.stem_file import is_stem_file
|
||||||
[
|
|
||||||
projection.to_track(row, self._drive_path(row))
|
tracks = []
|
||||||
for row in self._store.iter_content()
|
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:
|
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
|
return str(resolved) if resolved is not None else None
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
@@ -70,14 +77,27 @@ class OneLibraryAdapter:
|
|||||||
self._store.close()
|
self._store.close()
|
||||||
|
|
||||||
def reload(self) -> None:
|
def reload(self) -> None:
|
||||||
self._store._load()
|
"""Re-read the drive, DISCARDING unsaved edits."""
|
||||||
|
self._store.discard()
|
||||||
self._rebuild()
|
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 --------------------------------------------------------
|
# ---- identity --------------------------------------------------------
|
||||||
def capabilities(self) -> Capabilities:
|
def capabilities(self) -> Capabilities:
|
||||||
return caps.capabilities_for(
|
return caps.capabilities_for(
|
||||||
device_name=self._store.device_name,
|
device_name=self._store.device_name,
|
||||||
version=self._store.db_version,
|
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 ------------------------------------------------------------
|
# ---- read ------------------------------------------------------------
|
||||||
@@ -144,7 +164,9 @@ class OneLibraryAdapter:
|
|||||||
rather than an absence, and treating 0 as a real id would orphan every
|
rather than an absence, and treating 0 as a real id would orphan every
|
||||||
top-level playlist.
|
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] = {}
|
nodes: dict[str, PlaylistNode] = {}
|
||||||
parents: dict[str, str] = {}
|
parents: dict[str, str] = {}
|
||||||
|
|
||||||
@@ -164,13 +186,14 @@ class OneLibraryAdapter:
|
|||||||
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
|
||||||
children=[],
|
children=[],
|
||||||
selectable=kind == "playlist",
|
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.
|
# `capabilities.writable` tells the UI why, once.
|
||||||
can_add_tracks=False,
|
can_add_tracks=writable and kind == "playlist",
|
||||||
can_reorder=False,
|
can_reorder=writable and kind == "playlist",
|
||||||
can_rename=False,
|
can_rename=writable,
|
||||||
can_delete=False,
|
can_delete=writable,
|
||||||
can_contain_children=kind == "folder",
|
can_contain_children=kind == "folder",
|
||||||
|
can_move=writable,
|
||||||
)
|
)
|
||||||
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
|
||||||
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
parents[node_id] = "root" if parent in ("0", "", "None") else parent
|
||||||
@@ -201,6 +224,9 @@ class OneLibraryAdapter:
|
|||||||
def audio_path(self, track_id: str):
|
def audio_path(self, track_id: str):
|
||||||
return self._store.audio_path(track_id)
|
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:
|
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||||
"""Ignored: a drive's paths are relative to wherever it is mounted.
|
"""Ignored: a drive's paths are relative to wherever it is mounted.
|
||||||
|
|
||||||
@@ -211,6 +237,13 @@ class OneLibraryAdapter:
|
|||||||
"""
|
"""
|
||||||
return None
|
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:
|
def path_prefix_suggestions(self) -> dict:
|
||||||
paths = self._store.all_audio_paths()
|
paths = self._store.all_audio_paths()
|
||||||
primary = common_dir_prefix(paths)
|
primary = common_dir_prefix(paths)
|
||||||
@@ -229,83 +262,324 @@ class OneLibraryAdapter:
|
|||||||
# ---- save -------------------------------------------------------------
|
# ---- save -------------------------------------------------------------
|
||||||
@property
|
@property
|
||||||
def dirty(self) -> bool:
|
def dirty(self) -> bool:
|
||||||
return False
|
return self._store.dirty
|
||||||
|
|
||||||
def save(self):
|
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:
|
def snapshot(self) -> bytes:
|
||||||
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
|
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
|
||||||
|
|
||||||
# ---- commands: all refused -------------------------------------------
|
# ---- commands -----------------------------------------------------------
|
||||||
def _readonly_reason(self, what: str) -> str:
|
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."
|
return f"{what} is not supported yet for OneLibrary drives."
|
||||||
|
|
||||||
def _refuse(self, what: str):
|
def _refuse(self, what: str):
|
||||||
raise Unsupported(self._readonly_reason(what))
|
raise Unsupported(self._readonly_reason(what))
|
||||||
|
|
||||||
def add_tracks(self, items: list) -> list[str]:
|
def _require_writable(self, what: str) -> None:
|
||||||
self._refuse("Adding tracks")
|
"""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:
|
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:
|
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_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||||
self._refuse("Editing cover art")
|
self._refuse("Editing cover art")
|
||||||
|
|
||||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
def _refresh_cues(self, track_id: str) -> TrackCues:
|
||||||
self._refuse("Editing cues")
|
"""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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
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:
|
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||||
raise Unsupported("OneLibrary has no beatgrid lock")
|
raise Unsupported("OneLibrary has no beatgrid lock")
|
||||||
@@ -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"]
|
__all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from_anlz"]
|
||||||
|
|
||||||
|
|
||||||
def beats_from_pqtz(anlz) -> tuple[list[float], list[float]] | None:
|
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
|
||||||
"""Per-beat ``(times_sec, bpms)`` from a parsed ANLZ file's `PQTZ` tag.
|
"""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
|
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
|
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", []):
|
for tag in getattr(anlz, "tags", []):
|
||||||
if tag.type != "PQTZ":
|
if tag.type != "PQTZ":
|
||||||
continue
|
continue
|
||||||
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
|
entries = tag.entries
|
||||||
if not entries:
|
if not entries:
|
||||||
return None
|
return None
|
||||||
times: list[float] = []
|
times: list[float] = []
|
||||||
bpms: list[float] = []
|
bpms: list[float] = []
|
||||||
|
beats: list[int] = []
|
||||||
for e in entries:
|
for e in entries:
|
||||||
try:
|
try:
|
||||||
times.append(int(e.time) / 1000.0)
|
time, tempo, beat = int(e.time) / 1000.0, int(e.tempo) / 100.0, int(e.beat)
|
||||||
bpms.append(int(e.tempo) / 100.0)
|
|
||||||
except (AttributeError, TypeError, ValueError):
|
except (AttributeError, TypeError, ValueError):
|
||||||
continue
|
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
|
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
|
Opened as THE library, a drive is writable, and the per-feature flags say which
|
||||||
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
|
edits have landed: track metadata, playlists, hot cues, the grid, and adding
|
||||||
cloud-synced Rekordbox library is refused permanently to protect the user's other
|
and removing tracks, so the UI never offers an edit the adapter
|
||||||
machines; a OneLibrary drive simply has no write path yet, and the UI must word
|
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
|
||||||
those two very differently.
|
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
|
With `writable=False` the per-feature flags still report what the FORMAT
|
||||||
being blanked to false, because that is what `writable=False` is for: the UI can
|
supports rather than being blanked, because that is what the library-level flag
|
||||||
show a drive's cues and grid honestly, and say once, in one place, that the whole
|
is for: the UI can show a drive's cues and grid honestly and say once, in one
|
||||||
library is read-only. Blanking them would claim OneLibrary has no hot cues.
|
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
|
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
|
getting them wrong later would be a silent data bug rather than a missing
|
||||||
feature:
|
feature:
|
||||||
|
|
||||||
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
|
* cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
|
||||||
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
|
and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
|
||||||
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
|
RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
|
||||||
"palette" because `djmdCue` stores an index into a built-in table — the same
|
16 swatches and both are written. (This was first read as "free RGB" off the
|
||||||
vendor, two genuinely different representations.
|
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
|
* 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
|
as Traktor and Rekordbox, and NOT the `separate_bank` the original
|
||||||
multi-platform plan assumed.
|
multi-platform plan assumed.
|
||||||
@@ -34,44 +36,61 @@ from ...core.capabilities import (
|
|||||||
SaveCapabilities,
|
SaveCapabilities,
|
||||||
TrackCapabilities,
|
TrackCapabilities,
|
||||||
)
|
)
|
||||||
|
from ..rekordbox import memory_palette, 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,
|
# 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`).
|
# so the bank really is 1..8 (see `cues.py`).
|
||||||
HOTCUE_SLOTS = 8
|
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(
|
return Capabilities(
|
||||||
platform="onelibrary",
|
platform="onelibrary",
|
||||||
version=version,
|
version=version,
|
||||||
# A roadmap gap, not a protective refusal — the UI words the two
|
writable=not read_only,
|
||||||
# differently, which is the whole reason `readonly_cause` exists.
|
readonly_cause="browsing" if read_only else None,
|
||||||
writable=False,
|
|
||||||
readonly_cause="platform_incomplete",
|
|
||||||
cues=CueCapabilities(
|
cues=CueCapabilities(
|
||||||
editable=False,
|
editable=True,
|
||||||
hotcue_slots=HOTCUE_SLOTS,
|
hotcue_slots=HOTCUE_SLOTS,
|
||||||
slot_labels="letter",
|
slot_labels="letter",
|
||||||
# OneLibrary carries memory cues, as Rekordbox does. They are
|
# Memory cues, editable as in Rekordbox — in the ANLZ files, the
|
||||||
# projected and preserved; nothing here is editable anyway.
|
# way rekordbox 7 edits them on a stick (measured, kit M2).
|
||||||
memory_cues=True,
|
memory_cues=True,
|
||||||
max_memory_cues=None,
|
max_memory_cues=MAX_MEMORY_CUES,
|
||||||
types=["cue", "loop"],
|
memory_color="palette",
|
||||||
color="free", # PCO2 stores RGB per cue, not a palette index
|
memory_palette=list(memory_palette.SWATCHES),
|
||||||
palette=[],
|
types=WRITABLE_CUE_TYPES,
|
||||||
|
color="palette",
|
||||||
|
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||||
named=True, # PCO2 carries a per-cue comment
|
named=True, # PCO2 carries a per-cue comment
|
||||||
loops="cue_type",
|
loops="cue_type",
|
||||||
),
|
),
|
||||||
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
|
# The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
|
||||||
# survive an export — so the format is flexible even though Konduktor
|
# No per-track grid lock exists in the format.
|
||||||
# does not write it here.
|
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
|
||||||
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
|
|
||||||
tracks=TrackCapabilities(
|
tracks=TrackCapabilities(
|
||||||
rating_max=5, # stored 0-5 directly, as in master.db
|
rating_max=5, # stored 0-5 directly, as in master.db
|
||||||
editable_fields=[],
|
# The Rekordbox adapter's set: `producer`/`mix` have no column.
|
||||||
media_kinds=["audio"],
|
editable_fields=sorted(editable_fields or []),
|
||||||
# The drive has an `image` table and an Artwork folder, but nothing
|
media_kinds=["audio", "stem"],
|
||||||
# is wired up to read them yet.
|
# 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,
|
||||||
|
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=False,
|
||||||
artwork_note=None,
|
artwork_note=None,
|
||||||
),
|
),
|
||||||
@@ -80,13 +99,18 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
|
|||||||
# A drive carries no smart playlists: rekordbox resolves them to
|
# A drive carries no smart playlists: rekordbox resolves them to
|
||||||
# static lists on export, because a CDJ cannot evaluate rules.
|
# static lists on export, because a CDJ cannot evaluate rules.
|
||||||
smart="none",
|
smart="none",
|
||||||
reorder=False,
|
reorder=True,
|
||||||
),
|
),
|
||||||
save=SaveCapabilities(
|
save=SaveCapabilities(
|
||||||
app_name="OneLibrary",
|
# Named for the DRIVE ("Save to Goober"): a person has several
|
||||||
library_label=device_name or "exportLibrary.db",
|
# sticks, and "Save to OneLibrary" would not say which.
|
||||||
# Nothing is written, so nothing can be overwritten by another app.
|
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",
|
overwrite_risk="none",
|
||||||
|
managed_by_export=managed_by_export,
|
||||||
# A drive is a database plus N analysis files plus the audio itself,
|
# 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
|
# so there is no single blob that IS the library — the same reason
|
||||||
# Rekordbox libraries are not versioned.
|
# Rekordbox libraries are not versioned.
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from ...core.model import CuePoint
|
from ...core.model import CuePoint
|
||||||
|
from ..rekordbox import memory_palette, palette
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
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.
|
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
|
||||||
MEMORY_SLOT = 0
|
MEMORY_SLOT = 0
|
||||||
|
|
||||||
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
|
# PCO2/PCOB entry kinds. The value is the same in both tags.
|
||||||
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
|
|
||||||
ENTRY_CUE = 1
|
ENTRY_CUE = 1
|
||||||
ENTRY_LOOP = 2
|
ENTRY_LOOP = 2
|
||||||
|
|
||||||
|
|
||||||
def _entry_kind(value) -> int:
|
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:
|
try:
|
||||||
return int(value)
|
return int(value)
|
||||||
except (TypeError, ValueError):
|
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
|
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
|
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.
|
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:
|
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)
|
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
|
||||||
except (AttributeError, TypeError, ValueError):
|
except (AttributeError, TypeError, ValueError):
|
||||||
return None
|
return None
|
||||||
@@ -78,7 +87,7 @@ def _color(entry) -> str | None:
|
|||||||
return f"#{r:02X}{g:02X}{b:02X}"
|
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."""
|
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
|
||||||
try:
|
try:
|
||||||
hot_cue = int(entry.hot_cue)
|
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
|
slot = None if role == "memory" else hot_cue - 1
|
||||||
|
|
||||||
comment = getattr(entry, "comment", None)
|
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(
|
return CuePoint(
|
||||||
name=(str(comment) or None) if comment else None,
|
name=(str(comment) or None) if comment else None,
|
||||||
type="loop" if length > 0 else "cue",
|
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,
|
start=start_ms / 1000.0,
|
||||||
length=length,
|
length=length,
|
||||||
slot=slot,
|
slot=slot,
|
||||||
color=_color(entry) if with_color else None,
|
color=color,
|
||||||
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
|
# Editable on a drive opened for editing (the caller says so), memory
|
||||||
# command. `capabilities.writable` is what the UI actually gates on;
|
# cues included; browsing a device is read-only.
|
||||||
# this keeps the per-cue answer consistent with it.
|
editable=editable,
|
||||||
editable=False,
|
readonly_reason=None if editable else "platform_managed",
|
||||||
readonly_reason="platform_managed",
|
|
||||||
grid_marker=None,
|
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:
|
def _entries(anlz, tag_type: str) -> list:
|
||||||
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
|
"""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 = []
|
out: list = []
|
||||||
for tag in getattr(anlz, "tags", []):
|
for tag in getattr(anlz, "tags", []):
|
||||||
if tag.type != tag_type:
|
if tag.type == tag_type:
|
||||||
continue
|
out.extend(tag.entries)
|
||||||
content = getattr(tag.struct, "content", None)
|
|
||||||
out.extend(getattr(content, "entries", None) or [])
|
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
|
||||||
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
|
"""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
|
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.
|
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:
|
for f in files:
|
||||||
pco2.extend(_entries(f, "PCO2"))
|
pco2.extend(_entries(f, "PCO2"))
|
||||||
if 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:
|
else:
|
||||||
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
|
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
|
||||||
# .EXT the rest, so either alone is an incomplete bank.
|
# .EXT the rest, so either alone is an incomplete bank.
|
||||||
pcob: list = []
|
pcob: list = []
|
||||||
for f in files:
|
for f in files:
|
||||||
pcob.extend(_entries(f, "PCOB"))
|
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)
|
return _dedupe(cues)
|
||||||
|
|
||||||
@@ -168,18 +193,23 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
|
|||||||
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
|
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
|
||||||
"""Collapse the same cue appearing in more than one tag or file.
|
"""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
|
Identity is (role, slot, start, type, length) rather than the whole cue:
|
||||||
be described by both `PCOB` and `PCO2`, and by both files, and those copies
|
the same pad can be described by both `PCOB` and `PCO2`, and by both files,
|
||||||
agree on position while differing in how much detail they carry. The first
|
and those copies agree on all five while differing in how much detail they
|
||||||
one wins, which — given PCO2 is read first — is the richest.
|
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
|
Ordered by position, then by slot, so the projection is stable across reads
|
||||||
regardless of the order the tags happened to store.
|
regardless of the order the tags happened to store.
|
||||||
"""
|
"""
|
||||||
seen: set[tuple[str, int | None, int]] = set()
|
seen: set[tuple] = set()
|
||||||
out: list[CuePoint] = []
|
out: list[CuePoint] = []
|
||||||
for c in cues:
|
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:
|
if key in seen:
|
||||||
continue
|
continue
|
||||||
seen.add(key)
|
seen.add(key)
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
"""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, bpm, year, released,
|
||||||
|
comment, *fresh) in session.execute(text(
|
||||||
|
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
|
||||||
|
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
|
||||||
|
"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))), "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:
|
def _has_onelibrary_schema(path: Path) -> bool:
|
||||||
try:
|
try:
|
||||||
import sqlcipher3.dbapi2 as sqlcipher
|
import sqlcipher3.dbapi2 as sqlcipher
|
||||||
from pyrekordbox.devicelib_plus.database import BLOB
|
from pyrekordbox.onelibrary.database import BLOB
|
||||||
from pyrekordbox.utils import deobfuscate
|
from pyrekordbox.utils import deobfuscate
|
||||||
except ImportError: # pragma: no cover — dependency missing
|
except ImportError: # pragma: no cover — dependency missing
|
||||||
return False
|
return False
|
||||||
@@ -73,8 +73,8 @@ class OneLibraryDriver:
|
|||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def open(self, path: Path) -> OneLibraryAdapter:
|
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
|
||||||
return OneLibraryAdapter(path)
|
return OneLibraryAdapter(path, read_only=read_only)
|
||||||
|
|
||||||
def detect(self) -> list[dict]:
|
def detect(self) -> list[dict]:
|
||||||
return discovery.detect_libraries()
|
return discovery.detect_libraries()
|
||||||
|
|||||||
@@ -42,7 +42,10 @@ from datetime import date
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||||
|
from ...core.cue_colors import effective_color
|
||||||
from ..rekordbox import anlz_writer as W
|
from ..rekordbox import anlz_writer as W
|
||||||
|
from ..rekordbox import artwork, memory_palette, palette, timebase
|
||||||
|
from ..rekordbox.cue_types import MAX_MEMORY_CUES
|
||||||
from ..rekordbox.beatgrid import beats_from_markers
|
from ..rekordbox.beatgrid import beats_from_markers
|
||||||
from ..rekordbox.projection import render_key
|
from ..rekordbox.projection import render_key
|
||||||
from .capabilities import capabilities_for
|
from .capabilities import capabilities_for
|
||||||
@@ -51,11 +54,21 @@ from .layout import DB_SUBPATH
|
|||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
SCHEMA = Path(__file__).resolve().parents[3] / "fixtures" / "onelibrary" / "schema.sql"
|
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.
|
#: rekordbox writes this in `property.dbVersion` on a real export.
|
||||||
DB_VERSION = "1000"
|
DB_VERSION = "1000"
|
||||||
#: Seen on every track of a real export; semantics undocumented, copied as-is.
|
#: Seen on every track of a real export; semantics undocumented, copied as-is.
|
||||||
ANALYSED_BITS = 41
|
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"
|
OTHER_PLAYLIST = "Other"
|
||||||
|
|
||||||
@@ -84,8 +97,11 @@ def _anlz_dir(drive_relative: str) -> str:
|
|||||||
|
|
||||||
class OneLibraryExporter:
|
class OneLibraryExporter:
|
||||||
platform = "onelibrary"
|
platform = "onelibrary"
|
||||||
|
menu_order = 10
|
||||||
#: Relative to the drive root, which is what the destination folder is.
|
#: Relative to the drive root, which is what the destination folder is.
|
||||||
library_filename = str(Path("PIONEER") / DB_SUBPATH)
|
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):
|
def capabilities(self):
|
||||||
"""What a drive can hold — no device, no path, no library to read.
|
"""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
|
yes to. Leaving the adapter's answer here would have the UI report that
|
||||||
the thing it just wrote cannot be written.
|
the thing it just wrote cannot be written.
|
||||||
"""
|
"""
|
||||||
return capabilities_for().model_copy(
|
caps = capabilities_for()
|
||||||
update={"writable": True, "readonly_cause": None}
|
# 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:
|
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||||
import sqlcipher3.dbapi2 as sqlcipher
|
import sqlcipher3.dbapi2 as sqlcipher
|
||||||
from pyrekordbox.devicelib_plus.database import BLOB
|
from pyrekordbox.onelibrary.database import BLOB
|
||||||
from pyrekordbox.utils import deobfuscate
|
from pyrekordbox.utils import deobfuscate
|
||||||
|
|
||||||
root = Path(destination)
|
root = Path(destination)
|
||||||
library = root / "PIONEER" / DB_SUBPATH
|
library = root / "PIONEER" / DB_SUBPATH
|
||||||
library.parent.mkdir(parents=True, exist_ok=True)
|
library.parent.mkdir(parents=True, exist_ok=True)
|
||||||
if library.exists():
|
# SQLCipher will not re-key an existing file — and the WAL and shared
|
||||||
library.unlink() # SQLCipher will not re-key an existing file
|
# 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] = []
|
extra: list[Path] = []
|
||||||
con = sqlcipher.connect(str(library))
|
con = sqlcipher.connect(str(library))
|
||||||
@@ -118,6 +144,7 @@ class OneLibraryExporter:
|
|||||||
# stick is readable by any of them, which is the point of it.
|
# stick is readable by any of them, which is the point of it.
|
||||||
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
|
||||||
con.executescript(SCHEMA.read_text())
|
con.executescript(SCHEMA.read_text())
|
||||||
|
con.executescript(SEED.read_text(encoding="utf-8"))
|
||||||
extra += self._fill(con, payload, root)
|
extra += self._fill(con, payload, root)
|
||||||
con.commit()
|
con.commit()
|
||||||
finally:
|
finally:
|
||||||
@@ -128,10 +155,17 @@ class OneLibraryExporter:
|
|||||||
|
|
||||||
def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]:
|
def _fill(self, con, payload: ExportPayload, root: Path) -> list[Path]:
|
||||||
lookups = {name: {} for name in ("artist", "album", "genre", "label", "key")}
|
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] = []
|
written: list[Path] = []
|
||||||
by_source: dict[str, int] = {}
|
by_source: dict[str, int] = {}
|
||||||
|
|
||||||
|
total = len(payload.tracks)
|
||||||
for n, item in enumerate(payload.tracks, start=1):
|
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
|
by_source[item.source_id] = n
|
||||||
written += self._write_track(con, n, item, root, lookups)
|
written += self._write_track(con, n, item, root, lookups)
|
||||||
|
|
||||||
@@ -170,16 +204,18 @@ class OneLibraryExporter:
|
|||||||
size = item.destination.stat().st_size
|
size = item.destination.stat().st_size
|
||||||
except OSError:
|
except OSError:
|
||||||
size = 0
|
size = 0
|
||||||
|
sample_rate, bit_depth = _audio_format(item.destination)
|
||||||
|
image_id, art_files = self._write_art(con, item, root, lookups["image"])
|
||||||
|
|
||||||
con.execute(
|
con.execute(
|
||||||
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
|
"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, image_id, "
|
||||||
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
|
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
|
||||||
"fileType, bitrate, samplingRate, isHotCueAutoLoadOn, "
|
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
|
||||||
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
|
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
|
||||||
"analysisDataFilePath, analysedBits, hasModified, cueUpdateCount, "
|
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
|
||||||
"analysisDataUpdateCount, informationUpdateCount) "
|
"analysisDataUpdateCount, informationUpdateCount) "
|
||||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||||
(
|
(
|
||||||
content_id, track.title, (track.title or "").lower(),
|
content_id, track.title, (track.title or "").lower(),
|
||||||
int(round((track.bpm or 0) * 100)) or None, track.length,
|
int(round((track.bpm or 0) * 100)) or None, track.length,
|
||||||
@@ -193,40 +229,112 @@ class OneLibraryExporter:
|
|||||||
# where the deck expects "Cm". Rendered from the parsed wheel.
|
# where the deck expects "Cm". Rendered from the parsed wheel.
|
||||||
self._lookup(con, "key", lookups["key"],
|
self._lookup(con, "key", lookups["key"],
|
||||||
render_key(track.key_wheel, track.key_mode)),
|
render_key(track.key_wheel, track.key_mode)),
|
||||||
|
image_id,
|
||||||
track.comment, track.rating or 0, track.release_date,
|
track.comment, track.rating or 0, track.release_date,
|
||||||
date.today().isoformat(), rel, item.destination.name, size,
|
date.today().isoformat(), rel, item.destination.name, size,
|
||||||
1, track.bitrate, None, 1, 1, 0, content_id,
|
# kbps, as every Pioneer library stores it; the generic model
|
||||||
anlz_rel, ANALYSED_BITS, 0, 0, 0, 0,
|
# 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 --------------------------------------------------
|
# ---- the analysis files --------------------------------------------------
|
||||||
|
|
||||||
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
|
||||||
"""The `.DAT` and, when there are cues beyond pad C, the `.EXT`.
|
"""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
|
All three, and every cue list, even for a track with no cues: rekordbox
|
||||||
is the complete list, which is what the reader prefers.
|
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)
|
# rekordbox's clock runs ~25 ms behind the decoded audio on MP3/AAC (see
|
||||||
beats = self._beats(item)
|
# `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:
|
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)
|
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:
|
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
|
||||||
written.append(
|
written = []
|
||||||
W.write_anlz(dat.with_suffix(".EXT"),
|
for suffix, data in self.anlz_files(item, rel):
|
||||||
[W.path_tag(rel), *W.cue_tags(cues, extended=True)])
|
path = dat.with_suffix(suffix)
|
||||||
)
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(data)
|
||||||
|
written.append(path)
|
||||||
return written
|
return written
|
||||||
|
|
||||||
@staticmethod
|
@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.
|
"""Every beat, expanded from the generic marker list.
|
||||||
|
|
||||||
A Pioneer grid has no tempo markers — it is a flat list of beats — so a
|
A Pioneer grid has no tempo markers — it is a flat list of beats — so a
|
||||||
@@ -237,12 +345,13 @@ class OneLibraryExporter:
|
|||||||
cues = item.cues
|
cues = item.cues
|
||||||
if not cues or not cues.grid_markers:
|
if not cues or not cues.grid_markers:
|
||||||
return []
|
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)
|
nums, bpms, times = beats_from_markers(cues.grid_markers, duration)
|
||||||
return list(zip(nums, bpms, times))
|
return list(zip(nums, bpms, times))
|
||||||
|
|
||||||
@staticmethod
|
@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.
|
"""Generic cues in the shape `anlz_writer` packs.
|
||||||
|
|
||||||
Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue.
|
Slot numbering is ANLZ's own: **dense 1-based**, 0 for a memory cue.
|
||||||
@@ -251,22 +360,44 @@ class OneLibraryExporter:
|
|||||||
too far along.
|
too far along.
|
||||||
"""
|
"""
|
||||||
out: list[dict] = []
|
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_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({
|
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,
|
"kind": 2 if is_loop else 1,
|
||||||
"time_ms": int(round(cue.start * 1000)),
|
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
|
||||||
"loop_ms": int(round((cue.start + cue.length) * 1000)) if is_loop else None,
|
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
|
||||||
"rgb": _rgb(cue.color),
|
if is_loop else None),
|
||||||
"beats": None,
|
"rgb": rgb,
|
||||||
|
"code": code,
|
||||||
|
"beats": _loop_beats(cue.start, cue.length, beats or []) if is_loop else None,
|
||||||
})
|
})
|
||||||
return out
|
return out
|
||||||
|
|
||||||
# ---- playlists -----------------------------------------------------------
|
# ---- playlists -----------------------------------------------------------
|
||||||
|
|
||||||
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
|
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
|
`playlist` is a flat table with `playlist_id_parent`, so folders and
|
||||||
playlists are the same row kind told apart by `attribute` (1 = folder).
|
playlists are the same row kind told apart by `attribute` (1 = folder).
|
||||||
@@ -282,8 +413,8 @@ class OneLibraryExporter:
|
|||||||
)
|
)
|
||||||
return next_id[0]
|
return next_id[0]
|
||||||
|
|
||||||
root = add(payload.name, None, folder=True)
|
root = add(payload.name, None, folder=True) if payload.root_folder else None
|
||||||
folders: dict[tuple[str, ...], int] = {(): root}
|
folders: dict[tuple[str, ...], int | None] = {(): root}
|
||||||
|
|
||||||
for playlist in payload.playlists:
|
for playlist in payload.playlists:
|
||||||
parent = root
|
parent = root
|
||||||
@@ -312,10 +443,62 @@ class OneLibraryExporter:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _rgb(color: str | None) -> tuple[int, int, int] | None:
|
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
|
||||||
if not color or not color.startswith("#") or len(color) != 7:
|
#: 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 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:
|
try:
|
||||||
return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
|
import mutagen
|
||||||
except ValueError:
|
|
||||||
|
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
|
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.
|
"""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.
|
`TrackCues`. Everything above this file sees generic types exclusively.
|
||||||
|
|
||||||
Field conventions are read off a real rekordbox 7 export rather than guessed:
|
Field conventions are read off a real rekordbox 7 export rather than guessed:
|
||||||
@@ -54,7 +54,7 @@ def _bpm(row) -> float | None:
|
|||||||
return round(int(raw) / 100.0, 2)
|
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.
|
"""Project one ``Content`` row.
|
||||||
|
|
||||||
**The three count fields are approximations here**, and deliberately so. Cues
|
**The three count fields are approximations here**, and deliberately so. Cues
|
||||||
@@ -93,7 +93,8 @@ def to_track(row, drive_path: str | None = None) -> Track:
|
|||||||
rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))),
|
rating=max(0, min(5, int(getattr(row, "rating", 0) or 0))),
|
||||||
playcount=getattr(row, "djPlayCount", None),
|
playcount=getattr(row, "djPlayCount", None),
|
||||||
length=getattr(row, "length", 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)),
|
import_date=_iso_date(getattr(row, "dateAdded", None)),
|
||||||
last_played=None, # the drive records history as playlists, not per track
|
last_played=None, # the drive records history as playlists, not per track
|
||||||
release_date=_iso_date(getattr(row, "releaseDate", None))
|
release_date=_iso_date(getattr(row, "releaseDate", None))
|
||||||
@@ -103,7 +104,8 @@ def to_track(row, drive_path: str | None = None) -> Track:
|
|||||||
hotcue_count=0,
|
hotcue_count=0,
|
||||||
grid_marker_count=1 if (bpm and has_analysis) else 0,
|
grid_marker_count=1 if (bpm and has_analysis) else 0,
|
||||||
grid_locked=False, # OneLibrary has no grid lock
|
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",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -112,7 +114,7 @@ def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
|
|||||||
|
|
||||||
`cues` are already generic — see `store.cues` for why that boundary sits
|
`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.
|
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
|
Each cue already says whether it is editable (the store knows whether the
|
||||||
`capabilities.writable` says so at the library level.
|
drive was opened for editing or is only being browsed).
|
||||||
"""
|
"""
|
||||||
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
|
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 export as core_export
|
||||||
from ...core import registry
|
from ...core import registry
|
||||||
from .driver import RekordboxDriver
|
from .driver import RekordboxDriver
|
||||||
|
from .device_export import RekordboxDeviceExporter
|
||||||
from .export import RekordboxExporter
|
from .export import RekordboxExporter
|
||||||
|
|
||||||
REKORDBOX = RekordboxDriver()
|
REKORDBOX = RekordboxDriver()
|
||||||
@@ -15,3 +16,8 @@ registry.register(REKORDBOX)
|
|||||||
|
|
||||||
REKORDBOX_EXPORTER = RekordboxExporter()
|
REKORDBOX_EXPORTER = RekordboxExporter()
|
||||||
core_export.register(REKORDBOX_EXPORTER)
|
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)
|
||||||
@@ -21,13 +21,14 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from pathlib import Path
|
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.capabilities import Capabilities
|
||||||
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
||||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||||
from ...core.query import TrackIndex
|
from ...core.query import TrackIndex
|
||||||
from . import capabilities as caps
|
from . import capabilities as caps
|
||||||
from . import projection
|
from . import memory_palette, palette, projection, timebase
|
||||||
|
from ...core import add_analysis
|
||||||
from .store import RekordboxStore
|
from .store import RekordboxStore
|
||||||
|
|
||||||
|
|
||||||
@@ -46,7 +47,8 @@ class RekordboxAdapter:
|
|||||||
kinds = self._store.cue_kinds()
|
kinds = self._store.cue_kinds()
|
||||||
self._index.rebuild(
|
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)))
|
||||||
for row in self._store.iter_content()
|
for row in self._store.iter_content()
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -68,7 +70,8 @@ class RekordboxAdapter:
|
|||||||
"""
|
"""
|
||||||
kinds = self._store.cue_kinds()
|
kinds = self._store.cue_kinds()
|
||||||
row = self._store.content(track_id)
|
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))))
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
"""Release the database connection.
|
"""Release the database connection.
|
||||||
@@ -80,7 +83,9 @@ class RekordboxAdapter:
|
|||||||
self._store.close()
|
self._store.close()
|
||||||
|
|
||||||
def reload(self) -> None:
|
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._cloud_synced = self._store.cloud_synced
|
||||||
self._rebuild()
|
self._rebuild()
|
||||||
|
|
||||||
@@ -124,7 +129,8 @@ class RekordboxAdapter:
|
|||||||
if self._index.get(track_id) is None:
|
if self._index.get(track_id) is None:
|
||||||
return None
|
return None
|
||||||
cues = projection.to_track_cues(
|
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
|
# The track projection carries an APPROXIMATE grid_marker_count until the
|
||||||
# grid is actually read (see projection.to_track). This is that moment —
|
# grid is actually read (see projection.to_track). This is that moment —
|
||||||
@@ -166,6 +172,7 @@ class RekordboxAdapter:
|
|||||||
can_rename=writable,
|
can_rename=writable,
|
||||||
can_delete=writable,
|
can_delete=writable,
|
||||||
can_contain_children=kind == "folder",
|
can_contain_children=kind == "folder",
|
||||||
|
can_move=writable,
|
||||||
)
|
)
|
||||||
parent = str(r.ParentID or "root")
|
parent = str(r.ParentID or "root")
|
||||||
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
|
||||||
@@ -197,8 +204,25 @@ class RekordboxAdapter:
|
|||||||
def audio_path(self, track_id: str):
|
def audio_path(self, track_id: str):
|
||||||
return self._store.audio_path(track_id)
|
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:
|
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||||
self._store.set_path_mapping(mapping)
|
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:
|
def path_prefix_suggestions(self) -> dict:
|
||||||
paths = self._store.all_audio_paths()
|
paths = self._store.all_audio_paths()
|
||||||
@@ -230,6 +254,12 @@ class RekordboxAdapter:
|
|||||||
self._refresh(track_id)
|
self._refresh(track_id)
|
||||||
return self._index.get(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)
|
||||||
|
|
||||||
# ---- commands: playlists ----------------------------------------------
|
# ---- commands: playlists ----------------------------------------------
|
||||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||||
self._require_writable("Creating playlists")
|
self._require_writable("Creating playlists")
|
||||||
@@ -247,6 +277,10 @@ class RekordboxAdapter:
|
|||||||
self._require_writable("Deleting playlists")
|
self._require_writable("Deleting playlists")
|
||||||
self._store.delete_playlist(node_id)
|
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:
|
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||||
self._require_writable("Editing playlists")
|
self._require_writable("Editing playlists")
|
||||||
return self._store.set_playlist_entries(node_id, track_ids)
|
return self._store.set_playlist_entries(node_id, track_ids)
|
||||||
@@ -269,12 +303,8 @@ class RekordboxAdapter:
|
|||||||
) -> TrackCues:
|
) -> TrackCues:
|
||||||
self._require_writable("Editing cues")
|
self._require_writable("Editing cues")
|
||||||
if role != "hotcue":
|
if role != "hotcue":
|
||||||
# Rekordbox is the ONLY platform with memory cues, so under the
|
# A memory cue has no slot to set; it has its own commands.
|
||||||
# two-platform promotion rule they stay preserved-but-uneditable:
|
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
|
||||||
# they are projected and shown, never written.
|
|
||||||
raise Unsupported(
|
|
||||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
|
||||||
)
|
|
||||||
self._check_cue_type(cue_type)
|
self._check_cue_type(cue_type)
|
||||||
self._store.set_cue(
|
self._store.set_cue(
|
||||||
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||||
@@ -288,11 +318,70 @@ class RekordboxAdapter:
|
|||||||
self._store.set_cue_type(track_id, slot, cue_type)
|
self._store.set_cue_type(track_id, slot, cue_type)
|
||||||
return self._refresh_cues(track_id)
|
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:
|
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||||
self._require_writable("Deleting cues")
|
self._require_writable("Deleting cues")
|
||||||
self._store.delete_cue(track_id, slot)
|
self._store.delete_cue(track_id, slot)
|
||||||
return self._refresh_cues(track_id)
|
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:
|
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||||
self._require_writable("Placing cues")
|
self._require_writable("Placing cues")
|
||||||
for cue in cues:
|
for cue in cues:
|
||||||
@@ -355,6 +444,12 @@ class RekordboxAdapter:
|
|||||||
def dirty(self) -> bool:
|
def dirty(self) -> bool:
|
||||||
return self._store.dirty
|
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):
|
def save(self):
|
||||||
self._require_writable("Saving")
|
self._require_writable("Saving")
|
||||||
return self._store.save()
|
return self._store.save()
|
||||||
@@ -389,25 +484,123 @@ class RekordboxAdapter:
|
|||||||
if self._cloud_synced:
|
if self._cloud_synced:
|
||||||
raise Unsupported(self._readonly_reason(what))
|
raise Unsupported(self._readonly_reason(what))
|
||||||
|
|
||||||
def add_tracks(self, items: list) -> list[str]:
|
def analysis_lead(self, audio: Path) -> float:
|
||||||
# Not a refusal in principle — Rekordbox could receive imported
|
"""The time-base lead `add_tracks` measures a file's waveform with —
|
||||||
# tracks — but adding one means a djmdContent row, its lookup-table
|
rekordbox's clock against the decoded audio, read from the file's
|
||||||
# foreign keys, a USN, and an ANLZ file built from scratch, which
|
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
|
||||||
# is unexplored (see the export handoff). Traktor is the only
|
not analyse what it adds has none, and whoever prepares an analysis
|
||||||
# import target for now.
|
for this one (a client of a server-held library) asks for it."""
|
||||||
self._refuse("Adding tracks")
|
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)
|
||||||
|
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))
|
||||||
|
|
||||||
|
added: list[str] = []
|
||||||
|
for item, track, audio, measured, markers, art 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)
|
||||||
|
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:
|
def remove_tracks(self, track_ids: list[str]) -> int:
|
||||||
# Same shape as adding: a track is a djmdContent row plus its cues,
|
# What goes with a track was measured in Rekordbox 7 — see the store.
|
||||||
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
|
self._require_writable("Removing tracks")
|
||||||
# which of those Rekordbox expects to be deleted together is unmeasured.
|
n = self._store.remove_tracks(track_ids)
|
||||||
self._refuse("Removing tracks")
|
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:
|
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||||
self._refuse("Editing cover art")
|
self._refuse("Editing cover art")
|
||||||
|
|
||||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||||
return None
|
return self._store.cover_art(track_id)
|
||||||
|
|
||||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||||
# Rekordbox has no per-track grid lock; capabilities.grid.lockable says so.
|
# Rekordbox has no per-track grid lock; capabilities.grid.lockable says so.
|
||||||
|
|||||||
@@ -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
|
satisfy a string `Const` and an integer field. So cue entries are packed here by
|
||||||
hand, to the layout `pyrekordbox`'s own structs document:
|
hand, to the layout `pyrekordbox`'s own structs document:
|
||||||
|
|
||||||
PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · 3x
|
PCP2: 4s magic · I len_header · I len_entry · I hot_cue · B kind · x
|
||||||
I time · I loop_time · B color_id · 7x · H loop_num · H loop_den
|
H 1000 · I time · I loop_time · B color_id · B 1 · 6x
|
||||||
I len_comment · {n}s comment(utf-16-be) · 4B colour · {pad}x
|
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
|
**`pyrekordbox` accepting the result is NOT enough.** Its parser ignores
|
||||||
the only check that matters: the reader is the thing that has to accept it.
|
`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
|
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.
|
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 construct import Container, ListContainer
|
||||||
from pyrekordbox.anlz import structs
|
from pyrekordbox.anlz import structs
|
||||||
|
|
||||||
|
from ...core.waveform import even_slices
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
NO_LOOP = 0xFFFFFFFF
|
NO_LOOP = 0xFFFFFFFF
|
||||||
@@ -54,7 +71,9 @@ _TAG_PREFIX = 12
|
|||||||
|
|
||||||
#: Each tag counts a different number of its leading CONTENT fields as part of
|
#: 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.
|
#: 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:
|
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)
|
return _wrap("PQTZ", body)
|
||||||
|
|
||||||
|
|
||||||
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
|
# ---- what rekordbox needs before it will show a grid or cues ------------------
|
||||||
rgb: tuple[int, int, int] | None, beats: int | None) -> bytes:
|
#
|
||||||
comment = b""
|
# 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)
|
red, green, blue = rgb or (0, 0, 0)
|
||||||
|
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
|
||||||
return struct.pack(
|
return struct.pack(
|
||||||
">4sIIIB3xIIB7xHHI",
|
">4sIIIBxHIIBB6xHHI",
|
||||||
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind,
|
b"PCP2", 16, length, hot_cue, kind, 1000,
|
||||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
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),
|
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
|
||||||
) + comment + struct.pack(">4B", 0, red, green, blue) + bytes(
|
# The colour is the palette CODE, then RGB: rekordbox draws from the code
|
||||||
PCP2_ENTRY_LEN - 48 - len(comment)
|
# (`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,
|
#: rekordbox's COMPACT `PCP2` entry: the first 44 bytes of a full one — no
|
||||||
first: int, last: int) -> bytes:
|
#: 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(
|
return struct.pack(
|
||||||
">4sIIIIIHHBxHII",
|
">4sIIIIIHHBxHII",
|
||||||
b"PCPT", 12, PCPT_ENTRY_LEN, hot_cue,
|
b"PCPT", 28, PCPT_ENTRY_LEN, hot_cue,
|
||||||
4 if loop_ms is not None else 4, # status: 4 = active, as rekordbox writes
|
0 if hot_cue else 4,
|
||||||
0x10000, first, last, kind, 1000,
|
0x10000, 0xFFFF, 0xFFFF, kind, 1000,
|
||||||
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
|
||||||
) + bytes(16)
|
) + bytes(16)
|
||||||
|
|
||||||
|
|
||||||
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
|
def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
|
||||||
"""`PCOB` (+ `PCO2` in the .EXT) for one track's cues.
|
"""A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
|
||||||
|
or new ones from `pcpt_entry`)."""
|
||||||
`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`.
|
|
||||||
"""
|
|
||||||
hot = [c for c in cues if c["hot_cue"]]
|
|
||||||
memory = [c for c in cues if not c["hot_cue"]]
|
|
||||||
tags: list[bytes] = []
|
|
||||||
|
|
||||||
# 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
|
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
|
||||||
# shifts every following field and the reader sees garbage.
|
# shifts every following field and the reader sees garbage. The last field
|
||||||
header = struct.pack(">IHHi", cue_type, 0, len(chosen), len(chosen))
|
# is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
|
||||||
tags.append(_wrap("PCOB", header + blob))
|
# 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))
|
||||||
|
|
||||||
if extended and cues:
|
|
||||||
blob = b"".join(
|
def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
|
||||||
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
"""A `PCO2` around already-built `PCP2` entries."""
|
||||||
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"))
|
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(entries), 0) + b"".join(entries))
|
||||||
for c in cues
|
|
||||||
)
|
|
||||||
header = struct.pack(">IHH", 1 if hot else 0, len(cues), 0)
|
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
|
||||||
tags.append(_wrap("PCO2", header + blob))
|
entries = [
|
||||||
return tags
|
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.
|
||||||
|
"""
|
||||||
|
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
#: `PMAI` + len_header + len_file + four unknowns.
|
||||||
_FILE_HEADER_LEN = 28
|
_FILE_HEADER_LEN = 28
|
||||||
|
|
||||||
|
|
||||||
def write_anlz(path: Path, tags: list[bytes]) -> Path:
|
def anlz_bytes(tags: list[bytes]) -> bytes:
|
||||||
"""Assemble and write an ANLZ file from built tag bytes."""
|
"""Assemble an ANLZ file from built tag bytes."""
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
body = b"".join(tags)
|
body = b"".join(tags)
|
||||||
header = struct.pack(
|
header = struct.pack(
|
||||||
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
|
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
|
||||||
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
|
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
|
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]:
|
) -> list[GridMarker]:
|
||||||
"""Collapse a per-beat grid into the generic marker list.
|
"""Collapse a per-beat grid into the generic marker list.
|
||||||
|
|
||||||
`times` are seconds, `bpms` the tempo in force at each beat. A marker is
|
`times` are seconds, `bpms` the tempo in force at each beat, `beats` the
|
||||||
emitted for the first beat and wherever the tempo changes.
|
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:
|
if not times or not bpms:
|
||||||
return []
|
return []
|
||||||
@@ -42,6 +52,12 @@ def markers_from_beats(
|
|||||||
if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON:
|
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))
|
out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None))
|
||||||
last_bpm = float(bpm)
|
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
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -54,8 +70,10 @@ def beats_from_markers(
|
|||||||
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
|
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
|
||||||
each marker, which is how Rekordbox numbers bars.
|
each marker, which is how Rekordbox numbers bars.
|
||||||
|
|
||||||
Not used by the read-only adapter, but it is the inverse of
|
The first marker's tempo also runs BACKWARDS to the start of the track: a
|
||||||
`markers_from_beats` and belongs beside it.
|
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] = []
|
beat_nums: list[int] = []
|
||||||
bpms: list[float] = []
|
bpms: list[float] = []
|
||||||
@@ -63,6 +81,15 @@ def beats_from_markers(
|
|||||||
if not markers:
|
if not markers:
|
||||||
return beat_nums, bpms, times
|
return beat_nums, bpms, times
|
||||||
ordered = sorted(markers, key=lambda m: m.start)
|
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):
|
for i, m in enumerate(ordered):
|
||||||
if m.bpm <= 0:
|
if m.bpm <= 0:
|
||||||
continue
|
continue
|
||||||
@@ -72,6 +99,12 @@ def beats_from_markers(
|
|||||||
n = 1
|
n = 1
|
||||||
# Guard against a zero/negative span producing an endless loop.
|
# Guard against a zero/negative span producing an endless loop.
|
||||||
while t < end - 1e-9 and step > 0:
|
while t < end - 1e-9 and step > 0:
|
||||||
|
# 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)
|
beat_nums.append(n)
|
||||||
bpms.append(m.bpm)
|
bpms.append(m.bpm)
|
||||||
times.append(t)
|
times.append(t)
|
||||||
|
|||||||
@@ -30,7 +30,8 @@ from ...core.capabilities import (
|
|||||||
SaveCapabilities,
|
SaveCapabilities,
|
||||||
TrackCapabilities,
|
TrackCapabilities,
|
||||||
)
|
)
|
||||||
from .cue_types import WRITABLE_CUE_TYPES
|
from . import memory_palette, 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
|
# 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
|
# 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,
|
writable=not cloud_synced,
|
||||||
readonly_cause="cloud_synced" if cloud_synced else None,
|
readonly_cause="cloud_synced" if cloud_synced else None,
|
||||||
cues=CueCapabilities(
|
cues=CueCapabilities(
|
||||||
# Hot cues are writable: djmdCue rows plus the contentCue JSON
|
# Hot AND memory cues are writable: djmdCue rows plus the
|
||||||
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
|
# contentCue JSON mirror, kept in step (memory cues: measured
|
||||||
# Rekordbox is the only platform that has them, and the two-platform
|
# 2026-10-16, kit M1).
|
||||||
# promotion rule says a one-platform concept does not become an
|
|
||||||
# editing feature.
|
|
||||||
editable=True,
|
editable=True,
|
||||||
hotcue_slots=HOTCUE_SLOTS,
|
hotcue_slots=HOTCUE_SLOTS,
|
||||||
slot_labels="letter",
|
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,
|
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.
|
# Both cue types write; Rekordbox has no fade/load types.
|
||||||
types=WRITABLE_CUE_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",
|
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
|
named=True, # djmdCue.Comment
|
||||||
loops="cue_type",
|
loops="cue_type",
|
||||||
),
|
),
|
||||||
@@ -83,7 +87,12 @@ def capabilities_for(
|
|||||||
# column (its Composer is a different field), so they are absent
|
# column (its Composer is a different field), so they are absent
|
||||||
# rather than mapped onto something approximate.
|
# rather than mapped onto something approximate.
|
||||||
editable_fields=sorted(editable_fields or []),
|
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,
|
||||||
artwork=False,
|
artwork=False,
|
||||||
artwork_note=None,
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
MEMORY_KIND = 0
|
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.
|
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
|
||||||
CUE_TYPES = ["cue", "loop"]
|
CUE_TYPES = ["cue", "loop"]
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
"""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
|
||||||
|
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))),
|
||||||
|
"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
|
||||||
@@ -63,7 +63,7 @@ class RekordboxDriver:
|
|||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def open(self, path: Path) -> RekordboxAdapter:
|
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
|
||||||
return RekordboxAdapter(path)
|
return RekordboxAdapter(path)
|
||||||
|
|
||||||
def detect(self) -> list[dict]:
|
def detect(self) -> list[dict]:
|
||||||
|
|||||||
@@ -57,11 +57,14 @@ from pathlib import Path
|
|||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
|
||||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||||
from . import anlz_writer as W
|
from ...core.cue_colors import effective_color
|
||||||
|
from . import memory_palette, new_content, palette
|
||||||
|
from . import timebase
|
||||||
from .beatgrid import beats_from_markers
|
from .beatgrid import beats_from_markers
|
||||||
from .capabilities import capabilities_for
|
from .capabilities import capabilities_for
|
||||||
from .cue_types import kind_for
|
from .cue_types import kind_for
|
||||||
from .projection import render_key
|
from .projection import render_key
|
||||||
|
from .store import rekordbox_probe_suppressed
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -77,12 +80,35 @@ SEED = _FIXTURES / "seed.sql"
|
|||||||
|
|
||||||
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
|
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
|
||||||
FRAMES_PER_SECOND = 150
|
FRAMES_PER_SECOND = 150
|
||||||
|
|
||||||
|
#: `djmdContent.ContentLink` — see `new_content`, where its bits are measured.
|
||||||
|
CONTENT_LINK = new_content.CONTENT_LINK
|
||||||
|
|
||||||
|
#: Rekordbox's playlist side file, beside master.db. It lists every playlist
|
||||||
|
#: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the
|
||||||
|
#: file does not vouch for is not shown. The skeleton is a real Rekordbox 7
|
||||||
|
#: file's, minus its nodes — pyrekordbox adds ours as it creates them.
|
||||||
|
PLAYLISTS_XML = "masterPlaylists6.xml"
|
||||||
|
PLAYLISTS_XML_SKELETON = (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8"?>\n\n'
|
||||||
|
'<MASTER_PLAYLIST Version="3.0.0" AutomaticSync="0">\n'
|
||||||
|
' <PRODUCT Name="rekordbox" Version="7.2.18" Company="Pioneer DJ"/>\n'
|
||||||
|
' <PLAYLISTS>\n </PLAYLISTS>\n'
|
||||||
|
'</MASTER_PLAYLIST>\n'
|
||||||
|
)
|
||||||
OTHER_PLAYLIST = "Other"
|
OTHER_PLAYLIST = "Other"
|
||||||
|
|
||||||
|
|
||||||
class RekordboxExporter:
|
class RekordboxExporter:
|
||||||
platform = "rekordbox"
|
platform = "rekordbox"
|
||||||
|
menu_order = 40
|
||||||
|
#: A COMPUTER library (master.db), which Rekordbox never reads from a stick —
|
||||||
|
#: named so, beside "Rekordbox Export" (the stick's Device Library).
|
||||||
|
display_name = "Rekordbox Library"
|
||||||
|
#: Rekordbox opens a master.db only from its own library folder.
|
||||||
|
computer_only = True
|
||||||
library_filename = "master.db"
|
library_filename = "master.db"
|
||||||
|
drive_root = False
|
||||||
|
|
||||||
def capabilities(self):
|
def capabilities(self):
|
||||||
"""What a Rekordbox library can hold, with no library to read.
|
"""What a Rekordbox library can hold, with no library to read.
|
||||||
@@ -99,7 +125,7 @@ class RekordboxExporter:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
|
||||||
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
|
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
|
||||||
# OneLibrary drive uses a universal key shared across vendors, and
|
# OneLibrary drive uses a universal key shared across vendors, and
|
||||||
# master.db does not. Mixing them up produces a database Rekordbox
|
# master.db does not. Mixing them up produces a database Rekordbox
|
||||||
# cannot open, and pyrekordbox rejects the wrong one outright.
|
# cannot open, and pyrekordbox rejects the wrong one outright.
|
||||||
@@ -124,19 +150,34 @@ class RekordboxExporter:
|
|||||||
finally:
|
finally:
|
||||||
con.close()
|
con.close()
|
||||||
|
|
||||||
|
# BEFORE the database is opened: pyrekordbox keeps masterPlaylists6.xml
|
||||||
|
# in step with every playlist it creates — but only if the file exists
|
||||||
|
# at open time. Without it Rekordbox opened the library, generated its
|
||||||
|
# own file listing our playlists with Timestamp 0, and showed NONE of
|
||||||
|
# them (measured by swapping an export into a real Rekordbox 7).
|
||||||
|
playlists_xml = root / PLAYLISTS_XML
|
||||||
|
playlists_xml.write_text(PLAYLISTS_XML_SKELETON, encoding="utf-8")
|
||||||
|
|
||||||
db = MasterDatabase(path=str(library), key=key)
|
db = MasterDatabase(path=str(library), key=key)
|
||||||
extra: list[Path] = []
|
extra: list[Path] = [playlists_xml]
|
||||||
ids: dict[str, str] = {}
|
ids: dict[str, str] = {}
|
||||||
try:
|
try:
|
||||||
self._seed_registry(db, models)
|
self._seed_registry(db, models)
|
||||||
self._seed_device(db, payload)
|
self._seed_device(db, payload)
|
||||||
rows = {}
|
rows = {}
|
||||||
for item in payload.tracks:
|
total = len(payload.tracks)
|
||||||
|
for n, item in enumerate(payload.tracks, start=1):
|
||||||
|
# Each track is decoded for its waveform: the slow part.
|
||||||
|
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||||
content = self._add_track(db, item)
|
content = self._add_track(db, item)
|
||||||
rows[item.source_id] = content
|
rows[item.source_id] = content
|
||||||
ids[item.source_id] = str(content.ID)
|
ids[item.source_id] = str(content.ID)
|
||||||
extra += self._write_anlz(item, content, root, db)
|
extra += self._write_anlz(item, content, root, db)
|
||||||
|
extra += self._write_art(item, content, root)
|
||||||
self._write_playlists(db, payload, rows)
|
self._write_playlists(db, payload, rows)
|
||||||
|
# A brand-new file: a running Rekordbox cannot have it open, so its
|
||||||
|
# process-wide veto protects nothing here.
|
||||||
|
with rekordbox_probe_suppressed():
|
||||||
db.commit()
|
db.commit()
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
@@ -146,7 +187,7 @@ class RekordboxExporter:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _replay_cues(library: Path, payload: ExportPayload, ids: dict) -> None:
|
def _replay_cues(library: Path, payload: ExportPayload, ids: dict) -> None:
|
||||||
"""Write the cues through the ORDINARY adapter, not by hand.
|
"""Write the cues through the ORDINARY cue-row code, not by hand.
|
||||||
|
|
||||||
Same reason the Traktor exporter replays commands: `set_cue` already
|
Same reason the Traktor exporter replays commands: `set_cue` already
|
||||||
owns every convention a cue row needs — the sparse `Kind` bank, frames
|
owns every convention a cue row needs — the sparse `Kind` bank, frames
|
||||||
@@ -158,24 +199,40 @@ class RekordboxExporter:
|
|||||||
from .adapter import RekordboxAdapter
|
from .adapter import RekordboxAdapter
|
||||||
|
|
||||||
adapter = RekordboxAdapter(library)
|
adapter = RekordboxAdapter(library)
|
||||||
|
# The store, not the adapter's commands: the adapter's set_cue takes no
|
||||||
|
# colour and its memory-cue command takes only a swatch. A NEW library
|
||||||
|
# maps any source colour to the nearest one instead — through the same
|
||||||
|
# `_write_cue` every edit uses.
|
||||||
|
store = adapter._store
|
||||||
try:
|
try:
|
||||||
for item in payload.tracks:
|
for item in payload.tracks:
|
||||||
track_id = ids.get(item.source_id)
|
track_id = ids.get(item.source_id)
|
||||||
if track_id is None or not item.cues:
|
if track_id is None or not item.cues:
|
||||||
continue
|
continue
|
||||||
for cue in item.cues.cues:
|
memory = 0
|
||||||
# Memory cues are a Rekordbox-only concept the generic model
|
for cue in sorted(item.cues.cues, key=lambda c: c.start):
|
||||||
# preserves but never writes; a cue with no slot has no pad
|
if cue.role == "memory" or cue.slot is None:
|
||||||
# to land on.
|
# rekordbox keeps 10 (earliest first; the rest are
|
||||||
if cue.role != "hotcue" or cue.slot is None:
|
# dropped, per the lossiness rule). Colour: what
|
||||||
|
# Konduktor SHOWS — stored, else the type's — as the
|
||||||
|
# nearest of the memory palette's 8, as for a hot cue.
|
||||||
|
if memory >= store.MAX_MEMORY_CUES:
|
||||||
continue
|
continue
|
||||||
adapter.set_cue(
|
store.add_memory_cue(
|
||||||
track_id,
|
track_id, start_sec=cue.start, cue_type=cue.type,
|
||||||
slot=cue.slot,
|
length_sec=cue.length, name=cue.name,
|
||||||
start_sec=cue.start,
|
color_code=memory_palette.nearest_code(effective_color(cue)),
|
||||||
cue_type=cue.type,
|
)
|
||||||
length_sec=cue.length,
|
memory += 1
|
||||||
name=cue.name,
|
continue
|
||||||
|
# What Konduktor SHOWS — stored colour, else the type's (blue
|
||||||
|
# cue, green loop) — as a palette code, which is what
|
||||||
|
# rekordbox draws from. White (a grid companion) has no swatch:
|
||||||
|
# code 0, i.e. uncoloured.
|
||||||
|
code, _rgb = palette.code_for(effective_color(cue))
|
||||||
|
store.set_cue(
|
||||||
|
track_id, slot=cue.slot, start_sec=cue.start, cue_type=cue.type,
|
||||||
|
length_sec=cue.length, name=cue.name, color_code=code or None,
|
||||||
)
|
)
|
||||||
adapter.save()
|
adapter.save()
|
||||||
finally:
|
finally:
|
||||||
@@ -255,32 +312,13 @@ class RekordboxExporter:
|
|||||||
# NOT `track.key`: that is the SOURCE platform's notation, so a Traktor
|
# NOT `track.key`: that is the SOURCE platform's notation, so a Traktor
|
||||||
# export would put "10m" where Rekordbox shows "Cm".
|
# export would put "10m" where Rekordbox shows "Cm".
|
||||||
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
|
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
|
||||||
|
content.ContentLink = CONTENT_LINK
|
||||||
db.flush()
|
db.flush()
|
||||||
return content
|
return content
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _lookup(db, kind: str, name: str | None):
|
def _lookup(db, kind: str, name: str | None):
|
||||||
"""Find-or-create a lookup row, returning its id.
|
return new_content.lookup(db, kind, name)
|
||||||
|
|
||||||
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
|
|
||||||
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
|
|
||||||
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
|
|
||||||
"""
|
|
||||||
if not name:
|
|
||||||
return None
|
|
||||||
if kind == "key":
|
|
||||||
found = db.get_key(ScaleName=name).first()
|
|
||||||
if found is not None:
|
|
||||||
return found.ID
|
|
||||||
return _insert_key(db, name)
|
|
||||||
found = {"artist": db.get_artist, "album": db.get_album,
|
|
||||||
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
|
|
||||||
if found is not None:
|
|
||||||
return found.ID
|
|
||||||
created = {"artist": db.add_artist, "album": db.add_album,
|
|
||||||
"genre": db.add_genre, "label": db.add_label}[kind](name)
|
|
||||||
db.flush()
|
|
||||||
return created.ID
|
|
||||||
|
|
||||||
# ---- analysis ---------------------------------------------------------------
|
# ---- analysis ---------------------------------------------------------------
|
||||||
|
|
||||||
@@ -291,31 +329,71 @@ class RekordboxExporter:
|
|||||||
and the file on disk have to agree — so the same derivation is used here
|
and the file on disk have to agree — so the same derivation is used here
|
||||||
rather than a path of our own choosing.
|
rather than a path of our own choosing.
|
||||||
"""
|
"""
|
||||||
track_uuid = str(content.UUID)
|
rel = new_content.anlz_rel(str(content.UUID))
|
||||||
# Rekordbox derives these two levels from the track's UUID, and the
|
|
||||||
# column and the file have to agree — so the same derivation is used.
|
|
||||||
rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
|
|
||||||
content.AnalysisDataPath = rel
|
content.AnalysisDataPath = rel
|
||||||
content.Analysed = 105 # what a rekordbox-analysed track carries
|
content.Analysed = 105 # what a rekordbox-analysed track carries
|
||||||
content.AnalysisUpdated = 1
|
content.AnalysisUpdated = 1
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|
||||||
tags = [W.path_tag(str(item.destination))]
|
off = timebase.offset(item.destination)
|
||||||
|
measured = item.waveform(lead=off)
|
||||||
|
beats = None
|
||||||
markers = item.cues.grid_markers if item.cues else []
|
markers = item.cues.grid_markers if item.cues else []
|
||||||
if markers:
|
if markers:
|
||||||
duration = float(item.track.length or 0) or (markers[-1].start + 60.0)
|
duration = ((measured.duration if measured else 0.0)
|
||||||
|
or float(item.track.length or 0) or (markers[-1].start + 60.0))
|
||||||
nums, bpms, times = beats_from_markers(markers, duration)
|
nums, bpms, times = beats_from_markers(markers, duration)
|
||||||
if nums:
|
if nums:
|
||||||
tags.append(W.beatgrid_tag(list(zip(nums, bpms, times))))
|
# Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`).
|
||||||
|
# The cues need no such line: they are replayed through
|
||||||
|
# `set_cue`, which applies the same offset itself.
|
||||||
|
beats = [(n, bpm, timebase.to_pioneer(t, off))
|
||||||
|
for n, bpm, t in zip(nums, bpms, times)]
|
||||||
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
|
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
|
||||||
# not at the library root — the read path joins it that way, and writing
|
# not at the library root — the read path joins it that way, and writing
|
||||||
# it anywhere else produces a track whose grid silently reads as empty.
|
# it anywhere else produces a track whose grid silently reads as empty.
|
||||||
return [W.write_anlz(root / "share" / rel.lstrip("/"), tags)]
|
dat = root / "share" / rel.lstrip("/")
|
||||||
|
written = []
|
||||||
|
for suffix, data in new_content.anlz_files(item.destination, measured, beats).items():
|
||||||
|
target = dat.with_suffix(suffix)
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
target.write_bytes(data)
|
||||||
|
written.append(target)
|
||||||
|
return written
|
||||||
|
|
||||||
|
# ---- artwork ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _write_art(item: ExportTrack, content, root: Path) -> list[Path]:
|
||||||
|
"""The cover, as a rekordbox-managed track carries it.
|
||||||
|
|
||||||
|
Three JPEGs under `share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/` — the
|
||||||
|
same UUID split as the analysis folder — named `artwork.jpg` (the cover,
|
||||||
|
fit to 800 px), `artwork_m.jpg` (240) and `artwork_s.jpg` (80), the last
|
||||||
|
two letterboxed square. `djmdContent.ImagePath` names `artwork.jpg`,
|
||||||
|
rooted at `share/` like `AnalysisDataPath`. All measured on a real
|
||||||
|
Rekordbox 7 library.
|
||||||
|
"""
|
||||||
|
files = new_content.artwork_files(item.art[0] if item.art else None)
|
||||||
|
if files is None:
|
||||||
|
return []
|
||||||
|
rel = new_content.artwork_rel(str(content.UUID))
|
||||||
|
folder = root / "share" / rel.lstrip("/")
|
||||||
|
folder.mkdir(parents=True, exist_ok=True)
|
||||||
|
written = []
|
||||||
|
for name, data in files.items():
|
||||||
|
(folder / name).write_bytes(data)
|
||||||
|
written.append(folder / name)
|
||||||
|
content.ImagePath = f"{rel}/artwork.jpg"
|
||||||
|
return written
|
||||||
|
|
||||||
# ---- playlists ---------------------------------------------------------------
|
# ---- playlists ---------------------------------------------------------------
|
||||||
|
|
||||||
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
|
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
|
||||||
"""The tree, under one folder named after the export."""
|
"""The tree — at the top level, or with `payload.root_folder` under one
|
||||||
|
folder named after the export (None = the top level)."""
|
||||||
|
root = None
|
||||||
|
if payload.root_folder:
|
||||||
root = db.create_playlist_folder(payload.name)
|
root = db.create_playlist_folder(payload.name)
|
||||||
db.flush()
|
db.flush()
|
||||||
folders: dict[tuple[str, ...], object] = {(): root}
|
folders: dict[tuple[str, ...], object] = {(): root}
|
||||||
@@ -346,20 +424,3 @@ class RekordboxExporter:
|
|||||||
db.add_to_playlist(playlist, content)
|
db.add_to_playlist(playlist, content)
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|
||||||
|
|
||||||
def _insert_key(db, name: str) -> str:
|
|
||||||
"""A `djmdKey` row. Raw SQL for the same reason the registry row is: the
|
|
||||||
ORM's DateTime binder raises on the NULLs a real row carries."""
|
|
||||||
from pyrekordbox.masterdb import models
|
|
||||||
|
|
||||||
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
|
||||||
seq = (db.query(models.DjmdKey).count() or 0) + 1
|
|
||||||
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
|
||||||
db.session.execute(
|
|
||||||
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
|
|
||||||
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
|
|
||||||
{"id": key_id, "name": name, "seq": seq,
|
|
||||||
"uuid": str(uuidlib.uuid4()), "now": now},
|
|
||||||
)
|
|
||||||
db.flush()
|
|
||||||
return key_id
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""rekordbox's MEMORY-cue colours — a palette of its own, not the hot cues'.
|
||||||
|
|
||||||
|
rekordbox 7 offers a memory cue eight colours plus "No Color" (Pink, Red,
|
||||||
|
Orange, Yellow, Green, Aqua, Blue, Purple — the same eight names as its track
|
||||||
|
colours), against sixteen swatches for a hot cue. MEASURED 2026-10-16 (kits M1 /
|
||||||
|
M2 in `.claude/discussions/discuss-memory-cues-2026-10-16.md`), by colouring
|
||||||
|
memory cues one per colour, in that order, in rekordbox itself:
|
||||||
|
|
||||||
|
* `master.db`: the code is `djmdCue.Color`, **0-based** in menu order (Pink 0
|
||||||
|
… Purple 7) and `ColorTableIndex` stays NULL — the opposite of a hot cue,
|
||||||
|
which keeps its code in `ColorTableIndex` with `Color = -1`. "No colour" is
|
||||||
|
`-1` on a cue never coloured and **255** on one set back to "No Color".
|
||||||
|
* the ANLZ `.EXT`: `PCP2` byte 28, **1-based** (Blue = 7), 0 = none. The
|
||||||
|
hot-cue colour tail after the comment stays zero on a memory cue.
|
||||||
|
|
||||||
|
The RGB values are DISPLAY colours only — nothing stores them. They were
|
||||||
|
sampled from the dots in rekordbox 7's own colour menu (a screenshot), so they
|
||||||
|
are what rekordbox shows, not what it writes.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import colorsys
|
||||||
|
|
||||||
|
from .palette import _parse
|
||||||
|
|
||||||
|
#: code (0-based, master.db) -> display RGB, in rekordbox's menu order.
|
||||||
|
COLOURS: list[tuple[str, tuple[int, int, int]]] = [
|
||||||
|
("Pink", (0xE5, 0x77, 0xEF)),
|
||||||
|
("Red", (0xE1, 0x31, 0x21)),
|
||||||
|
("Orange", (0xEA, 0xA3, 0x49)),
|
||||||
|
("Yellow", (0xF2, 0xE2, 0x57)),
|
||||||
|
("Green", (0x65, 0xDB, 0x41)),
|
||||||
|
("Aqua", (0x55, 0xBB, 0xF1)),
|
||||||
|
("Blue", (0x1F, 0x4E, 0xED)),
|
||||||
|
("Purple", (0x8A, 0x1D, 0xED)),
|
||||||
|
]
|
||||||
|
|
||||||
|
#: `master.db`'s `Color` for a memory cue set back to "No Color" (measured);
|
||||||
|
#: a cue never coloured keeps -1. Both read as uncoloured.
|
||||||
|
CLEARED = 255
|
||||||
|
|
||||||
|
#: Below this saturation a colour is white/grey, which the palette cannot show.
|
||||||
|
_GREY = 0.2
|
||||||
|
|
||||||
|
|
||||||
|
def _hex(rgb: tuple[int, int, int]) -> str:
|
||||||
|
return f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
|
||||||
|
|
||||||
|
|
||||||
|
#: The swatches a user can pick — what `capabilities.cues.memory_palette` offers.
|
||||||
|
SWATCHES: list[str] = [_hex(rgb) for _name, rgb in COLOURS]
|
||||||
|
|
||||||
|
|
||||||
|
def hex_for(code: int | None) -> str | None:
|
||||||
|
"""`#RRGGBB` for a stored 0-based code; None for -1, 255 or anything unknown."""
|
||||||
|
if code is None or not 0 <= code < len(COLOURS):
|
||||||
|
return None
|
||||||
|
return _hex(COLOURS[code][1])
|
||||||
|
|
||||||
|
|
||||||
|
def code_for(color: str | None) -> int | None:
|
||||||
|
"""The 0-based code of an EXACT swatch (a user's pick), else None."""
|
||||||
|
rgb = _parse(color) if color else None
|
||||||
|
return next((i for i, (_n, value) in enumerate(COLOURS) if value == rgb), None)
|
||||||
|
|
||||||
|
|
||||||
|
def nearest_code(color: str | None) -> int | None:
|
||||||
|
"""The swatch nearest in hue to any `#RRGGBB` — for a colour arriving from
|
||||||
|
another platform (an import, an export). None for no colour or a grey."""
|
||||||
|
exact = code_for(color)
|
||||||
|
if exact is not None:
|
||||||
|
return exact
|
||||||
|
rgb = _parse(color) if color else None
|
||||||
|
if rgb is None:
|
||||||
|
return None
|
||||||
|
h, _l, s = colorsys.rgb_to_hls(*(v / 255 for v in rgb))
|
||||||
|
if s < _GREY or max(rgb) - min(rgb) < 40:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def hue_gap(i: int) -> float:
|
||||||
|
ph = colorsys.rgb_to_hls(*(v / 255 for v in COLOURS[i][1]))[0]
|
||||||
|
d = abs(ph - h)
|
||||||
|
return min(d, 1 - d)
|
||||||
|
|
||||||
|
return min(range(len(COLOURS)), key=hue_gap)
|
||||||
|
|
||||||
|
|
||||||
|
def anlz_byte(code: int | None) -> int:
|
||||||
|
"""`PCP2` byte 28 for a 0-based code: code + 1, and 0 for none."""
|
||||||
|
return 0 if code is None else code + 1
|
||||||
|
|
||||||
|
|
||||||
|
def from_anlz_byte(value: int) -> int | None:
|
||||||
|
"""The 0-based code from `PCP2` byte 28 (0 = none)."""
|
||||||
|
return value - 1 if 1 <= value <= len(COLOURS) else None
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""A NEW track's rows and files in a `master.db` library.
|
||||||
|
|
||||||
|
Shared by the two places a track is created rather than edited: the Rekordbox
|
||||||
|
Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks`
|
||||||
|
(a track added to the user's own library). One definition, because a track
|
||||||
|
row, its lookups and its analysis files are the same thing in both, and two
|
||||||
|
copies would drift.
|
||||||
|
|
||||||
|
What a track Rekordbox itself adds looks like was MEASURED (two files dragged
|
||||||
|
into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a
|
||||||
|
`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three
|
||||||
|
JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own
|
||||||
|
analysis results — key, mixer gain, phrases — which nothing here can produce.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid as uuidlib
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from . import anlz_writer as W
|
||||||
|
from . import artwork
|
||||||
|
|
||||||
|
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
|
||||||
|
#: five tracks of a Konduktor-written library different values and loading it
|
||||||
|
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
|
||||||
|
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
|
||||||
|
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
|
||||||
|
#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses
|
||||||
|
#: itself — adds two more bits that draw an extra badge, most likely claiming
|
||||||
|
#: phrase/vocal analysis Konduktor does not write. So the value that claims
|
||||||
|
#: only what is written: 0x2C060E.
|
||||||
|
CONTENT_LINK = 2885134
|
||||||
|
|
||||||
|
|
||||||
|
def anlz_rel(track_uuid: str) -> str:
|
||||||
|
"""`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from
|
||||||
|
the track's UUID, and the column and the file have to agree."""
|
||||||
|
return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
|
||||||
|
|
||||||
|
|
||||||
|
def artwork_rel(track_uuid: str) -> str:
|
||||||
|
"""The track's artwork FOLDER — the same UUID split as its analysis."""
|
||||||
|
return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
|
||||||
|
|
||||||
|
|
||||||
|
def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]:
|
||||||
|
"""The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`.
|
||||||
|
|
||||||
|
The same files as a rekordbox-analysed track. The `.DAT` needs PVBR and the
|
||||||
|
preview waveforms before rekordbox shows a grid at all (measured on a
|
||||||
|
OneLibrary stick; the same Pioneer file here); the `.EXT`/`.2EX` carry the
|
||||||
|
drawn waveforms. Cue lists are present but EMPTY — master.db keeps cues in
|
||||||
|
djmdCue. `measured` is `waveform.analyse`'s result (None: flat previews).
|
||||||
|
`beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes
|
||||||
|
no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later.
|
||||||
|
"""
|
||||||
|
path = str(audio)
|
||||||
|
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))]
|
||||||
|
if beats is not None:
|
||||||
|
tags.append(W.beatgrid_tag(beats))
|
||||||
|
if measured:
|
||||||
|
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
|
||||||
|
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
|
||||||
|
else:
|
||||||
|
tags += W.flat_preview_tags()
|
||||||
|
ext_waves, two_ex = [], []
|
||||||
|
tags += W.cue_tags([], extended=False)
|
||||||
|
out = {
|
||||||
|
".DAT": W.anlz_bytes(tags),
|
||||||
|
".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1],
|
||||||
|
*W.cue_tags([], extended=True), *ext_waves[1:]]),
|
||||||
|
}
|
||||||
|
if two_ex:
|
||||||
|
out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def artwork_files(art: bytes | None) -> dict[str, bytes] | None:
|
||||||
|
"""The cover as a rekordbox-managed track carries it, by file name.
|
||||||
|
|
||||||
|
`artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and
|
||||||
|
`artwork_s.jpg` (80), the last two letterboxed square; `djmdContent.
|
||||||
|
ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library.
|
||||||
|
None when there is no art or it cannot be read.
|
||||||
|
"""
|
||||||
|
if not art:
|
||||||
|
return None
|
||||||
|
jpegs = artwork.library_jpegs(art)
|
||||||
|
if jpegs is None:
|
||||||
|
return None
|
||||||
|
return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs))
|
||||||
|
|
||||||
|
|
||||||
|
def lookup(db, kind: str, name: str | None):
|
||||||
|
"""Find-or-create a lookup row, returning its id.
|
||||||
|
|
||||||
|
Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name,
|
||||||
|
so every one is find-or-create — the same rule the in-place adapter follows.
|
||||||
|
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
|
||||||
|
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
|
||||||
|
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
|
||||||
|
"""
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
if kind == "key":
|
||||||
|
found = db.get_key(ScaleName=name).first()
|
||||||
|
if found is not None:
|
||||||
|
return found.ID
|
||||||
|
return insert_key(db, name)
|
||||||
|
found = {"artist": db.get_artist, "album": db.get_album,
|
||||||
|
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
|
||||||
|
if found is not None:
|
||||||
|
return found.ID
|
||||||
|
created = {"artist": db.add_artist, "album": db.add_album,
|
||||||
|
"genre": db.add_genre, "label": db.add_label}[kind](name)
|
||||||
|
db.flush()
|
||||||
|
return created.ID
|
||||||
|
|
||||||
|
|
||||||
|
def insert_key(db, name: str) -> str:
|
||||||
|
"""A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs
|
||||||
|
a real row carries."""
|
||||||
|
from pyrekordbox.masterdb import models
|
||||||
|
|
||||||
|
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
|
||||||
|
seq = (db.query(models.DjmdKey).count() or 0) + 1
|
||||||
|
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
|
||||||
|
db.session.execute(
|
||||||
|
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
|
||||||
|
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
|
||||||
|
{"id": key_id, "name": name, "seq": seq,
|
||||||
|
"uuid": str(uuidlib.uuid4()), "now": now},
|
||||||
|
)
|
||||||
|
db.flush()
|
||||||
|
return key_id
|
||||||
Loaded 100 of 374 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user