Compare commits

..
49 Commits
Author SHA1 Message Date
patben8 4340e948ac Bumped version number 2026-10-17 20:21:28 +02:00
patben8 fe63acc2a2 Merge pull request #13 from MrPatben8/dev
Implemented Cross-Platform Track Color Support
2026-10-17 20:08:02 +02:00
patben8 06361a851f Implemented cross-platform track color support 2026-10-17 19:50:56 +02:00
patben8 0605dbabe6 Improved release description and file names 2026-10-16 18:04:54 +02:00
patben8 6be99e6d7e Merge pull request #12 from MrPatben8/dev
Implemented self-updating
2026-10-16 17:39:28 +02:00
patben8 0eac972173 Implemented self-updating 2026-10-16 17:38:35 +02:00
patben8 422297d890 Merge pull request #11 from MrPatben8/dev
Implemented Memory Cue Support
2026-10-16 16:06:47 +02:00
patben8 ee48e80440 Bumped version number 2026-10-16 16:04:49 +02:00
patben8 0aeb5019ad Fixed issue with Traktor 4.5 collection round-trip 2026-10-16 15:53:52 +02:00
patben8 1f2ca18e8a Fixed issues with cross-platform memory-cue naming and coloring 2026-10-16 15:04:43 +02:00
patben8 19a604f730 Added full support for memory-cues 2026-10-16 14:50:46 +02:00
patben8 83b0978b14 Merge pull request #10 from MrPatben8/dev
Implemented Raw Waveform View
2026-10-15 17:51:59 +02:00
patben8 0ced274f73 Bumped version number 2026-10-15 17:48:40 +02:00
patben8 fc4e7804b3 Changed how patchnotes are compiled 2026-10-15 17:48:17 +02:00
patben8 77b063ba0e Implemented time readout accuracy setting 2026-10-15 17:42:26 +02:00
patben8 16c3552be6 Changed option keyboard shortcuts to use command instead 2026-10-15 16:36:10 +02:00
patben8 32cfb034e2 Implemented better shortcut menu 2026-10-15 16:30:34 +02:00
patben8 b70798a0fe Implemented track info dialog popup 2026-10-15 15:46:39 +02:00
patben8 4c51f57fe9 Improved context menu positioning when near the bottom of the window 2026-10-15 14:22:40 +02:00
patben8 7b2d6de411 Implemented new set playlist position mode 2026-10-15 10:48:14 +02:00
patben8 8230722105 Implemented raw waveform mode 2026-10-15 10:26:41 +02:00
patben8 1464b1e211 Merge pull request #9 from MrPatben8/dev
Fixed issues on Windows, Implemented drag & drop importing, Improved STEM encoding speed
2026-10-13 17:47:09 +02:00
patben8 10f175b206 Bumped version number 2026-10-13 17:43:20 +02:00
patben8 a65ef959b2 Implemented drag to import 2026-10-13 17:42:24 +02:00
patben8 87cbd3720e Fixed STEM analysis not working on Windows 2026-10-13 10:59:22 +02:00
patben8 591f2bc791 Pararellized STEM aac encoding 2026-10-13 10:45:52 +02:00
patben8 ebe30c1128 Fixed analysis not working on windows 2026-10-12 23:49:19 +02:00
patben8 cd1914216f Fixed library options not appearing in windows 2026-10-12 23:26:33 +02:00
patben8 d10b11f8eb Merge pull request #8 from MrPatben8/dev
Fixed Rekordbox exports
2026-10-12 19:12:41 +02:00
patben8 79a8a843c5 Bumped version number 2026-10-12 19:12:09 +02:00
patben8 0204a322ff Fixed and pinned rekordbox exports 2026-10-12 19:10:20 +02:00
patben8 05051e7056 Merge pull request #7 from MrPatben8/dev
Implemented remote file exploring, fixed STEM playback and improved startup time.
2026-10-12 15:04:40 +02:00
patben8 b5dabbc8a0 Updated the readme 2026-10-12 15:02:46 +02:00
patben8 86bbb7b961 Bumped version number 2026-10-12 13:51:23 +02:00
patben8 d474c662db Fixed slow build startup time and implemented loading screen 2026-10-12 13:20:00 +02:00
patben8 a0df683fee Fixed stem playback not working in build 2026-10-12 11:31:44 +02:00
patben8 3385b794e9 Added setting for export playlist root folder toggle 2026-10-12 10:56:32 +02:00
patben8 2c352b76a1 Added konduktor settings menu 2026-10-12 10:15:14 +02:00
patben8 40630ff78e Added support for remote file exploring 2026-10-12 09:23:34 +02:00
patben8 966f3fe8c5 Bumped version number 2026-10-10 17:42:17 +02:00
patben8 a03b9056a9 Merge pull request #6 from MrPatben8/dev
Implemented dragging engine
2026-10-10 17:40:06 +02:00
patben8 26b556d975 Updated remote protocol version 2026-10-06 23:17:21 +02:00
patben8 c87444bda5 Implemented drag and drop loading 2026-10-06 23:08:34 +02:00
patben8 7ba71981c8 Implemented library rearrangement 2026-10-06 22:51:34 +02:00
patben8 89c7dade25 Tracks can be added to playlists via drag 2026-10-06 22:41:29 +02:00
patben8 b154df430a Implemented drag core and song reorganizing 2026-10-06 22:32:31 +02:00
patben8 e5c7b67626 Implemented playlist reorganizing 2026-10-06 22:25:01 +02:00
patben8 9f79f5a849 Search now includes comments 2026-10-05 23:16:12 +02:00
patben8 c8b86100f0 Track position in playlist can now be typed 2026-10-05 21:01:25 +02:00
175 changed files with 10838 additions and 1350 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
"""Lay out one release's assets under user-facing names, plus the updater's
latest.json and the release notes' Download section.
Run by build.yml's release job:
python3 .github/scripts/release_assets.py artifacts release \\
--version 0.6.0 --tag v0.6.0-b42 --repo owner/konduktor
Finds, anywhere under `artifacts`, what `tauri build` produced: the macOS
`*.dmg` and `*.app.tar.gz` (+ `.sig`) and the Windows `*-setup.exe` (+ `.sig`).
Copies them into `release` as
Konduktor-<version>-macOS.dmg (download)
Konduktor-<version>-Windows-Setup.exe (download; the Windows updater runs it too)
Konduktor-<version>-app-updater.tar.gz (the macOS updater's package)
latest.json (the updater's manifest)
and writes `download.md`. Renaming is safe: the signatures cover contents,
not names, and latest.json is written from the final names. `latest.json`
itself keeps its name: the app asks for releases/download/<tag>/latest.json.
Fails if anything is missing: a manifest lacking a platform is refused by the
updater as a whole.
"""
import argparse
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote
def find_one(root: Path, suffix: str) -> Path:
found = [p for p in root.rglob(f"*{suffix}") if p.is_file()]
if len(found) != 1:
sys.exit(f"expected exactly one *{suffix} under {root}, found {len(found)}")
return found[0]
def signature(asset: Path) -> str:
sig = asset.with_name(asset.name + ".sig")
if not sig.is_file():
sys.exit(f"missing signature {sig}")
return sig.read_text(encoding="utf-8").strip()
def lay_out(artifacts: Path, out: Path, version: str, tag: str, repo: str) -> None:
def url(name: str) -> str:
return f"https://github.com/{repo}/releases/download/{quote(tag)}/{quote(name)}"
dmg = find_one(artifacts, ".dmg")
app = find_one(artifacts, ".app.tar.gz")
setup = find_one(artifacts, "-setup.exe")
names = {
dmg: f"Konduktor-{version}-macOS.dmg",
setup: f"Konduktor-{version}-Windows-Setup.exe",
app: f"Konduktor-{version}-app-updater.tar.gz",
}
# Tauri's platform keys -> the file that platform's updater installs.
manifest = {
"version": version,
"pub_date": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
"platforms": {
"darwin-aarch64": {"signature": signature(app), "url": url(names[app])},
"windows-x86_64": {"signature": signature(setup), "url": url(names[setup])},
},
}
out.mkdir(parents=True, exist_ok=True)
for src, name in names.items():
shutil.copy2(src, out / name)
(out / "latest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
(out / "download.md").write_text(
"## Download\n"
f"- **macOS** (Apple Silicon): [{names[dmg]}]({url(names[dmg])})\n"
f"- **Windows**: [{names[setup]}]({url(names[setup])})\n",
encoding="utf-8",
)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("artifacts", type=Path)
ap.add_argument("out", type=Path)
ap.add_argument("--version", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--repo", required=True)
args = ap.parse_args()
lay_out(args.artifacts, args.out, args.version, args.tag, args.repo)
for p in sorted(args.out.iterdir()):
print(p.name)
if __name__ == "__main__":
main()
+76 -6
View File
@@ -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: |
@@ -85,20 +86,31 @@ jobs:
working-directory: frontend working-directory: frontend
run: npm ci run: npm ci
# createUpdaterArtifacts also signs the in-app update packages
# (Konduktor.app.tar.gz / the NSIS setup.exe) with the updater key, whose
# public half is plugins.updater.pubkey in tauri.conf.json. Losing the
# private key means installed copies can never update themselves again.
- name: Build Tauri app - name: Build Tauri app
working-directory: frontend working-directory: frontend
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: npx tauri build run: npx tauri build
# Stage the single installer per OS into a flat folder. Uploading one # Stage the single installer per OS into a flat folder. Uploading one
# directory (not multiple bundle subpaths) keeps the artifact root at # directory (not multiple bundle subpaths) keeps the artifact root at
# ./installer, so the zip holds the bare file — no nested dmg/ or nsis/ # ./installer, so the zip holds the bare file — no nested dmg/ or nsis/
# folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows # folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows
# (the .msi is intentionally left out). # (the .msi is intentionally left out), plus what the in-app updater
# installs: the .app.tar.gz on macOS (the setup.exe on Windows) and the
# .sig files the release job folds into latest.json.
- name: Stage installer (macOS) - name: Stage installer (macOS)
if: runner.os == 'macOS' if: runner.os == 'macOS'
run: | run: |
mkdir -p installer mkdir -p installer
cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/ cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz.sig installer/
- name: Stage installer (Windows) - name: Stage installer (Windows)
if: runner.os == 'Windows' if: runner.os == 'Windows'
@@ -106,6 +118,7 @@ jobs:
run: | run: |
New-Item -ItemType Directory -Force installer | Out-Null New-Item -ItemType Directory -Force installer | Out-Null
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/ Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe.sig installer/
- name: Upload installer - name: Upload installer
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
@@ -168,6 +181,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
@@ -187,12 +201,68 @@ jobs:
pattern: konduktor-* pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/… path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
# The release's files under user-facing names, the in-app updater's
# latest.json (the app reads releases/download/<tag>/latest.json) and the
# notes' Download section. The .sig files are folded into latest.json and
# not uploaded themselves.
- name: Release assets
run: |
python3 .github/scripts/release_assets.py artifacts release \
--version "${{ steps.version.outputs.version }}" \
--tag "v${{ steps.version.outputs.version }}-b${{ github.run_number }}" \
--repo "${{ github.repository }}"
# Release notes from the "Patch notes" section of the PR that merged this
# commit into main (dev → main merges carry many features in one PR, so
# its title alone says little). Written under "What's Changed", the
# heading the app's update dialog reads. No PR (a manual run, a direct
# push) or no such section → GitHub's generated notes, as before. The
# Download section always comes first (the action puts the body above
# generated notes); the dialog reads only "What's Changed".
- name: Patch notes from the merged PR
id: notes
env:
GH_TOKEN: ${{ github.token }}
run: |
gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \
--jq '[.[] | select(.base.ref == "main" and .merged_at != null)][0].body // ""' \
> pr-body.md || : > pr-body.md
python3 - <<'EOF'
import os, re
body = open("pr-body.md", encoding="utf-8").read().replace("\r\n", "\n")
body = re.sub(r"<!--.*?-->", "", body, flags=re.S)
section, level = [], None
for line in body.split("\n"):
m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line)
if level is None:
if m and re.fullmatch(r"patch[\s-]?notes:?", m.group(2), re.I):
level = len(m.group(1))
elif m and len(m.group(1)) <= level:
break
else:
section.append(line)
notes = "\n".join(section).strip()
found = bool(notes)
with open("release-notes.md", "w", encoding="utf-8") as f:
f.write(open("release/download.md", encoding="utf-8").read())
if found:
f.write("\n## What's Changed\n\n" + notes + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as out:
out.write(f"found={'true' if found else 'false'}\n")
print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.")
EOF
- name: Publish release - 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: release-notes.md
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
fail_on_unmatched_files: true fail_on_unmatched_files: true
files: artifacts/**/* files: |
release/*.dmg
release/*.exe
release/*.tar.gz
release/latest.json
+107 -30
View File
@@ -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,120 @@ 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 --config src-tauri/tauri.unsigned.conf.json
``` ```
The `--config` override skips the in-app updater packages, which are signed
with the release key that only CI holds (`TAURI_SIGNING_PRIVATE_KEY`). With
that key set in the environment, plain `npx tauri build` makes them too.
`build.ps1` picks the right one by itself.
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
gotcha 4 in [CLAUDE.md](CLAUDE.md).
## Output ## 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` as above). Frontend-only changes just need
(its `beforeBuildCommand` rebuilds the web app). `.\build.ps1 -SkipSidecar`.
## Not part of this build: the stem engine
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
released on its own channel by
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
and `windows-x64-cuda`). The app downloads it at runtime into a short
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
limit. You don't need it to build or run the app.
## Known Windows caveats ## 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.
+388 -52
View File
@@ -35,6 +35,21 @@ Two independent apps that talk over HTTP:
- `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the - `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the
error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422), error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422),
mapped to status codes once in `main.py` rather than per route. mapped to status codes once in `main.py` rather than per route.
**`move_playlist(node_id, parent_id, index)`** (sidebar drag and drop,
`POST /api/playlists/move`) moves any tree node; `index` counts the new
parent's children WITHOUT the node, and it returns the node's id AFTER
the move — a Traktor folder's / smart playlist's id is its path, so it
changes (playlists keep their UUID, so export sets never need
retargeting). Gated per node on `PlaylistNode.can_move`. Traktor refuses a
folder or smart playlist landing beside a namesake (as rename does);
Rekordbox renumbers `Seq` itself (pyrekordbox's version cannot move to the
top level) and keeps `masterPlaylists6.xml`'s `ParentId` in step;
OneLibrary renumbers `sequenceNo` from 0, and the pdb follows at Save.
`POST /api/playlists/{id}/add` takes `duplicates`: `skip` / `add` / `ask`
(nothing changes, the count comes back so the UI can ask and resend);
`add` only where `capabilities.playlists.duplicates` — Traktor only, since
OneLibrary's `playlist_content` is keyed on (playlist, content) and
rekordbox's tolerance of a repeat is unmeasured.
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so - `capabilities.py` — `Capabilities`: what the loaded library can persist, so
the UI can gate controls instead of branching on the platform. the UI can gate controls instead of branching on the platform.
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
@@ -155,7 +170,14 @@ Two independent apps that talk over HTTP:
file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz
streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0, streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place
(moov is last, so only two sizes change). The separation is a CALLBACK — (moov is last, so only two sizes change). **Each stream encodes on its
own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`,
104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in
the single-threaded order, so the file is byte-identical; every codec is
opened and the header written before a worker starts, since the first
`mux()` would otherwise open codecs a worker is using. `aac_coder=fast`
was measured and rejected: 3-4x faster per stream, but it drops whole
8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK —
the backend never imports torch; the engine (below) supplies it, the the backend never imports torch; the engine (below) supplies it, the
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB, tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB,
so mono is duplicated by hand; resampling does not move time; both so mono is duplicated by hand; resampling does not move time; both
@@ -293,8 +315,19 @@ Two independent apps that talk over HTTP:
cue at `Kind=4` lands on no pad and Rekordbox shows it as a memory cue. cue at `Kind=4` lands on no pad and Rekordbox shows it as a memory cue.
Get this wrong and cues silently move to the wrong pad or vanish from the Get this wrong and cues silently move to the wrong pad or vanish from the
bank. Point cues AND loops both write; `cue_types` owns the translation. bank. Point cues AND loops both write; `cue_types` owns the translation.
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only **Memory cues are editable** (`add_memory_cue` / `rename_` /
platform with them — the two-platform promotion rule). `set_memory_cue_color` / `delete_memory_cue`, addressed by `CuePoint.id`
= `djmdCue.ID`; decided and MEASURED 2026-10-16, kit M1 in
[the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
`Kind=0`, no ANLZ write, **at most 10 per track** (rekordbox stops
storing the 11th SILENTLY, so the store refuses it with a reason), and
a colour of their OWN — 8 colours (`memory_palette.py`, display RGB
sampled from rekordbox's menu), the 0-based code in **`Color`** with
`ColorTableIndex` NULL (the opposite of a hot cue), `-1` never coloured,
**255** after "No Color", and an unnamed memory LOOP has `Comment=''`.
`_sync_content_cue` writes the mirror in **ROW order** (`rowid`), as
rekordbox does — not by position. A cue on the reserved `Kind=4` is
shown as a memory cue but is not one, so it is not editable.
**Hot cue colour is writable** (`set_cue_color`, `PATCH **Hot cue colour is writable** (`set_cue_color`, `PATCH
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's /api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
@@ -370,8 +403,19 @@ Two independent apps that talk over HTTP:
A pad keeps its colour and (unless given one) its name through a move or A pad keeps its colour and (unless given one) its name through a move or
retype. An `.EXT` without `PCO2` gets both lists seeded from its `PCOB`s on retype. An `.EXT` without `PCO2` gets both lists seeded from its `PCOB`s on
the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest. the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest.
A track with no analysis files refuses cue/grid edits. Memory cues stay A track with no analysis files refuses cue/grid edits.
preserved-but-uneditable. **Memory cues are editable** the way rekordbox 7 edits them on a stick
(kit M2; rekordbox's own bytes are `fixtures/onelibrary-memory-edits`):
`memory_cues.py` does the list edits — ONLY the analysis files change (the
database and both pdbs keep every row); the `.DAT` `PCOB` memory list
PREPENDS a new cue and is relinked as a whole (status 0, bytes 24–27 =
prev/next list index, `anlz_writer.relinked_memory_pcpts`), the `.EXT`
`PCO2` memory list APPENDS it in rekordbox's compact 44-byte form; colour =
`PCP2` byte 28, 1-based (`memory_palette.anlz_byte`), name = the `PCP2`
comment, which grows the entry by its length; cap 10. The id is
content-derived (`cues.memory_cue_id`: stored time, kind, loop end), the
same in both lists. When rekordbox rewrites a `.DAT` it also re-sorts the
untouched hot `PCOB` ascending; Konduktor changes only the list it edits.
**`device_library.py` keeps the stick's legacy `export.pdb` in step** at **`device_library.py` keeps the stick's legacy `export.pdb` in step** at
every Save (rekordbox's own edits let its playlists drift — measured). The every Save (rekordbox's own edits let its playlists drift — measured). The
stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are
@@ -553,7 +597,11 @@ Two independent apps that talk over HTTP:
/ `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED / `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED
to the content folder — resolve then `is_relative_to`, so neither `..` to the content folder — resolve then `is_relative_to`, so neither `..`
nor a symlink escapes — never overwriting, `-2` suffixes, per-session nor a symlink escapes — never overwriting, `-2` suffixes, per-session
so a cancel deletes only its own), `fs/list|space`, `save`, `discard`, so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads`
(the content folder as a Files tree: tags via the shared `FolderScanner`,
file facts, `held` = file → the library's id; audio only for a file a
listing returned, confined; `leads` = the analysis lead per file, None
unless the platform analyses), `save`, `discard`,
`history`, `export-sets`, and the stems routes below. Capabilities are `history`, `export-sets`, and the stems routes below. Capabilities are
the adapter's plus `tracks.audio_destination="library"`, the adapter's plus `tracks.audio_destination="library"`,
`reference=False`, `paths.remappable=False`, `overwrite_risk="none"`. `reference=False`, `paths.remappable=False`, `overwrite_risk="none"`.
@@ -602,6 +650,21 @@ Two independent apps that talk over HTTP:
Rekordbox's add analysis — waveform, grid AND key — is computed HERE Rekordbox's add analysis — waveform, grid AND key — is computed HERE
(`core/add_analysis.prepare` with the lead the upload reports, sent as (`core/add_analysis.prepare` with the lead the upload reports, sent as
`NewTrack.analysis`). `NewTrack.analysis`).
**The content folder browsed like a drive** (decided 2026-10-10,
`folder.py`): `/api/fs/drives` lists the server FIRST (`kind:
"server"`, path `server:`) while a remote is open, and the ordinary
Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` +
the path ON THE SERVER — so the folder view, deck and add dialog need no
second set of routes, and a server path is never taken for the same path
here. `RemoteAdapter.folder_listing` remembers what was listed
(`ServerFiles`, a read-only source); `folder_audio` downloads into the
shared cache by the same facts as a library track's. Adding one is IN
PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`):
nothing uploaded, nothing asked; files the library holds map to their
ids; where the server reports a lead the file is fetched and analysed
here, as an upload is. Server paths go back to the server in its own
spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on
Windows.
**Convert to Stems** (`stems/remote_convert.py`): the server plans **Convert to Stems** (`stems/remote_convert.py`): the server plans
(`/v1/stems/plan`, its `convert.plan`), this computer downloads, (`/v1/stems/plan`, its `convert.plan`), this computer downloads,
separates and encodes, uploads each verified file (`/v1/stems/stage`, separates and encodes, uploads each verified file (`/v1/stems/stage`,
@@ -776,9 +839,17 @@ Two independent apps that talk over HTTP:
expandable Local Storage. A drive carrying a OneLibrary library opens as a expandable Local Storage. A drive carrying a OneLibrary library opens as a
device as before, and EVERY drive has a lazily-fetched **Files** tree; device as before, and EVERY drive has a lazily-fetched **Files** tree;
clicking a folder is the `folder` source kind — its audio in the ordinary clicking a folder is the `folder` source kind — its audio in the ordinary
table, read-only via `readonly_cause: 'not_in_library'`, with files the table, with files the collection already holds checked off in the #
collection already holds checked off in the # column (`TrackTable`'s column (`TrackTable`'s `marked`). **A held file's row IS the collection
`marked`). A browsed device is read-only (cause `browsing`); **"Open for track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps
its collection id back to the folder id that adding takes): it shows the
collection's key/rating/cues/plays, loads into the deck as origin
`collection` (`loadTrack`), edits inline and from the menu, and drops onto
a playlist directly. The table runs on the COLLECTION's capabilities; a
LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor
opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add
it first (`askToAdd`), and in the deck it stays read-only
(`not_in_library`). A browsed device is read-only (cause `browsing`); **"Open for
editing…"** — the drive row's right-click menu, and a button while browsing editing…"** — the drive row's right-click menu, and a button while browsing
a device whose caps say `browsing` — opens it as THE library via App's a device whose caps say `browsing` — opens it as THE library via App's
`openForEditing` (unsaved-edits confirm, source closed, library opened). `openForEditing` (unsaved-edits confirm, source closed, library opened).
@@ -811,6 +882,21 @@ Two independent apps that talk over HTTP:
space below the rows creates at the top level, and the new node is named space below the rows creates at the top level, and the new node is named
in place (Esc or an empty name creates nothing). Rename/Delete are on the in place (Esc or an empty name creates nothing). Rename/Delete are on the
same menu and the row's hover buttons, which share one set of actions. same menu and the row's hover buttons, which share one set of actions.
**Drag and drop** (lib/drag.tsx, below): a row is a drag source and a drop
target with ZONES — a playlist's upper/lower half is before/after; a
folder's top/bottom quarter before/after and its middle INTO (appended),
except the bottom quarter of an OPEN folder, which is "first inside"; the
empty space below the rows is "end of the top level". Never into the
dragged node's own subtree, and a drop that would change nothing shows no
indicator. Holding over a collapsed folder opens it after 0.6 s (tracks
too, so nested playlists are reachable). Tracks dropped on a playlist go
through `lib/addTracks.ts` — shared with the context menu's "Add to" —
which ASKS about duplicates where the platform can hold them (decided:
ask each time), and Cmd (Ctrl on Windows; `lib/modKey.ts`) moves them out of the editable playlist
they came from. A device's or Files folder's tracks open `ImportDialog`
(`trackIds` + `target`) / `AddFilesDialog` with the target filled in
(`onAddForeign`), so copy-vs-reference is still asked. Export rows take the
collection's tracks and any playlist/folder (as "Add to export" does).
A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE` A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE`
playlist routes take a `:path` param, a folder name may not contain `/`, playlist routes take a `:path` param, a folder name may not contain `/`,
and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close / and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close /
@@ -818,8 +904,18 @@ Two independent apps that talk over HTTP:
shell quits anyway after ~2 s without one, so a hung page cannot trap the shell quits anyway after ~2 s without one, so a hung page cannot trap the
user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard
· Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer; · Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer;
browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx`
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), around everything but `AmbientBackdrop`: the shell opens the window AT ONCE
and starts the sidecar beside it, so nothing that calls the API mounts
until `backend_status` / `konduktor://backend` says ready, which is when
`setApiBase` gets the sidecar's address. Meanwhile `StartupScreen` shows
the icon with a generated waveform scrolling under a fixed playhead, a
"first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s,
and if the sidecar exits its last 30 output lines with Copy details / Quit
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
ready it answers quit requests itself — nothing can be unsaved — and stops
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
dirty, and the settings gear beside it, whose menu (or `?` anywhere) opens `ShortcutsDialog` — a KEYBOARD MAP (decided 2026-10-15): keys lit in the colour of what they do, a caption explaining the key pointed at or pressed (pressing explains, it never acts: a capture-phase listener keeps the deck's and table's keys from firing), holding or picking ⇧ / Cmd-Ctrl relights it with that layer, mouse gestures listed beneath. It shrinks to fit the dialog and drops the words on the keys when too small. Its content is `lib/shortcuts.ts`, written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder` — and `timeReadoutDecimals` (0–3, default 1: the deck's ELAPSED / REMAIN, truncated, never rounded). The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
`TrackTable` (**the one track list** — All Tracks, playlists, exports and `TrackTable` (**the one track list** — All Tracks, playlists, exports and
devices. TanStack Table + **virtualized** grid; per-row play button, devices. TanStack Table + **virtualized** grid; per-row play button,
configurable columns, header sorting, inline double-click editing, and configurable columns, header sorting, inline double-click editing, and
@@ -838,7 +934,43 @@ Two independent apps that talk over HTTP:
not dnd-kit sortable**: a SortableContext around the virtualizer loops on its not dnd-kit sortable**: a SortableContext around the virtualizer loops on its
flushSync-driven measurement — which is why playlists were once a separate, flushSync-driven measurement — which is why playlists were once a separate,
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.) pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.
Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row
carries the selection, the payload's `lead` is the row grabbed, `dragFrom`
says whose ids they are and which editable playlist a Cmd/Ctrl-drag leaves — a Cmd/Ctrl press arms a drag, and stays a toggle-click if it never moves);
the in-table reorder is just the table's own drop target.)
**`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06,
[the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)):
ONE gesture, the TARGET decides what it means. Pointer events, NOT HTML5
DnD — Tauri's webview captures native drag events for file drops on
Windows. A source calls `beginDrag` past a 6 px threshold (`usePressToDrag`
for plain elements); targets register with `useDropTarget({ hint, label,
onDrop })` and are found by `elementFromPoint` then up the ancestors, the
innermost whose `hint` is non-null winning, so a target declines a spot by
returning null. A module-level store read through narrow
`useSyncExternalStore` selectors: a move re-renders only the target under
the pointer and the ghost (`DragLayer`, mounted in main.tsx), never the
table. Esc cancels (before every other Esc handler); the click after a drop
is swallowed; `data-drag-scroll="<top inset>"` makes an element scroll at a
20 px edge after a 250 ms dwell — any less and the first/last visible row
could not be dropped on. Targets: playlist + export rows (Sidebar,
ExportsSection), the tree's zones, the table's reorder, and the DECK
(App), which loads the grabbed row paused, in its own origin.
**Files from Finder / Explorer** (decided 2026-10-13) ride the same store
as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent`
(real paths; a plain browser has none, so no file drop there) through
`nativeDragStart`/`Move`/`End`, refused at enter while an `aria-modal`
dialog is open or no library is loaded. A playlist/export row opens
`AddFilesDialog` with its target, ONE audio file on the deck loads it to
listen to, anywhere else (App's root target, with a window overlay) adds
to the collection — or says why the library cannot. `POST
/api/folder/dropped` resolves the paths first (`FolderScanner.dropped`:
folders RECURSIVELY, capped at `MAX_DROPPED`; single files held apart
from the folder cache so a partial listing never hides a folder's other
files from the sidebar) and makes each file addable and playable through
the folder routes. Copy vs in place is asked as for a browsed folder; the
add preview counts external-drive files PER FILE (`removable_count` /
`removable_drives`, a drop can mix drives) and `in_destination`.
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where = `ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
Replace the originals (its option STATES that Save deletes them, since Replace the originals (its option STATES that Save deletes them, since
the choice is remembered and may be preselected) or Save to a folder; In the choice is remembered and may be preselected) or Save to a folder; In
@@ -884,7 +1016,14 @@ Two independent apps that talk over HTTP:
`ContextMenu` (supports `▸` submenus, section headings, separators and `ContextMenu` (supports `▸` submenus, section headings, separators and
checkbox items that toggle without closing — the header row's right-click checkbox items that toggle without closing — the header row's right-click
column chooser uses those; "Add to" lists column chooser uses those; "Add to" lists
playlists + exports and acts on the whole selection; "Remove ▸" holds playlists + exports and acts on the whole selection; in an editable
playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`)
moves the selection as ONE block so its first track lands at #N —
allowed while sorted/filtered, unlike drag, because it reorders the FULL
entry list. While the table is sorted the dialog asks the block's Order:
"As sorted" (default; the menu's ids arrive in VIEW order, so the sort is
written into the playlist and survives clearing it) or playlist order;
"Remove ▸" holds
From this playlist / From this export / Grids / Hotcues / From collection, From this playlist / From this export / Grids / Hotcues / From collection,
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog` confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
@@ -896,10 +1035,28 @@ Two independent apps that talk over HTTP:
stem engine publishes `engine-v*` releases in the same repo — and, stem engine publishes `engine-v*` releases in the same repo — and,
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
`-b<N>` bumps don't count — shows an update dialog with the release's `-b<N>` bumps don't count — shows an update dialog with the release's
"What's Changed" bullets; Download opens the release page in the system "What's Changed" bullets; "Skip this version" persists
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` `skippedUpdateVersion` to userprefs via `/api/prefs`; check failures are
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to silent. **In the desktop app, Update installs it** (decided 2026-10-16,
userprefs via `/api/prefs`; all failures are silent). [the discussion](.claude/discussions/discuss-self-update-2026-10-16.md)):
`update_download` (lib.rs, tauri-plugin-updater) reads THAT release's
`latest.json`, downloads with progress in the dialog, verifies the
signature and STAGES the package in app-cache; `update_restart` then
quits through the ordinary quit request, so QuitGuard asks about unsaved
edits. The package is installed in `exit_now`, only AFTER the sidecar is
killed — on macOS the running backend lazily loads native libraries from
inside the bundle being replaced, on Windows its `.exe` is locked (the
shell waits until it can open it for writing) — then the app relaunches.
Cancel in QuitGuard keeps it staged (`konduktor://update-deferred`) and the
next ordinary quit installs it without relaunching. On macOS a bundle run
from the DMG, translocated, or in a folder the user cannot write is
refused BEFORE downloading (the updater's own admin-password fallback
runs on the main thread, which the quit path may hold). Any failure shows
its reason + "Open release page" (the old Download, still the button in a
plain browser); an install that failed at exit is written to
`failed.json` and reported by the next launch (`update_take_failure`).
The updater's crate is built WITHOUT its `zip` feature — only for v1-style
zipped Windows installers, and every zip 4.x is yanked.
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four - **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
their SUM, as Traktor's stem deck does — the mix stream is never decoded, their SUM, as Traktor's stem deck does — the mix stream is never decoded,
@@ -912,7 +1069,7 @@ Two independent apps that talk over HTTP:
one amplitude lane per stem, each normalised to its own 99.5th percentile one amplitude lane per stem, each normalised to its own 99.5th percentile
but never below 5% of the loudest (a silent stem stays silent). but never below 5% of the loudest (a silent stem stays silent).
`MainWaveform` draws the lanes in the file's own colours with a mute `MainWaveform` draws the lanes in the file's own colours with a mute
button at each lane's left edge (click = mute, Alt/Option-click = solo); button at each lane's left edge (click = mute, Cmd/Ctrl-click = solo);
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
mutes (every other stem muted), so each stem stays freely mutable after mutes (every other stem muted), so each stem stays freely mutable after
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
@@ -923,11 +1080,14 @@ Two independent apps that talk over HTTP:
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` — badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and
Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**: Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**:
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, owned `MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll,
by `PrepStrip` so it survives track switches and persists) over 0.25–64 s across, owned by `PrepStrip` so it survives track switches and
persists; a toggle under the zoom buttons draws the RAW signal instead
of bars — `lib/rawWave.ts`, below; persisted as `mainWaveRaw`) over
`OverviewWaveform`, which frames the main view's visible range around the `OverviewWaveform`, which frames the main view's visible range around the
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls` (where `cues.memory_cues`) the **Hot / Mem** switch (`ModeSwitch`, the same component as BEAT / MAN), then
`HotcueBar`, `MemoryCueStrip` (Mem) OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
(±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a (±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a
**container** and gives way in stages instead of overlapping: each pad **container** and gives way in stages instead of overlapping: each pad
queries its own width and drops its name below 4rem (the bank never goes queries its own width and drops its name below 4rem (the bank never goes
@@ -951,6 +1111,20 @@ Two independent apps that talk over HTTP:
and only jump the playhead when no loop is engaged. The move sets the new and only jump the playhead when no loop is engaged. The move sets the new
loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so
seeking first wraps the playhead back into the old loop. seeking first wraps the playhead back into the old loop.
- **Memory cues** (decided 2026-10-16, [the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
Mem mode replaces the pads with `MemoryCueStrip` — chips in TIME order,
scrolling sideways, labelled by name else `m:ss.s`, after a + Memory button
(at the snapped playhead, or the engaged loop as a memory loop;
disabled with the reason past `max_memory_cues`). **Clicking a chip is
CDJ CALL, not a trigger**: jump there and make it the CUE point (paused
stays paused), a memory loop engaging as a loop pad does (`enterCue`).
Right-click: Type (point types, where the platform has more than one —
Traktor; `set_memory_cue_type`, a loop is not retyped), Colour
(`memory_palette`), Rename… (the shared `RenameField`), Delete — no move
(rekordbox has none: a move is delete + add). An uncoloured memory cue
draws in its TYPE colour, exactly as a hot cue does (`cueColor` /
`core/cue_colors.effective_color`). Digit keys stay on hot cues. The mode
persists as `cueBankMode`.
- **Hotcue edits live on the pad's right-click menu** (type as one-click - **Hotcue edits live on the pad's right-click menu** (type as one-click
choices, a colour swatch grid + Default where `cues.color` is `palette` — choices, a colour swatch grid + Default where `cues.color` is `palette` —
`ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone `ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone
@@ -981,9 +1155,24 @@ Two independent apps that talk over HTTP:
`cues.palette`; a `free` platform gets no picker yet), the rating scale `cues.palette`; a `free` platform gets no picker yet), the rating scale
(`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`, (`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`,
`can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag, `can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag,
since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter since a platform may allow renaming but not deleting. Memory cues: the deck's
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`, and Hot / Mem toggle shows on `cues.memory_cues`, + Memory refuses past
memory-cue *editing* (one-platform features stay preserved-but-uneditable). `cues.max_memory_cues`, and a memory cue's swatches are `cues.memory_palette`
where `cues.memory_color` is `palette` (its own 8, not `palette`'s 16).
**Track colour** (decided 2026-10-17, [the discussion](.claude/discussions/discuss-track-colour-2026-10-17.md)):
shown as the Type column's icon in `Track.color_hex`; set from the context
menu's **Colour ▸** (swatches from `tracks.colors`, + No Color, the whole
selection, `PATCH /api/tracks/color`) — nowhere else. `Track.color` is a
neutral NAME (`TrackColor`: pink red orange yellow green aqua blue purple),
which is what crosses platforms; each adapter's `track_palette.py` maps its
codes to it BY NAME, not hue: Traktor `INFO@COLOR` 1-7 = Red Orange Yellow
Green Blue Violet(purple) Magenta(pink), measured (kit T1), no file tag;
rekordbox `ColorID` / OneLibrary `color_id` / pdb `color_id` 1-8 = Pink…
Purple, 0 none. Traktor's Blue LOOKS like rekordbox's Aqua but crosses as
Blue (the name is the DJ's category); aqua arriving in Traktor becomes Blue.
Unmeasured: what Traktor leaves after "None" (Konduktor removes the attribute).
Carried but deliberately unused until a second adapter
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`.
- `lib/trackColumns.tsx` — single source of truth for the library table's - `lib/trackColumns.tsx` — single source of truth for the library table's
columns (defs, default widths/visibility/order, the Columns-menu list, the columns (defs, default widths/visibility/order, the Columns-menu list, the
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
@@ -1006,6 +1195,7 @@ Two independent apps that talk over HTTP:
```bash ```bash
./dev.sh # start both servers (see README for one-time setup) ./dev.sh # start both servers (see README for one-time setup)
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
# Backend # Backend
cd backend && source .venv/bin/activate cd backend && source .venv/bin/activate
@@ -1051,10 +1241,31 @@ serialization path.** It enforces:
KEY attribute and one `<MUSICAL_KEY>` between LOUDNESS and CUE_V2 in KEY attribute and one `<MUSICAL_KEY>` between LOUDNESS and CUE_V2 in
Traktor's layout; the encoding matches the real collection; a Camelot Traktor's layout; the encoding matches the real collection; a Camelot
collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the
key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. And
**`move_playlist`** (O): the COLLECTION is untouched, a move round-trips and
moving back is byte-identical; a folder moves with its subtree and answers
its new path id; into its own descendant / beside a namesake is refused with
nothing changed; a smart playlist moves by its path id; a no-op is not dirty.
And **memory cues** (P): add / rename / delete change only that `<ENTRY>`'s
cue lines, in Traktor's shape (`HOTCUE="-1"`, `n.n.`), add + delete
round-trips byte for byte, new cues (hot ones too) are INSERTED by START,
and a pad + memory cue at one START project once, as the pad.
And **`>` / quotes in attribute values** (Q): Traktor leaves `>` raw, and
an empty element holding one (4.5's default "Recently added" query
`$IMPORTDATE >= MONTHS_AGO(1)`, a comment, a file name) once came back
self-closed (`/>`, which Traktor never writes); a value containing
`name='x'` once came back with a bare `"` (malformed). Both were in the
fork's `format_traktor_layout`, fixed there (2026-10-16).
And **track colour** (R): `set_track_color` changes one line, that
entry's `<INFO>`, with `COLOR` last as Traktor writes it; aqua is stored as
Blue; clearing restores the original bytes; and a Traktor 4.5 collection
holding coloured tracks (when on the machine) renders byte-identically.
The guard that catches serialization regressions like the lxml reformatting bug. The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
changes nothing and counts) and `/api/playlists/move` (path id answered,
400 into itself, 404 unknown).
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated - `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every
@@ -1071,7 +1282,10 @@ serialization path.** It enforces:
48 kHz resampling does not move time; MP3 and FLAC through both encoders give 48 kHz resampling does not move time; MP3 and FLAC through both encoders give
five streams with only the mix enabled, no shift (cross-correlation), the five streams with only the mix enabled, no shift (cross-correlation), the
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a
shifted, truncated or box-less file; a raising checkpoint cancels. shifted, truncated or box-less file; a raising checkpoint cancels. The
threaded encode is byte-identical to a single-threaded reference (with each
encoder present), reports progress 0 → 1, and a cancel or a failing encoder
thread leaves no thread running.
- `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real - `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real
collection with a generated MP3 (with header) and a real stem file: prep collection with a generated MP3 (with header) and a real stem file: prep
reads back at the same decoded second while its START moves by the 2257- reads back at the same decoded second while its START moves by the 2257-
@@ -1122,7 +1336,9 @@ serialization path.** It enforces:
against SQLite). Asserts a no-op save changes zero rows; a one-field edit against SQLite). Asserts a no-op save changes zero rows; a one-field edit
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
counter up by one and the edited row stamped with it; edits are invisible on counter up by one and the edited row stamped with it; edits are invisible on
disk until save; and playlist create/fill/rename/delete round-trip. And disk until save; and playlist create/fill/rename/delete round-trip, and
`move_playlist` (E2) changes only `djmdPlaylist` rows + the counter with
`Seq` 1..n in both parents. And
**removing a track** deletes exactly the rows Rekordbox 7 deletes (measured **removing a track** deletes exactly the rows Rekordbox 7 deletes (measured
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`, 2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist` `djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
@@ -1144,7 +1360,13 @@ serialization path.** It enforces:
and the counter, pointing at its OWN row (found by meaning, not name); a and the counter, pointing at its OWN row (found by meaning, not name); a
missing key adds one `djmdKey` row as rekordbox creates its own — its missing key adds one `djmdKey` row as rekordbox creates its own — its
spelling, `Seq` NULL, its own USN (so through the ORM; a raw insert is spelling, `Seq` NULL, its own USN (so through the ORM; a raw insert is
left unstamped) — which the next `set_key` reuses. left unstamped) — which the next `set_key` reuses. And **memory cues** (G2):
M1's measured row shapes (point: `Color -1`, CTI NULL; loop: `255/0`,
`Comment ''`), colour in `Color` (Blue 6) with CTI NULL, No Color = 255, the
mirror in ROW order, rename touching only `Comment` (+ the USN pyrekordbox
stamps on every cue write — rekordbox's own leave it NULL, and it has
accepted ours), the 11th refused with nothing changed, delete removing the
row outright.
- `test_onelibrary_adapter.py` — the third adapter against the same contract. - `test_onelibrary_adapter.py` — the third adapter against the same contract.
Unlike the Rekordbox tests it needs **nothing installed and nothing plugged Unlike the Rekordbox tests it needs **nothing installed and nothing plugged
in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed
@@ -1161,7 +1383,8 @@ serialization path.** It enforces:
changes zero rows, a title edit exactly `content.title` (no counter, as changes zero rows, a title edit exactly `content.title` (no counter, as
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries `nameForSearch` NULL, a new playlist on top with siblings shifted, entries
from 1; and the stick hazards — another app's write refused, an unplugged from 1, a move changing only parent + `sequenceNo` (0..n-1 in both
parents); and the stick hazards — another app's write refused, an unplugged
drive keeps the edits, stale `-shm` deleted, the backup holds the old rows, drive keeps the edits, stale `-shm` deleted, the backup holds the old rows,
the drive never held open, file tags written (title yes, rating no). And the drive never held open, file tags written (title yes, rating no). And
`set_key`: an existing key changes only `content.key_id` and reaches TKEY as `set_key`: an existing key changes only `content.key_id` and reaches TKEY as
@@ -1174,10 +1397,15 @@ serialization path.** It enforces:
new `PQTZ` keeps the marker where it was (rekordbox's own halving moved its new `PQTZ` keeps the marker where it was (rekordbox's own halving moved its
anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the
drive before Save, only the touched tags change (in place, order kept), a drive before Save, only the touched tags change (in place, order kept), a
moved pad keeps colour and name, memory cues refused, swatches only, a moved pad keeps colour and name, swatches only, a
same-tempo marker collapses (a per-beat grid has no markers), another app's same-tempo marker collapses (a per-beat grid has no markers), another app's
ANLZ write refused, an `.EXT` with no `PCO2` keeps every pad, a track with no ANLZ write refused, an `.EXT` with no `PCO2` keeps every pad, a track with no
analysis files refuses. analysis files refuses. And **memory cues against rekordbox's own edits**
(`fixtures/onelibrary-memory-edits`): add a cue, add a loop, add up to 10, recolour,
comment and delete, each replayed with `memory_cues` on `before/` and equal
to `after/` tag for tag (the `.DAT` hot list compared as a set — rekordbox
re-sorts it); then through the adapter on the demo drive: palette, cap,
NotFound, nothing before Save, and Save changing only the two memory lists.
- `test_onelibrary_pdb.py` — the Device Library rebuild on Goober's own - `test_onelibrary_pdb.py` — the Device Library rebuild on Goober's own
`export.pdb`: every track row reads (rows end at their last string; stale `export.pdb`: every track row reads (rows end at their last string; stale
heap tails ignored), a no-op rebuild returns None and a no-op save leaves the heap tails ignored), a no-op rebuild returns None and a no-op save leaves the
@@ -1194,10 +1422,15 @@ serialization path.** It enforces:
and files only at Save, renumbers playlists and prunes empty folders. and files only at Save, renumbers playlists and prunes empty folders.
- `test_import.py` — the import feature end to end: a drive's tracks into a temp - `test_import.py` — the import feature end to end: a drive's tracks into a temp
copy of the real collection. Asserts the prep survives (hot cues keep their copy of the real collection. Asserts the prep survives (hot cues keep their
PAD, memory cues fill spare ones, the flexible grid crosses intact, no PAD, memory cues arrive as Traktor memory cues (`HOTCUE="-1"`; one on a
pad's START shows once, as the pad), a hot cue displaced with no spare pad
becomes a memory cue instead of being dropped, the flexible grid crosses intact, no
companion cue is invented), that the existing 8,485 entries render companion cue is invented), that the existing 8,485 entries render
byte-identically, that the job registry runs/fails/cancels, and that a byte-identically, that the job registry runs/fails/cancels, and that a
cancelled import leaves **no orphaned audio and an untouched collection**. cancelled import leaves **no orphaned audio and an untouched collection**.
And the route with chosen `track_ids` + `into_playlist` + `export_id` (a
device drop): only that track, into the playlist and the export, no drive
folder made.
- `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the - `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the
tempo and first beat are known rather than borrowed from another analyser: tempo and first beat are known rather than borrowed from another analyser:
exact integer and non-integer BPMs, the 125 BPM the old detector could not exact integer and non-integer BPMs, the 125 BPM the old detector could not
@@ -1262,7 +1495,11 @@ serialization path.** It enforces:
scan did not find; **a file the collection already points at is never added scan did not find; **a file the collection already points at is never added
twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt
collection) but still reaches the playlist/export it was headed for; "copy" collection) but still reaches the playlist/export it was headed for; "copy"
points the entry at the copy and "reference" at the original. points the entry at the copy and "reference" at the original. And a DROP
(`/api/folder/dropped`): folders recursively minus hidden ones, dropped
non-audio counted as skipped, only what was dropped becomes streamable, the
folder's own listing stays whole, the cap, held files as their collection
track, and the preview's per-file external-drive count and `in_destination`.
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it - `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
replaced was invisible: `/api/library/options` flattened every driver's replaced was invisible: `/api/library/options` flattened every driver's
detections and returned `[0]`, so a plugged-in USB stick could be offered as detections and returned `[0]`, so a plugged-in USB stick could be offered as
@@ -1345,7 +1582,11 @@ serialization path.** It enforces:
only the edited `<ENTRY>` THROUGH the trip, one download per file, Analyze only the edited `<ENTRY>` THROUGH the trip, one download per file, Analyze
on the cached copy, export (and a re-export copying nothing), an upload on the cached copy, export (and a re-export copying nothing), an upload
stored in the mapping's stored form, takeover → read-only at once, stored in the mapping's stored form, takeover → read-only at once,
reopening names the holder and the edits left, leaving releases. reopening names the holder and the edits left, leaving releases. And the
content folder as a drive: listed first, confined, held files ticked off,
auditioned with one download, an add IN PLACE (no upload, the held one not
added twice, both into the playlist, analysed here when the server reports
a lead).
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine: - `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
the plan's transfer and two-machine space, Replace parks and swaps ON THE the plan's transfer and two-machine space, Replace parks and swaps ON THE
SERVER (saved file untouched until Save, which deletes the parked SERVER (saved file untouched until Save, which deletes the parked
@@ -1366,14 +1607,25 @@ frontend at `http://localhost:5173`.
1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is 1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is
stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins the dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin. GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.
**`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no **`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so `onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` → (`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`; rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
the Rekordbox adapter uses the new names. `db6` still works as a deprecated `models`, `BLOB` in `masterdb.database`).
alias and is **removed in 0.6.0**. **Both GitHub deps are pinned to a COMMIT, never bare master**: the
`devicelib_plus` → `onelibrary` rename reached CI's fresh install while dev
venvs kept the old commit, and a release shipped that could not export or
read OneLibrary while every local test passed. Move a pin on purpose, with
`./run_tests.sh`.
**PyAV: open files for reading through `core/pyav.open_input`, never
`av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless
given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs
fresh (it got 19) while a dev venv keeps what it had (18), so code passing
the keyword passed every local test and shipped a release whose deck played
every stem track as the mix. `requirements.txt` caps `av<20`: check
`pyav.py` before raising it.
2. **The collection is real, irreplaceable data — protect it.** Every save 2. **The collection is real, irreplaceable data — protect it.** Every save
writes a timestamped `.bak` first (into a `backups/` folder next to the writes a timestamped `.bak` first (into a `backups/` folder next to the
collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the
@@ -1383,6 +1635,21 @@ frontend at `http://localhost:5173`.
render is the library's own pipeline (see "Write path"), which reproduces render is the library's own pipeline (see "Write path"), which reproduces
Traktor's byte-exact layout so a no-op save is byte-identical and only edited Traktor's byte-exact layout so a no-op save is byte-identical and only edited
objects diff. `test_save_fidelity.py` enforces this. objects diff. `test_save_fidelity.py` enforces this.
4. **The desktop sidecar is a PyInstaller ONEDIR folder — never go back to
onefile.** A onefile binary unpacked ~390 native libraries into a NEW temp
folder on every launch, and macOS (XProtect / syspolicyd) checks each library
it has not seen before as it is dlopen()ed, keyed per FILE: the window
appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load
them all fresh, 1 s once seen). As a folder in the app they are checked
once; a launch is ~0.5 s. `build_sidecar.*` stages
`src-tauri/binaries/konduktor-sidecar/`; `lib.rs` spawns
`<resources>/sidecar/konduktor-sidecar[.exe]`. On macOS it is bundled by
`tauri.macos.conf.json`'s `bundle.macOS.files`, NOT `bundle.resources`:
the resource copier follows symlinks, turning PyInstaller's 37 library
aliases (`_internal/libavcodec… -> av/.dylibs/…`, `Python.framework`'s
`Versions/Current`) into second copies a library could be loaded twice
from. Windows has no such links and uses `resources`
(`tauri.windows.conf.json`).
## Data model notes ## Data model notes
@@ -1399,6 +1666,9 @@ frontend at `http://localhost:5173`.
`add_entry` write BOTH, the text in the collection's majority notation `add_entry` write BOTH, the text in the collection's majority notation
(`TraktorStore.key_notation()`; an empty collection — an export — takes a (`TraktorStore.key_notation()`; an empty collection — an export — takes a
Traktor-native source's own, so Traktor→Traktor keeps the user's). Traktor-native source's own, so Traktor→Traktor keeps the user's).
- **Track colour** = `INFO@COLOR`, 1-7 in the Color menu's order (Red …
Magenta), the LAST attribute of `<INFO>`; collection-only (`_COLLECTION_ONLY_FIELDS`).
See `track_palette.py`.
- **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor. - **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor.
Traktor stores each as a `CUE_V2 TYPE="4"` with its own `<GRID BPM>` child Traktor stores each as a `CUE_V2 TYPE="4"` with its own `<GRID BPM>` child
(flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by (flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
@@ -1420,6 +1690,16 @@ frontend at `http://localhost:5173`.
load-bearing: 49 uncoloured cues and 18 *loops* also sit within 1 ms of a load-bearing: 49 uncoloured cues and 18 *loops* also sit within 1 ms of a
marker and must not be dragged or deleted. `backend/konduktor/beatgrid.py` marker and must not be dragged or deleted. `backend/konduktor/beatgrid.py`
is the single shared definition of all of this. is the single shared definition of all of this.
- **Memory cues are `CUE_V2`s on no pad** (`HOTCUE="-1"`) WITHOUT a `<GRID>`
— a grid marker is also `HOTCUE="-1"`, and the `<GRID>` child is the only
test (`projection.is_memory_cue`). Measured in Traktor 4.5 (kit M3,
2026-10-16): any type, no limit, drawn on the waveform, reached with the
cue panel's ‹ ›, a name shown in the cue panel, and a Konduktor-written one
kept byte for byte. MAP puts a pad on one and leaves the memory cue at the
same START; Traktor draws ONE marker, so the projection shows the pad only.
Their id is content-derived (`m:<START>:<TYPE>:<LEN>:<n>`). Traktor keeps
`CUE_V2` sorted by START, so the store INSERTS new cues in place
(`_insert_cue`) rather than appending.
- **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type` - **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type`
is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and
have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`; have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`;
@@ -1528,7 +1808,22 @@ that number and nothing else — everything derives from it:
- **CI release** — `.github/workflows/build.yml` reads it with - **CI release** — `.github/workflows/build.yml` reads it with
`jq .version frontend/package.json` and tags each push `jq .version frontend/package.json` and tags each push
`v<version>-b<run_number>` (release name `Konduktor v<version>-b<run_number>`). `v<version>-b<run_number>` (release name `Konduktor v<version>-b<run_number>`).
The `-b<N>` suffix keeps every push's tag/release unique. The `-b<N>` suffix keeps every push's tag/release unique. Each release also
carries its files under user-facing names, laid out by
`.github/scripts/release_assets.py`: `Konduktor-<v>-macOS.dmg`,
`Konduktor-<v>-Windows-Setup.exe` (also the Windows update package),
`Konduktor-<v>-app-updater.tar.gz` (the macOS update package) and the
in-app updater's `latest.json` (`version` = package.json's, each platform's
URL + signature inlined; the name is fixed — the app asks for it by name).
The notes open with a "Download" section linking the two installers, above
the PR's patch notes or GitHub's generated ones; the update dialog reads
only "What's Changed" and skips "Download" when falling back.
`bundle.createUpdaterArtifacts` signs those with the updater key: the
repo secrets `TAURI_SIGNING_PRIVATE_KEY` / `_PASSWORD`, public half in
`tauri.conf.json` `plugins.updater.pubkey`. **Losing the private key means
installed copies can never update themselves again** — it is backed up
outside the repo. A local build without it passes
`--config src-tauri/tauri.unsigned.conf.json` (`build.ps1` does so itself).
- **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata - **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata
(Tauri uses the config's `../package.json`); don't treat it as the app version. (Tauri uses the config's `../package.json`); don't treat it as the app version.
@@ -1617,9 +1912,11 @@ that number and nothing else — everything derives from it:
that swap so `SaveBar` still saves collection edits. While a device's that swap so `SaveBar` still saves collection edits. While a device's
capabilities load the fallback is read-only, never the collection's — capabilities load the fallback is read-only, never the collection's —
guessing "writable" for one frame would offer an edit bound for the wrong guessing "writable" for one frame would offer an edit bound for the wrong
library. Lossiness follows the settled rule: memory cues become hot cues in library. Lossiness follows the settled rule: memory cues stay memory cues
spare pads (earliest first), cue colour is dropped (Traktor derives it from (Traktor's `HOTCUE="-1"`; until 2026-10-16 they were promoted to spare
type). pads), a hot cue whose pad is taken moves to a spare pad, else becomes a
memory cue; cue colour is dropped (Traktor derives it from type). Into
Rekordbox / OneLibrary only the first 10 memory cues cross (rekordbox's cap).
- ✅ OneLibrary adapter — **reading and editing done**, at parity with the - ✅ OneLibrary adapter — **reading and editing done**, at parity with the
Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)). Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)).
A OneLibrary USB drive opens, projects, browses and searches: tracks, A OneLibrary USB drive opens, projects, browses and searches: tracks,
@@ -1628,8 +1925,7 @@ that number and nothing else — everything derives from it:
files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild
on save, adding/removing tracks (the library places the audio), Save via a on save, adding/removing tracks (the library places the audio), Save via a
working copy, and "Open for editing…" on a Devices row — all verified in working copy, and "Open for editing…" on a Devices row — all verified in
rekordbox 7. Same gaps as Rekordbox: cover-art writing, memory-cue editing, rekordbox 7. Same gaps as Rekordbox: cover-art writing, stem conversion. All format research — including the schema, which has no
stem conversion. All format research — including the schema, which has no
public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow - 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
are settled; see are settled; see
@@ -1648,7 +1944,11 @@ that number and nothing else — everything derives from it:
**volume-relative** `DIR`, never a host path — so a USB export is portable by **volume-relative** `DIR`, never a host path — so a USB export is portable by
construction, and the `.nml` cannot be written until the destination is known. construction, and the `.nml` cannot be written until the destination is known.
Also settled: loose tracks land in an **"Other" playlist**, playlist folders Also settled: loose tracks land in an **"Other" playlist**, playlist folders
are preserved, and the export is a **standalone `collection.nml`** the user are preserved — at the exported library's TOP LEVEL by default; the
`exportRootFolder` setting (`ExportPayload.root_folder`) nests the whole
tree, Other included, in one folder named after the export, in all four
writers (decided 2026-10-12: the export is a library of its own, so the
wrapper was one more click at the gig), and the export is a **standalone `collection.nml`** the user
swaps into a Traktor install — so it needs the full skeleton, verified from the swaps into a Traktor install — so it needs the full skeleton, verified from the
real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`, real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`,
`<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a `<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a
@@ -1679,7 +1979,7 @@ that number and nothing else — everything derives from it:
deliberately NOT in the fixture, since they carry the machine's name and deliberately NOT in the fixture, since they carry the machine's name and
UUIDs; those are generated fresh per export. UUIDs; those are generated fresh per export.
- **The two Pioneer key blobs are different.** `masterdb`'s key and - **The two Pioneer key blobs are different.** `masterdb`'s key and
`devicelib_plus`'s are not the same string; mixing them up yields a database `onelibrary`'s are not the same string; mixing them up yields a database
Rekordbox cannot open. Rekordbox cannot open.
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/ `adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`, exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
@@ -1788,7 +2088,8 @@ that number and nothing else — everything derives from it:
0x2C060E. **Parity with the OneLibrary target is done and verified in 0x2C060E. **Parity with the OneLibrary target is done and verified in
Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`, Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`,
`Color` -1 — coloured loops included), memory cues (`store.add_memory_cue`, `Color` -1 — coloured loops included), memory cues (`store.add_memory_cue`,
export-only: the adapter still refuses memory-cue edits), and artwork the same write as the adapter's memory-cue edit: colour in `Color` from the
memory palette, the first 10 per track), and artwork
(`share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/artwork.jpg` fit to 800 px plus (`share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/artwork.jpg` fit to 800 px plus
`_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes `_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes
cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with
@@ -1895,6 +2196,9 @@ that number and nothing else — everything derives from it:
yet**, since nothing can be written. Note the OneLibrary work already demonstrated yet**, since nothing can be written. Note the OneLibrary work already demonstrated
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
is the DDL to do it with. is the DDL to do it with.
- ✅ **Drag and drop** (2026-10-06) — tracks onto playlists / exports / the
deck, playlists around the tree and onto exports; see `lib/drag.tsx` and
the Sidebar under Architecture.
- ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container - ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container
(TrueNAS) holds a Traktor or Rekordbox library; the app opens it as (TrueNAS) holds a Traktor or Rekordbox library; the app opens it as
"Remote": browse, prep, edit, Save (versioned on the server), export sticks, "Remote": browse, prep, edit, Save (versioned on the server), export sticks,
@@ -1994,6 +2298,38 @@ The prep strip plays every track through the **Web Audio API** (a plain
full scale for whole sections, so a linear map draws a solid orange wall full scale for whole sections, so a linear map draws a solid orange wall
instead of the kick pulse. The main view draws 2 px bars with a 1 px gap, instead of the kick pulse. The main view draws 2 px bars with a 1 px gap,
**binned in track space** so bars scroll rather than flicker. **binned in track space** so bars scroll rather than flicker.
- `rawWave.ts` — **the raw waveform** (decided 2026-10-15,
[the discussion](.claude/discussions/discuss-raw-waveform-2026-10-15.md)):
the bars' ~7 ms columns of unsigned band energy hide where a kick starts, so
the main view can draw the signal itself as a thin line, after Traktor at
full zoom. Its own toggle (under the zoom buttons), NOT tied to Grid mode —
tried first, changed after use.
**Shape exact, colour approximate**: the tint is the bar palette weighted by
the ~7 ms band columns, lerped, mixed in OKLab with the CHROMA restored
(`bandColour`) — a plain RGB mean of orange/violet/cyan lands near grey and
read as mud; chosen from five variants rendered on real tracks; the scale is fixed by the track's loudest
sample (no per-view gain, so nothing pumps while scrolling). Each pixel is a
min→max stroke stretched to touch its neighbour's, so it reads as an
envelope zoomed out and a line zoomed in with no switch-over. Data: min/max
per 32 samples summarised at load (~4 MB / 6 min) for wide views; below 128
samples a pixel, the visible window read straight from the `AudioBuffer`
(`copyFromChannel` — no full-length mono copy). Bins sit on a track-space
grid like the bars'. A stem track's lanes each draw their own raw line, in
the stem's colour, each at its own peak floored at 5% of the loudest.
Measured in WKWebView: 0.3 ms a frame at 0.25 s, ~5 ms at 64 s.
- `decodeAlign.ts` — **the deck's decode vs the grid's time base.** Positions
are in the backend's PyAV decode; the deck decodes with `decodeAudioData`.
Measured 2026-10-15 with click files: identical on every format and engine
EXCEPT a **header-less MP3 under WebKit** (the macOS app), decoded 529
samples (12 ms) EARLY — CoreAudio trims the decoder delay with no header to
say so; FFmpeg (and Chromium/WebView2) do not. Invisible under bars, a
12 ms miss on the raw line. The engine's offset is MEASURED once per session
by decoding a built-in 2.7 KB header-less MP3 (`decodeProbe.ts`, click at a
known FFmpeg sample), and a header-less MP3's buffer (`mp3HeaderFrame`, a
port of `core/mp3_gapless.parse` behind an is-it-an-MP3 gate) is padded by
it in `decodeUrl` — so playback, scratch and both waveforms move together.
Not measured: a header without a trusted encoder-delay field; Edge on a real
Windows machine (Chromium on macOS matched).
- `cues.ts` — canvas drawers for cue markers (type-colored), the active loop - `cues.ts` — canvas drawers for cue markers (type-colored), the active loop
band, the beatgrid (per-segment white beats/brighter downbeats, plus marker band, the beatgrid (per-segment white beats/brighter downbeats, plus marker
lines — gold for the one governing the playhead, accent otherwise, with the lines — gold for the one governing the playhead, accent otherwise, with the
+125 -240
View File
@@ -1,256 +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: the prep deck with a track loaded, above a playlist](docs/screenshots/library.png)
Konduktor opens the library you already have, in the format it already uses.
You can tidy tags, build playlists, set grids and cues, and pack a USB stick
for the gig without launching your full DJ software. When you open your DJ
software again, everything you changed is there.
--- ---
## Why you'll like it ## One app for every library
- **Instant, searchable library.** Your whole collection loads into a snappy, <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 ![The prep deck in beatgrid editing mode](docs/screenshots/deck.png)
- **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
![A stem file in the deck: drums, bass, synths and vocals each in their own lane](docs/screenshots/stems.png)
**Play stem files as stems.** Load a stem file and the deck splits into
drums, bass, synths and vocals, each drawn in its own lane. Click a lane's
button to mute it, Alt/Option-click to solo it, or use Q W E R.
**Convert to Stems.** In a Traktor collection, right-click any tracks and
choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and
beatgrid intact.
- The separation runs on your own computer, so your music isn't sent to an
online service.
- Replace the originals, or save the stems to a folder and add them as new
tracks.
- Convert a whole playlist in one go.
## Let it do the boring parts
| Auto Hotcues | Analyze |
|:---:|:---:|
| ![Auto Hotcues: choose an event for each pad](docs/screenshots/auto-hotcues.png) | ![Analyze: BPM, grid and key](docs/screenshots/analyze.png) |
| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. |
## Export to USB for CDJs, or other platforms
<img src="docs/screenshots/export.png" align="right" width="380" alt="An export set for OneLibrary, Traktor and Rekordbox">
Make an **export** in the sidebar, drag playlists onto it, and press Export.
One stick can carry a Traktor collection, a OneLibrary library for current
CDJs and a Rekordbox Device Library for older players, all sharing **one copy
of the audio**.
- Hotcues, memory cues, loops, grids, keys and cover art are converted for
each platform.
- Playlists stay linked: edit a playlist, re-export, and the stick catches up.
- Re-exports copy only what changed, so updating a stick is quick.
- Konduktor only ever clears a folder that it wrote itself.
<br clear="right">
## Your library is safe
- **Saves are surgical.** A Traktor save changes only the entries you edited.
The rest of the file stays byte-for-byte identical.
- **Backups and history.** Every Traktor save makes a backup first and is kept
in a version history that you can restore from in the app.
- **Nothing is written until you press Save.** Discard changes throws away
everything you did since your last save.
- Tag edits are also written into the audio files themselves, so other apps
see them too.
## And also
- A fast library with search, filters, sorting and columns you can rearrange,
even with thousands of tracks.
- Edit tags inline or in a full tag and cover-art editor.
- Drag and drop tracks onto playlists, exports or the deck, and drag playlists
to reorganise them.
- If you open a Traktor collection on a different computer or drive,
Konduktor finds the missing files for you.
--- ---
## Getting started ## Get Konduktor
Konduktor runs as two small local servers (a Python backend and a web 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.
---
## A remote library (Konduktor server on a NAS)
Keep your whole library — the collection file and the music — on a server, and
open it from any computer with Konduktor. Prep tracks, edit playlists, and
export sticks for your gigs without the music ever living on your performance
laptop.
The server is a small container (`server/`). It holds the library and saves it.
Playback, analysis and stem separation run on the computer you open it from,
on copies it downloads, so the server needs no GPU and does very little work.
**On the server (e.g. TrueNAS SCALE):**
1. Copy `server/compose.yaml` and `server/.env.example` (renamed to `.env`)
onto the NAS. Point the volumes at your datasets, and fill in `.env`: the
platform (`traktor` or `rekordbox`), the library file, the music folder, a
username and password, and — for a collection made on a Mac — the path
mapping (`/Users/you/Music => /music`).
2. Install it: on TrueNAS, **Apps → Discover Apps → ⋮ → Install via YAML** and
paste the compose file; anywhere else, `docker compose up -d`. A bad setting
stops the container with one clear line in its log.
**In the app:** choose **Remote** on the platform screen → **Add a remote
library** → enter the server's address (and a fallback, such as its Tailscale
address, for when you're away from home), the username and the password.
Konduktor checks the server before it saves the remote, and keeps the
password in your keychain.
Good to know:
- **One computer at a time.** If another computer has the library open,
Konduktor says who has it and offers to take over. Edits that computer
hadn't saved stay with the library, and you're asked to save or discard
them.
- **Plain HTTP.** Reach the server over your home network or a VPN
(Tailscale / WireGuard). Don't expose its port to the internet.
- **Unsaved edits live on the server** until you save. Restarting the
container drops them.
- Downloaded tracks are cached on your computer (Settings → **Remote audio**
sets the size), so a track you've prepped and then export is fetched once.
---
## 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.
+17 -10
View File
@@ -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\"
+19 -23
View File
@@ -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 DEST="$ROOT/../frontend/src-tauri/binaries"
TRIPLE="$(rustc -vV | sed -n 's/host: //p')" mkdir -p "$DEST"
DEST="$ROOT/../frontend/src-tauri/binaries" rm -rf "$DEST/konduktor-sidecar"
mkdir -p "$DEST" cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE" echo "Staged: $DEST/konduktor-sidecar/"
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
else
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
fi
@@ -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`.
+20 -4
View File
@@ -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
@@ -82,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,
@@ -97,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",
)
@@ -26,7 +26,7 @@ from ...core.capabilities import Capabilities
from ...core.model import GridMarker, 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 palette from ..rekordbox import memory_palette, palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME from ...exporter import MANIFEST_NAME
from . import capabilities as caps from . import capabilities as caps
@@ -193,6 +193,7 @@ class OneLibraryAdapter:
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(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
@@ -403,6 +404,12 @@ class OneLibraryAdapter:
self._refresh(track_id) self._refresh(track_id)
return self._index.get(track_id) return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
def 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")
@@ -425,6 +432,10 @@ class OneLibraryAdapter:
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)
@@ -452,10 +463,8 @@ class OneLibraryAdapter:
) -> TrackCues: ) -> TrackCues:
self._require_writable("Editing cues") self._require_writable("Editing cues")
if role != "hotcue": if role != "hotcue":
# Preserved-but-uneditable, exactly as in the Rekordbox adapter. # A memory cue has no slot to set; it has its own commands.
raise Unsupported( raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
"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(track_id, slot=slot, start_sec=start_sec, 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) length_sec=length_sec, name=name)
@@ -489,6 +498,53 @@ class OneLibraryAdapter:
self._store.place_cues(track_id, cues, overwrite=overwrite) self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id) 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 ----------------------------------------------- # ---- commands: beatgrid -----------------------------------------------
@staticmethod @staticmethod
def _markers_from(markers: list) -> list: def _markers_from(markers: list) -> list:
@@ -36,8 +36,8 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, TrackCapabilities,
) )
from ..rekordbox import palette from ..rekordbox import memory_palette, palette, track_palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES 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`).
@@ -61,10 +61,12 @@ def capabilities_for(
editable=True, editable=True,
hotcue_slots=HOTCUE_SLOTS, hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter", slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does: projected and # Memory cues, editable as in Rekordbox — in the ANLZ files, the
# preserved, NOT editable (the two-platform rule, as in Rekordbox). # 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,
memory_color="palette",
memory_palette=list(memory_palette.SWATCHES),
types=WRITABLE_CUE_TYPES, types=WRITABLE_CUE_TYPES,
color="palette", color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES], palette=[palette.hex_for(code) for code in palette.SWATCHES],
@@ -85,6 +87,8 @@ def capabilities_for(
addable=not read_only, addable=not read_only,
removable=not read_only, removable=not read_only,
key_writable=not read_only, key_writable=not read_only,
# `content.color_id`, rekordbox's eight; the pdb row follows at Save.
colors=[] if read_only else list(track_palette.SWATCHES),
places_audio=True, places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either # `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows # (parity). Reading works: `store.cover_art` follows
+24 -7
View File
@@ -37,7 +37,7 @@ from __future__ import annotations
import logging import logging
from ...core.model import CuePoint from ...core.model import CuePoint
from ..rekordbox import palette from ..rekordbox import memory_palette, palette
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -112,6 +112,13 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
slot = None if role == "memory" else hot_cue - 1 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",
@@ -119,16 +126,26 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
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,
# Hot cues are editable on a drive opened for editing (the caller says # Editable on a drive opened for editing (the caller says so), memory
# so). MEMORY cues never are — preserved-but-uneditable, as in the # cues included; browsing a device is read-only.
# Rekordbox adapter (the two-platform rule). editable=editable,
editable=editable and role == "hotcue", readonly_reason=None if editable else "platform_managed",
readonly_reason=None if editable and role == "hotcue" else "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.
@@ -121,10 +121,10 @@ def rebuild(existing: bytes, session) -> bytes | None:
# ---- tracks ----------------------------------------------------------------- # ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)} old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {} want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released, for (cid, title, artist, remixer, album, genre, label, rating, color, bpm, year, released,
comment, *fresh) in session.execute(text( comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, " "SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, " "label_id, rating, color_id, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, " "path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")): "analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid) cid = int(cid)
@@ -134,7 +134,8 @@ def rebuild(existing: bytes, session) -> bytes | None:
fields, strings = _fresh_track(cid, *fresh) fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0, 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, "album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0), "rating": max(0, min(5, int(rating or 0))), "color_id": int(color or 0),
"tempo": int(bpm or 0),
"year": int(year or 0)} "year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "", strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""} "release_date": released or ""}
@@ -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
+35 -16
View File
@@ -44,7 +44,8 @@ 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 ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, palette, timebase from ..rekordbox import artwork, memory_palette, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox.beatgrid import beats_from_markers from ..rekordbox.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
@@ -121,7 +122,7 @@ class OneLibraryExporter:
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)
@@ -208,13 +209,13 @@ class OneLibraryExporter:
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, image_id, " "trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, color_id, image_id, "
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, " "djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, " "fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, " "isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, contentLink, 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,
@@ -228,6 +229,7 @@ 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)),
track_palette.id_for(track.color),
image_id, 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,
@@ -359,15 +361,29 @@ 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
# A hot cue carries what Konduktor SHOWS — stored colour, else the is_memory = cue.role == "memory" or cue.slot is None
# type's (blue cue, green loop) — as a rekordbox palette CODE, which if is_memory:
# is what rekordbox draws from; "unset" draws its own defaults. A # rekordbox keeps 10 (earliest first; the rest are dropped, per
# memory cue keeps rekordbox's own "unset". # the lossiness rule). A memory cue's colour is PCP2 byte 28 from
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue)) # 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(timebase.to_pioneer(cue.start, off) * 1000)), "time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000)) "loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
@@ -381,7 +397,8 @@ class OneLibraryExporter:
# ---- 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).
@@ -397,8 +414,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
@@ -427,8 +444,10 @@ class OneLibraryExporter:
) )
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them. #: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player. #: 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, _FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12} ".aif": 12, ".aiff": 12}
@@ -0,0 +1,102 @@
"""Memory-cue edits on a track's two analysis files, the way rekordbox 7 makes them.
Pure functions over parsed `AnlzFile`s, so they are pinned byte for byte
against rekordbox's own edits (`fixtures/onelibrary-memory-edits`, kit M2,
2026-10-16) without a drive; the store adds the drive, the time base and Save.
A stick keeps memory cues ONLY in the analysis files — the database and both
pdbs keep every row — in two lists kept in OPPOSITE orders:
* `.DAT` `PCOB` memory: a new cue is PREPENDED, and the whole list is
relinked (`anlz_writer.relinked_memory_pcpts`: status 0, prev/next
indexes) on any add or delete; header field = count − 1.
* `.EXT` `PCO2` memory: a new cue is APPENDED in the compact 44-byte form;
every other entry keeps its bytes. The `.EXT`'s own `PCOB` memory list
stays empty.
A colour is `PCP2` byte 28 and a name the `PCP2` comment; neither touches the
`.DAT`. A cue is addressed by `cues.memory_cue_id` (stored time, kind, loop
end), which is the same in both lists.
"""
from __future__ import annotations
from ..rekordbox import anlz_file
from ..rekordbox import anlz_writer as W
from .cues import memory_cue_id
DAT_ORDER = ("PPTH", "PVBR", "PQTZ", "PWAV", "PWV2", "PCOB")
EXT_ORDER = ("PPTH", "PWV3", "PCOB", "PCO2")
def entries(f: anlz_file.AnlzFile, kind: str) -> list[bytes]:
"""The raw entries of a file's `kind` (PCOB / PCO2) MEMORY list."""
i = f.find(kind, anlz_file.LIST_MEMORY)
return anlz_file.raw_entries(f.tags[i]) if i is not None else []
def count(ext: anlz_file.AnlzFile) -> int:
return len(entries(ext, "PCO2"))
def _matches(entry: bytes, cue_id: str) -> bool:
return memory_cue_id(anlz_file.decode_entry(entry)) == cue_id
def _put(dat, ext, pcob: list[bytes] | None, pco2: list[bytes] | None) -> None:
if pcob is not None:
dat.put("PCOB", W.pcob_tag(anlz_file.LIST_MEMORY, W.relinked_memory_pcpts(pcob)),
list_kind=anlz_file.LIST_MEMORY, after=DAT_ORDER)
if pco2 is not None:
ext.put("PCO2", W.pco2_tag(anlz_file.LIST_MEMORY, pco2),
list_kind=anlz_file.LIST_MEMORY, after=EXT_ORDER)
def add(dat, ext, *, kind: int, time_ms: int, loop_ms: int | None, beats: int | None,
name: str | None = None, color_id: int = 0) -> None:
"""Add one memory cue (kind 1 cue, 2 loop): prepended to the `.DAT`'s list,
appended — compact unless named — to the `.EXT`'s."""
pcp2 = W.pcp2_compact_entry(kind=kind, time_ms=time_ms, loop_ms=loop_ms,
beats=beats, color_id=color_id)
if name:
pcp2 = anlz_file.entry_with_comment(pcp2, name)
pcpt = W.pcpt_entry(hot_cue=0, kind=kind, time_ms=time_ms, loop_ms=loop_ms)
_put(dat, ext, [pcpt] + entries(dat, "PCOB"), entries(ext, "PCO2") + [pcp2])
def _index(ext, cue_id: str) -> tuple[list[bytes], int | None]:
pco2 = entries(ext, "PCO2")
return pco2, next((n for n, e in enumerate(pco2) if _matches(e, cue_id)), None)
def rename(ext, cue_id: str, name: str | None) -> bool:
"""Rename in the `.EXT` only; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_comment(pco2[i], name)
_put(None, ext, None, pco2)
return True
def recolour(ext, cue_id: str, color_id: int) -> bool:
"""Byte 28 of the cue's `PCP2` entry, nothing else; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_color_id(pco2[i], color_id)
_put(None, ext, None, pco2)
return True
def delete(dat, ext, cue_id: str) -> bool:
"""Out of both lists (the `.DAT`'s relinked); False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
del pco2[i]
pcob = entries(dat, "PCOB")
j = next((n for n, e in enumerate(pcob) if _matches(e, cue_id)), None)
if j is not None:
del pcob[j]
_put(dat, ext, pcob if j is not None else None, pco2)
return True
@@ -1,6 +1,6 @@
"""OneLibrary rows -> the generic projection. """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:
@@ -16,6 +16,7 @@ Field conventions are read off a real rekordbox 7 export rather than guessed:
from __future__ import annotations from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox import track_palette
from ..rekordbox.projection import parse_key from ..rekordbox.projection import parse_key
@@ -106,6 +107,8 @@ def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track
grid_locked=False, # OneLibrary has no grid lock grid_locked=False, # OneLibrary has no grid lock
# What the FILE is, as the deck plays it — see the Rekordbox projection. # What the FILE is, as the deck plays it — see the Rekordbox projection.
media_kind="stem" if stem else "audio", media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "color_id", None)),
color_hex=track_palette.hex_for(getattr(row, "color_id", None)),
) )
@@ -114,7 +117,7 @@ def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
`cues` are already generic — see `store.cues` for why that boundary sits `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))
+130 -18
View File
@@ -1,7 +1,7 @@
"""The retained native model for a OneLibrary drive. """The retained native model for a OneLibrary drive.
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched. place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
with a **different and universal key**: every OneLibrary drive from every vendor with a **different and universal key**: every OneLibrary drive from every vendor
@@ -54,8 +54,9 @@ from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands from ...core.grid_edit import ReplaceGridCommands
from ...core.model import CuePoint from ...core.model import CuePoint
from ... import paths from ... import paths
from . import beatgrid, cues as cue_reader from . import beatgrid, cues as cue_reader, memory_cues
from ..rekordbox import anlz_file, palette, timebase from ..rekordbox import anlz_file, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox import anlz_writer as W from ..rekordbox import anlz_writer as W
from ..rekordbox import beatgrid as rb_beatgrid from ..rekordbox import beatgrid as rb_beatgrid
from .layout import DriveLayout from .layout import DriveLayout
@@ -170,10 +171,10 @@ class OneLibraryStore(ReplaceGridCommands):
def _load(self) -> None: def _load(self) -> None:
"""Copy the drive's database into app-data and open the copy.""" """Copy the drive's database into app-data and open the copy."""
try: try:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus from pyrekordbox.onelibrary import OneLibrary
except ImportError as ex: # pragma: no cover — dependency missing except ImportError as ex: # pragma: no cover — dependency missing
raise LibraryNotSupported( raise LibraryNotSupported(
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus" "Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
) from ex ) from ex
_clear_stale_work() _clear_stale_work()
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root())) work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
@@ -186,7 +187,7 @@ class OneLibraryStore(ReplaceGridCommands):
sidecar = self.path.with_name(self.path.name + suffix) sidecar = self.path.with_name(self.path.name + suffix)
if sidecar.is_file() and sidecar.stat().st_size: if sidecar.is_file() and sidecar.stat().st_size:
shutil.copyfile(sidecar, working.with_name(working.name + suffix)) shutil.copyfile(sidecar, working.with_name(working.name + suffix))
db = DeviceLibraryPlus(str(working)) db = OneLibrary(str(working))
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
shutil.rmtree(work, ignore_errors=True) shutil.rmtree(work, ignore_errors=True)
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
@@ -206,7 +207,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""Release the working copy and delete it. """Release the working copy and delete it.
The drive itself is never held open (see the module docstring); the copy The drive itself is never held open (see the module docstring); the copy
is, and `DeviceLibraryPlus.close()` only unregisters events, so the is, and `OneLibrary.close()` only unregisters events, so the
session and engine are closed here explicitly. session and engine are closed here explicitly.
""" """
db, self._db = self._db, None db, self._db = self._db, None
@@ -316,7 +317,7 @@ class OneLibraryStore(ReplaceGridCommands):
image_id = getattr(self.content(track_id), "image_id", None) image_id = getattr(self.content(track_id), "image_id", None)
if not image_id: if not image_id:
return None return None
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none() row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
@@ -456,7 +457,7 @@ class OneLibraryStore(ReplaceGridCommands):
""" """
if not name: if not name:
return None return None
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
model = getattr(models, model_name) model = getattr(models, model_name)
pk = f"{model.__tablename__}_id" pk = f"{model.__tablename__}_id"
@@ -497,7 +498,7 @@ class OneLibraryStore(ReplaceGridCommands):
stick already has. A new key gets rekordbox's own spelling.""" stick already has. A new key gets rekordbox's own spelling."""
if wheel is None or mode is None: if wheel is None or mode is None:
return None return None
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
from ..rekordbox.projection import parse_key, render_key from ..rekordbox.projection import parse_key, render_key
@@ -565,9 +566,26 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush() db.flush()
db.session.expire(row) db.session.expire(row)
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`content.color_id`, a 1-based id into the `color` table (see
`track_palette`); 0 = none, as rekordbox exports an uncoloured track.
Not a file tag; the pdb's track row follows at Save (`device_library`)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
db = self._require_db()
row = self.content(track_id)
before = row.color_id
if int(before or 0) == new:
return
row.color_id = new
self._journal.record("track", "set", track_id, "color", before, new)
db.flush()
db.session.expire(row)
# ---- writes: playlists -------------------------------------------------- # ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str): def _playlist(self, node_id: str):
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
try: try:
pid = int(node_id) pid = int(node_id)
@@ -579,14 +597,14 @@ class OneLibraryStore(ReplaceGridCommands):
return row return row
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list: def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all() rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
rows = [r for r in rows if r.playlist_id != excluding] rows = [r for r in rows if r.playlist_id != excluding]
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id))) return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str: def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
name = (name or "").strip() name = (name or "").strip()
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist" noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
@@ -631,7 +649,7 @@ class OneLibraryStore(ReplaceGridCommands):
def delete_playlist(self, node_id: str) -> None: def delete_playlist(self, node_id: str) -> None:
"""Delete a playlist, or a folder WITH everything in it, and close the gap """Delete a playlist, or a folder WITH everything in it, and close the gap
its `sequenceNo` leaves among its siblings.""" its `sequenceNo` leaves among its siblings."""
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
db = self._require_db() db = self._require_db()
row = self._playlist(node_id) row = self._playlist(node_id)
@@ -652,9 +670,48 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush() db.flush()
self._journal.record("playlist", "delete", name) self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children, renumbering
`sequenceNo` from 0 in both parents as create and delete do. The
Device Library's playlist tree follows at Save (`device_library`
mirrors parent and sort from these rows)."""
db = self._require_db()
row = self._playlist(node_id)
dest = 0
if parent_id:
folder = self._playlist(parent_id)
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
raise InvalidCommand("A playlist can only be moved into a folder")
dest = int(folder.playlist_id)
ancestor = folder
while ancestor is not None:
if int(ancestor.playlist_id) == int(row.playlist_id):
raise InvalidCommand("A folder cannot be moved into itself")
up = int(ancestor.playlist_id_parent or 0)
ancestor = self._playlist(str(up)) if up else None
source = int(row.playlist_id_parent or 0)
siblings = self._siblings(dest, excluding=row.playlist_id)
index = max(0, min(int(index), len(siblings)))
order = siblings[:index] + [row] + siblings[index:]
if source == dest and [r.playlist_id for r in order] == [
r.playlist_id for r in self._siblings(dest)
]:
return str(row.playlist_id)
row.playlist_id_parent = dest
for n, r in enumerate(order):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
if source != dest:
for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
db.flush()
self._journal.record("playlist", "move", row.name)
return str(row.playlist_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in order, numbered from 1 (measured).""" """Replace a playlist's contents, in order, numbered from 1 (measured)."""
from pyrekordbox.devicelib_plus import models from pyrekordbox.onelibrary import models
db = self._require_db() db = self._require_db()
playlist = self._playlist(node_id) playlist = self._playlist(node_id)
@@ -877,6 +934,60 @@ class OneLibraryStore(ReplaceGridCommands):
self._replace_hot(track_id, hot, None, None) self._replace_hot(track_id, hot, None, None)
self._journal.record("cue", "delete", track_id, f"slot:{slot}") self._journal.record("cue", "delete", track_id, f"slot:{slot}")
# ---- memory cues -------------------------------------------------------
# The list edits — and what rekordbox was measured doing — are in
# `memory_cues`; here: the drive, the time base, the cap and the journal.
MAX_MEMORY_CUES = MAX_MEMORY_CUES # rekordbox stops storing at 10, silently (measured)
def _memory_files(self, track_id: str):
dat, ext = self._editing(track_id)
self._ensure_pco2(dat, ext)
return dat, ext
def add_memory_cue(self, track_id: str, *, start_sec: float, cue_type: str,
length_sec: float = 0.0, name: str | None = None,
color_id: int = 0) -> None:
"""Add a memory cue (a memory loop with a length) the way rekordbox does.
`color_id` is `PCP2` byte 28 (`memory_palette.anlz_byte`), 0 = none."""
from .export import _loop_beats
if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track")
dat, ext = self._memory_files(track_id)
if memory_cues.count(ext) >= self.MAX_MEMORY_CUES:
raise InvalidCommand(
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
)
is_loop = cue_type == "loop" and length_sec > 0
off = self._offset(track_id)
time_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000))
loop_ms = int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000)) if is_loop else None
grid = self.anlz_grid(track_id)
beats = (_loop_beats(start_sec, length_sec, list(zip(grid[2], grid[1], grid[0])))
if is_loop and grid else None)
memory_cues.add(dat, ext, kind=2 if is_loop else 1, time_ms=time_ms, loop_ms=loop_ms,
beats=beats, name=name, color_id=color_id)
self._journal.record("cue", "add", track_id, "memory")
def _memory_edit(self, track_id: str, cue_id: str, op: str, edit) -> None:
dat, ext = self._memory_files(track_id)
if not edit(dat, ext):
raise NotFound(f"No memory cue {cue_id!r} on this track")
self._journal.record("cue", op, track_id, "memory")
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
self._memory_edit(track_id, cue_id, "modify",
lambda _d, ext: memory_cues.rename(ext, cue_id, name))
def set_memory_cue_color(self, track_id: str, cue_id: str, color_id: int) -> None:
self._memory_edit(track_id, cue_id, "modify",
lambda _d, ext: memory_cues.recolour(ext, cue_id, color_id))
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
self._memory_edit(track_id, cue_id, "delete",
lambda dat, ext: memory_cues.delete(dat, ext, cue_id))
def hot_slots(self, track_id: str) -> set[int]: def hot_slots(self, track_id: str) -> set[int]:
"""Occupied 0-based slots (pending edits included).""" """Occupied 0-based slots (pending edits included)."""
return {c.slot for c in self.cues(track_id) if c.role == "hotcue" and c.slot is not None} return {c.slot for c in self.cues(track_id) if c.role == "hotcue" and c.slot is not None}
@@ -1088,7 +1199,7 @@ class OneLibraryStore(ReplaceGridCommands):
"isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, " "isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, "
"masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, " "masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, "
"hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, " "hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, "
":album, :genre, :label, :key, 0, :image, :comment, :rating, :year, :released, " ":album, :genre, :label, :key, :color, :image, :comment, :rating, :year, :released, "
":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, " ":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, "
"'', 0, :cid, :anlz, :bits, :link, 0)"), { "'', 0, :cid, :anlz, :bits, :link, 0)"), {
"cid": cid, "title": getattr(track, "title", None) or final.stem, "cid": cid, "title": getattr(track, "title", None) or final.stem,
@@ -1098,6 +1209,7 @@ class OneLibraryStore(ReplaceGridCommands):
"label": lookup("Label", track.label), "label": lookup("Label", track.label),
# Rendered from the parsed wheel: a source's "10m" means nothing here. # Rendered from the parsed wheel: a source's "10m" means nothing here.
"key": self._key_id(track.key_wheel, track.key_mode), "key": self._key_id(track.key_wheel, track.key_mode),
"color": track_palette.id_for(getattr(track, "color", None)),
"image": image_id, "comment": track.comment or "", "image": image_id, "comment": track.comment or "",
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released, "rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel, "added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
@@ -1339,9 +1451,9 @@ class OneLibraryStore(ReplaceGridCommands):
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results) return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
def _reopen_working(self, work: Path) -> None: def _reopen_working(self, work: Path) -> None:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus from pyrekordbox.onelibrary import OneLibrary
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work self._db, self._work = OneLibrary(str(work / self.path.name)), work
self._content_cache = None self._content_cache = None
self._by_id = None self._by_id = None
+72 -13
View File
@@ -27,7 +27,7 @@ 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 palette, projection, timebase from . import memory_palette, palette, projection, timebase
from ...core import add_analysis from ...core import add_analysis
from .store import RekordboxStore from .store import RekordboxStore
@@ -172,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
@@ -259,6 +260,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_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
# ---- 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")
@@ -276,6 +283,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)
@@ -298,12 +309,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,
@@ -334,6 +341,53 @@ class RekordboxAdapter:
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:
@@ -516,20 +570,25 @@ class RekordboxAdapter:
def _place_imported_cues(self, track_id: str, cues) -> None: def _place_imported_cues(self, track_id: str, cues) -> None:
"""Hot cues on their own pads; memory cues — and a hot cue with no """Hot cues on their own pads; memory cues — and a hot cue with no
free pad — as memory cues. Colour as the nearest palette swatch.""" free pad — as memory cues, up to rekordbox's 10 (earliest first; the
rest are dropped, per the lossiness rule). Colour as the nearest swatch
of the palette the cue lands in: a hot cue's 16, a memory cue's 8."""
taken: set[int] = set() taken: set[int] = set()
memory = 0
for cue in sorted(cues.cues or [], key=lambda c: c.start): for cue in sorted(cues.cues or [], key=lambda c: c.start):
cue_type = "loop" if getattr(cue, "length", 0) else "cue" cue_type = "loop" if getattr(cue, "length", 0) else "cue"
code, _rgb = palette.code_for(cue.color)
common = dict(start_sec=cue.start, cue_type=cue_type, common = dict(start_sec=cue.start, cue_type=cue_type,
length_sec=getattr(cue, "length", 0.0) or 0.0, length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), color_code=code or None) name=getattr(cue, "name", None))
slot = cue.slot if cue.role == "hotcue" else None 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: if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
self._store.set_cue(track_id, slot=slot, **common) code, _rgb = palette.code_for(cue.color)
self._store.set_cue(track_id, slot=slot, color_code=code or None, **common)
taken.add(slot) taken.add(slot)
else: elif memory < self._store.MAX_MEMORY_CUES:
self._store.add_memory_cue(track_id, **common) 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:
# What goes with a track was measured in Rekordbox 7 — see the store. # What goes with a track was measured in Rekordbox 7 — see the store.
@@ -158,6 +158,9 @@ class CueEntry:
color_green: int | None = None color_green: int | None = None
color_blue: int | None = None color_blue: int | None = None
len_entry: int = 0 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]: def raw_entries(tag: Tag) -> list[bytes]:
@@ -197,6 +200,35 @@ def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> byt
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:] 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: def entry_without_loop_beats(entry: bytes) -> bytes:
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what """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), rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
@@ -245,7 +277,8 @@ def _pco2(data: bytes) -> list[CueEntry]:
hot_cue, = struct.unpack_from(">I", data, off + 12) hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 16] kind = data[off + 16]
time, loop = struct.unpack_from(">II", data, off + 20) time, loop = struct.unpack_from(">II", data, off + 20)
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n) e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n,
color_id=data[off + 28] if n > 28 else 0)
if n >= 44: if n >= 44:
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36) e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
colour_at = off + 44 + len_comment colour_at = off + 44 + len_comment
@@ -315,7 +315,7 @@ def flat_preview_tags() -> list[bytes]:
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None, 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, rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
comment: str | None = None) -> bytes: comment: str | None = None, color_id: int = 0) -> bytes:
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it. """One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
Two constants in here are rekordbox's, not the documented struct's: the Two constants in here are rekordbox's, not the documented struct's: the
@@ -328,6 +328,9 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
Konduktor's reader and pyrekordbox's agree with. No reference cue carries 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 one, so that detail is documented rather than measured. The entry stays the
exported 88 bytes unless the name needs more. exported 88 bytes unless the name needs more.
`color_id` is byte 28: a MEMORY cue's colour, 1-based (`memory_palette`),
0 = none. A hot cue's colour is the code + RGB tail instead.
""" """
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b"" comment_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)
@@ -336,7 +339,7 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
">4sIIIBxHIIBB6xHHI", ">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, length, hot_cue, kind, 1000, 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, 1, beats or 0, 1 if beats else 0, len(comment_bytes), color_id & 0xFF, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
# The colour is the palette CODE, then RGB: rekordbox draws from the code # The colour is the palette CODE, then RGB: rekordbox draws from the code
# (`palette`); a code of 0 draws its default colour whatever the RGB says. # (`palette`); a code of 0 draws its default colour whatever the RGB says.
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes( ) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
@@ -344,6 +347,41 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
) )
#: rekordbox's COMPACT `PCP2` entry: the first 44 bytes of a full one — no
#: comment and no colour tail. What rekordbox 7 appends when it ADDS a memory cue
#: on a stick (measured 2026-10-16, `fixtures/onelibrary-memory-edits`).
PCP2_COMPACT_LEN = 44
def pcp2_compact_entry(*, kind: int, time_ms: int, loop_ms: int | None,
beats: int | None, color_id: int = 0, hot_cue: int = 0) -> bytes:
"""A compact 44-byte `PCP2` entry, byte for byte as rekordbox 7 writes one
for a memory cue it adds: the same fields as `pcp2_entry` up to
`len_comment` (0), including the `1000` and the `1` after byte 28."""
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, PCP2_COMPACT_LEN, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, 0,
)
def relinked_memory_pcpts(entries: list[bytes]) -> list[bytes]:
"""A `PCOB` MEMORY list's entries with their link fields rewritten, as
rekordbox 7 leaves them after ANY add or delete (measured 2026-10-16,
`fixtures/onelibrary-memory-edits`): status (bytes 16-19) 0, and bytes 24-27 the
previous / next entry's INDEX IN THE LIST, 0xFFFF at either end — so every
entry changes when one is added or removed. rekordbox's exports agree on any
list of two or more; a lone exported entry is status 4, 0xFFFF/0xFFFF."""
n = len(entries)
out = []
for i, e in enumerate(entries):
prev = i - 1 if i > 0 else 0xFFFF
nxt = i + 1 if i < n - 1 else 0xFFFF
out.append(e[:16] + struct.pack(">I", 0) + e[20:24] + struct.pack(">HH", prev, nxt) + e[28:])
return out
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes: 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. """One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
@@ -378,18 +416,25 @@ def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
def _pcob(cue_type: int, chosen: list[dict]) -> bytes: def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
return pcob_tag(cue_type, [ entries = [
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"]) loop_ms=c["loop_ms"])
for c in chosen 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: def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
return pco2_tag(cue_type, [ return pco2_tag(cue_type, [
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], 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"), loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0), comment=c.get("comment")) code=c.get("code", 0), comment=c.get("comment"),
color_id=c.get("color_id", 0))
for c in chosen for c in chosen
]) ])
@@ -30,8 +30,8 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, TrackCapabilities,
) )
from . import palette from . import memory_palette, palette, track_palette
from .cue_types import WRITABLE_CUE_TYPES 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
@@ -55,18 +55,19 @@ 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 # A hot cue's colour is one of rekordbox's 16 swatches (all
@@ -92,6 +93,8 @@ def capabilities_for(
removable=True, removable=True,
addable=True, addable=True,
key_writable=True, key_writable=True,
# `djmdContent.ColorID`, rekordbox's eight (see `track_palette`).
colors=list(track_palette.SWATCHES),
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"]
@@ -41,7 +41,7 @@ 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 . import artwork, pdb from . import artwork, pdb, track_palette
from .projection import render_key from .projection import render_key
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -138,6 +138,7 @@ class RekordboxDeviceExporter:
"id": n, "year": year, "sample_depth": bit_depth or 0, "id": n, "year": year, "sample_depth": bit_depth or 0,
"duration": min(int(track.length or 0), 0xFFFF), "duration": min(int(track.length or 0), 0xFFFF),
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))), "u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
"color_id": track_palette.id_for(track.color),
"u6": _file_type(item.destination), "u7": 3, "u6": _file_type(item.destination), "u7": 3,
}, },
{ {
@@ -198,8 +199,9 @@ class RekordboxDeviceExporter:
@staticmethod @staticmethod
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]: def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
"""The tree under one folder named after the export, as the other """The tree as the other targets build it — at the top level (parent
targets build it. `sort_order` is a node's position among its siblings.""" 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] = [] tree: list[bytes] = []
entries: list[bytes] = [] entries: list[bytes] = []
next_id = [0] next_id = [0]
@@ -220,7 +222,7 @@ class RekordboxDeviceExporter:
index += 1 index += 1
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id)) entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
root = add(payload.name, 0, folder=True) root = add(payload.name, 0, folder=True) if payload.root_folder else 0
folders: dict[tuple[str, ...], int] = {(): root} folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists: for playlist in payload.playlists:
parent = root parent = root
+24 -13
View File
@@ -58,7 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color from ...core.cue_colors import effective_color
from . import new_content, palette from . import memory_palette, new_content, palette, track_palette
from . import timebase from . import timebase
from .beatgrid import beats_from_markers from .beatgrid import beats_from_markers
from .capabilities import capabilities_for from .capabilities import capabilities_for
@@ -125,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.
@@ -199,24 +199,31 @@ 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 refuses memory cues # The store, not the adapter's commands: the adapter's set_cue takes no
# (editing them in a user's library is off-limits) and takes no colour. # colour and its memory-cue command takes only a swatch. A NEW library
# Building a NEW library is neither an edit nor lossy by choice, so the # maps any source colour to the nearest one instead — through the same
# exporter writes both — through the same `_write_cue` every edit uses. # `_write_cue` every edit uses.
store = adapter._store 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
for cue in sorted(item.cues.cues, key=lambda c: c.start):
if cue.role == "memory" or cue.slot is None: if cue.role == "memory" or cue.slot is None:
# rekordbox's own "unset" for a memory cue with no colour. # rekordbox keeps 10 (earliest first; the rest are
code, _rgb = palette.code_for(cue.color) # dropped, per the lossiness rule). Colour: what
# Konduktor SHOWS — stored, else the type's — as the
# nearest of the memory palette's 8, as for a hot cue.
if memory >= store.MAX_MEMORY_CUES:
continue
store.add_memory_cue( store.add_memory_cue(
track_id, start_sec=cue.start, cue_type=cue.type, track_id, start_sec=cue.start, cue_type=cue.type,
length_sec=cue.length, name=cue.name, color_code=code or None, length_sec=cue.length, name=cue.name,
color_code=memory_palette.nearest_code(effective_color(cue)),
) )
memory += 1
continue continue
# What Konduktor SHOWS — stored colour, else the type's (blue # What Konduktor SHOWS — stored colour, else the type's (blue
# cue, green loop) — as a palette code, which is what # cue, green loop) — as a palette code, which is what
@@ -306,6 +313,7 @@ class RekordboxExporter:
# 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 content.ContentLink = CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
db.flush() db.flush()
return content return content
@@ -383,9 +391,12 @@ class RekordboxExporter:
# ---- 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
root = db.create_playlist_folder(payload.name) folder named after the export (None = the top level)."""
db.flush() root = None
if payload.root_folder:
root = db.create_playlist_folder(payload.name)
db.flush()
folders: dict[tuple[str, ...], object] = {(): root} folders: dict[tuple[str, ...], object] = {(): root}
for playlist in payload.playlists: for playlist in payload.playlists:
@@ -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
@@ -7,8 +7,8 @@ from __future__ import annotations
from ...core import musical_key from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, palette, timebase from . import beatgrid, memory_palette, palette, timebase, track_palette
from .cue_types import cue_type, role_and_slot from .cue_types import cue_type, kind_for, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also # Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
# holds whatever text a track's key TAG carried when it was imported, so a real # holds whatever text a track's key TAG carried when it was imported, so a real
@@ -127,6 +127,8 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
# file's mix, but Konduktor's deck plays its stems, and the Type column # file's mix, but Konduktor's deck plays its stems, and the Type column
# must not disagree with the deck. # must not disagree with the deck.
media_kind="stem" if stem else "audio", media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "ColorID", None)),
color_hex=track_palette.hex_for(getattr(row, "ColorID", None)),
) )
@@ -140,10 +142,10 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
`editable` says whether the adapter will accept a command on THIS cue, which `editable` says whether the adapter will accept a command on THIS cue, which
is the only thing the UI gates on. Every hot cue is editable, loops included. is the only thing the UI gates on. Every hot cue is editable, loops included.
**Memory cues are not**: Rekordbox is the only platform that has them, so So is every memory cue (`Kind` 0), addressed by its row id (`CuePoint.id`)
under the two-platform promotion rule they are shown and never written. A cue since it has no pad. A cue sitting on the reserved `Kind` 4 occupies no pad
sitting on the reserved `Kind` occupies no pad and is projected the same way, either and is SHOWN as a memory cue, because that is how Rekordbox itself
because that is how Rekordbox itself displays one. displays one — but it is not one, so it is not editable.
""" """
markers: list[GridMarker] = [] markers: list[GridMarker] = []
if grid is not None: if grid is not None:
@@ -158,7 +160,9 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
length = 0.0 length = 0.0
if out_msec is not None and out_msec > 0: if out_msec is not None and out_msec > 0:
length = max(0.0, (out_msec - in_msec) / 1000.0) length = max(0.0, (out_msec - in_msec) / 1000.0)
editable = role == "hotcue" memory = role == "memory"
# Kind 4 (reserved) displays as a memory cue but is not one.
editable = not memory or getattr(c, "Kind", None) == kind_for("memory", None)
cues.append( cues.append(
CuePoint( CuePoint(
name=(getattr(c, "Comment", None) or None), name=(getattr(c, "Comment", None) or None),
@@ -169,15 +173,27 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
start=timebase.from_pioneer(in_msec / 1000.0, time_offset), start=timebase.from_pioneer(in_msec / 1000.0, time_offset),
length=length, length=length,
slot=slot, slot=slot,
color=_cue_color(c), color=_memory_cue_color(c) if memory else _cue_color(c),
editable=editable, editable=editable,
readonly_reason=None if editable else "platform_managed", readonly_reason=None if editable else "platform_managed",
grid_marker=None, grid_marker=None,
# A memory cue is addressed by its row id (`CuePoint.id`).
id=str(c.ID) if memory and editable and getattr(c, "ID", None) is not None else None,
) )
) )
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues) return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
def _memory_cue_color(row) -> str | None:
"""A memory cue keeps its 0-based `memory_palette` code in `Color` (-1 and
255 = none). A row Konduktor wrote before that was measured carries a
hot-cue code in `ColorTableIndex` instead; read it rather than lose it."""
colour = memory_palette.hex_for(getattr(row, "Color", None))
if colour is None and (getattr(row, "OutMsec", -1) or -1) <= 0:
colour = palette.hex_for(getattr(row, "ColorTableIndex", None))
return colour
def _cue_color(row) -> str | None: def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value; """Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0.""" `Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
+179 -10
View File
@@ -47,8 +47,8 @@ from ...core.adapter import (
from ...core.edit_journal import EditJournal from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping, stored_form from ...core.pathmap import PathMapping, stored_form
from . import timebase from . import memory_palette, timebase, track_palette
from .cue_types import beat_loop_size, kind_for, role_and_slot from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -556,6 +556,24 @@ class RekordboxStore(ReplaceGridCommands):
self._db.flush() self._db.flush()
self._db.session.expire(row) self._db.session.expire(row)
# ---- writes: track colour ---------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`djmdContent.ColorID`, a 1-based id into `djmdColor` (see
`track_palette`). Cleared = "0", as on the uncoloured rows of the local
library (a few hold NULL; both read as none)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
row = self.content(track_id)
before = row.ColorID
if track_palette.id_for(track_palette.color_for(before)) == new:
return
row.ColorID = str(new)
self._journal.record("track", "set", track_id, "color", before, row.ColorID)
# A foreign key into djmdColor: flush + expire, as for the others.
self._db.flush()
self._db.session.expire(row)
# ---- writes: playlists ------------------------------------------------ # ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str): def _playlist(self, node_id: str):
t = self._tables t = self._tables
@@ -608,6 +626,79 @@ class RekordboxStore(ReplaceGridCommands):
self._db.delete_playlist(row) self._db.delete_playlist(row)
self._journal.record("playlist", "delete", name) self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s visible children.
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
parent", so nothing can be moved to the top level with it. The same
writes are made here — `ParentID`, the moved row's `updated_at`, and
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
share the table and the numbering, so `index` is placed relative to
the VISIBLE siblings and the hidden ones keep their order around it."""
import datetime
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
t = self._tables
row = self._playlist(node_id)
dest = self._playlist(parent_id) if parent_id else None
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
raise InvalidCommand("A playlist can only be moved into a folder")
ancestor = dest
while ancestor is not None:
if str(ancestor.ID) == str(row.ID):
raise InvalidCommand("A folder cannot be moved into itself")
up = str(ancestor.ParentID or "root")
ancestor = None if up in ("root", "0", "") else self._playlist(up)
def children(key: str) -> list:
return (
self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.ParentID == key)
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdPlaylist.Seq)
.all()
)
old_key = str(row.ParentID or "root")
new_key = str(dest.ID) if dest is not None else "root"
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
index = max(0, min(int(index), len(visible)))
if index < len(visible):
at = siblings.index(visible[index])
else:
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
order = siblings[:at] + [row] + siblings[at:]
if old_key == new_key and [str(c.ID) for c in order] == [
str(c.ID) for c in children(new_key)
]:
return str(row.ID)
row.ParentID = new_key
with self._db.registry.disabled():
row.updated_at = datetime.datetime.now()
for n, c in enumerate(order, start=1):
if c.Seq != n:
c.Seq = n
if old_key != new_key:
for n, c in enumerate(
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
):
if c.Seq != n:
c.Seq = n
xml = getattr(self._db, "playlist_xml", None)
if xml is not None:
try:
xml.update(row.ID, parent_id=new_key)
except ValueError:
pass # a playlist the XML never listed: nothing to keep in step
self._db.flush()
self._journal.record("playlist", "move", row.Name)
return str(row.ID)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in the given order. """Replace a playlist's contents, in the given order.
@@ -688,6 +779,7 @@ class RekordboxStore(ReplaceGridCommands):
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused. # Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
content.KeyID = self._key_id(track.key_wheel, track.key_mode) content.KeyID = self._key_id(track.key_wheel, track.key_mode)
content.ContentLink = new_content.CONTENT_LINK content.ContentLink = new_content.CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
if stored != audio: if stored != audio:
# pyrekordbox reads the file where it IS; the row names it as the # pyrekordbox reads the file where it IS; the row names it as the
# library stores every other path (the server's mapping, inverted). # library stores every other path (the server's mapping, inverted).
@@ -1074,6 +1166,25 @@ class RekordboxStore(ReplaceGridCommands):
) )
self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}") self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}")
MAX_MEMORY_CUES = MAX_MEMORY_CUES # see `cue_types`
def memory_cue_rows(self, track_id: str) -> list:
"""A track's memory cues (`Kind` 0), in row order."""
t = self._tables
return list(
self._db.session.query(t.DjmdCue)
.filter(t.DjmdCue.ContentID == str(track_id))
.filter(t.DjmdCue.Kind == kind_for("memory", None))
.filter(t.DjmdCue.rb_local_deleted == 0)
)
def _memory_cue_row(self, track_id: str, cue_id: str):
"""The memory cue whose `djmdCue.ID` is `cue_id` (`CuePoint.id`)."""
row = next((c for c in self.memory_cue_rows(track_id) if str(c.ID) == str(cue_id)), None)
if row is None:
raise NotFound(f"No memory cue {cue_id!r} on this track")
return row
def add_memory_cue( def add_memory_cue(
self, self,
track_id: str, track_id: str,
@@ -1083,23 +1194,59 @@ class RekordboxStore(ReplaceGridCommands):
length_sec: float = 0.0, length_sec: float = 0.0,
name: str | None = None, name: str | None = None,
color_code: int | None = None, color_code: int | None = None,
enforce_cap: bool = True,
) -> None: ) -> None:
"""Add a MEMORY cue (`Kind` 0) — for the exporter building a new library. """Add a MEMORY cue (`Kind` 0); a memory loop when `length_sec` > 0.
The adapter never calls this: editing memory cues in a user's library `color_code` is a 0-based `memory_palette` code — NOT a hot-cue palette
stays refused under the two-platform promotion rule. A new export is not code: a memory cue keeps its colour in `Color`, not `ColorTableIndex`.
an edit, and dropping the source's memory cues would lose prep. `enforce_cap` refuses the 11th (an edit); the exporter, building a
library from a source that may hold more, trims before calling.
""" """
if enforce_cap and len(self.memory_cue_rows(track_id)) >= self.MAX_MEMORY_CUES:
raise InvalidCommand(
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
)
self._write_cue( self._write_cue(
track_id, None, kind=kind_for("memory", None), start_sec=start_sec, track_id, None, kind=kind_for("memory", None), start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code, cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
) )
self._journal.record("cue", "add", track_id, "memory") self._journal.record("cue", "add", track_id, "memory")
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
"""A memory cue's name is rekordbox's `Comment`; only that column changes."""
cue = self._memory_cue_row(track_id, cue_id)
is_loop = (cue.OutMsec or 0) > 0
# An unnamed memory LOOP is '' (measured); an unnamed point cue NULL.
cue.Comment = name or ("" if is_loop else None)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, "memory")
def set_memory_cue_color(self, track_id: str, cue_id: str, color_code: int | None) -> None:
"""Recolour a memory cue; None = rekordbox's "No Color" (255, measured)."""
cue = self._memory_cue_row(track_id, cue_id)
self._apply_memory_color(cue, color_code, (cue.OutMsec or 0) > 0, cleared=True)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, "memory")
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
"""Delete the row outright, as rekordbox does (never `rb_local_deleted`)."""
cue = self._memory_cue_row(track_id, cue_id)
self._db.delete(cue)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "delete", track_id, "memory")
def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str, def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str,
length_sec: float, name: str | None, color_code: int | None) -> None: length_sec: float, name: str | None, color_code: int | None) -> None:
"""Fill one `djmdCue` row (a new one when `cue` is None) and resync the """Fill one `djmdCue` row (a new one when `cue` is None) and resync the
`contentCue` mirror — the single definition of a cue row's fields.""" `contentCue` mirror — the single definition of a cue row's fields.
`color_code` is a hot-cue palette code on a hot cue and a 0-based
`memory_palette` code on a memory cue (`Kind` 0): the two keep their
colour in different columns."""
if start_sec < 0: if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track") raise InvalidCommand("A cue cannot be before the start of the track")
row = self.content(track_id) row = self.content(track_id)
@@ -1144,8 +1291,13 @@ class RekordboxStore(ReplaceGridCommands):
cue.BeatLoopSize = None cue.BeatLoopSize = None
cue.ActiveLoop = None cue.ActiveLoop = None
cue.CueMicrosec = None cue.CueMicrosec = None
self._apply_color(cue, color_code, is_loop) if kind == kind_for("memory", None):
cue.Comment = name or None self._apply_memory_color(cue, color_code, is_loop)
# Measured: an unnamed memory LOOP has Comment '', a point cue NULL.
cue.Comment = name or ("" if is_loop else None)
else:
self._apply_color(cue, color_code, is_loop)
cue.Comment = name or None
self._db.flush() self._db.flush()
self._sync_content_cue(track_id) self._sync_content_cue(track_id)
@@ -1167,6 +1319,21 @@ class RekordboxStore(ReplaceGridCommands):
cue.Color = -1 cue.Color = -1
cue.ColorTableIndex = None cue.ColorTableIndex = None
@staticmethod
def _apply_memory_color(cue, code: int | None, is_loop: bool, *, cleared: bool = False) -> None:
"""A MEMORY cue's colour columns (measured 2026-10-16, kit M1): the
0-based `memory_palette` code in `Color`, `ColorTableIndex` untouched by
colour — NULL on a point cue, 0 on a loop (rekordbox's loop marker).
Uncoloured is -1 on a new point cue, 255 on a loop and on any cue set
back to "No Color" (`cleared`)."""
cue.ColorTableIndex = 0 if is_loop else None
if code is not None:
cue.Color = int(code)
elif cleared or is_loop:
cue.Color = memory_palette.CLEARED
else:
cue.Color = -1
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None: def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the """Recolour the cue in `slot`; None makes it uncoloured. Touches only the
colour columns, so the position does not take a time-base round trip.""" colour columns, so the position does not take a time-base round trip."""
@@ -1235,11 +1402,13 @@ class RekordboxStore(ReplaceGridCommands):
""" """
t = self._tables t = self._tables
row = self.content(track_id) row = self.content(track_id)
# In ROW order, as rekordbox writes it (measured: a memory cue added at
# 1:55 is listed after older ones at 2:04 and 3:26), not by position.
cues = ( cues = (
self._db.session.query(t.DjmdCue) self._db.session.query(t.DjmdCue)
.filter(t.DjmdCue.ContentID == str(track_id)) .filter(t.DjmdCue.ContentID == str(track_id))
.filter(t.DjmdCue.rb_local_deleted == 0) .filter(t.DjmdCue.rb_local_deleted == 0)
.order_by(t.DjmdCue.InMsec) .order_by(text("djmdCue.rowid"))
.all() .all()
) )
fields = ( fields = (
@@ -0,0 +1,50 @@
"""rekordbox's TRACK colours — the eight a track can be tagged with.
Stored as a 1-based id into the `djmdColor` table (master.db `djmdContent.ColorID`,
a string: "0" = none) and OneLibrary's `color` table (`content.color_id`, an
integer, 0 = none); the stick's legacy `export.pdb` track row has a `color_id`
byte with the same numbering. Both tables list the same eight rows in the same
order: 1 Pink, 2 Red, 3 Orange, 4 Yellow, 5 Green, 6 Aqua, 7 Blue, 8 Purple —
one per generic `TrackColor`, so the mapping is one to one.
Those are the memory-cue palette's names in its order, so the display RGB is
`memory_palette.COLOURS`' (sampled from rekordbox 7's own colour menu). Nothing
stores the RGB — `djmdColor.ColorCode` is NULL in a real library.
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
from . import memory_palette
#: id - 1 -> the generic colour, in rekordbox's menu order.
_NAMES: list[TrackColor] = ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
#: What `capabilities.tracks.colors` offers.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color=name, hex=memory_palette.SWATCHES[i], label=memory_palette.COLOURS[i][0])
for i, name in enumerate(_NAMES)
]
def _id(color_id: int | str | None) -> int:
try:
return int(color_id) if color_id is not None else 0
except (TypeError, ValueError):
return 0
def color_for(color_id: int | str | None) -> TrackColor | None:
"""The generic colour for a stored id; None for 0, NULL or anything unknown."""
n = _id(color_id)
return _NAMES[n - 1] if 1 <= n <= len(_NAMES) else None
def hex_for(color_id: int | str | None) -> str | None:
"""rekordbox's display colour for a stored id; None when uncoloured."""
n = _id(color_id)
return SWATCHES[n - 1].hex if 1 <= n <= len(SWATCHES) else None
def id_for(color: TrackColor | str | None) -> int:
"""The id to store for a generic colour; 0 for none (or an unknown name)."""
return _NAMES.index(color) + 1 if color in _NAMES else 0
+93 -6
View File
@@ -30,6 +30,7 @@ from ... import remote_protocol as rp
from ...core.adapter import ( from ...core.adapter import (
AudioFacts, AudioFacts,
FileTagResult, FileTagResult,
NotFound,
SaveOutcome, SaveOutcome,
Unavailable, Unavailable,
Unsupported, Unsupported,
@@ -39,6 +40,7 @@ from ...core.query import TrackIndex
from .cache import RemoteAudioCache, StaleFacts from .cache import RemoteAudioCache, StaleFacts
from .cache import shared as shared_cache from .cache import shared as shared_cache
from .client import RemoteClient, SessionLost from .client import RemoteClient, SessionLost
from .folder import ServerFile, ServerFiles
from .session import RemoteSession from .session import RemoteSession
_NOT_HERE = "A remote library's paths are the server's configuration" _NOT_HERE = "A remote library's paths are the server's configuration"
@@ -60,6 +62,13 @@ class RemoteAdapter:
self._facts: dict[str, AudioFacts] = {} self._facts: dict[str, AudioFacts] = {}
#: Server path of an upload → (the local file it came from, its analysis lead). #: Server path of an upload → (the local file it came from, its analysis lead).
self._uploads: dict[str, tuple[Path, float | None]] = {} self._uploads: dict[str, tuple[Path, float | None]] = {}
#: Content-folder files a listing returned, by their server path.
self._listed: dict[str, ServerFile] = {}
#: `str(Path(p))` → `p` for every server path this side has turned into
#: a `Path` (an upload's target, a listed file): on Windows that
#: conversion rewrites the separators, and the server must get its own
#: spelling back.
self._server_paths: dict[str, str] = {}
self._dirty = bool(hello.get("dirty")) self._dirty = bool(hello.get("dirty"))
self._load() self._load()
@@ -194,6 +203,9 @@ class RemoteAdapter:
def delete_playlist(self, node_id): def delete_playlist(self, node_id):
return self._call("delete_playlist", node_id=node_id) return self._call("delete_playlist", node_id=node_id)
def move_playlist(self, node_id, parent_id, index):
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
def set_playlist_entries(self, node_id, track_ids): def set_playlist_entries(self, node_id, track_ids):
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids)) return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
@@ -206,6 +218,9 @@ class RemoteAdapter:
def set_key(self, track_id, wheel, mode): def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode) return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
def set_track_color(self, track_id, color):
return self._call("set_track_color", track_id=track_id, color=color)
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None): def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec, return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, role=role, name=name) cue_type=cue_type, length_sec=length_sec, role=role, name=name)
@@ -222,6 +237,22 @@ class RemoteAdapter:
def place_cues(self, track_id, cues, *, overwrite=False): def place_cues(self, track_id, cues, *, overwrite=False):
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite) return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
def add_memory_cue(self, track_id, *, start_sec, cue_type, length_sec=0.0, name=None, color=None):
return self._call("add_memory_cue", track_id=track_id, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color=color)
def rename_memory_cue(self, track_id, cue_id, name):
return self._call("rename_memory_cue", track_id=track_id, cue_id=cue_id, name=name)
def set_memory_cue_type(self, track_id, cue_id, cue_type):
return self._call("set_memory_cue_type", track_id=track_id, cue_id=cue_id, cue_type=cue_type)
def set_memory_cue_color(self, track_id, cue_id, color):
return self._call("set_memory_cue_color", track_id=track_id, cue_id=cue_id, color=color)
def delete_memory_cue(self, track_id, cue_id):
return self._call("delete_memory_cue", track_id=track_id, cue_id=cue_id)
def add_grid_marker(self, track_id, start_sec, bpm=None): def add_grid_marker(self, track_id, start_sec, bpm=None):
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm) return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
@@ -257,6 +288,7 @@ class RemoteAdapter:
self.session.lost(ex.holder) self.session.lost(ex.holder)
raise raise
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead")) self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
self._server_paths[str(Path(landed["path"]))] = landed["path"]
return Path(landed["path"]) return Path(landed["path"])
def free_space(self, path: str) -> int: def free_space(self, path: str) -> int:
@@ -265,8 +297,13 @@ class RemoteAdapter:
def delete_upload(self, path) -> None: def delete_upload(self, path) -> None:
"""Undo `upload_audio` (a cancelled or failed import).""" """Undo `upload_audio` (a cancelled or failed import)."""
self._uploads.pop(str(path), None) key = self._server_key(path)
self.client.delete_upload(str(path)) self._uploads.pop(key, None)
self.client.delete_upload(key)
def _server_key(self, path) -> str:
text = str(path)
return self._server_paths.get(text, text)
def add_tracks(self, items, *, checkpoint=None): def add_tracks(self, items, *, checkpoint=None):
"""Add uploaded files. Where the platform analyses what it adds (the """Add uploaded files. Where the platform analyses what it adds (the
@@ -276,10 +313,20 @@ class RemoteAdapter:
wire = [] wire = []
total = len(items) total = len(items)
for n, item in enumerate(items, start=1): keys = [self._server_key(item.audio_path) for item in items]
key = str(item.audio_path) # Files already in the content folder (added in place): the server says
# whether the platform analyses, and only then is the file fetched.
in_place = [k for k, item in zip(keys, items)
if item.analysis is None and k not in self._uploads and k in self._listed]
leads = self.client.folder_leads(in_place) if in_place else {}
for n, (item, key) in enumerate(zip(items, keys), start=1):
source, lead = self._uploads.get(key, (None, None)) source, lead = self._uploads.get(key, (None, None))
analysis = item.analysis analysis = item.analysis
if analysis is None and source is None and leads.get(key) is not None:
lead = leads[key]
if checkpoint is not None:
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
source = self.folder_audio(key)
if analysis is None and lead is not None and source is not None: if analysis is None and lead is not None and source is not None:
if checkpoint is not None: if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total) checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
@@ -299,8 +346,8 @@ class RemoteAdapter:
self.session.lost(ex.holder) self.session.lost(ex.holder)
raise raise
self._apply(envelope) self._apply(envelope)
for item in items: for key in keys:
self._uploads.pop(str(item.audio_path), None) self._uploads.pop(key, None)
return envelope["result"] return envelope["result"]
def apply_stem_swaps(self, swaps, *, add_to_playlist=None): def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
@@ -390,6 +437,46 @@ class RemoteAdapter:
facts = self.audio_facts([track_id]).get(track_id) facts = self.audio_facts([track_id]).get(track_id)
return self.cache.get(facts) if facts else None return self.cache.get(facts) if facts else None
# ---- the content folder, browsed --------------------------------------------------
def folder_listing(self, path: str | None) -> ServerFiles:
"""The audio directly inside a content folder (None: the folder itself),
as the server lists it — and remembered, so a file can then be played
or added by its path."""
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
with self._lock:
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
self._listed.update(listing.files)
self._server_paths.update({str(Path(k)): k for k in listing.files})
return listing
def listed_files(self, paths) -> ServerFiles | None:
"""The listed files among `paths` as one source (they may come from
several folders); None when none of them was listed."""
with self._lock:
found = [self._listed[p] for p in paths if p in self._listed]
return ServerFiles(self, found[0].folder, found) if found else None
def folder_audio(self, path: str, *, progress=None) -> Path:
"""A local copy of a listed file, downloaded into the shared cache —
keyed by the same facts as a library track's, so a file that is both
downloads once."""
for attempt in range(2):
with self._lock:
found = self._listed.get(path)
if found is None:
raise NotFound("File not found — browse to its folder first")
cached = self.cache.get(found.facts)
if cached is not None:
return cached
try:
return self.cache.fetch(
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
except StaleFacts:
if attempt:
raise
self.folder_listing(found.folder) # changed on the server: re-read it
raise NotFound(path)
# ---- paths: the server's business ------------------------------------------------ # ---- paths: the server's business ------------------------------------------------
def set_path_mapping(self, mapping): def set_path_mapping(self, mapping):
raise Unsupported(_NOT_HERE) raise Unsupported(_NOT_HERE)
@@ -246,6 +246,29 @@ class RemoteClient:
def fs_list(self, path: str | None) -> dict: def fs_list(self, path: str | None) -> dict:
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json() return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
def folder_tracks(self, path: str | None) -> dict:
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
timeout=None).json()
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
"""Stream a listed content-folder file into `target` (as `download`)."""
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
if response.status_code >= 400:
response.read()
self.check(response)
with open(target, "wb") as out:
for chunk in response.iter_bytes(1 << 20):
out.write(chunk)
if progress is not None:
progress(len(chunk))
return {
"size": int(response.headers.get("X-Konduktor-Size") or 0),
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
}
def fs_space(self, path: str | None) -> int: def fs_space(self, path: str | None) -> int:
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"]) return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
+102
View File
@@ -0,0 +1,102 @@
"""The server's content folder, browsed from this computer like a drive.
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
remote library the music lives in the server's content folder, which this
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
facts, and which files the library already holds) and this module holds the
answer as a read-only SOURCE, the shape the table, the deck and the importer
already read.
Adding one of these files never uploads anything: it is already where the
library can reach it, so it is added IN PLACE (`on_library_host`), and the
importer skips both the copy and the copy-or-reference question.
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
until the importer needs one, because a server path is not a path here (on a
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from ...core.adapter import AudioFacts
from ...core.model import PlaylistNode, Track, TrackCues
@dataclass
class ServerFile:
folder: str
track: Track
facts: AudioFacts
#: The library's id for this file, when it already points at it.
held: str | None = None
class ServerFiles:
"""Files in the content folder, as the read half of a source."""
#: The importer's cue that these are already on the machine holding the
#: library: added where they are, neither copied nor uploaded.
on_library_host = True
def __init__(self, adapter, path: str, files: list[ServerFile]):
self.adapter = adapter
self.path = path
self._files = {f.track.id: f for f in files}
@classmethod
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
folder = body["path"]
facts = body.get("files") or {}
held = body.get("held") or {}
files = []
for raw in body.get("tracks") or []:
track = Track.model_validate(raw)
fact = facts.get(track.id)
if fact is None:
continue
files.append(ServerFile(
folder=folder, track=track,
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
held=held.get(track.id),
))
return cls(adapter, folder, files)
@property
def files(self) -> dict[str, ServerFile]:
return self._files
@property
def tracks(self) -> list[Track]:
return [f.track for f in self._files.values()]
def track(self, track_id: str) -> Track | None:
found = self._files.get(track_id)
return found.track if found else None
def held(self, track_id: str) -> str | None:
found = self._files.get(track_id)
return found.held if found else None
def size(self, track_id: str) -> int:
found = self._files.get(track_id)
return found.facts.size if found else 0
def track_cues(self, track_id: str) -> TrackCues | None:
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
return {t: self._files[t].facts for t in track_ids if t in self._files}
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
"""A local copy (downloaded into the shared cache, like a library track)."""
if track_id not in self._files:
return None
return self.adapter.folder_audio(track_id, progress=progress)
def playlist_tree(self) -> list[PlaylistNode]:
return []
def playlist_tracks(self, node_id: str) -> list[Track] | None:
return None
+84 -20
View File
@@ -131,6 +131,10 @@ class TraktorAdapter:
with _translate(): with _translate():
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:
with _translate():
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents. The adapter resolves each id to its """Replace a playlist's contents. The adapter resolves each id to its
native entry kind, so callers never see Traktor's STEM/TRACK split.""" native entry kind, so callers never see Traktor's STEM/TRACK split."""
@@ -152,6 +156,12 @@ class TraktorAdapter:
self._refresh(track_id) self._refresh(track_id)
return self._index.get(track_id) return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
with _translate():
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
def 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:
with _translate(): with _translate():
self._store.set_track_art(track_id, data, mime) self._store.set_track_art(track_id, data, mime)
@@ -193,10 +203,11 @@ class TraktorAdapter:
Lossiness follows the settled rule — degrade to the nearest equivalent, Lossiness follows the settled rule — degrade to the nearest equivalent,
drop only where none exists: drop only where none exists:
* **Memory cues become hot cues in spare slots.** Traktor has no * **Memory cues stay memory cues** — Traktor's cues on no pad
memory cues, and every Traktor cue occupies a slot. Filling the (HOTCUE="-1"), decided 2026-10-16 once Traktor was measured keeping
leftovers preserves the positions a DJ actually marked; when the them. They used to be promoted to spare pads.
bank is full the rest are dropped, because there is nowhere left. * **A hot cue whose pad is taken** moves to a spare pad, else becomes a
memory cue — never dropped.
* **Cue colour is dropped.** Traktor derives a cue's colour from its * **Cue colour is dropped.** Traktor derives a cue's colour from its
type, so a free RGB value has nowhere to go. type, so a free RGB value has nowhere to go.
@@ -246,29 +257,43 @@ class TraktorAdapter:
self._place_imported_cue(track_id, cue.slot, cue) self._place_imported_cue(track_id, cue.slot, cue)
taken.add(cue.slot) taken.add(cue.slot)
# Everything without a pad of its own competes for what is left: memory # A hot cue whose pad was taken (or is past the bank) moves to a spare
# cues, which Traktor has no equivalent for, and any hot cue whose pad # pad, earliest first, because muscle memory is most of what a hot cue
# was already occupied. Earliest first, so that when the bank runs out # layout is; once the bank is full it becomes a memory cue rather than
# it is the late cues that are lost rather than an arbitrary set — and # being lost. Memory cues cross as memory cues.
# a displaced hot cue is moved rather than dropped, because losing one
# silently is much worse than having it turn up on the wrong pad.
leftovers = displaced + [c for c in (cues.cues or []) if c.role != "hotcue"]
spare = (s for s in range(slots) if s not in taken) spare = (s for s in range(slots) if s not in taken)
for cue in sorted(leftovers, key=lambda c: c.start): for cue in sorted(displaced, key=lambda c: c.start):
slot = next(spare, None) slot = next(spare, None)
if slot is None: if slot is None:
break # bank full: the rest are dropped, per the lossiness rule self._place_imported_memory_cue(track_id, cue)
self._place_imported_cue(track_id, slot, cue) else:
self._place_imported_cue(track_id, slot, cue)
for cue in sorted((c for c in (cues.cues or []) if c.role != "hotcue" or c.slot is None),
key=lambda c: c.start):
self._place_imported_memory_cue(track_id, cue)
@staticmethod
def _imported_type(cue) -> str:
"""A loop stays a loop; Traktor's own point types (fade, load) survive."""
if getattr(cue, "length", 0):
return "loop"
return cue.type if cue.type in ("cue", "fade_in", "fade_out", "load") else "cue"
def _place_imported_cue(self, track_id: str, slot: int, cue) -> None: def _place_imported_cue(self, track_id: str, slot: int, cue) -> None:
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
if cue_type not in CUE_TYPE_TO_NATIVE:
return
self.set_cue( self.set_cue(
track_id, track_id,
slot=slot, slot=slot,
start_sec=cue.start, start_sec=cue.start,
cue_type=cue_type, cue_type=self._imported_type(cue),
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None),
)
def _place_imported_memory_cue(self, track_id: str, cue) -> None:
self.add_memory_cue(
track_id,
start_sec=cue.start,
cue_type=self._imported_type(cue),
length_sec=getattr(cue, "length", 0.0) or 0.0, length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), name=getattr(cue, "name", None),
) )
@@ -292,8 +317,8 @@ class TraktorAdapter:
name: str | None = None, name: str | None = None,
) -> TrackCues: ) -> TrackCues:
if role != "hotcue": if role != "hotcue":
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot. # A memory cue has no slot to set; it has its own commands.
raise Unsupported("Traktor cues always occupy a hotcue slot") raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
with _translate(): with _translate():
self._store.set_hotcue( self._store.set_hotcue(
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
@@ -314,6 +339,45 @@ class TraktorAdapter:
self._store.delete_hotcue(track_id, slot) self._store.delete_hotcue(track_id, slot)
return self._refresh(track_id) return self._refresh(track_id)
# ---- memory cues: cues on no pad (HOTCUE="-1") ----------------------------
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
# Traktor colours a cue by its type, so a colour has nowhere to go; an
# import passes none, and the capabilities offer none.
if color is not None:
raise Unsupported("Traktor colours cues by their type")
with _translate():
self._store.add_memory_cue(
track_id, start_sec, self._native_cue_type(cue_type), length_sec, name
)
return self._refresh(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
with _translate():
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
with _translate():
self._store.set_memory_cue_type(track_id, cue_id, self._native_cue_type(cue_type))
return self._refresh(track_id)
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
raise Unsupported("Traktor colours cues by their type")
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
with _translate():
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
native = [ native = [
SimpleNamespace( SimpleNamespace(
@@ -19,6 +19,7 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, TrackCapabilities,
) )
from . import track_palette
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"') _VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
@@ -46,8 +47,11 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable=True, editable=True,
hotcue_slots=8, hotcue_slots=8,
slot_labels="number", slot_labels="number",
# Traktor has no memory cues — every cue occupies a bank slot. # Memory cues are CUE_V2s on no pad (HOTCUE="-1"), any type, no
memory_cues=False, # limit (measured in Traktor 4.5, 2026-10-16). No colour: by type.
memory_cues=True,
max_memory_cues=None,
memory_color="none",
types=CUE_TYPES, types=CUE_TYPES,
# Traktor colours a cue by its TYPE; the only COLOR it stores is a # Traktor colours a cue by its TYPE; the only COLOR it stores is a
# grid marker's white companion, so there is nothing to pick. # grid marker's white companion, so there is nothing to pick.
@@ -65,6 +69,8 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
addable=True, addable=True,
stem_convertible=True, stem_convertible=True,
key_writable=True, key_writable=True,
# INFO@COLOR, seven colours (measured, see `track_palette`).
colors=list(track_palette.SWATCHES),
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both. # but only on Windows, and a file added on one OS must play on both.
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"], audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
@@ -74,7 +80,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
"need a manual Import Cover Art to show up." "need a manual Import Cover Art to show up."
), ),
), ),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True), playlists=PlaylistCapabilities(
folders=True, smart="read_only", reorder=True,
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
# itself adds a track twice when asked.
duplicates=True,
),
save=SaveCapabilities( save=SaveCapabilities(
app_name="Traktor", app_name="Traktor",
library_label="collection.nml", library_label="collection.nml",
+5 -9
View File
@@ -106,14 +106,10 @@ class TraktorExporter:
return WrittenLibrary(library=library) return WrittenLibrary(library=library)
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None: def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
"""Recreate the tree under one folder named after the export. """Recreate the tree — at the top level, or with `payload.root_folder`
under one folder named after the export (None = the top level)."""
Nested under the export's own name for the same reason import nests a root = adapter.create_folder(payload.name) if payload.root_folder else None
drive's playlists under the drive's name: a collection swapped onto folders: dict[tuple[str, ...], str | None] = {(): root}
another machine should say where its playlists came from.
"""
root = adapter.create_folder(payload.name)
folders: dict[tuple[str, ...], str] = {(): root}
for playlist in payload.playlists: for playlist in payload.playlists:
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root) parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
@@ -128,7 +124,7 @@ class TraktorExporter:
adapter.set_playlist_entries(node_id, loose) adapter.set_playlist_entries(node_id, loose)
@staticmethod @staticmethod
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str) -> str: def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str | None) -> str | None:
"""Create (once) the folder chain a playlist sits under, and return it.""" """Create (once) the folder chain a playlist sits under, and return it."""
for depth in range(1, len(path) + 1): for depth in range(1, len(path) + 1):
branch = path[:depth] branch = path[:depth]
@@ -9,7 +9,7 @@ import re
from ...core import musical_key from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase from . import beatgrid, timebase, track_palette
from .cue_types import NATIVE_TO_CUE_TYPE from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"), # Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
@@ -172,9 +172,48 @@ def to_track(e) -> Track:
grid_marker_count=len(markers), grid_marker_count=len(markers),
grid_locked=bool(e.lock), grid_locked=bool(e.lock),
media_kind="stem" if getattr(e, "stems", None) is not None else "audio", media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
color=track_palette.color_for(info.color if info else None),
color_hex=track_palette.hex_for(info.color if info else None),
) )
#: Traktor's NAME for a cue nobody named.
UNNAMED = "n.n."
def is_memory_cue(c) -> bool:
"""A cue on no pad that is not a grid marker — Traktor's memory cue.
Traktor stores it as an ordinary CUE_V2 with HOTCUE="-1", any type, drawn
on the waveform and reached with the cue panel's ‹ › (measured in Traktor
4.5, 2026-10-16). A grid marker is ALSO HOTCUE="-1"; its <GRID> child is
what tells them apart — never its name or position.
"""
return getattr(c, "grid", None) is None and (c.hotcue is None or c.hotcue < 0)
def memory_cue_id(c, n: int) -> str:
"""`CuePoint.id` for a memory cue: its stored START, TYPE and LEN, plus `n`
— how many identical memory cues come before it (Traktor allows several at
one START). Content-derived, so it is the same on every read."""
return f"m:{c.start or 0.0:.6f}:{c.type}:{c.len or 0.0:.6f}:{n}"
def with_memory_ids(entry) -> list:
"""(cue, its memory id or None) for every CUE_V2 of an entry, in order."""
seen: dict[str, int] = {}
out = []
for c in entry.cue_v2 or []:
if not is_memory_cue(c):
out.append((c, None))
continue
base = memory_cue_id(c, 0)
n = seen.get(base, 0)
seen[base] = n + 1
out.append((c, memory_cue_id(c, n)))
return out
def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues: def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
"""Project an ENTRY's beatgrid + cues. """Project an ENTRY's beatgrid + cues.
@@ -200,20 +239,30 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
) )
for i, m in enumerate(markers) for i, m in enumerate(markers)
] ]
# A pad MAP put on a memory cue leaves the memory cue in place at the same
# START (measured in Traktor 4.5); Traktor draws ONE marker, so the pad
# stands for both (decided 2026-10-16).
pad_starts = {c.start for c in entry.cue_v2 or []
if getattr(c, "grid", None) is None and c.hotcue is not None and c.hotcue >= 0}
cues = [] cues = []
for c in entry.cue_v2 or []: for c, memory_id in with_memory_ids(entry):
if getattr(c, "grid", None) is not None: if getattr(c, "grid", None) is not None:
continue # a grid marker is projected as a beatgrid marker, not a cue continue # a grid marker is projected as a beatgrid marker, not a cue
if memory_id is not None and c.start in pad_starts:
continue
marker = marker_of.get(id(c)) marker = marker_of.get(id(c))
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
cues.append( cues.append(
CuePoint( CuePoint(
name=c.name, # "n.n." is the name Traktor gives every cue the user did not
# name — a placeholder, not a name, so it crosses as none
# (it once landed in rekordbox as a comment reading "n.n.").
name=None if c.name in (None, "", UNNAMED) else c.name,
# An unknown TYPE is projected as a plain cue rather than dropped: # An unknown TYPE is projected as a plain cue rather than dropped:
# preserving a cue we cannot name beats hiding it from the user. # preserving a cue we cannot name beats hiding it from the user.
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"), type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
# Every Traktor cue lives in the hotcue bank. # A cue on no pad (HOTCUE="-1") is a memory cue.
role="hotcue", role="hotcue" if slot is not None else "memory",
start=timebase.from_traktor_ms(c.start or 0.0, offset_ms), start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
length=(c.len or 0.0) / 1000.0, length=(c.len or 0.0) / 1000.0,
slot=slot, slot=slot,
@@ -221,6 +270,7 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
editable=True, editable=True,
readonly_reason=None, readonly_reason=None,
grid_marker=marker, grid_marker=marker,
id=memory_id,
) )
) )
return TrackCues( return TrackCues(
+185 -19
View File
@@ -53,10 +53,10 @@ from ...core.pathmap import PathMapping, stored_form
from ...core.relocate import PathGroup from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode from ...schemas import PlaylistNode
from . import beatgrid, timebase from . import beatgrid, timebase, track_palette
from .locations import os_path_to_location, resolve_path from .locations import os_path_to_location, resolve_path
from ...core import musical_key from ...core import musical_key
from .projection import iso_date, musical_key_value, traktor_date from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under # Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
# this email is what makes the stars show up in Traktor itself. # this email is what makes the stars show up in Traktor itself.
@@ -160,11 +160,13 @@ class TraktorStore:
can_reorder=True, can_reorder=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
if ntype == "SMARTLIST" or node.smartplaylist is not None: if ntype == "SMARTLIST" or node.smartplaylist is not None:
# Rule-based, so it has no static entry list to show or edit. # Rule-based, so it has no static entry list to show or edit.
return PlaylistNode( return PlaylistNode(
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart" id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
can_move=True,
) )
path = parent_path + [name] path = parent_path + [name]
return PlaylistNode( return PlaylistNode(
@@ -175,6 +177,7 @@ class TraktorStore:
can_contain_children=True, can_contain_children=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
@staticmethod @staticmethod
@@ -348,6 +351,79 @@ class TraktorStore:
self._note("playlist-delete", node.name) self._note("playlist-delete", node.name)
self.dirty = True self.dirty = True
def _find_node(self, node_id: str) -> Nodetype:
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
smart playlist's `sl:` path (its folder path plus its own name)."""
if node_id.startswith("fld:"):
return self._find_folder(node_id)
if node_id.startswith("sl:"):
*folders, name = node_id[len("sl:"):].split("/")
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
match = next(
(c for c in self._children(parent)
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
None,
)
if match is None:
raise PlaylistError(f"Smart playlist not found: {node_id}")
return match
node = self._find_playlist_node(node_id)
if node is None:
raise PlaylistError(f"Playlist not found: {node_id}")
return node
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children (counted without
it) and return its id afterwards — a folder's and a smart playlist's id
is their path of names, so moving one changes it (and its subtree's).
A folder or smart playlist landing beside a namesake of its own kind is
refused, as rename refuses it: the two paths would be one, and one of
them unaddressable. Playlists are UUIDs, so their names may repeat."""
with self._lock:
node = self._find_node(node_id)
if node is self._root():
raise PlaylistError("Cannot move the root folder")
dest = self._find_folder(parent_id)
if dest is node or any(n is dest for n in self._iter_nodes(node)):
raise PlaylistError("A folder cannot be moved into itself")
is_folder = node.playlist is None and node.smartplaylist is None and (
node.type or "FOLDER") == "FOLDER"
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
if is_folder or is_smart:
kind = "folder" if is_folder else "smart playlist"
for c in self._children(dest):
same_kind = (
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
and c.smartplaylist is None
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
if c is not node and same_kind and c.name == node.name:
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
source = self._find_parent_of(node)
if source is None:
raise PlaylistError("Cannot move a top-level node")
siblings = [c for c in self._children(dest) if c is not node]
index = max(0, min(int(index), len(siblings)))
if source is dest and self._children(dest).index(node) == index:
return self._node_id(node, parent_id) # already there
source.subnodes.node.remove(node)
source.subnodes.count = len(source.subnodes.node)
if dest.subnodes is None:
dest.subnodes = Subnodestype(node=[], count=0)
dest.subnodes.node.insert(index, node)
dest.subnodes.count = len(dest.subnodes.node)
self._note("playlist-move", node.name)
self.dirty = True
return self._node_id(node, parent_id)
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
if node.playlist is not None:
return node.playlist.uuid
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
with self._lock: with self._lock:
node = self._find_playlist_node(playlist_uuid) node = self._find_playlist_node(playlist_uuid)
@@ -370,7 +446,8 @@ class TraktorStore:
EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS
# Fields that live only in the collection: Traktor itself writes no file tag # Fields that live only in the collection: Traktor itself writes no file tag
# for "Comment 2" (verified on an m4a it had just edited), so neither do we. # for "Comment 2" (verified on an m4a it had just edited), so neither do we.
_COLLECTION_ONLY_FIELDS = {"comment2"} # Nor for the track colour (kit T1: no audio file's mtime moved).
_COLLECTION_ONLY_FIELDS = {"comment2", "color"}
def set_track_metadata(self, track_id: str, fields: dict) -> None: def set_track_metadata(self, track_id: str, fields: dict) -> None:
with self._lock: with self._lock:
@@ -468,6 +545,27 @@ class TraktorStore:
self._journal.record("track", "set", track_id, "key", before, entry.info.key) self._journal.record("track", "set", track_id, "key", before, entry.info.key)
self.dirty = True self.dirty = True
# ---- track colour -----------------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""INFO@COLOR (see `track_palette`). Cleared = the attribute removed, as
every never-coloured entry has it; what Traktor itself leaves after
"None" (absent, or `COLOR="0"`) is not yet measured (kit T1 step 3)."""
code = track_palette.code_for(color)
if color is not None and code is None:
raise InvalidCommand(f"Not a track colour: {color!r}")
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
before = entry.info.color if entry.info is not None else None
if before == code:
return
if entry.info is None:
entry.info = Infotype()
entry.info.color = code
self._journal.record("track", "set", track_id, "color", before, code)
self.dirty = True
# ---- adding tracks -------------------------------------------------- # ---- adding tracks --------------------------------------------------
def add_entry(self, track, audio_path: Path) -> str: def add_entry(self, track, audio_path: Path) -> str:
"""Append a brand-new ENTRY for `audio_path` and return its track id. """Append a brand-new ENTRY for `audio_path` and return its track id.
@@ -522,6 +620,7 @@ class TraktorStore:
# attribute at all rather than a zero. # attribute at all rather than a zero.
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None, ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
playtime=getattr(track, "length", None) or None, playtime=getattr(track, "length", None) or None,
color=track_palette.code_for(getattr(track, "color", None)),
) )
album = None album = None
if getattr(track, "album", None): if getattr(track, "album", None):
@@ -694,21 +793,7 @@ class TraktorStore:
if name is not None: if name is not None:
existing.name = name existing.name = name
else: else:
if entry.cue_v2 is None: self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, slot, name))
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
name=name or "n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
len=len_ms,
repeats=-1,
hotcue=slot,
color=None,
grid=None,
)
)
# "add" only when it's a genuinely new hotcue; repositioning/retyping # "add" only when it's a genuinely new hotcue; repositioning/retyping
# an existing slot is a "modify" (keeps the net add/remove count honest). # an existing slot is a "modify" (keeps the net add/remove count honest).
self._note( self._note(
@@ -740,6 +825,87 @@ class TraktorStore:
name=getattr(spec, "name", None), name=getattr(spec, "name", None),
) )
@staticmethod
def _new_cue(cue_type: int, start_ms: float, len_ms: float, hotcue: int,
name: str | None) -> CueV2Type:
"""A CUE_V2 as Traktor writes one by hand — on a pad, or on none
(`hotcue` -1, a memory cue: the same element, measured in Traktor 4.5)."""
return CueV2Type(
name=name or "n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
len=len_ms,
repeats=-1,
hotcue=hotcue,
color=None,
grid=None,
)
@staticmethod
def _insert_cue(entry: Entrytype, cue: CueV2Type) -> None:
"""Insert a new cue at its place BY START, after every cue at or before
it — Traktor keeps CUE_V2 sorted by START (8485/8485 reference entries,
and its own saves), so a later Traktor save moves nothing. Nothing else
moves either, unlike a re-sort of an entry another tool left unsorted."""
if entry.cue_v2 is None:
entry.cue_v2 = []
at = len(entry.cue_v2)
while at > 0 and (entry.cue_v2[at - 1].start or 0.0) > (cue.start or 0.0):
at -= 1
entry.cue_v2.insert(at, cue)
# ---- memory cues: CUE_V2 on no pad (HOTCUE="-1"), not a grid marker -----
# Measured in Traktor 4.5 (2026-10-16, kit M3): any type, no limit, drawn
# on the waveform and reached with the cue panel's ‹ ›, a name shown in the
# cue panel — and a cue written here survives Traktor's own save byte for
# byte. Addressed by `projection.memory_cue_id`.
def _memory_cue(self, entry: Entrytype, cue_id: str) -> CueV2Type:
cue = next((c for c, mid in with_memory_ids(entry) if mid == cue_id), None)
if cue is None:
raise PlaylistError(f"Memory cue {cue_id!r} not found on this track")
return cue
def add_memory_cue(self, track_id: str, start_sec: float, cue_type: int,
length_sec: float = 0.0, name: str | None = None) -> None:
if cue_type not in self.CREATABLE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
len_ms = max(0.0, length_sec * 1000.0)
self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, -1, name))
self._note("hotcue", "add", track_id, "memory")
self.dirty = True
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
self._memory_cue(entry, cue_id).name = name or "n.n."
self._note("hotcue", "modify", track_id, "memory")
self.dirty = True
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: int) -> None:
"""A point type only, as for a hot cue: a loop is not retyped."""
if cue_type not in self.POINT_CUE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
cue = self._memory_cue(entry, cue_id)
if cue.type not in self.POINT_CUE_TYPES:
raise PlaylistError("A memory loop keeps its type")
cue.type = cue_type
self._note("hotcue", "modify", track_id, "memory")
self.dirty = True
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
cue = self._memory_cue(entry, cue_id)
entry.cue_v2 = [c for c in entry.cue_v2 if c is not cue]
self._note("hotcue", "delete", track_id, "memory")
self.dirty = True
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None: def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
"""Change the type of the existing hotcue in `slot` (keeps its position).""" """Change the type of the existing hotcue in `slot` (keeps its position)."""
if cue_type not in self.POINT_CUE_TYPES: if cue_type not in self.POINT_CUE_TYPES:
@@ -0,0 +1,59 @@
"""Traktor's TRACK colours — `INFO@COLOR`, an integer.
MEASURED in Traktor 4.5 (kit T1, 2026-10-17,
`.claude/discussions/discuss-track-colour-2026-10-17.md`) by colouring one track
per entry of the browser's Color menu, in its order: 1 Red · 2 Orange ·
3 Yellow · 4 Green · 5 Blue · 6 Violet · 7 Magenta. Traktor keeps it in the
collection only — it does not tag the audio file.
Mapped to the generic colours BY NAME (decided 2026-10-17): Violet is `purple`,
Magenta `pink`, and Blue is `blue` even though it LOOKS like rekordbox's Aqua —
the name is the DJ's category. Traktor has no seventh-and-a-half colour, so
`aqua` arriving from rekordbox is stored as Blue.
The RGB values are DISPLAY colours only — nothing stores them. They were
sampled from the colour dots in Traktor's own browser (a screenshot).
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
#: What `capabilities.tracks.colors` offers; code - 1 -> swatch, menu order.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color="red", hex="#FB413E", label="Red"),
ColorSwatch(color="orange", hex="#F79525", label="Orange"),
ColorSwatch(color="yellow", hex="#F9F918", label="Yellow"),
ColorSwatch(color="green", hex="#52FA52", label="Green"),
ColorSwatch(color="blue", hex="#1ACBFA", label="Blue"),
ColorSwatch(color="purple", hex="#B26CFA", label="Violet"),
ColorSwatch(color="pink", hex="#FA51EB", label="Magenta"),
]
#: Generic colours Traktor has no swatch of its own for.
_FOLDED: dict[str, int] = {"aqua": 5}
def _swatch(code: int | None) -> ColorSwatch | None:
return SWATCHES[code - 1] if isinstance(code, int) and 1 <= code <= len(SWATCHES) else None
def color_for(code: int | None) -> TrackColor | None:
"""The generic colour for a stored code; None for absent, 0 or unknown."""
s = _swatch(code)
return s.color if s else None
def hex_for(code: int | None) -> str | None:
"""Traktor's display colour for a stored code; None when uncoloured."""
s = _swatch(code)
return s.hex if s else None
def code_for(color: TrackColor | str | None) -> int | None:
"""The `INFO@COLOR` to store for a generic colour; None for none."""
if color is None:
return None
for i, s in enumerate(SWATCHES, start=1):
if s.color == color:
return i
return _FOLDED.get(color)
+33 -1
View File
@@ -22,7 +22,7 @@ from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Protocol, runtime_checkable from typing import Protocol, runtime_checkable
from .capabilities import Capabilities from .capabilities import Capabilities, TrackColor
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping from .pathmap import PathMapping
from .relocate import PathGroup from .relocate import PathGroup
@@ -247,6 +247,12 @@ class LibraryAdapter(Protocol):
def create_folder(self, name: str, parent_id: str | None = None) -> str: ... def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
def rename_playlist(self, node_id: str, name: str) -> None: ... def rename_playlist(self, node_id: str, name: str) -> None: ...
def delete_playlist(self, node_id: str) -> None: ... def delete_playlist(self, node_id: str) -> None: ...
# Move a node (playlist, folder or smart playlist) to `index` among
# `parent_id`'s children (None = the top level), counted with the moved
# node left out. Returns the node's id AFTER the move: an id is opaque, and
# on a platform that addresses a folder by its path it changes. A folder
# cannot go into itself or a descendant (InvalidCommand).
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ... def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
# ---- commands: adding tracks ---------------------------------------- # ---- commands: adding tracks ----------------------------------------
@@ -290,6 +296,9 @@ class LibraryAdapter(Protocol):
# analysis writes. Each platform renders it in its own notation (and its own # analysis writes. Each platform renders it in its own notation (and its own
# analysed-key field, where it has one). Gated on `tracks.key_writable`. # analysed-key field, where it has one). Gated on `tracks.key_writable`.
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ... def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ...
# The track's colour tag (None clears it), mapped onto the platform's own
# palette by name. Gated on `tracks.colors` being non-empty.
def set_track_color(self, track_id: str, color: TrackColor | None) -> Track | None: ...
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: ...
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ... def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
@@ -312,6 +321,29 @@ class LibraryAdapter(Protocol):
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ... def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
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: ...
# ---- commands: memory cues --------------------------------------------
# Cues on no pad, addressed by `CuePoint.id`. Gated on `cues.memory_cues`.
# Past `cues.max_memory_cues` -> InvalidCommand; an unknown id -> NotFound;
# `color` is from `cues.memory_palette` (Unsupported where memory_color is
# "none"). There is deliberately no move: rekordbox has none either, so a
# move is a delete and an add.
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues: ...
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues: ...
# A POINT type from `cues.types` (Traktor: cue / fade in / fade out / load);
# a loop is not retyped. Unsupported where the platform has one point type.
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues: ...
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues: ...
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues: ...
# ---- commands: beatgrid --------------------------------------------- # ---- commands: beatgrid ---------------------------------------------
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: ...
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: ...
+29 -2
View File
@@ -36,6 +36,20 @@ CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"] CueRole = Literal["hotcue", "memory"]
MediaKind = Literal["audio", "stem", "video"] MediaKind = Literal["audio", "stem", "video"]
PlaylistKind = Literal["folder", "playlist", "smart"] PlaylistKind = Literal["folder", "playlist", "smart"]
# A track's colour tag, as a platform-neutral IDENTITY — what crosses between
# libraries. Each adapter maps its own codes to and from these BY NAME (decided
# 2026-10-17, `.claude/discussions/discuss-track-colour-2026-10-17.md`): eight
# names because rekordbox has eight; Traktor's seven cover all but `aqua`,
# which it receives as its Blue.
TrackColor = Literal["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
class ColorSwatch(BaseModel):
"""One track colour a library offers, in its own menu order."""
color: TrackColor
hex: str # the platform's own display colour
label: str # the platform's own name for it ("Violet" in Traktor)
class CueCapabilities(BaseModel): class CueCapabilities(BaseModel):
@@ -45,10 +59,17 @@ class CueCapabilities(BaseModel):
editable: bool = False editable: bool = False
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
slot_labels: Literal["number", "letter"] = "number" slot_labels: Literal["number", "letter"] = "number"
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED # Cues on no pad, listed in time order and called CDJ-style (decided
# but not editable anywhere yet (the two-platform promotion rule). # 2026-10-16). Editable wherever `editable` is: every platform that has them
# can store them (Rekordbox, OneLibrary, and Traktor's HOTCUE="-1").
memory_cues: bool = False memory_cues: bool = False
# Per track; None = no limit. rekordbox stops storing at 10 WITHOUT saying
# so, so the adapter refuses the 11th itself.
max_memory_cues: int | None = None max_memory_cues: int | None = None
# A memory cue's colour is its own palette, not `palette` (rekordbox offers
# 8 colours for memory cues against 16 for hot cues).
memory_color: Literal["none", "palette"] = "none"
memory_palette: list[str] = []
types: list[CueType] = ["cue"] types: list[CueType] = ["cue"]
color: Literal["none", "free", "palette"] = "none" color: Literal["none", "free", "palette"] = "none"
palette: list[str] = [] palette: list[str] = []
@@ -100,12 +121,18 @@ class TrackCapabilities(BaseModel):
# Whether added files can be left where they are ("reference") rather than # Whether added files can be left where they are ("reference") rather than
# copied. False where the library cannot see this computer's files at all. # copied. False where the library cannot see this computer's files at all.
reference: bool = True reference: bool = True
# The track colours this library can store (`set_track_color`), in its own
# menu order. Empty: the platform has no track colour.
colors: list[ColorSwatch] = []
class PlaylistCapabilities(BaseModel): class PlaylistCapabilities(BaseModel):
folders: bool = False folders: bool = False
smart: Literal["none", "read_only"] = "none" smart: Literal["none", "read_only"] = "none"
reorder: bool = False reorder: bool = False
# A playlist can hold the same track more than once. Where it cannot, a
# drop of tracks already there skips them rather than asking.
duplicates: bool = False
class PathCapabilities(BaseModel): class PathCapabilities(BaseModel):
+2 -3
View File
@@ -25,9 +25,8 @@ MEMORY_COLOR = "#9AA1B2" # grey
def effective_color(cue: CuePoint) -> str: def effective_color(cue: CuePoint) -> str:
"""`#RRGGBB` — the stored colour, or the type's.""" """`#RRGGBB` — the stored colour, or the type's: hot and memory cues alike
(a memory cue's type colours it too, decided 2026-10-16)."""
if cue.color: if cue.color:
return cue.color.upper() return cue.color.upper()
if cue.role == "memory":
return MEMORY_COLOR
return TYPE_COLORS.get(cue.type, MEMORY_COLOR) return TYPE_COLORS.get(cue.type, MEMORY_COLOR)
+16 -12
View File
@@ -167,21 +167,23 @@ class EditJournal:
else: else:
parts.append(f"{verb} {len(names)} {noun}s") parts.append(f"{verb} {len(names)} {noun}s")
# --- hotcues: net change in count, scoped by how many tracks were touched --- # --- cues: net change in count, scoped by how many tracks were touched.
hc_add = hc_del = 0 # Memory cues (detail "memory") are counted apart from hotcues, so a
hc_tracks: set[str] = set() # session of memory-cue edits is not described as hotcue work.
counts = {kind: [0, 0, set()] for kind in ("hotcue", "memory cue")}
grid_edit: set[str] = set() grid_edit: set[str] = set()
grid_del: set[str] = set() grid_del: set[str] = set()
lock_on: set[str] = set() lock_on: set[str] = set()
lock_off: set[str] = set() lock_off: set[str] = set()
for c in self.changes: for c in self.changes:
if c.scope == "cue": if c.scope == "cue":
bucket = counts["memory cue" if c.detail == "memory" else "hotcue"]
if c.target: if c.target:
hc_tracks.add(c.target) bucket[2].add(c.target)
if c.op == "add": if c.op == "add":
hc_add += 1 bucket[0] += 1
elif c.op == "delete": elif c.op == "delete":
hc_del += 1 bucket[1] += 1
elif c.scope == "grid": elif c.scope == "grid":
# "delete" is the ONLY deletion op. Everything else — including # "delete" is the ONLY deletion op. Everything else — including
# ops added later — counts as an edit, because mis-labelling an # ops added later — counts as an edit, because mis-labelling an
@@ -190,15 +192,17 @@ class EditJournal:
elif c.scope == "lock": elif c.scope == "lock":
(lock_on if c.op == "on" else lock_off).add(c.target or "") (lock_on if c.op == "on" else lock_off).add(c.target or "")
if hc_tracks: for noun, (added, deleted, touched) in counts.items():
net = hc_add - hc_del if not touched:
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else "" continue
net = added - deleted
scope = f" across {tracks(len(touched))}" if len(touched) > 1 else ""
if net > 0: if net > 0:
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}") parts.append(f"added {net} {noun}{'' if net == 1 else 's'}{scope}")
elif net < 0: elif net < 0:
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}") parts.append(f"removed {-net} {noun}{'' if -net == 1 else 's'}{scope}")
else: # net zero but there was activity (moves / retypes / add-then-delete) else: # net zero but there was activity (moves / retypes / add-then-delete)
parts.append(f"adjusted hotcues{scope}") parts.append(f"adjusted {noun}s{scope}")
# --- beatgrids & lock: per-track counts --- # --- beatgrids & lock: per-track counts ---
if grid_edit: if grid_edit:
+7 -1
View File
@@ -94,8 +94,14 @@ class ExportPayload:
tracks: list[ExportTrack] = field(default_factory=list) tracks: list[ExportTrack] = field(default_factory=list)
playlists: list[ExportPlaylist] = field(default_factory=list) playlists: list[ExportPlaylist] = field(default_factory=list)
#: The export's name, used for the folder its playlists are nested under. #: The export's name, used for the folder its playlists are nested under
#: when `root_folder` is set.
name: str = "Export" name: str = "Export"
#: Nest the whole playlist tree (and "Other") in one folder named `name`.
#: Off — the default, a Konduktor setting — the playlists sit at the
#: library's top level: an export is a library of its own, so a folder
#: saying where it came from is one more click at the gig.
root_folder: bool = False
#: Called by a writer before each slow step (e.g. decoding a track for its #: Called by a writer before each slow step (e.g. decoding a track for its
#: waveform) with a message for the status bar, and — for a per-track loop — #: waveform) with a message for the status bar, and — for a per-track loop —
#: `step` of `of`, which drives the progress bar. RAISES when the user has #: `step` of `of`, which drives the progress bar. RAISES when the user has
+102 -6
View File
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
Three rules: Three rules:
* **This folder only.** Subfolders are not scanned — the tree is how you get to * **This folder only.** Subfolders are not scanned — the tree is how you get to
them — so a click on a drive root never walks the whole drive. them — so a click on a drive root never walks the whole drive. A folder
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
* **A track id is the file's absolute path.** It is the one identity a loose * **A track id is the file's absolute path.** It is the one identity a loose
file has, and it is what the audio route checks a request against. file has, and it is what the audio route checks a request against.
* **Tags are read once per folder state.** Reading tags opens every file, which * **Tags are read once per folder state.** Reading tags opens every file, which
@@ -26,6 +28,7 @@ from __future__ import annotations
import logging import logging
import os import os
import threading import threading
from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
@@ -165,17 +168,88 @@ class FolderSource:
return capabilities_for(self.path) return capabilities_for(self.path)
# A drop of a whole drive must not read tags for hours: past this many audio
# files the rest are left out and the answer says so.
MAX_DROPPED = 20_000
@dataclass
class Dropped:
"""What a drop onto the window resolved to."""
tracks: list[Track] = field(default_factory=list)
# Dropped FILES that are not audio this library can hold (or are gone).
# Non-audio inside a dropped folder is not counted: an album folder's
# cover and cue sheet are not something the user asked to add.
skipped: int = 0
# More than MAX_DROPPED audio files: the rest were left out.
truncated: bool = False
class FolderScanner: class FolderScanner:
"""Scans folders on request, caching each until its contents change. """Scans folders on request, caching each until its contents change.
Also the gatekeeper for streaming: `source_for_file` answers only for a file Also the gatekeeper for streaming: `source_for_file` answers only for a file
found by a scan, so the audio route cannot be used to read an arbitrary path found by a scan — or dropped onto the window by the user — so the audio
off the disk — only audio the user has browsed to. route cannot be used to read an arbitrary path off the disk, only audio the
user has browsed to or handed over.
""" """
def __init__(self) -> None: def __init__(self) -> None:
self._lock = threading.Lock() self._lock = threading.Lock()
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {} self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
# Files dropped one by one: their folder was never scanned (and is not
# cached as if it had been — a partial listing would hide its other
# files from the sidebar), so each is held on its own.
self._files: dict[str, Track] = {}
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
and OS-housekeeping folders left out, as the tree leaves them out),
files as themselves. Every audio file found becomes addable and
playable through the folder routes, exactly as if it had been browsed."""
wanted = {f.lower() for f in formats}
out = Dropped()
seen: set[str] = set()
def take(tracks: list[Track]) -> bool:
for t in tracks:
if t.id in seen:
continue
if len(out.tracks) >= limit:
out.truncated = True
return False
seen.add(t.id)
out.tracks.append(t)
return True
for raw in paths:
path = Path(raw).expanduser()
if path.is_dir():
for folder in _walk(path):
if not audio_files(folder, formats):
continue
if not take(self.scan(folder, formats).tracks):
return out
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
track = self._file_track(path)
if not take([track]):
return out
else:
out.skipped += 1
return out
def _file_track(self, path: Path) -> Track:
key = str(path)
with self._lock:
hit = self._cache.get(str(path.parent))
known = hit[2].track(key) if hit is not None else None
if known is not None:
return known
track = read_track(path)
with self._lock:
self._files[key] = track
return track
def scan(self, folder: Path, formats: list[str]) -> FolderSource: def scan(self, folder: Path, formats: list[str]) -> FolderSource:
folder = Path(folder) folder = Path(folder)
@@ -198,10 +272,32 @@ class FolderScanner:
folder = str(Path(track_id).parent) folder = str(Path(track_id).parent)
with self._lock: with self._lock:
hit = self._cache.get(folder) hit = self._cache.get(folder)
if hit is None or hit[2].track(track_id) is None: loose = self._files.get(track_id)
return None if hit is not None and hit[2].track(track_id) is not None:
return hit[2] return hit[2]
if loose is not None:
return FolderSource(Path(folder), [loose])
return None
def clear(self) -> None: def clear(self) -> None:
with self._lock: with self._lock:
self._cache.clear() self._cache.clear()
self._files.clear()
def _walk(root: Path):
"""`root` and every visible folder under it, depth first, sorted by name."""
yield root
try:
with os.scandir(root) as it:
subs = []
for entry in it:
try:
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
subs.append(Path(entry.path))
except OSError:
continue
except OSError:
return
for sub in sorted(subs, key=lambda p: p.name.lower()):
yield from _walk(sub)
+2 -2
View File
@@ -235,8 +235,8 @@ def detect_grid(
if bpm is not None and not (20.0 <= bpm <= 400.0): if bpm is not None and not (20.0 <= bpm <= 400.0):
raise ValueError(f"Not a usable BPM: {bpm}") raise ValueError(f"Not a usable BPM: {bpm}")
if y is None: if y is None:
import librosa from . import waveform
y, sr = librosa.load(audio_path, sr=sr, mono=True) y, sr = waveform.load(audio_path, sr=sr)
y = np.asarray(y, dtype=np.float32) y = np.asarray(y, dtype=np.float32)
duration = len(y) / sr duration = len(y) / sr
if duration < 1.5: if duration < 1.5:
+2 -2
View File
@@ -178,7 +178,7 @@ def with_detected_key(track, y: np.ndarray | None, sr: int):
def detect_key(audio_path: str) -> KeyResult | None: def detect_key(audio_path: str) -> KeyResult | None:
import librosa from . import waveform
y, sr = librosa.load(audio_path, sr=SR, mono=True) y, sr = waveform.load(audio_path, sr=SR)
return detect_key_samples(y, sr) return detect_key_samples(y, sr)
+15 -3
View File
@@ -13,7 +13,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind from .capabilities import CueRole, CueType, MediaKind, PlaylistKind, TrackColor
class HotcueChip(BaseModel): class HotcueChip(BaseModel):
@@ -71,6 +71,11 @@ class Track(BaseModel):
grid_marker_count: int = 0 grid_marker_count: int = 0
grid_locked: bool = False grid_locked: bool = False
media_kind: MediaKind = "audio" media_kind: MediaKind = "audio"
# The track's colour tag: the neutral identity (what crosses platforms) and
# the platform's own display colour for it, both mapped from the stored
# code by the adapter. None = no colour.
color: TrackColor | None = None
color_hex: str | None = None
class TrackPage(BaseModel): class TrackPage(BaseModel):
@@ -130,6 +135,9 @@ class PlaylistNode(BaseModel):
can_rename: bool = False can_rename: bool = False
can_delete: bool = False can_delete: bool = False
can_contain_children: bool = False # a valid parent for a new playlist can_contain_children: bool = False # a valid parent for a new playlist
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
# its siblings or moved into another folder.
can_move: bool = False
PlaylistNode.model_rebuild() PlaylistNode.model_rebuild()
@@ -141,8 +149,8 @@ PlaylistNode.model_rebuild()
class CuePoint(BaseModel): class CuePoint(BaseModel):
name: str | None = None name: str | None = None
type: CueType = "cue" type: CueType = "cue"
# "memory" cues have no bank slot. Only Rekordbox has them, so they are # A "memory" cue has no bank slot: Rekordbox's / OneLibrary's memory cues,
# modelled and preserved but not yet editable anywhere. # Traktor's cues on no pad (HOTCUE="-1"). Addressed by `id`, not `slot`.
role: CueRole = "hotcue" role: CueRole = "hotcue"
start: float # seconds start: float # seconds
length: float # seconds (>0 for loops) length: float # seconds (>0 for loops)
@@ -155,6 +163,10 @@ class CuePoint(BaseModel):
# Index of the grid marker this cue mirrors, where the platform pairs them. # Index of the grid marker this cue mirrors, where the platform pairs them.
# A display hint only; None on platforms that do not. # A display hint only; None on platforms that do not.
grid_marker: int | None = None grid_marker: int | None = None
# The handle the memory-cue commands take (None on a hot cue, which is
# addressed by slot). Opaque and adapter-defined; an edit of THIS cue may
# change it, which is fine because every command returns fresh TrackCues.
id: str | None = None
class GridMarker(BaseModel): class GridMarker(BaseModel):
+33
View File
@@ -0,0 +1,33 @@
"""Opening a file for reading with PyAV, on every PyAV version the app ships.
A file whose tags are not valid UTF-8 must still open: it is still audio.
PyAV 18 decodes tags strictly by default and raises UnicodeDecodeError at open
unless given `metadata_errors="ignore"`; PyAV 19 REMOVED that keyword (passing
it is a TypeError) and opens such a file as it is, the bad bytes as surrogates.
Measured on both with a generated M4A and MP3 whose title is invalid UTF-8.
The keyword once went straight into `av.open`, which worked on the dev venv's
18.1 while CI's fresh install took 19.0.1: every stem file then failed to open
in the released app, and the deck played stem tracks as the mix. Every read
goes through `open_input`, so the difference lives in one place.
"""
from __future__ import annotations
from functools import cache
from pathlib import Path
@cache
def _takes_metadata_errors() -> bool:
import av
return int(av.__version__.split(".")[0]) < 19
def open_input(path: Path | str):
"""`av.open(path)` for reading, tolerant of tags that are not UTF-8."""
import av
if _takes_metadata_errors():
return av.open(str(path), metadata_errors="ignore")
return av.open(str(path))
+2
View File
@@ -105,6 +105,8 @@ class TrackIndex:
if (t.artist and ql in t.artist.lower()) if (t.artist and ql in t.artist.lower())
or (t.title and ql in t.title.lower()) or (t.title and ql in t.title.lower())
or (t.album and ql in t.album.lower()) or (t.album and ql in t.album.lower())
or (t.comment and ql in t.comment.lower())
or (t.comment2 and ql in t.comment2.lower())
] ]
if genre: if genre:
items = [t for t in items if t.genre == genre] items = [t for t in items if t.genre == genre]
+90 -23
View File
@@ -37,15 +37,17 @@ from __future__ import annotations
import fractions import fractions
import json import json
import queue
import struct import struct
import sys import sys
import threading
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Callable from typing import Callable
import numpy as np import numpy as np
from . import mp4_edit, tag_copy from . import mp4_edit, pyav, tag_copy
SR = 44100 SR = 44100
FRAME = 1024 # AAC-LC frame size, for both encoders FRAME = 1024 # AAC-LC frame size, for both encoders
@@ -132,7 +134,7 @@ def decode(path: Path | str) -> Source:
"""Decode the first audio stream to stereo float32 at 44.1 kHz.""" """Decode the first audio stream to stereo float32 at 44.1 kHz."""
import av import av
with av.open(str(path), metadata_errors="ignore") as container: with pyav.open_input(path) as container:
stream = container.streams.audio[0] stream = container.streams.audio[0]
codec = stream.codec_context.name codec = stream.codec_context.name
bit_rate = stream.bit_rate or container.bit_rate or None bit_rate = stream.bit_rate or container.bit_rate or None
@@ -151,15 +153,36 @@ def decode(path: Path | str) -> Source:
return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate) return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate)
#: Encoded frames each stream's thread may run ahead of the muxer.
_ENCODE_QUEUE = 64
#: Frames between `checkpoint()` / `progress()` calls (~6 s of audio).
_ENCODE_TICK = 256
def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str, def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
checkpoint: Callable[[], None] | None) -> None: checkpoint: Callable[[], None] | None,
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the progress: Callable[[float], None] | None = None) -> None:
muxer never buffers a whole stream (which it would if they came one after """Encode the AAC streams on one thread EACH and mux them on this one, IN
another).""" LOCKSTEP — per frame stream 0..4, then each stream's flush — so the muxer
never buffers a whole stream (which it would if they came one after another).
The encoders are independent and PyAV releases the GIL inside FFmpeg, so
this is ~3x faster than one thread with FFmpeg's `aac` (a 5-minute track's
real stems: 104 s -> 35 s on a 6-core i7) — and since the mux order is the single-threaded
one, the file is byte-identical. Every codec is opened and the header written
HERE before any worker starts: the first `mux()` would otherwise open (and
read) codec contexts a worker may be opening or encoding with. After that
this thread never touches a codec, and a worker never touches the container.
`checkpoint()` and `progress(fraction)` are called from this thread only.
"""
import av import av
n = tracks[0].shape[1] n = tracks[0].shape[1]
tb = fractions.Fraction(1, SR) tb = fractions.Fraction(1, SR)
offsets = range(0, n, FRAME)
stop = threading.Event()
threads: list[threading.Thread] = []
container = av.open(fp, "w", format="ipod") container = av.open(fp, "w", format="ipod")
try: try:
streams = [] streams = []
@@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
if k: if k:
s.disposition = 0 # present, not enabled: a plain player plays the mix s.disposition = 0 # present, not enabled: a plain player plays the mix
streams.append(s) streams.append(s)
for i, offset in enumerate(range(0, n, FRAME)):
if checkpoint is not None and i % 512 == 0:
checkpoint()
for s, x in zip(streams, tracks):
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
for packet in s.encode(frame):
container.mux(packet)
for s in streams: for s in streams:
for packet in s.encode(None): s.codec_context.open(strict=False)
container.start_encoding()
queues = [queue.Queue(maxsize=_ENCODE_QUEUE) for _ in tracks]
def put(q: queue.Queue, item) -> bool:
while not stop.is_set():
try:
q.put(item, timeout=0.1)
return True
except queue.Full:
pass
return False # the muxer gave up: stop encoding
def work(s, x: np.ndarray, q: queue.Queue) -> None:
try:
for offset in offsets:
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
if not put(q, s.encode(frame)):
return
put(q, s.encode(None))
except BaseException as ex: # noqa: BLE001 — re-raised by the muxer
put(q, ex)
def mux(q: queue.Queue) -> None:
packets = q.get()
if isinstance(packets, BaseException):
raise packets
for packet in packets:
container.mux(packet) container.mux(packet)
threads = [threading.Thread(target=work, args=(s, x, q), daemon=True, name=f"stem-encode-{k}")
for k, (s, x, q) in enumerate(zip(streams, tracks, queues))]
for t in threads:
t.start()
for i in range(len(offsets)):
if i % _ENCODE_TICK == 0:
if checkpoint is not None:
checkpoint()
if progress is not None:
progress(i / len(offsets))
for q in queues:
mux(q)
for q in queues:
mux(q) # each stream's flush
if progress is not None:
progress(1.0)
finally: finally:
# A cancel or a failure: the workers stop at their next frame, and must
# have stopped before the container (and their codecs) are freed.
stop.set()
for t in threads:
t.join()
container.close() container.close()
@@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]]
def build(source_path: Path | str, target: Path | str, separate: Separate, *, def build(source_path: Path | str, target: Path | str, separate: Separate, *,
encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written: encoder: str | None = None, checkpoint: Callable[[], None] | None = None,
on_encode: Callable[[float], None] | None = None) -> Written:
"""Convert `source_path` into a stem file at `target`. """Convert `source_path` into a stem file at `target`.
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems `separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems
in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch
writes a `*.konduktor-partial` and renames it once the batch commits — since writes a `*.konduktor-partial` and renames it once the batch commits — since
nothing here infers a format from the suffix. `checkpoint()` is called between nothing here infers a format from the suffix. `checkpoint()` is called between
phases and during the encode, and may raise to cancel. phases and during the encode, and may raise to cancel. `on_encode(fraction)`
reports the encode's progress, 0 to 1 (verifying after it takes ~1 s).
""" """
target = Path(target) target = Path(target)
tick = checkpoint or (lambda: None) tick = checkpoint or (lambda: None)
@@ -322,7 +389,7 @@ def build(source_path: Path | str, target: Path | str, separate: Separate, *,
bit_rate = choose_bitrate(source) bit_rate = choose_bitrate(source)
with open(target, "wb") as fp: with open(target, "wb") as fp:
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate, _encode(fp, [source.pcm, *stems], bit_rate=bit_rate,
encoder=encoder or default_encoder(), checkpoint=checkpoint) encoder=encoder or default_encoder(), checkpoint=checkpoint, progress=on_encode)
add_stem_box(target) add_stem_box(target)
tags = tag_copy.copy_tags(source_path, target) tags = tag_copy.copy_tags(source_path, target)
verify(target, source) verify(target, source)
@@ -381,7 +448,7 @@ def _audio_stream_count(path: Path) -> int:
av = None av = None
if av is not None: if av is not None:
try: try:
with av.open(str(path), metadata_errors="ignore") as c: with pyav.open_input(path) as c:
return len(c.streams.audio) return len(c.streams.audio)
except av.FFmpegError as ex: except av.FFmpegError as ex:
raise ValueError(str(ex)) raise ValueError(str(ex))
@@ -453,7 +520,7 @@ def extract_stream(path: Path | str, stream: int, fp) -> None:
""" """
import av import av
with av.open(str(path), metadata_errors="ignore") as inp: with pyav.open_input(path) as inp:
if not 0 <= stream < len(inp.streams.audio): if not 0 <= stream < len(inp.streams.audio):
raise StemFileError(f"The file has no audio stream {stream}") raise StemFileError(f"The file has no audio stream {stream}")
ist = inp.streams.audio[stream] ist = inp.streams.audio[stream]
+2 -2
View File
@@ -273,8 +273,8 @@ def analyse(
if not markers: if not markers:
raise ValueError("Set a beatgrid first") raise ValueError("Set a beatgrid first")
if y is None: if y is None:
import librosa from . import waveform
y, _ = librosa.load(audio_path, sr=_SR, mono=True) y, _ = waveform.load(audio_path, sr=_SR)
y = np.asarray(y, dtype=np.float32) y = np.asarray(y, dtype=np.float32)
duration = len(y) / _SR duration = len(y) / _SR
beats, bar0 = grid_beats(markers, duration) beats, bar0 = grid_beats(markers, duration)
+20 -10
View File
@@ -84,8 +84,8 @@ class Analysis:
return self.columns.duration return self.columns.duration
def _decode_pyav(path: Path) -> np.ndarray: def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray:
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel. """Mono float32 at `sr`, via PyAV — FFmpeg's decoders, bundled in its wheel.
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
@@ -94,9 +94,11 @@ def _decode_pyav(path: Path) -> np.ndarray:
""" """
import av import av
with av.open(str(path)) as container: from . import pyav
with pyav.open_input(path) as container:
stream = container.streams.audio[0] stream = container.streams.audio[0]
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR) resampler = av.AudioResampler(format="flt", layout="mono", rate=sr)
chunks = [] chunks = []
for frame in container.decode(stream): for frame in container.decode(stream):
for out in resampler.resample(frame): for out in resampler.resample(frame):
@@ -120,16 +122,24 @@ def even_slices(n: int, k: int) -> list[slice]:
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])] return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
def _decode(path: Path) -> np.ndarray | None: def load(path: Path | str, sr: int = SR) -> tuple[np.ndarray, int]:
"""Mono float32 at `sr` as `(y, sr)` — `librosa.load`'s shape, raising as it
does. EVERY analysis decode goes through here, never `librosa.load` itself:
librosa reads AAC only through CoreAudio or a system ffmpeg, so on Windows
a `.stem.m4a` failed with "Format not recognised"."""
try: try:
return _decode_pyav(path) return _decode_pyav(Path(path), sr), sr
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex) log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
try: import librosa
import librosa
y, _ = librosa.load(str(path), sr=SR, mono=True) y, _ = librosa.load(str(path), sr=sr, mono=True)
return y return y, sr
def _decode(path: Path) -> np.ndarray | None:
try:
return load(path)[0]
except Exception as ex: # any decoder failure: no waveform, not a failed export except Exception as ex: # any decoder failure: no waveform, not a failed export
log.warning("could not decode %s for a waveform: %s", path, ex) log.warning("could not decode %s for a waveform: %s", path, ex)
return None return None
+6 -1
View File
@@ -433,9 +433,13 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
# ---- running ----------------------------------------------------------------- # ---- running -----------------------------------------------------------------
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict: def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
root_folder: bool = False) -> dict:
"""Copy what changed, then write every target's library over the audio. """Copy what changed, then write every target's library over the audio.
`root_folder` nests the playlists in a folder named after the export (the
"Put exported playlists in a folder" setting); otherwise they sit at the top.
Rolls back EVERYTHING this run wrote on cancel or on any failure — Rolls back EVERYTHING this run wrote on cancel or on any failure —
including the libraries of targets that had already been written when a including the libraries of targets that had already been written when a
later one failed. What it KEPT from the previous export stays, and the later one failed. What it KEPT from the previous export stays, and the
@@ -545,6 +549,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
payload = ExportPayload( payload = ExportPayload(
name=export_set.name, name=export_set.name,
root_folder=root_folder,
tracks=payload_tracks, tracks=payload_tracks,
playlists=built.playlists, playlists=built.playlists,
checkpoint=checkpoint, checkpoint=checkpoint,
+25 -1
View File
@@ -191,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids
return plan return plan
def plan_on_host(source, track_ids) -> ImportPlan:
"""A plan for files that are already on the machine holding the library — a
remote library's content folder, browsed from this computer
(`source.on_library_host`). Nothing is checked on THIS disk, where those
paths mean nothing: the source says each file's size and which ones the
library already holds. Added in place (`run(reference=True)`), so there is
no destination and nothing to copy.
"""
plan = ImportPlan(destination=None)
for track_id in dict.fromkeys(track_ids):
track = source.track(track_id)
if track is None:
continue
name = track_id.replace("\\", "/").rsplit("/", 1)[-1]
plan.tracks.append(PlannedTrack(
track_id=track_id,
title=track.title or name,
source_path=Path(track_id),
size=source.size(track_id),
existing_id=source.held(track_id),
))
return plan
def _playlist_name(source, node_id: str) -> str | None: def _playlist_name(source, node_id: str) -> str | None:
for nid, name in _all_playlists(source): for nid, name in _all_playlists(source):
if nid == node_id: if nid == node_id:
@@ -321,7 +345,7 @@ def run(
# a folder on the server, instead of copied here. Nothing can be left in # a folder on the server, instead of copied here. Nothing can be left in
# place — the server cannot see this computer's files. # place — the server cannot see this computer's files.
uploads = not places and uploads_audio(dest) uploads = not places and uploads_audio(dest)
if uploads and reference: if uploads and reference and not getattr(source, "on_library_host", False):
raise ValueError("A remote library cannot reference files on this computer") raise ValueError("A remote library cannot reference files on this computer")
if not reference and not places and not uploads: if not reference and not places and not uploads:
assert destination is not None assert destination is not None
+264 -27
View File
@@ -60,6 +60,7 @@ from .schemas import (
LibraryInfo, LibraryInfo,
PlatformOption, PlatformOption,
EditTrack, EditTrack,
SetTrackColor,
Facets, Facets,
FileTagOutcome, FileTagOutcome,
CreateExportSet, CreateExportSet,
@@ -69,6 +70,8 @@ from .schemas import (
ExportSetOut, ExportSetOut,
ExportPreview, ExportPreview,
Drive, Drive,
DroppedFiles,
DroppedPaths,
FolderAddRequest, FolderAddRequest,
FolderTracks, FolderTracks,
FsEntry, FsEntry,
@@ -92,12 +95,18 @@ from .schemas import (
RemapResult, RemapResult,
RenamePlaylist, RenamePlaylist,
SaveResult, SaveResult,
AddEntries,
MovePlaylist,
SetEntries, SetEntries,
SourceCandidate, SourceCandidate,
SourceStatus, SourceStatus,
SetCue, SetCue,
SetCueColor, SetCueColor,
SetCueType, SetCueType,
AddMemoryCue,
RenameMemoryCue,
SetMemoryCueColor,
SetMemoryCueType,
SetGridLock, SetGridLock,
Stats, Stats,
Track, Track,
@@ -118,8 +127,12 @@ app.add_middleware(
"http://localhost:5173", "http://localhost:5173",
"http://127.0.0.1:5173", "http://127.0.0.1:5173",
# Packaged desktop app: the webview's origin when Tauri loads the built # Packaged desktop app: the webview's origin when Tauri loads the built
# frontend (macOS uses tauri://, Windows/Linux use https://tauri.localhost). # frontend. macOS uses tauri://; Windows/Linux default to
# https://tauri.localhost, but lib.rs forces the http scheme
# (use_https_scheme(false)) so the sidecar is not mixed content —
# without the http origin here, the Windows app reaches no API at all.
"tauri://localhost", "tauri://localhost",
"http://tauri.localhost",
"https://tauri.localhost", "https://tauri.localhost",
], ],
allow_methods=["*"], allow_methods=["*"],
@@ -763,7 +776,10 @@ def run_export(set_id: str) -> JobStatus:
built = exporter.plan(adapter, found) built = exporter.plan(adapter, found)
if built.blocked: if built.blocked:
raise HTTPException(409, built.blocked) raise HTTPException(409, built.blocked)
job = JOBS.submit("export", lambda handle: exporter.run(adapter, found, built, handle)) # A Konduktor setting, read when the export starts.
root_folder = bool(prefs.load_prefs().get("exportRootFolder", False))
job = JOBS.submit("export", lambda handle: exporter.run(
adapter, found, built, handle, root_folder=root_folder))
return JobStatus(**job.as_dict()) return JobStatus(**job.as_dict())
@@ -1227,6 +1243,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
can_reorder=True, can_reorder=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
@@ -1241,6 +1258,7 @@ def create_folder(body: CreatePlaylist) -> PlaylistNode:
can_contain_children=True, can_contain_children=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
@@ -1265,17 +1283,35 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
return {"status": "updated", "id": playlist_uuid, "count": n} return {"status": "updated", "id": playlist_uuid, "count": n}
@app.post("/api/playlists/move")
def move_playlist(body: MovePlaylist) -> dict:
"""Move a playlist, folder or smart playlist in the tree. Answers the
node's id AFTER the move, which on some platforms is not the one sent."""
new_id = require_adapter().move_playlist(body.node_id, body.parent_id, body.index)
return {"status": "moved", "id": new_id}
@app.post("/api/playlists/{playlist_uuid}/add") @app.post("/api/playlists/{playlist_uuid}/add")
def add_entries(playlist_uuid: str, body: SetEntries) -> dict: def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
"""Append tracks to a playlist (skips ids already present).""" """Append tracks to a playlist. Tracks already there are skipped, added
again, or — `duplicates="ask"` — counted with nothing changed (see
`AddEntries`). `duplicates` in the answer is how many there were."""
a = require_adapter() a = require_adapter()
current = a.playlist_entries(playlist_uuid) current = a.playlist_entries(playlist_uuid)
if current is None: if current is None:
raise HTTPException(404, f"Playlist not found: {playlist_uuid}") raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
have = set(current) have = set(current)
added = [tid for tid in body.track_ids if tid not in have] dupes = [tid for tid in body.track_ids if tid in have]
n = a.set_playlist_entries(playlist_uuid, current + added) mode = body.duplicates
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n} if mode != "skip" and not a.capabilities().playlists.duplicates:
mode = "skip"
if mode == "ask" and dupes:
return {"status": "duplicates", "id": playlist_uuid, "added": 0,
"duplicates": len(dupes), "count": len(current)}
added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have]
n = a.set_playlist_entries(playlist_uuid, current + added) if added else len(current)
return {"status": "added", "id": playlist_uuid, "added": len(added),
"duplicates": len(dupes), "count": n}
@app.patch("/api/tracks") @app.patch("/api/tracks")
@@ -1285,6 +1321,17 @@ def edit_track(body: EditTrack) -> dict:
return {"status": "updated", "id": body.track_id} return {"status": "updated", "id": body.track_id}
@app.patch("/api/tracks/color")
def set_track_color(body: SetTrackColor) -> dict:
"""Set (or clear) the colour tag of every given track (in-memory; persisted
on save). Gated on `tracks.colors`: the platform's swatches."""
a = require_adapter()
if not a.capabilities().tracks.colors:
raise Unsupported("This library cannot store a track colour")
tracks = [a.set_track_color(tid, body.color) for tid in body.track_ids]
return {"status": "updated", "tracks": [t for t in tracks if t is not None]}
@app.get("/api/tracks/art") @app.get("/api/tracks/art")
def track_art(track_id: str) -> Response: def track_art(track_id: str) -> Response:
"""Stream a track's embedded cover art (staged replacement if unsaved).""" """Stream a track's embedded cover art (staged replacement if unsaved)."""
@@ -1637,10 +1684,10 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
def _decode_for_analysis(path: Path): def _decode_for_analysis(path: Path):
"""Mono samples at the rate BOTH detectors work at (they share one decode).""" """Mono samples at the rate BOTH detectors work at (they share one decode)."""
import librosa from .core import waveform
assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate" assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate"
return librosa.load(str(path), sr=key_detect.SR, mono=True) return waveform.load(path, sr=key_detect.SR)
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None: def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
@@ -1811,6 +1858,45 @@ def delete_cue(track_id: str, slot: int) -> TrackCues:
return require_adapter().delete_cue(track_id, slot) return require_adapter().delete_cue(track_id, slot)
# Memory cues — cues on no pad, addressed by CuePoint.id (gated on
# capabilities.cues.memory_cues; the adapter refuses past max_memory_cues).
@app.post("/api/tracks/memory-cue", response_model=TrackCues)
def add_memory_cue(body: AddMemoryCue) -> TrackCues:
"""Add a memory cue (a memory loop when `length` > 0)."""
return require_adapter().add_memory_cue(
body.track_id,
start_sec=body.start,
cue_type=body.type,
length_sec=body.length,
name=body.name,
color=body.color,
)
@app.patch("/api/tracks/memory-cue", response_model=TrackCues)
def rename_memory_cue(body: RenameMemoryCue) -> TrackCues:
"""Name a memory cue (rekordbox calls it the comment); None/"" clears it."""
return require_adapter().rename_memory_cue(body.track_id, body.cue_id, body.name or None)
@app.patch("/api/tracks/memory-cue/type", response_model=TrackCues)
def edit_memory_cue_type(body: SetMemoryCueType) -> TrackCues:
"""Change a memory cue's point type (keeps its position)."""
return require_adapter().set_memory_cue_type(body.track_id, body.cue_id, body.type)
@app.patch("/api/tracks/memory-cue/color", response_model=TrackCues)
def edit_memory_cue_color(body: SetMemoryCueColor) -> TrackCues:
"""Recolour a memory cue from capabilities.cues.memory_palette (None = uncoloured)."""
return require_adapter().set_memory_cue_color(body.track_id, body.cue_id, body.color)
@app.delete("/api/tracks/memory-cue", response_model=TrackCues)
def delete_memory_cue(track_id: str, cue_id: str) -> TrackCues:
"""Remove a memory cue."""
return require_adapter().delete_memory_cue(track_id, cue_id)
@app.post("/api/tracks/grid/marker", response_model=TrackCues) @app.post("/api/tracks/grid/marker", response_model=TrackCues)
def add_grid_marker(body: AddGridMarker) -> TrackCues: def add_grid_marker(body: AddGridMarker) -> TrackCues:
"""Add a beatgrid marker. Omitting `bpm` inherits the governing tempo.""" """Add a beatgrid marker. Omitting `bpm` inherits the governing tempo."""
@@ -2161,6 +2247,50 @@ def source_track_stems(track_id: str) -> dict:
FOLDERS = FolderScanner() FOLDERS = FolderScanner()
# A remote library's content folder rides the same routes. Its paths carry this
# prefix, so a path on the server can never be taken for the same path on this
# computer — and the UI's folder view, deck and add dialog need no second set of
# routes. The prefix alone is the content folder itself.
SERVER_FOLDER = "server:"
def _on_server(path: str) -> str | None:
"""The server path behind a prefixed one ('' = the content folder), else None."""
return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None
def _server_track(track: Track) -> Track:
return track.model_copy(update={"id": SERVER_FOLDER + track.id})
def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]:
"""A folder's files as table rows. Where the library holds a file, the row
IS the library's track — its key, rating, comments, cues and plays, and
its id, so it plays, edits and drags as the collection track it is
(decided 2026-10-10) — else the file's own tags. Also returns library id →
the file's folder id, for the rows that are library tracks: adding still
speaks in folder ids."""
rows: list[Track] = []
files: dict[str, str] = {}
for track in tracks:
known = held_of(track)
held = dest.track(known) if known else None
if held is None or held.id in files:
rows.append(track)
continue
rows.append(held)
files[held.id] = track.id
return rows, files
def _server_file(track_id: str) -> tuple[object, str]:
"""The remote adapter and the server path of a listed content-folder file."""
adapter = _require_remote()
raw = _on_server(track_id) or ""
if adapter.listed_files([raw]) is None:
raise HTTPException(404, "Track not found — browse to its folder first")
return adapter, raw
def _drive_of(path: Path, drives: list[dict]) -> dict | None: def _drive_of(path: Path, drives: list[dict]) -> dict | None:
"""The drive `path` lives on: the longest drive root that contains it.""" """The drive `path` lives on: the longest drive root that contains it."""
@@ -2187,6 +2317,10 @@ def fs_drives() -> list[Drive]:
found = places.drives() found = places.drives()
libraries = sources() libraries = sources()
out = [Drive(**d) for d in found] out = [Drive(**d) for d in found]
if STATE.remote is not None and STATE.remote_config is not None:
# The server holding the library, first: its content folder is where
# this library's music is, and this computer cannot see it otherwise.
out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server"))
externals = [d for d in found if d["path"] != "/"] externals = [d for d in found if d["path"] != "/"]
for lib in libraries: for lib in libraries:
home = _drive_of(Path(lib.path), externals) home = _drive_of(Path(lib.path), externals)
@@ -2201,6 +2335,11 @@ def fs_drives() -> list[Drive]:
@app.get("/api/fs/folders", response_model=list[FsEntry]) @app.get("/api/fs/folders", response_model=list[FsEntry])
def fs_folders(path: str) -> list[FsEntry]: def fs_folders(path: str) -> list[FsEntry]:
"""The visible folders directly inside `path` — one level of a Files tree.""" """The visible folders directly inside `path` — one level of a Files tree."""
raw = _on_server(path)
if raw is not None:
listing = _require_remote().client.fs_list(raw or None)
return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"])
for e in listing["entries"] if e["is_dir"]]
base = Path(path).expanduser() base = Path(path).expanduser()
if not base.is_dir(): if not base.is_dir():
raise HTTPException(404, f"Not a folder: {base}") raise HTTPException(404, f"Not a folder: {base}")
@@ -2214,20 +2353,43 @@ def _formats() -> list[str]:
@app.get("/api/folder/tracks", response_model=FolderTracks) @app.get("/api/folder/tracks", response_model=FolderTracks)
def folder_tracks(path: str) -> FolderTracks: def folder_tracks(path: str) -> FolderTracks:
"""The audio files directly inside a folder, and which are already held.""" """The audio files directly inside a folder, and which are already held."""
raw = _on_server(path)
if raw is not None:
adapter = _require_remote()
listing = adapter.folder_listing(raw or None)
rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks],
lambda t: listing.held(t.id[len(SERVER_FOLDER):]))
return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows,
in_collection=list(files), files=files, removable=False)
base = Path(path).expanduser() base = Path(path).expanduser()
if not base.is_dir(): if not base.is_dir():
raise HTTPException(404, f"Not a folder: {base}") raise HTTPException(404, f"Not a folder: {base}")
source = FOLDERS.scan(base, _formats()) source = FOLDERS.scan(base, _formats())
held = importer._existing_files(require_adapter()) dest = require_adapter()
held = importer._existing_files(dest)
rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id))))
drive = _drive_of(base, places.drives()) drive = _drive_of(base, places.drives())
return FolderTracks( return FolderTracks(
path=str(base), path=str(base),
tracks=source.tracks, tracks=rows,
in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held], in_collection=list(files),
files=files,
removable=drive is None or drive["kind"] == "external", removable=drive is None or drive["kind"] == "external",
) )
@app.post("/api/folder/dropped", response_model=DroppedFiles)
def folder_dropped(body: DroppedPaths) -> DroppedFiles:
"""Files and folders dropped onto the window. Folders are searched all the
way down; every audio file found is then addable and playable through the
folder routes, as if it had been browsed to in the sidebar."""
dest = require_adapter()
dropped = FOLDERS.dropped(body.paths, _formats())
held = importer._existing_files(dest)
rows, files = _folder_rows(dest, dropped.tracks, lambda t: held.get(importer._key(Path(t.id))))
return DroppedFiles(tracks=rows, files=files, skipped=dropped.skipped, truncated=dropped.truncated)
def _folder_track(track_id: str) -> FolderSource: def _folder_track(track_id: str) -> FolderSource:
# Only a file a scan found. This is what keeps the audio route from being a # Only a file a scan found. This is what keeps the audio route from being a
# way to read any path on the disk. # way to read any path on the disk.
@@ -2241,11 +2403,17 @@ def _folder_track(track_id: str) -> FolderSource:
def folder_capabilities(path: str) -> Capabilities: def folder_capabilities(path: str) -> Capabilities:
from .core.folder import capabilities_for from .core.folder import capabilities_for
raw = _on_server(path)
if raw is not None:
return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server"))
return capabilities_for(Path(path)) return capabilities_for(Path(path))
@app.get("/api/folder/tracks/cues", response_model=TrackCues) @app.get("/api/folder/tracks/cues", response_model=TrackCues)
def folder_track_cues(track_id: str) -> TrackCues: def folder_track_cues(track_id: str) -> TrackCues:
if _on_server(track_id) is not None:
_server_file(track_id)
return TrackCues(cues=[], grid_markers=[])
cues = _folder_track(track_id).track_cues(track_id) cues = _folder_track(track_id).track_cues(track_id)
assert cues is not None assert cues is not None
return cues return cues
@@ -2253,7 +2421,11 @@ def folder_track_cues(track_id: str) -> TrackCues:
@app.get("/api/folder/tracks/audio") @app.get("/api/folder/tracks/audio")
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse: def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
path = _folder_track(track_id).audio_path(track_id) if _on_server(track_id) is not None:
adapter, raw = _server_file(track_id)
path = adapter.folder_audio(raw) # this computer's copy, as for a library track
else:
path = _folder_track(track_id).audio_path(track_id)
if path is None or not path.is_file(): if path is None or not path.is_file():
raise HTTPException(404, "Audio file not found") raise HTTPException(404, "Audio file not found")
if stem is not None: if stem is not None:
@@ -2264,6 +2436,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
@app.get("/api/folder/tracks/stems") @app.get("/api/folder/tracks/stems")
def folder_track_stems(track_id: str) -> dict: def folder_track_stems(track_id: str) -> dict:
if _on_server(track_id) is not None:
adapter, raw = _server_file(track_id)
return _stem_layout_of(adapter.folder_audio(raw))
return _stem_layout_of(_folder_track(track_id).audio_path(track_id)) return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
@@ -2273,6 +2448,34 @@ def _require_addable(dest) -> None:
raise HTTPException(422, "Tracks cannot be added to this library") raise HTTPException(422, "Tracks cannot be added to this library")
def _check_add_targets(dest, body: FolderAddRequest) -> None:
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
if body.export_id is not None:
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
raise HTTPException(404, f"Export not found: {body.export_id}")
def _is_server_add(body: FolderAddRequest) -> bool:
on_server = [_on_server(t) is not None for t in body.track_ids]
if any(on_server) and not all(on_server):
raise HTTPException(400, "Files on the server and on this computer are added separately")
return bool(on_server) and all(on_server)
def _server_add_plan(body: FolderAddRequest):
"""Files in the remote library's content folder: already where the library
can reach them, so they are added IN PLACE — nothing uploaded, nothing asked."""
dest = _require_remote()
_require_addable(dest)
paths = [_on_server(t) for t in body.track_ids]
source = dest.listed_files(paths)
if source is None:
raise HTTPException(400, "No tracks to add")
_check_add_targets(dest, body)
return source, dest, importer.plan_on_host(source, paths)
def _folder_add_plan(body: FolderAddRequest): def _folder_add_plan(body: FolderAddRequest):
dest = require_adapter() dest = require_adapter()
_require_addable(dest) _require_addable(dest)
@@ -2293,11 +2496,7 @@ def _folder_add_plan(body: FolderAddRequest):
if not body.destination: if not body.destination:
raise HTTPException(400, "Copying needs a destination folder") raise HTTPException(400, "Copying needs a destination folder")
destination = Path(body.destination).expanduser() destination = Path(body.destination).expanduser()
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None: _check_add_targets(dest, body)
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
if body.export_id is not None:
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
raise HTTPException(404, f"Export not found: {body.export_id}")
return source, dest, destination, importer.plan( return source, dest, destination, importer.plan(
source, dest, destination, track_ids=[t.id for t in tracks] source, dest, destination, track_ids=[t.id for t in tracks]
) )
@@ -2305,6 +2504,11 @@ def _folder_add_plan(body: FolderAddRequest):
@app.post("/api/folder/add/preview") @app.post("/api/folder/add/preview")
def folder_add_preview(body: FolderAddRequest) -> dict: def folder_add_preview(body: FolderAddRequest) -> dict:
if _is_server_add(body):
_source, _dest, plan = _server_add_plan(body)
out = plan.as_dict()
out.update(total_bytes=0, free_bytes=None, enough_space=None, removable=False)
return out
_source, dest, destination, plan = _folder_add_plan(body) _source, dest, destination, plan = _folder_add_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None) out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None)
if importer.places_audio(dest): if importer.places_audio(dest):
@@ -2312,8 +2516,28 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
elif body.mode == "reference": elif body.mode == "reference":
# Nothing is copied, so there is no size to fit anywhere. # Nothing is copied, so there is no size to fit anywhere.
out.update(total_bytes=0, free_bytes=None, enough_space=None) out.update(total_bytes=0, free_bytes=None, enough_space=None)
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None elif destination is not None:
out["removable"] = drive is None or drive["kind"] == "external" # Copying a file that is already in the import folder makes a second
# copy beside it — legal, but rarely meant, so the dialog says so.
home = destination.resolve()
out["in_destination"] = sum(
1 for t in plan.importable
if t.source_path is not None and t.source_path.resolve().is_relative_to(home)
)
# Per FILE, not per request: a drop can mix the computer's own disk with a
# stick, and only the files on the stick go missing when it is unplugged.
drives = places.drives()
external: dict[str, int] = {}
for t in plan.importable:
if t.source_path is None:
continue
drive = _drive_of(t.source_path, drives)
if drive is None or drive["kind"] == "external":
name = drive["name"] if drive else str(t.source_path.anchor or t.source_path.parent)
external[name] = external.get(name, 0) + 1
out["removable"] = bool(external)
out["removable_count"] = sum(external.values())
out["removable_drives"] = sorted(external)
return out return out
@@ -2321,10 +2545,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
def folder_add(body: FolderAddRequest) -> JobStatus: def folder_add(body: FolderAddRequest) -> JobStatus:
"""Add browsed files to the collection. A job, like import: copying can be long.""" """Add browsed files to the collection. A job, like import: copying can be long."""
_require_no_pending_stems("Adding files") _require_no_pending_stems("Adding files")
source, dest, destination, plan = _folder_add_plan(body) in_place = _is_server_add(body)
if in_place:
source, dest, plan = _server_add_plan(body)
destination = None
else:
source, dest, destination, plan = _folder_add_plan(body)
if not plan.importable and not plan.existing: if not plan.importable and not plan.existing:
raise HTTPException(400, "Nothing to add (none of those files exist)") raise HTTPException(400, "Nothing to add (none of those files exist)")
if body.mode == "copy" or importer.places_audio(dest): # Nothing is copied in place, so there is no space to check.
if not in_place and (body.mode == "copy" or importer.places_audio(dest)):
free = importer.free_bytes(destination, dest) free = importer.free_bytes(destination, dest)
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
if free is not None and free < needed + importer.SPACE_HEADROOM: if free is not None and free < needed + importer.SPACE_HEADROOM:
@@ -2340,7 +2570,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
def work(handle): def work(handle):
result = importer.run( result = importer.run(
source, dest, plan, handle, source, dest, plan, handle,
reference=body.mode == "reference", reference=in_place or body.mode == "reference",
into_playlist=body.playlist_id, into_playlist=body.playlist_id,
) )
# Export sets are Konduktor's own data, not the library's, so they are # Export sets are Konduktor's own data, not the library's, so they are
@@ -2423,11 +2653,18 @@ def start_import(body: ImportRequest) -> JobStatus:
folder_name = body.folder_name folder_name = body.folder_name
if folder_name is None and STATE.source is not None: if folder_name is None and STATE.source is not None:
folder_name = STATE.source.capabilities().save.library_label folder_name = STATE.source.capabilities().save.library_label
library = STATE.library_id
job = JOBS.submit( def work(handle):
"import", result = importer.run(
lambda handle: importer.run(source, dest, plan, handle, folder_name=folder_name), source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist,
) )
# As folder add: an export set is Konduktor's data, updated afterwards.
if body.export_id is not None and library is not None:
exports.add(library, body.export_id, track_ids=result["track_ids"])
return result
job = JOBS.submit("import", work)
return JobStatus(**job.as_dict()) return JobStatus(**job.as_dict())
+10 -3
View File
@@ -34,7 +34,12 @@ from .core.model import AutoHotcue, Track, TrackCues
#: (major, minor). A client speaks to a server of the SAME major whose minor is #: (major, minor). A client speaks to a server of the SAME major whose minor is
#: at least its own: minors only add. Bump the minor for an added route or #: at least its own: minors only add. Bump the minor for an added route or
#: method, the major for anything an older client would misread. #: method, the major for anything an older client would misread.
API_VERSION: tuple[int, int] = (1, 0) #: 1.1 — `move_playlist` (sidebar drag and drop).
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
#: 1.3 — memory cues: `add_memory_cue`, `rename_memory_cue`,
#: `set_memory_cue_type`, `set_memory_cue_color`, `delete_memory_cue`.
#: 1.4 — track colour: `set_track_color`, `Track.color` / `color_hex`.
API_VERSION: tuple[int, int] = (1, 4)
#: How long a session survives without a heartbeat, and how often the holder #: How long a session survives without a heartbeat, and how often the holder
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback #: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
@@ -73,8 +78,10 @@ _READ = (
) )
_MUTATING = ( _MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist", "create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue", "move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker", "set_track_color", "set_cue",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_memory_cue",
"rename_memory_cue", "set_memory_cue_type", "set_memory_cue_color", "delete_memory_cue", "add_grid_marker",
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks", "set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
) )
+83 -3
View File
@@ -5,7 +5,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType from .core.capabilities import CueRole, CueType, TrackColor
class CreatePlaylist(BaseModel): class CreatePlaylist(BaseModel):
@@ -21,11 +21,32 @@ class SetEntries(BaseModel):
track_ids: list[str] # ordered; full desired contents of the playlist track_ids: list[str] # ordered; full desired contents of the playlist
class AddEntries(BaseModel):
track_ids: list[str]
# Tracks the playlist already holds: "skip" them, "add" them again (only
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and
# report how many, so the UI can ask and send again with skip/add.
duplicates: Literal["skip", "add", "ask"] = "skip"
class MovePlaylist(BaseModel):
node_id: str
parent_id: str | None = None # None = the top level
index: int # among the new parent's children, not counting the node
class EditTrack(BaseModel): class EditTrack(BaseModel):
track_id: str track_id: str
fields: dict[str, str | int | None] fields: dict[str, str | int | None]
class SetTrackColor(BaseModel):
"""The context menu's Colour ▸: one colour (None = No Color) for a selection."""
track_ids: list[str]
color: TrackColor | None = None
class FileTagOutcome(BaseModel): class FileTagOutcome(BaseModel):
track_id: str track_id: str
file: str file: str
@@ -186,6 +207,33 @@ class SetCueColor(BaseModel):
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
class AddMemoryCue(BaseModel):
track_id: str
start: float # seconds
type: CueType = "cue"
length: float = 0.0 # seconds (>0 for a memory loop)
name: str | None = None
color: str | None = None # a capabilities.cues.memory_palette entry
class RenameMemoryCue(BaseModel):
track_id: str
cue_id: str # CuePoint.id
name: str | None = None # None / "" = unnamed
class SetMemoryCueType(BaseModel):
track_id: str
cue_id: str
type: CueType # a point type from capabilities.cues.types
class SetMemoryCueColor(BaseModel):
track_id: str
cue_id: str
color: str | None = None # a capabilities.cues.memory_palette entry; None = uncoloured
class StemEngineInstall(BaseModel): class StemEngineInstall(BaseModel):
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one. # None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
target: str | None = None target: str | None = None
@@ -493,6 +541,11 @@ class ImportRequest(BaseModel):
# Playlists land in a folder named after the drive. Null keeps them at the # Playlists land in a folder named after the drive. Null keeps them at the
# root; the default is filled in from the source's label. # root; the default is filled in from the source's label.
folder_name: str | None = None folder_name: str | None = None
# Device tracks dropped on a collection playlist / an export (drag and
# drop): every imported track — and every one the collection already
# holds — goes into it, as folder add does.
into_playlist: str | None = None
export_id: str | None = None
class Drive(BaseModel): class Drive(BaseModel):
@@ -502,11 +555,15 @@ class Drive(BaseModel):
candidate `/api/sources` reports, attached to the drive it lives on so the candidate `/api/sources` reports, attached to the drive it lives on so the
sidebar can show one row per drive rather than a device list and a drive sidebar can show one row per drive rather than a device list and a drive
list that disagree about what is plugged in. list that disagree about what is plugged in.
`server` is a remote library's content folder (path `server:`), listed
first while a remote library is open — the one place its music can be
browsed by folder from this computer.
""" """
name: str name: str
path: str path: str
kind: Literal["local", "external"] kind: Literal["local", "external", "server"]
library: SourceCandidate | None = None library: SourceCandidate | None = None
@@ -514,14 +571,37 @@ class FolderTracks(BaseModel):
"""The audio files directly inside one folder, projected as tracks.""" """The audio files directly inside one folder, projected as tracks."""
path: str path: str
# A file the collection holds is listed AS the collection's track (its id,
# key, rating, cues…); any other file as its own tags, id = its path.
tracks: list[Track] tracks: list[Track]
# Ids (= absolute paths) of the files the collection already points at. # Collection ids of the rows that are collection tracks.
in_collection: list[str] in_collection: list[str]
# Those rows' collection id → the file's folder id, which adding takes.
files: dict[str, str] = {}
# On an external drive: a track referenced in place goes missing when the # On an external drive: a track referenced in place goes missing when the
# drive is unplugged, which the add dialog has to say. # drive is unplugged, which the add dialog has to say.
removable: bool removable: bool
class DroppedPaths(BaseModel):
"""Files and folders dropped onto the window from Finder / Explorer."""
paths: list[str]
class DroppedFiles(BaseModel):
"""What a drop resolved to: the audio in it, as a folder lists its files."""
tracks: list[Track]
# As FolderTracks: rows the collection holds are its tracks, and this maps
# their collection id back to the file's folder id, which adding takes.
files: dict[str, str] = {}
# Dropped files that are not audio the library can hold, or are gone.
skipped: int = 0
# Too many files: only the first MAX_DROPPED are here.
truncated: bool = False
class FolderAddRequest(BaseModel): class FolderAddRequest(BaseModel):
"""Add browsed files to the collection, and optionally to a playlist/export. """Add browsed files to the collection, and optionally to a playlist/export.
+72
View File
@@ -44,6 +44,7 @@ from ..core.adapter import (
NotFound, NotFound,
Unsupported, Unsupported,
) )
from ..core.folder import FolderScanner
from ..core.places import is_os_housekeeping from ..core.places import is_os_housekeeping
from .config import ConfigError, ServerConfig from .config import ConfigError, ServerConfig
from .session import InUse, Lost, SessionLock from .session import InUse, Lost, SessionLock
@@ -65,6 +66,10 @@ class Server:
self.lock = lock or SessionLock() self.lock = lock or SessionLock()
self.rev = 0 self.rev = 0
self._rev_lock = threading.Lock() self._rev_lock = threading.Lock()
#: The content folder's audio as browsed from a client's Files tree —
#: tags read once per folder state, and the gatekeeper for streaming
#: one of those files (only a file a listing found is served).
self.folders = FolderScanner()
# ---- opening --------------------------------------------------------------- # ---- opening ---------------------------------------------------------------
def open(self) -> None: def open(self) -> None:
@@ -388,6 +393,73 @@ def create_app(server: Server) -> FastAPI:
"entries": entries, "entries": entries,
} }
@app.get("/v1/folder/tracks")
def folder_tracks(path: str | None = None) -> dict:
"""The audio directly inside a content folder, projected as tracks — the
client's Files tree for the server, like `/api/folder/tracks` for a
drive of its own. Tags only (no decoding). `held` maps each file the
library already points at to the library's id for it, so the client
can tick it off and add it to a playlist without adding it twice."""
from .. import importer
folder = server.confine(path)
if not folder.is_dir():
raise HTTPException(404, f"Not a folder: {folder}")
adapter = server.adapter
source = server.folders.scan(folder, adapter.capabilities().tracks.audio_formats)
library = importer._existing_files(adapter)
files, held = {}, {}
for track in source.tracks:
try:
st = Path(track.id).stat()
except OSError:
continue
files[track.id] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
known = library.get(importer._key(Path(track.id)))
if known is not None:
held[track.id] = known
return {
"path": str(folder),
"tracks": [t.model_dump(mode="json") for t in source.tracks if t.id in files],
"files": files,
"held": held,
}
def listed_file(path: str) -> Path:
# Confined (a symlink in a listing cannot lead out of the content
# folder), and only a file a listing found: this is not a way to read
# any path on the server.
server.confine(path)
source = server.folders.source_for_file(path)
if source is None:
raise HTTPException(404, "File not found — list its folder first")
target = Path(path)
if not target.is_file():
raise HTTPException(404, "The audio file is missing")
return target
@app.get("/v1/folder/audio")
def folder_audio(path: str):
target = listed_file(path)
st = target.stat()
media = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
return FileResponse(target, media_type=media, headers={
"X-Konduktor-Size": str(st.st_size),
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
})
@app.post("/v1/folder/leads")
def folder_leads(body: dict = Body(...)) -> dict:
"""The analysis lead of each listed file, as an upload reports it: what
a client adding these files IN PLACE measures with. None for every file
when the platform does not analyse what it adds."""
lead = getattr(server.adapter, "analysis_lead", None)
out = {}
for path in body.get("paths") or []:
target = listed_file(str(path))
out[str(path)] = lead(target) if lead else None
return {"leads": out}
@app.get("/v1/fs/space") @app.get("/v1/fs/space")
def fs_space(path: str | None = None) -> dict: def fs_space(path: str | None = None) -> dict:
folder = server.confine(path) folder = server.confine(path)
+29 -14
View File
@@ -39,11 +39,25 @@ _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 *
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR _WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
#: Shares of ONE track's conversion time, for the status bar's within-track #: Shares of ONE track's conversion time (decode, separate; encoding + verifying
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode + #: take the rest), for the status bar's within-track progress, by AAC encoder.
#: verify ~4 s for a 4-minute track). #: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate
_DECODE_SHARE = 0.03 #: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute
_SEPARATE_SHARE = 0.90 #: track: decode 0.5 s, separate ~102 s, encode ~38 s on five threads, verify ~1 s).
_SHARES = {"aac_at": (0.03, 0.90), "aac": (0.01, 0.71)}
def track_shares(encoder: str) -> tuple[float, float]:
return _SHARES.get(encoder, _SHARES["aac"])
def encode_reporter(handle, start: float, end: float = 0.99) -> Callable[[float], None]:
"""`on_encode` for `stem_file.build`: the encode runs from `start` to `end`
of the track, and the ~1 s of tags + verification after it reads as such."""
def report(f: float) -> None:
frac = start + f * (end - start)
handle.progress(fraction=frac, status=f"{'verifying' if f >= 1 else 'encoding'} {frac * 100:.0f} %")
return report
class ConvertError(Exception): class ConvertError(Exception):
@@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
work = work_root() / f"batch-{id(handle):x}" work = work_root() / f"batch-{id(handle):x}"
finished: list[tuple[Planned, dict, sf.Written]] = [] finished: list[tuple[Planned, dict, sf.Written]] = []
needs_engine = any(p.reuse is None for p in items) needs_engine = any(p.reuse is None for p in items)
encoder = sf.default_encoder()
if needs_engine and not mgr.ready(): if needs_engine and not mgr.ready():
raise ConvertError("The stem engine is not installed") raise ConvertError("The stem engine is not installed")
@@ -258,22 +273,22 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)}) "stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
item.target.parent.mkdir(parents=True, exist_ok=True) item.target.parent.mkdir(parents=True, exist_ok=True)
# Of a TRACK's time, separation is nearly all (~90 % on MPS); # Of a TRACK's time, separation is nearly all; decoding before it
# decoding before it and encoding + verifying after share the rest. # and encoding + verifying after share the rest.
decode_share, separate_share = track_shares(encoder)
def on_progress(f: float) -> None: def on_progress(f: float) -> None:
frac = _DECODE_SHARE + f * (_SEPARATE_SHARE) frac = decode_share + f * separate_share
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %") handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
def separate(pcm): def separate(pcm):
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %") handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
done_at = _DECODE_SHARE + _SEPARATE_SHARE
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
return stems
handle.progress(status="decoding 0 %") handle.progress(status="decoding 0 %")
try: try:
written = sf.build(item.source, partial, separate, checkpoint=checkpoint) written = sf.build(item.source, partial, separate, encoder=encoder, checkpoint=checkpoint,
on_encode=encode_reporter(handle, decode_share + separate_share))
except (_Cancel, EngineCancelled): except (_Cancel, EngineCancelled):
partial.unlink(missing_ok=True) partial.unlink(missing_ok=True)
pending.drop([pitem]) pending.drop([pitem])
+3 -4
View File
@@ -153,13 +153,12 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu
def separate(pcm): def separate(pcm):
handle.progress(fraction=0.05, status="separating 5 %") handle.progress(fraction=0.05, status="separating 5 %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(fraction=0.85, status="encoding 85 %")
return stems
partial = work / f"{n}.stem.m4a" partial = work / f"{n}.stem.m4a"
try: try:
written = sf.build(local, partial, separate, checkpoint=checkpoint) written = sf.build(local, partial, separate, checkpoint=checkpoint,
on_encode=convert.encode_reporter(handle, 0.85, 0.9))
except (convert._Cancel, EngineCancelled): except (convert._Cancel, EngineCancelled):
partial.unlink(missing_ok=True) partial.unlink(missing_ok=True)
raise raise
+1 -1
View File
@@ -1,4 +1,4 @@
# Build-only dependencies (not needed to run the backend in dev). # Build-only dependencies (not needed to run the backend in dev).
# Freezes the backend into a standalone sidecar binary for the desktop build. # Freezes the backend into a standalone sidecar folder (onedir) for the desktop build.
# See konduktor-sidecar.spec and build_sidecar.sh. # See konduktor-sidecar.spec and build_sidecar.sh.
pyinstaller>=6.16 # 6.16+ supports Python 3.14 pyinstaller>=6.16 # 6.16+ supports Python 3.14
+2 -2
View File
@@ -14,5 +14,5 @@ Pillow>=11 # a Rekordbox add writes the cover's artwork files
dulwich>=0.22 # version history, beside the library dulwich>=0.22 # version history, beside the library
platformdirs>=4.0 platformdirs>=4.0
# From GitHub, NOT PyPI — see requirements.txt for why. # From GitHub, NOT PyPI — see requirements.txt for why.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@d7f472aaf5be53e53921de351e948233e9c1d1e8
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
+13 -10
View File
@@ -4,7 +4,7 @@ fastapi>=0.115
uvicorn[standard]>=0.34 uvicorn[standard]>=0.34
pydantic>=2.11 pydantic>=2.11
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF) mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
av>=18.1 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS av>=18.1,<20 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS. Before allowing a new major, check core/pyav.py (19 broke av.open)
Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries
python-multipart>=0.0.9 # multipart form parsing for cover-art upload python-multipart>=0.0.9 # multipart form parsing for cover-art upload
# Version-history backups: a self-contained git impl (no system git needed; # Version-history backups: a self-contained git impl (no system git needed;
@@ -18,19 +18,22 @@ librosa>=0.11
scikit-learn>=1.5 scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0), # Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files. # NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git #
# Both GitHub dependencies are PINNED TO A COMMIT. Unpinned, a fresh install
# (CI's release build) takes whatever master is that day while a dev venv keeps
# what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream,
# every local test passed, and the released app could not export or read a
# OneLibrary stick. Move a pin deliberately, with ./run_tests.sh.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@d7f472aaf5be53e53921de351e948233e9c1d1e8
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis # Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build. # files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
# #
# FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for # FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for
# the same kind of reason. PyPI's latest (0.4.4) has no `devicelib_plus`, which # the same kind of reason. PyPI's latest (0.4.4) has no `onelibrary` module
# is the OneLibrary (`exportLibrary.db`) reader the OneLibrary adapter is built # (`exportLibrary.db`, which the OneLibrary adapter is built on; it was called
# on; it exists only on master. Do not "simplify" this back to a version pin. # `devicelib_plus` before the rename) and no `masterdb` (formerly `db6`, now
# # removed). Do not "simplify" this back to a version pin.
# The upgrade also renames `db6` to `masterdb`. `db6` still works as a pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
# running as-is — but that rename is the thing to fix before taking 0.6.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a # The stem engine and its weights are downloaded over HTTPS by the sidecar; a
# frozen Python on macOS has no system CA bundle of its own. # frozen Python on macOS has no system CA bundle of its own.
certifi>=2024.7 certifi>=2024.7
+26 -4
View File
@@ -28,16 +28,38 @@ def _watch_parent_and_exit() -> None:
shut down, so the backend can never be orphaned (the Rust-side kill-on-exit shut down, so the backend can never be orphaned (the Rust-side kill-on-exit
only covers the graceful path). When run standalone from a terminal, stdin is only covers the graceful path). When run standalone from a terminal, stdin is
a TTY and this blocks harmlessly forever. a TTY and this blocks harmlessly forever.
NOT on Windows: there a read left pending on the stdin pipe stalls loading
scipy's OpenBLAS DLL in any other thread, forever — so the first analysis
hung the packaged app (dev runs no watcher). Measured 2026-10-12 with plain
Python, through the CRT and through kernel32.ReadFile alike. Windows waits
on the parent PROCESS instead, which also covers a crash.
""" """
try: if sys.platform == "win32":
while sys.stdin.buffer.read(1): _wait_for_parent_process()
else:
try:
while sys.stdin.buffer.read(1):
pass
except Exception:
pass pass
except Exception:
pass
_release_remote() _release_remote()
os._exit(0) os._exit(0)
def _wait_for_parent_process() -> None:
"""Block until the process that started us exits (Windows only)."""
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
synchronize, infinite = 0x00100000, 0xFFFFFFFF
handle = kernel32.OpenProcess(synchronize, False, os.getppid())
if handle: # None: the parent is already gone
kernel32.WaitForSingleObject(handle, infinite)
def _release_remote() -> None: def _release_remote() -> None:
"""Hand back a remote library's session on the way out, so the next """Hand back a remote library's session on the way out, so the next
computer opens it at once instead of waiting out the lease (or being asked computer opens it at once instead of waiting out the lease (or being asked
+14 -5
View File
@@ -153,7 +153,8 @@ for i, (title, artist, key) in enumerate((("One", "Artist A", (8, "minor")), ("T
png = __import__("io").BytesIO() png = __import__("io").BytesIO()
Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG") Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG")
t = Track(id=f"src{i}", title=title, artist=artist, album="LP", genre="House", bpm=125.0, t = Track(id=f"src{i}", title=title, artist=artist, album="LP", genre="House", bpm=125.0,
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio)) key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio),
color=("purple", None, "aqua")[i])
tracks.append(ExportTrack(track=t, destination=audio, art=(png.getvalue(), "image/png"), tracks.append(ExportTrack(track=t, destination=audio, art=(png.getvalue(), "image/png"),
cues=TrackCues(track_id=t.id, grid_markers=[GridMarker(start=0.0, bpm=125.0)], cues=TrackCues(track_id=t.id, grid_markers=[GridMarker(start=0.0, bpm=125.0)],
cues=[CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0)]))) cues=[CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0)])))
@@ -174,12 +175,14 @@ check("a track with no key has key 0", lib.tracks[1]["key_id"] == 0)
check("bpm x100, rating, file type, bitmask as rekordbox writes them", check("bpm x100, rating, file type, bitmask as rekordbox writes them",
all(t["tempo"] == 12500 and t["u6"] == 11 and t["bitmask"] == 0xC0700 and t["u5"] == 0x29 for t in lib.tracks) all(t["tempo"] == 12500 and t["u6"] == 11 and t["bitmask"] == 0xC0700 and t["u5"] == 0x29 for t in lib.tracks)
and [t["rating"] for t in lib.tracks] == [1, 2, 3]) and [t["rating"] for t in lib.tracks] == [1, 2, 3])
check("the track colour is the 1-based id (Purple 8, none 0, Aqua 6)",
[t["color_id"] for t in lib.tracks] == [8, 0, 6], str([t["color_id"] for t in lib.tracks]))
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"]) check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks)) check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
tree = {p["name"]: p for p in lib.playlists} tree = {p["name"]: p for p in lib.playlists}
check("the tree: a folder named after the export > House > Peak, plus Other for loose tracks", check("the tree: House > Peak, plus Other for loose tracks, at the top level (parent 0)",
tree["GIG"]["folder"] and tree["House"]["parent"] == tree["GIG"]["id"] "GIG" not in tree and tree["House"]["folder"] and tree["House"]["parent"] == 0
and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == tree["GIG"]["id"]) and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == 0)
peak = [e for e in lib.entries if e[2] == tree["Peak"]["id"]] peak = [e for e in lib.entries if e[2] == tree["Peak"]["id"]]
check("playlist entries in order, 1-based", peak == [(1, 1, tree["Peak"]["id"]), (2, 2, tree["Peak"]["id"])], peak) check("playlist entries in order, 1-based", peak == [(1, 1, tree["Peak"]["id"]), (2, 2, tree["Peak"]["id"])], peak)
check("every track has an analysis path, and the files exist", check("every track has an analysis path, and the files exist",
@@ -188,6 +191,13 @@ check("artwork rows name the a<n>.jpg files, which exist",
all((root / p.lstrip("/")).is_file() for p in lib.artwork.values()) and len(lib.artwork) == 3) all((root / p.lstrip("/")).is_file() for p in lib.artwork.values()) and len(lib.artwork) == 3)
check("every file written is reported, so a re-export can clear it", check("every file written is reported, so a re-export can clear it",
all(p.exists() for p in written.all_paths)) all(p.exists() for p in written.all_paths))
import dataclasses # noqa: E402
rooted_tree = {p["name"]: p for p in P.read(
dev.write(dataclasses.replace(payload, root_folder=True), root).library.read_bytes()).playlists}
check("with the root-folder setting: a folder named after the export holds House and Other",
rooted_tree["GIG"]["folder"] and rooted_tree["GIG"]["parent"] == 0
and rooted_tree["House"]["parent"] == rooted_tree["GIG"]["id"]
and rooted_tree["Other"]["parent"] == rooted_tree["GIG"]["id"])
print("== alongside OneLibrary: one set of analysis files and artwork ==") print("== alongside OneLibrary: one set of analysis files and artwork ==")
both = Path(tempfile.mkdtemp()) both = Path(tempfile.mkdtemp())
@@ -195,7 +205,6 @@ for t in tracks:
dst = both / t.destination.relative_to(root) dst = both / t.destination.relative_to(root)
dst.parent.mkdir(parents=True, exist_ok=True) dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_bytes(t.destination.read_bytes()) dst.write_bytes(t.destination.read_bytes())
import dataclasses # noqa: E402
moved = [dataclasses.replace(t, destination=both / t.destination.relative_to(root)) for t in tracks] moved = [dataclasses.replace(t, destination=both / t.destination.relative_to(root)) for t in tracks]
both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlists) both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlists)
ol_written = core_export.for_platform("onelibrary").write(both_payload, both) ol_written = core_export.for_platform("onelibrary").write(both_payload, both)
+33 -12
View File
@@ -66,11 +66,14 @@ chosen = [flexible, cued, plain]
dest = Path(tempfile.mkdtemp()) / "GIG" dest = Path(tempfile.mkdtemp()) / "GIG"
dest.mkdir(parents=True) dest.mkdir(parents=True)
items = [] items = []
# Colours by generic name: `aqua` is rekordbox's, which Traktor stores as Blue.
COLOURS = {flexible.id: "aqua", cued.id: "pink", plain.id: None}
for track in chosen: for track in chosen:
audio = dest / "Music" / "Library" / Path(track.filepath).name audio = dest / "Music" / "Library" / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True) audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 64) audio.write_bytes(b"\0" * 64)
items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id))) items.append(ExportTrack(track=track.model_copy(update={"color": COLOURS[track.id]}),
destination=audio, cues=src.track_cues(track.id)))
payload = ExportPayload( payload = ExportPayload(
name="GIG", name="GIG",
@@ -126,6 +129,11 @@ check("artist survived", by_title[plain.title].artist == plain.artist)
if plain.key: if plain.key:
check("key notation is copied, not converted", by_title[plain.title].key == plain.key) check("key notation is copied, not converted", by_title[plain.title].key == plain.key)
check("track colours cross by name: aqua -> Blue (5), pink -> Magenta (7), none -> no COLOR",
[by_title[t.title].color for t in chosen] == ["blue", "pink", None]
and 'COLOR="5"' in text and 'COLOR="7"' in text and text.count(' COLOR="') == 2,
str([by_title[t.title].color for t in chosen]))
print("== the playlist tree ==") print("== the playlist tree ==")
tree = {} tree = {}
@@ -137,19 +145,20 @@ def walk(nodes, path=()):
walk(back.playlist_tree()) walk(back.playlist_tree())
check("one folder named after the export", ("GIG",) in tree and tree[("GIG",)].kind == "folder") # By default the tree sits at the top level: an export is a library of its own.
check("nested folders are preserved", ("GIG", "House") in tree) check("no folder named after the export by default", ("GIG",) not in tree)
check("and nest further", ("GIG", "House", "Slow") in tree) check("nested folders are preserved", ("House",) in tree and tree[("House",)].kind == "folder")
check("and nest further", ("House", "Slow") in tree)
check("playlists land in their folder", check("playlists land in their folder",
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree) ("House", "Peak Time") in tree and ("House", "Slow", "Warmup") in tree)
check("with the right counts", check("with the right counts",
tree[("GIG", "House", "Peak Time")].count == 2 tree[("House", "Peak Time")].count == 2
and tree[("GIG", "House", "Slow", "Warmup")].count == 1) and tree[("House", "Slow", "Warmup")].count == 1)
# A track added individually would otherwise be reachable only by search. # A track added individually would otherwise be reachable only by search.
check("loose tracks get an 'Other' playlist", ("GIG", "Other") in tree) check("loose tracks get an 'Other' playlist, at the top level", ("Other",) in tree)
check("holding exactly the ones no playlist claimed", check("holding exactly the ones no playlist claimed",
tree[("GIG", "Other")].count == 1, tree[("GIG", "Other")].count) tree[("Other",)].count == 1, tree[("Other",)].count)
other_ids = back.playlist_entries(tree[("GIG", "Other")].id) other_ids = back.playlist_entries(tree[("Other",)].id)
check("and it is the right track", check("and it is the right track",
back.track(other_ids[0]).title == plain.title) back.track(other_ids[0]).title == plain.title)
@@ -182,7 +191,19 @@ again = exporter.write(payload, dest).library
check("the entry count did not double", check("the entry count did not double",
f'<COLLECTION ENTRIES="{len(chosen)}">' in again.read_text(encoding="utf-8")) f'<COLLECTION ENTRIES="{len(chosen)}">' in again.read_text(encoding="utf-8"))
check("and the tree did not duplicate", check("and the tree did not duplicate",
len(TraktorDriver().open(again).playlist_tree()) == 1) len(TraktorDriver().open(again).playlist_tree()) == len(back.playlist_tree()))
print("== with the root-folder setting: everything under one folder named after the export ==")
payload.root_folder = True
rooted = TraktorDriver().open(exporter.write(payload, dest).library)
tree.clear()
walk(rooted.playlist_tree())
check("one top-level node: a folder named after the export",
[n.name for n in rooted.playlist_tree()] == ["GIG"] and tree[("GIG",)].kind == "folder")
check("the tree nests inside it",
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree)
check("and so does 'Other'", ("GIG", "Other") in tree and tree[("GIG", "Other")].count == 1)
payload.root_folder = False
# ============================================================================== # ==============================================================================
# Running an export: the copy, the safety rules, and the rollback. # Running an export: the copy, the safety rules, and the rollback.
@@ -207,7 +228,7 @@ for i, track in enumerate(src.tracks[:4]):
seed_items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id))) seed_items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
exporter_obj = core_export.for_platform("traktor") exporter_obj = core_export.for_platform("traktor")
exporter_obj.write( exporter_obj.write(
_Payload(name="Source", tracks=seed_items, _Payload(name="Source", tracks=seed_items, root_folder=True,
playlists=[ExportPlaylist(name="Peak Time", playlists=[ExportPlaylist(name="Peak Time",
track_ids=[src.tracks[0].id, src.tracks[1].id])]), track_ids=[src.tracks[0].id, src.tracks[1].id])]),
lib_root, lib_root,
+65 -6
View File
@@ -58,13 +58,19 @@ cued = next(t for t in src.tracks
chosen = [flexible, cued] chosen = [flexible, cued]
COLOURS = ["purple", "aqua"]
def build(root: Path) -> ExportPayload: def build(root: Path) -> ExportPayload:
items = [] items = []
for i, track in enumerate(chosen): for i, track in enumerate(chosen):
audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True) audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 4096) audio.write_bytes(b"\0" * 4096)
items.append(ExportTrack(track=track, destination=audio, # A colour each, as the generic name crosses (Traktor's Violet is
# `purple`; `aqua` is rekordbox's own, with no Traktor swatch).
coloured = track.model_copy(update={"color": COLOURS[i % len(COLOURS)]})
items.append(ExportTrack(track=coloured, destination=audio,
cues=src.track_cues(track.id))) cues=src.track_cues(track.id)))
return ExportPayload( return ExportPayload(
name="GIG", tracks=items, name="GIG", tracks=items,
@@ -136,6 +142,10 @@ for platform, reopen in (
all(abs((by_title[t.title].bpm or 0) - (t.bpm or 0)) < 0.02 all(abs((by_title[t.title].bpm or 0) - (t.bpm or 0)) < 0.02
for t in chosen if t.bpm)) for t in chosen if t.bpm))
check("the track colour crossed by name",
[by_title[t.title].color for t in chosen] == COLOURS[:len(chosen)],
str([by_title[t.title].color for t in chosen]))
print(f"-- {platform}: the key was CONVERTED, not copied") print(f"-- {platform}: the key was CONVERTED, not copied")
for track in chosen: for track in chosen:
if not track.key: if not track.key:
@@ -173,9 +183,23 @@ for platform, reopen in (
tree.clear() tree.clear()
walk(back.playlist_tree()) walk(back.playlist_tree())
check("a folder named after the export", ("GIG",) in tree) check("no folder named after the export by default", ("GIG",) not in tree)
check("nested folders are preserved", ("GIG", "House") in tree) check("nested folders are preserved, at the top level", ("House",) in tree)
check("with the playlist inside", check("with the playlist inside",
("House", "Peak Time") in tree
and tree[("House", "Peak Time")].count == len(chosen))
print(f"-- {platform}: with the root-folder setting")
rooted_root = Path(tempfile.mkdtemp()) / "GIG"
rooted_payload = build(rooted_root)
rooted_payload.root_folder = True
exporter.write(rooted_payload, rooted_root)
rooted = reopen(rooted_root)
tree.clear()
walk(rooted.playlist_tree())
check("one top-level node: a folder named after the export",
[n.name for n in rooted.playlist_tree()] == ["GIG"])
check("the tree nests inside it",
("GIG", "House", "Peak Time") in tree ("GIG", "House", "Peak Time") in tree
and tree[("GIG", "House", "Peak Time")].count == len(chosen)) and tree[("GIG", "House", "Peak Time")].count == len(chosen))
@@ -222,7 +246,10 @@ def _real_cue_tags(path: Path) -> list[bytes]:
def _mask_colour(tag: bytes) -> bytes: def _mask_colour(tag: bytes) -> bytes:
"""A PCO2 tag with each entry's code + RGB (after its comment) zeroed.""" """A PCO2 tag with each entry's colours zeroed: the hot-cue code + RGB
(after its comment) and byte 28, a memory cue's colour. The fixture's
memory loop is uncoloured; Konduktor now exports one in its TYPE colour,
as it draws it (decided 2026-10-16) — pinned separately below."""
if tag[:4] != b"PCO2": if tag[:4] != b"PCO2":
return tag return tag
out, off = bytearray(tag), struct.unpack(">I", tag[4:8])[0] out, off = bytearray(tag), struct.unpack(">I", tag[4:8])[0]
@@ -230,6 +257,7 @@ def _mask_colour(tag: bytes) -> bytes:
length = struct.unpack(">I", tag[off + 8:off + 12])[0] length = struct.unpack(">I", tag[off + 8:off + 12])[0]
at = off + 44 + struct.unpack(">I", tag[off + 40:off + 44])[0] at = off + 44 + struct.unpack(">I", tag[off + 40:off + 44])[0]
out[at:at + 4] = bytes(4) out[at:at + 4] = bytes(4)
out[off + 28] = 0
off += length off += length
return bytes(out) return bytes(out)
@@ -410,6 +438,7 @@ print("\n== cue colours cross as rekordbox PALETTE CODES ==")
# rekordbox draws a hot cue from the palette code, not the RGB: an export writing # rekordbox draws a hot cue from the palette code, not the RGB: an export writing
# code 0 had every cue drawn in rekordbox's defaults (green cues, orange loops). # code 0 had every cue drawn in rekordbox's defaults (green cues, orange loops).
# The table was measured from a rekordbox 7 export of all 16 swatches. # The table was measured from a rekordbox 7 export of all 16 swatches.
from konduktor.adapters.rekordbox import anlz_file as A_ # noqa: E402
from konduktor.adapters.rekordbox import palette # noqa: E402 from konduktor.adapters.rekordbox import palette # noqa: E402
check("a measured swatch keeps its exact code and RGB", check("a measured swatch keeps its exact code and RGB",
@@ -437,6 +466,35 @@ entry = W.cue_tags([{"hot_cue": 1, "kind": 1, "time_ms": 1000, "loop_ms": None,
check("the code is packed where rekordbox 7 puts it — byte 44, before the RGB", check("the code is packed where rekordbox 7 puts it — byte 44, before the RGB",
entry[20 + 44:20 + 48] == bytes([0x16, 0x1A, 0xFF, 0x00]), entry[64:68].hex()) entry[20 + 44:20 + 48] == bytes([0x16, 0x1A, 0xFF, 0x00]), entry[64:68].hex())
# Memory cues (kit M2, 2026-10-16): colour is PCP2 byte 28 from the 8-colour
# memory palette, a list of two or more is LINKED in the .DAT, and rekordbox
# keeps 10.
from konduktor.adapters.rekordbox import memory_palette # noqa: E402
many_memory = [CuePoint(type="cue", role="memory", start=float(i), length=0.0, slot=None,
color="#E13121" if i == 0 else None) for i in range(12)]
mem_dicts = OneLibraryExporter._cue_dicts(
ExportTrack(track=cued, destination=Path("t.wav"),
cues=TrackCues(track_id="t", cues=many_memory, grid_markers=[])), [], 0.0)
check("rekordbox keeps 10 memory cues: the earliest 10 are exported",
len(mem_dicts) == 10 and [d["time_ms"] for d in mem_dicts] == [i * 1000 for i in range(10)],
[d["time_ms"] for d in mem_dicts])
check("a memory cue's colour is byte 28 from its own palette (Red = 2); no hot-cue code",
(mem_dicts[0]["color_id"], mem_dicts[0]["code"]) == (memory_palette.anlz_byte(1), 0),
(mem_dicts[0]["color_id"], mem_dicts[0]["code"]))
check("an uncoloured one exports in its type colour, as Konduktor shows it (cue -> Blue = 7)",
mem_dicts[1]["color_id"] == memory_palette.anlz_byte(6), mem_dicts[1]["color_id"])
dat_tags = W.cue_tags(mem_dicts[:3], extended=False)
mem_pcob = A_.raw_entries(A_.Tag("PCOB", dat_tags[1]))
check("a memory PCOB of two or more is linked, status 0, as rekordbox writes it",
[(e[16:20].hex(), e[24:28].hex()) for e in mem_pcob]
== [("00000000", "ffff0001"), ("00000000", "00000002"), ("00000000", "0001ffff")],
[(e[16:20].hex(), e[24:28].hex()) for e in mem_pcob])
ext_tags = W.cue_tags(mem_dicts[:1], extended=True)
pco2_mem = A_.raw_entries(A_.Tag("PCO2", ext_tags[3]))
check("and the colour lands in PCP2 byte 28",
len(pco2_mem) == 1 and pco2_mem[0][28] == memory_palette.anlz_byte(1), pco2_mem and pco2_mem[0][24:32].hex())
print("\n== artwork crosses the way rekordbox 7 writes it ==") print("\n== artwork crosses the way rekordbox 7 writes it ==")
# Measured on a rekordbox 7 export: PIONEER/Artwork/00001/{a,b}<n>{,_m}.jpg at # Measured on a rekordbox 7 export: PIONEER/Artwork/00001/{a,b}<n>{,_m}.jpg at
# 80 and 240 px (a == b byte for byte), baseline JPEG q85 4:2:0, non-square art # 80 and 240 px (a == b byte for byte), baseline JPEG q85 4:2:0, non-square art
@@ -490,7 +548,7 @@ print("\n== content.contentLink is what rekordbox writes ==")
# row's song-list preview plain blue and put a "?" beside CUE — exactly what # row's song-list preview plain blue and put a "?" beside CUE — exactly what
# every row of Konduktor's exports showed while it was NULL. # every row of Konduktor's exports showed while it was NULL.
import sqlcipher3.dbapi2 as _sq # noqa: E402 import sqlcipher3.dbapi2 as _sq # noqa: E402
from pyrekordbox.devicelib_plus.database import BLOB as _BLOB # noqa: E402 from pyrekordbox.onelibrary.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.utils import deobfuscate as _deob # noqa: E402 from pyrekordbox.utils import deobfuscate as _deob # noqa: E402
_con = _sq.connect(str(art_written.library)) _con = _sq.connect(str(art_written.library))
@@ -567,7 +625,8 @@ check("four cue rows: three hot cues and a memory cue (Kind 0)",
check("a plain cue is rekordbox's light blue (code 5)", by_kind.get(1) == (0x05, -1), by_kind.get(1)) check("a plain cue is rekordbox's light blue (code 5)", by_kind.get(1) == (0x05, -1), by_kind.get(1))
check("a loop is rekordbox's green (code 22)", by_kind.get(2) == (0x16, -1), by_kind.get(2)) check("a loop is rekordbox's green (code 22)", by_kind.get(2) == (0x16, -1), by_kind.get(2))
check("the white grid cue has no swatch, so stays uncoloured", by_kind.get(3) == (None, -1), by_kind.get(3)) check("the white grid cue has no swatch, so stays uncoloured", by_kind.get(3) == (None, -1), by_kind.get(3))
check("the memory cue is written, uncoloured", by_kind.get(0) == (None, -1), by_kind.get(0)) check("an uncoloured memory cue is written in its type colour (cue -> Blue, Color 6)",
by_kind.get(0) == (None, 6), by_kind.get(0))
check("the contentCue mirror holds all four, colours included", check("the contentCue mirror holds all four, colours included",
mirror is not None and mirror[0].count('"Kind"') == 4 and '"ColorTableIndex": 22' in mirror[0].replace(":22", ": 22"), mirror is not None and mirror[0].count('"Kind"') == 4 and '"ColorTableIndex": 22' in mirror[0].replace(":22", ": 22"),
mirror and mirror[0][:200]) mirror and mirror[0][:200])
+81 -1
View File
@@ -154,7 +154,11 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
check("it is in the playlist", a.playlist_entries(playlist) == [added]) check("it is in the playlist", a.playlist_entries(playlist) == [added])
check("it was saved, not left pending", not a.dirty) check("it was saved, not left pending", not a.dirty)
body = c.get("/api/folder/tracks", params={"path": str(music)}).json() body = c.get("/api/folder/tracks", params={"path": str(music)}).json()
check("the folder now marks it as held", body["in_collection"] == [str(one)], str(body["in_collection"])) check("the folder now marks it as held", body["in_collection"] == [added], str(body["in_collection"]))
row = next((t for t in body["tracks"] if t["id"] == added), None)
check("…its row IS the collection track (its id and data), mapped back to the file",
row is not None and body["files"] == {added: str(one)}
and row["import_date"] == a.track(added).import_date, str(body["files"]))
print("== a held file is never added twice, but still reaches its target ==") print("== a held file is never added twice, but still reaches its target ==")
library = STATE.library_id library = STATE.library_id
@@ -193,6 +197,82 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
c.post("/api/folder/add/preview", c.post("/api/folder/add/preview",
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404) json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
print("== a drop onto the window: folders all the way down, files as themselves ==")
drop = Path(tempfile.mkdtemp()) / "Dropped"
d_a = flac(drop / "Album" / "a.flac", title="Dropped A")
d_b = flac(drop / "Album" / "CD2" / "b.flac")
(drop / "Album" / "cover.jpg").write_bytes(b"not audio")
flac(drop / "Album" / ".cache" / "h.flac")
single = flac(drop / "Loose" / "single.flac", title="Single")
sibling = flac(drop / "Loose" / "sibling.flac")
(drop / "Loose" / "readme.txt").write_text("not audio")
r = c.post("/api/folder/dropped", json={"paths": [
str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"),
str(drop / "gone.flac"), str(single), str(d_a),
]})
check("answers 200", r.status_code == 200, r.text[:300])
body = r.json()
ids = [t["id"] for t in body["tracks"]]
check("the folder's audio, subfolders included, then the file — each once",
ids == [str(d_a), str(d_b), str(single)], str(ids))
check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids)
check("a dropped non-audio file and a missing one are counted as skipped",
body["skipped"] == 2, str(body["skipped"]))
check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2)
check("tags are read", body["tracks"][0]["title"] == "Dropped A")
check("not truncated", body["truncated"] is False)
check("a dropped file streams",
c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200)
check("so does one found inside a dropped folder",
c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200)
check("but not its undropped sibling",
c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404)
listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]]
check("browsing that folder afterwards still lists ALL of it",
listed == [str(sibling), str(single)], str(listed))
r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]})
check("a non-audio file is never made streamable",
r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={
"track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404)
capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1)
check("past the cap the rest are left out, and it says so",
len(capped.tracks) == 1 and capped.truncated)
body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json()
check("a dropped file the collection holds IS its collection track",
[t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)},
str(body))
req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")}
p = c.post("/api/folder/add/preview", json=req).json()
check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p))
req["destination"] = str(Path(tempfile.mkdtemp()))
p = c.post("/api/folder/add/preview", json=req).json()
check("…and not elsewhere", p.get("in_destination") == 0, str(p))
real_drives = main.places.drives
main.places.drives = lambda: [
{"name": "Computer", "path": drop.anchor, "kind": "local"},
{"name": "Stick", "path": str(drop / "Album"), "kind": "external"},
]
try:
req = {"track_ids": [str(d_a), str(single)], "mode": "reference"}
p = c.post("/api/folder/add/preview", json=req).json()
check("the external-drive warning counts files per drive, not by the first",
p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"],
str(p))
p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)],
"mode": "reference"}).json()
check("…whichever file comes first", p["removable_count"] == 1, str(p))
finally:
main.places.drives = real_drives
n = len(a.tracks)
job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)],
"mode": "reference"}).json())
check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2,
str(job))
print("== Rekordbox: the same route adds to a master.db ==") print("== Rekordbox: the same route adds to a master.db ==")
from konduktor.adapters.rekordbox import discovery as rb_discovery from konduktor.adapters.rekordbox import discovery as rb_discovery
+71 -14
View File
@@ -139,15 +139,29 @@ check("every hot cue keeps the pad it was on",
check("a loop stays a loop, with its length", check("a loop stays a loop, with its length",
got_by_slot[0].type == "loop" and abs(got_by_slot[0].length - 1.875) < 0.001) got_by_slot[0].type == "loop" and abs(got_by_slot[0].length - 1.875) < 0.001)
# Traktor has no memory cues, so they degrade into spare pads rather than being # Memory cues cross AS memory cues — Traktor's cues on no pad (HOTCUE="-1"),
# dropped — the settled lossiness rule. # decided 2026-10-16 once Traktor was measured keeping them. They used to be
# promoted to spare pads.
n_memory = sum(1 for c in src_cues.cues if c.role != "hotcue") n_memory = sum(1 for c in src_cues.cues if c.role != "hotcue")
check("memory cues are preserved in spare slots, not dropped", padless = [c for c in dest._store.model_entry(ids[0]).cue_v2
len(got.cues) == len(src_hot) + n_memory, f"{len(got.cues)} cues") if c.grid is None and c.hotcue == -1]
check("and they do not overwrite a hot cue", check("every memory cue is written as a memory cue (a CUE_V2 on no pad)",
len({c.slot for c in got.cues}) == len(got.cues)) len(padless) == n_memory and n_memory > 0, f"{len(padless)} of {n_memory}")
check("every imported cue occupies a real pad", check("and no extra pad is taken",
all(c.role == "hotcue" and c.slot is not None for c in got.cues)) sorted(c.slot for c in got.cues if c.role == "hotcue") == sorted(src_hot))
# The demo track's memory loop starts exactly where pad A's loop does. Traktor
# draws a pad and a memory cue at one START as ONE marker (measured), so the
# projection shows it once, as the pad (decided 2026-10-16).
pad_starts = {round(c.start, 3) for c in got.cues if c.role == "hotcue"}
got_memory = [c for c in got.cues if c.role == "memory"]
check("a memory cue is shown unless a pad sits on its START",
len(got_memory) + sum(1 for c in padless
if round((c.start - dest._store.time_offset_ms(
dest._store.model_entry(ids[0]))) / 1000, 3) in pad_starts)
== n_memory,
f"{len(got_memory)} shown, pads at {sorted(pad_starts)}")
check("a shown memory cue has no pad and an id",
all(c.slot is None and c.id for c in got_memory))
# `set_analysed_grid` would place Traktor's beat-1 companion on pad A. That both # `set_analysed_grid` would place Traktor's beat-1 companion on pad A. That both
# invents a cue the source never had and displaces the imported pad A cue — it # invents a cue the source never had and displaces the imported pad A cue — it
@@ -230,7 +244,9 @@ many = TrackCues(
grid_markers=[GridMarker(start=0.0, bpm=120.0)], grid_markers=[GridMarker(start=0.0, bpm=120.0)],
cues=[CuePoint(type="cue", role="hotcue", start=float(i), length=0.0, slot=i) cues=[CuePoint(type="cue", role="hotcue", start=float(i), length=0.0, slot=i)
for i in range(8)] for i in range(8)]
+ [CuePoint(type="cue", role="memory", start=99.0, length=0.0, slot=None)], + [CuePoint(type="cue", role="memory", start=99.0, length=0.0, slot=None),
# A pad past Traktor's bank: displaced, and with no spare pad left.
CuePoint(type="cue", role="hotcue", start=50.0, length=0.0, slot=9)],
) )
crowded_id = dest2.add_tracks([NewTrack( crowded_id = dest2.add_tracks([NewTrack(
track=Track(id="ignored", title="Crowded", bpm=120.0), track=Track(id="ignored", title="Crowded", bpm=120.0),
@@ -238,11 +254,15 @@ crowded_id = dest2.add_tracks([NewTrack(
cues=many, cues=many,
)])[0] )])[0]
crowded = dest2.track_cues(crowded_id) crowded = dest2.track_cues(crowded_id)
check("the bank is filled but not overflowed", len(crowded.cues) == 8, str(len(crowded.cues))) crowded_hot = [c for c in crowded.cues if c.role == "hotcue"]
check("the hot cues are the ones that survived", check("the bank is filled but not overflowed", len(crowded_hot) == 8, str(len(crowded_hot)))
sorted(c.slot for c in crowded.cues) == list(range(8))) check("the hot cues keep their own pads",
check("the memory cue that would not fit is dropped, not misplaced", sorted(c.slot for c in crowded_hot) == list(range(8))
all(c.start < 99.0 for c in crowded.cues)) and all(c.start == float(c.slot) for c in crowded_hot))
check("the memory cue stays a memory cue, and a displaced hot cue with no spare "
"pad becomes one — nothing is dropped",
sorted(round(c.start) for c in crowded.cues if c.role == "memory") == [50, 99],
str([(c.role, c.start) for c in crowded.cues]))
print("== the source slot ==") print("== the source slot ==")
# A source is a library read FROM, open alongside the loaded one. The whole slot # A source is a library read FROM, open alongside the loaded one. The whole slot
@@ -447,6 +467,43 @@ check("re-importing flags the tracks as already present",
check("but does not refuse them — the user chose to add everything", check("but does not refuse them — the user chose to add everything",
len(plan8.importable) == 2) len(plan8.importable) == 2)
print("== import route: chosen tracks into a playlist and an export (drag and drop) ==")
# Device tracks dropped on a collection playlist open Import with that playlist
# as the target: only the chosen tracks, no drive folder, all into the playlist.
nml9, music9, _ = fresh_collection()
drive9 = Path(tempfile.mkdtemp(prefix="konduktor-import-drive-")) / "Dingus"
shutil.copytree(FIXTURE, drive9, ignore=shutil.ignore_patterns("rekordbox-edited"))
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
with TestClient(main.app) as c:
check("the collection opens", c.post("/api/library/open", json={"path": str(nml9)}).status_code == 200)
check("the drive opens as a source", c.post("/api/source/open", json={"path": str(drive9)}).status_code == 200)
picked = c.get("/api/source/tracks", params={"limit": 10}).json()
picked = picked["items"][:1]
target = c.post("/api/playlists", json={"name": "Dropped"}).json()["id"]
eset = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"],
"destination": str(music9.parent / "gig")}).json()["id"]
r = c.post("/api/import", json={"destination": str(music9), "track_ids": [picked[0]["id"]],
"into_playlist": target, "export_id": eset})
check("the import starts", r.status_code == 200, r.text[:200])
job = r.json()
for _ in range(200):
job = c.get(f"/api/jobs/{job['id']}").json()
if job["state"] != "running":
break
time.sleep(0.05)
check("…and finishes", job["state"] == "done", str(job)[:300])
entries = c.get(f"/api/playlists/{target}/tracks").json()
check("the one chosen track lands in the target playlist",
len(entries) == 1 and entries[0]["title"] == picked[0]["title"], str([e["title"] for e in entries]))
names = [n["name"] for n in c.get("/api/playlists").json()]
check("no drive folder is made when no playlist was chosen", "Dingus" not in names, str(names))
ex = next(e for e in c.get("/api/exports").json() if e["id"] == eset)
check("…and it is added to the export too", ex["track_ids"] == [entries[0]["id"]], str(ex["track_ids"]))
c.delete("/api/source")
print() print()
print("RESULT:", "FAILED" if failed else "ALL PASSED") print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+23 -2
View File
@@ -317,8 +317,10 @@ memory = [c for c in cues.cues if c.role == "memory"]
check("the memory cue is preserved", len(memory) == 1) check("the memory cue is preserved", len(memory) == 1)
check("it has no slot", memory[0].slot is None) check("it has no slot", memory[0].slot is None)
check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001) check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001)
check("on an editable drive every hot cue is editable, no memory cue is", check("on an editable drive every cue is editable, memory cues included",
all(c.editable == (c.role == "hotcue") for c in cues.cues)) all(c.editable for c in cues.cues))
check("a memory cue is addressed by a content-derived id",
memory[0].id is not None and memory[0].id.startswith("m:"), str(memory[0].id))
_browse = OneLibraryAdapter(DRIVE, read_only=True) _browse = OneLibraryAdapter(DRIVE, read_only=True)
check("on a browsing drive no cue is editable", check("on a browsing drive no cue is editable",
all(not c.editable for c in _browse.track_cues(one.id).cues)) all(not c.editable for c in _browse.track_cues(one.id).cues))
@@ -436,6 +438,25 @@ check("refusing leaves nothing dirty", adapter.dirty is False)
check("an unknown track is a NotFound, not an Unsupported", check("an unknown track is a NotFound, not an Unsupported",
_raises(lambda: adapter.audio_path("no-such-track"), NotFound)) _raises(lambda: adapter.audio_path("no-such-track"), NotFound))
print("== track colour ==")
# Goober (`fixtures/onelibrary-goober`) is a stick coloured in rekordbox:
# `content.color_id` 1-based into the `color` table (1 Pink, 2 Red, 5 Green).
from konduktor.adapters.rekordbox import track_palette # noqa: E402
_gdir = Path(tempfile.mkdtemp(prefix="konduktor-ol-colour-")) / "goober"
shutil.copytree(FIXTURE.parent / "onelibrary-goober", _gdir)
_goober = OneLibraryAdapter(_gdir)
_colours = {t.title: (t.color, t.color_hex) for t in _goober.tracks}
check("rekordbox's track colours project by name + display RGB",
_colours.get("Nemean - Doomed") == ("red", "#E13121")
and _colours.get("Sleepnet - Lapse") == ("green", "#65DB41")
and _colours.get("Life Is A Loop - Grand Prix") == ("pink", "#E577EF"), str(_colours))
check("an uncoloured track has none", _colours.get("Demo Track 2") == (None, None))
_goober.close()
check("the palette maps ids both ways",
[track_palette.id_for(track_palette.color_for(i)) for i in range(9)] == list(range(9))
and track_palette.color_for("0") is None and track_palette.color_for(9) is None)
print("== reads that answer rather than refuse ==") print("== reads that answer rather than refuse ==")
check("cover art is absent, not an error", adapter.cover_art(one.id) is None) check("cover art is absent, not an error", adapter.cover_art(one.id) is None)
# A drive stores everything relative to its own root, so it cannot have stale # A drive stores everything relative to its own root, so it cannot have stale
+125 -4
View File
@@ -131,8 +131,8 @@ dat = dat_of(a, TRACK_1)
ext = dat.with_suffix(".EXT") ext = dat.with_suffix(".EXT")
original = {p: p.read_bytes() for p in (dat, ext)} original = {p: p.read_bytes() for p in (dat, ext)}
cues = {c.slot: c for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"} cues = {c.slot: c for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
check("hot cues are editable, memory cues are not", check("hot cues and memory cues are editable on a drive opened for editing",
all(c.editable == (c.role == "hotcue") for c in a.track_cues(TRACK_1).cues)) all(c.editable for c in a.track_cues(TRACK_1).cues))
a.set_cue(TRACK_1, slot=5, start_sec=10.0, cue_type="cue", name="Drop") a.set_cue(TRACK_1, slot=5, start_sec=10.0, cue_type="cue", name="Drop")
a.set_cue_color(TRACK_1, 5, "#FF0045") a.set_cue_color(TRACK_1, 5, "#FF0045")
@@ -154,8 +154,8 @@ check("a pad can be deleted (pad D, which lives in the .EXT's PCOB)",
check("deleting an empty pad is NotFound", _raises(lambda: a.delete_cue(TRACK_1, 7), NotFound)) check("deleting an empty pad is NotFound", _raises(lambda: a.delete_cue(TRACK_1, 7), NotFound))
check("a pad beyond the bank is refused", check("a pad beyond the bank is refused",
_raises(lambda: a.set_cue(TRACK_1, slot=8, start_sec=1.0, cue_type="cue"), InvalidCommand)) _raises(lambda: a.set_cue(TRACK_1, slot=8, start_sec=1.0, cue_type="cue"), InvalidCommand))
check("memory cues are not editable", check("set_cue refuses role=memory (memory cues have their own commands)",
_raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue", role="memory"), Unsupported)) _raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue", role="memory"), InvalidCommand))
check("a colour must be one of rekordbox's swatches", check("a colour must be one of rekordbox's swatches",
_raises(lambda: a.set_cue_color(TRACK_1, 5, "#123456"), InvalidCommand)) _raises(lambda: a.set_cue_color(TRACK_1, 5, "#123456"), InvalidCommand))
a.place_cues(TRACK_1, [CuePoint(slot=1, start=30.0, length=0.0, type="cue"), a.place_cues(TRACK_1, [CuePoint(slot=1, start=30.0, length=0.0, type="cue"),
@@ -256,6 +256,127 @@ check("a 44-byte compact entry has no colour bytes to patch",
/ "nemean.EXT", "PCO2", A.LIST_MEMORY)))[-1], / "nemean.EXT", "PCO2", A.LIST_MEMORY)))[-1],
9, (1, 2, 3)) is None) 9, (1, 2, 3)) is None)
# ---- memory cues: rekordbox's own edits, byte for byte --------------------------
# `fixtures/onelibrary-memory-edits`: six memory-cue edits rekordbox 7 made on a stick
# (kit M2, 2026-10-16), one per track. Each is replayed with `memory_cues` — the
# code the store runs — on `before/`, and the memory lists must equal `after/`.
print("== memory cues: the same edit as rekordbox 7 made, the same bytes ==")
from konduktor.adapters.onelibrary import memory_cues as M # noqa: E402
from konduktor.adapters.onelibrary.cues import memory_cue_id # noqa: E402
MEMORY_EDITS = HERE / "fixtures" / "onelibrary-memory-edits"
def memory_edit(name: str):
return (A.parse_file(MEMORY_EDITS / "before" / f"{name}.DAT"),
A.parse_file(MEMORY_EDITS / "before" / f"{name}.EXT"))
def same_as_rekordbox(name: str, dat, ext) -> bool:
"""Both files equal rekordbox's, tag for tag — except that when rekordbox
rewrites a `.DAT` it also re-sorts the UNTOUCHED hot-cue `PCOB` into
ascending pad order (measured: same entries, pads 3-2-1 -> 1-2-3).
Konduktor changes only the list it edits, so that one tag must hold the
same entries in either order."""
want_dat = A.parse_file(MEMORY_EDITS / "after" / f"{name}.DAT")
want_ext = A.parse_file(MEMORY_EDITS / "after" / f"{name}.EXT")
if ext.to_bytes() != want_ext.to_bytes() or len(dat.tags) != len(want_dat.tags):
return False
for got, want in zip(dat.tags, want_dat.tags):
if (got.type, got.list_kind) == ("PCOB", A.LIST_HOT):
if sorted(A.raw_entries(got)) != sorted(A.raw_entries(want)):
return False
elif got.data != want.data:
return False
return dat.header[:8] == want_dat.header[:8] and len(dat.to_bytes()) == len(want_dat.to_bytes())
def id_at(ext, time_ms: int) -> str:
return next(memory_cue_id(A.decode_entry(e)) for e in M.entries(ext, "PCO2")
if A.decode_entry(e).time == time_ms)
dat, ext = memory_edit("black-bloc")
M.add(dat, ext, kind=1, time_ms=131206, loop_ms=None, beats=None)
check("add a memory cue: .DAT prepended + relinked, .EXT appended compact — both FILES "
"equal rekordbox's", same_as_rekordbox("black-bloc", dat, ext))
dat, ext = memory_edit("formula")
M.add(dat, ext, kind=2, time_ms=80378, loop_ms=81773, beats=4)
check("add a memory loop (4 beats): rekordbox's bytes", same_as_rekordbox("formula", dat, ext))
dat, ext = memory_edit("lift-it")
for t in (3353, 4733, 6112, 7491, 8871, 10250, 11629, 13009):
M.add(dat, ext, kind=1, time_ms=t, loop_ms=None, beats=None)
check("add eight, up to rekordbox's cap of 10: rekordbox's bytes",
same_as_rekordbox("lift-it", dat, ext) and M.count(ext) == 10)
dat, ext = memory_edit("wtf")
check("recolour Blue: only PCP2 byte 28 (= 7), rekordbox's bytes",
M.recolour(ext, id_at(ext, 113186), 7) and same_as_rekordbox("wtf", dat, ext))
dat, ext = memory_edit("sell-my-soul")
check("a comment grows the PCP2 entry by its length (88 -> 100): rekordbox's bytes",
M.rename(ext, id_at(ext, 78645), "Loopy") and same_as_rekordbox("sell-my-soul", dat, ext))
dat, ext = memory_edit("doomed")
check("delete: out of both lists, the survivor relinked: rekordbox's bytes",
M.delete(dat, ext, id_at(ext, 121402)) and same_as_rekordbox("doomed", dat, ext))
check("an unknown id finds nothing", not M.delete(dat, ext, "m:1:1:4294967295"))
print("== memory cues through the adapter, on the demo drive ==")
from konduktor.adapters.rekordbox import memory_palette # noqa: E402
drive = copy_of(DEMO, "Memo")
a = OneLibraryAdapter(drive)
dat = dat_of(a, TRACK_1)
ext = dat.with_suffix(".EXT")
original = {p: p.read_bytes() for p in (dat, ext)}
caps = a.capabilities().cues
check("capabilities: memory cues, cap 10, the 8-colour palette",
caps.memory_cues and caps.max_memory_cues == 10 and caps.memory_color == "palette"
and caps.memory_palette == memory_palette.SWATCHES)
before_mem = [c for c in a.track_cues(TRACK_1).cues if c.role == "memory"]
tc = a.add_memory_cue(TRACK_1, start_sec=12.0, cue_type="cue", name="Break",
color=memory_palette.SWATCHES[1])
new = [c for c in tc.cues if c.role == "memory" and c not in before_mem]
check("add_memory_cue: named, coloured (Red), editable, with an id",
len(new) == 1 and new[0].name == "Break" and new[0].color == memory_palette.SWATCHES[1]
and new[0].editable and new[0].id, str(new))
check("nothing reaches the drive before Save", all(p.read_bytes() == b for p, b in original.items()))
tc = a.rename_memory_cue(TRACK_1, new[0].id, "Breakdown")
tc = a.set_memory_cue_color(TRACK_1, new[0].id, None)
got = next(c for c in tc.cues if c.id == new[0].id)
check("rename and clear the colour", got.name == "Breakdown" and got.color is None, str(got))
check("a hot-cue swatch is not a memory colour",
_raises(lambda: a.set_memory_cue_color(TRACK_1, new[0].id, "#00FF30"), InvalidCommand))
check("an unknown id is NotFound",
_raises(lambda: a.delete_memory_cue(TRACK_1, "m:1:1:4294967295"), NotFound))
while sum(c.role == "memory" for c in a.track_cues(TRACK_1).cues) < 10:
n = sum(c.role == "memory" for c in a.track_cues(TRACK_1).cues)
a.add_memory_cue(TRACK_1, start_sec=100.0 + n, cue_type="cue")
check("the 11th is refused", _raises(lambda: a.add_memory_cue(TRACK_1, start_sec=1.0,
cue_type="cue"), InvalidCommand))
a.delete_memory_cue(TRACK_1, new[0].id)
check("delete removes it", all(c.id != new[0].id for c in a.track_cues(TRACK_1).cues))
hot_before = {c.slot: (c.start, c.color) for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
a.save()
def changed_tags(path: Path) -> set:
now, was = tags_by_key(path), tags_by_key(original[path])
return {k for k in set(now) | set(was) if now.get(k) != was.get(k)}
check("Save: the .DAT changes only in its memory PCOB",
changed_tags(dat) == {("PCOB", A.LIST_MEMORY)}, str(changed_tags(dat)))
check("the .EXT only in its memory PCO2",
changed_tags(ext) == {("PCO2", A.LIST_MEMORY)}, str(changed_tags(ext)))
b = OneLibraryAdapter(drive)
check("reopened: the hot cues are untouched and 9 memory cues remain",
{c.slot: (c.start, c.color) for c in b.track_cues(TRACK_1).cues if c.role == "hotcue"}
== hot_before and sum(c.role == "memory" for c in b.track_cues(TRACK_1).cues) == 9)
b.close()
a.close()
print() print()
print("RESULT:", "FAILED" if failed else "ALL PASSED") print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+82 -1
View File
@@ -60,7 +60,7 @@ def dump(db: Path) -> dict:
"""Every row of every table; keyed by primary key, or by the whole row for """Every row of every table; keyed by primary key, or by the whole row for
the link tables, which have none.""" the link tables, which have none."""
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
con = sqlcipher.connect(str(db)) con = sqlcipher.connect(str(db))
@@ -264,6 +264,44 @@ seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs)) check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
a.close() a.close()
print("== moving playlists (sidebar drag and drop) ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
folder = a.create_folder("Gigs")
probe = a.create_playlist("Probe")
a.save()
before = dump(db_of(drive))
check("every node offers can_move", all(n.can_move for n in a.playlist_tree()))
demos = next(n for n in a.playlist_tree() if n.name == "demos")
a.move_playlist(demos.id, folder, 0)
a.move_playlist(probe, None, 1)
tree = a.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder).children] == [demos.id])
check("a playlist moves to the index asked for", [n.id for n in tree] == [folder, probe],
str([n.name for n in tree]))
check("a folder cannot be moved into itself",
_raises(lambda: a.move_playlist(folder, folder, 0), InvalidCommand))
check("nor into a playlist", _raises(lambda: a.move_playlist(probe, demos.id, 0), InvalidCommand))
a.save()
after = dump(db_of(drive))
changes = diff(before, after)
check("only playlist rows change, by UPDATE",
{(t, kind) for t, _, kind, _ in changes} == {("playlist", "UPDATE")}, describe(changes))
check("only parent and sequenceNo columns change",
{c for *_, f in changes for c in f} <= {"playlist_id_parent", "sequenceNo"},
str([f for *_, f in changes]))
for parent in (0, int(folder)):
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == parent)
check(f"sequenceNo stays 0..n-1 under {parent}", seqs == list(range(len(seqs))), str(seqs))
a.close()
reopened = OneLibraryAdapter(drive)
check("the move round-trips through a reopen",
[c.id for c in next(n for n in reopened.playlist_tree() if n.id == folder).children] == [demos.id])
reopened.move_playlist(probe, None, 1)
check("moving a node onto its own place is not an edit", reopened.dirty is False)
reopened.close()
# ---- E: a stick's hazards ------------------------------------------------------------ # ---- E: a stick's hazards ------------------------------------------------------------
print("== another app wrote the drive since it was opened ==") print("== another app wrote the drive since it was opened ==")
drive = fresh_drive() drive = fresh_drive()
@@ -404,6 +442,49 @@ check("setting 12A reuses the stick's '12A' row instead of adding 'Dbm'",
if r2["title"] == target.title))["key_id"]) == names["12A"]) if r2["title"] == target.title))["key_id"]) == names["12A"])
g.close() g.close()
print("== track colour ==")
# `content.color_id` (1 Pink .. 8 Purple, 0 none); the pdb track row's
# `color_id` byte uses the same ids, and Goober's two agree on every track.
from konduktor.adapters.rekordbox import pdb # noqa: E402
goober = Path(tempfile.mkdtemp(prefix="konduktor-olfid-colour-")) / "Goober"
shutil.copytree(FIXTURE.parent / "onelibrary-goober", goober, ignore=shutil.ignore_patterns("after"))
pdb_path = goober / "PIONEER" / "rekordbox" / "export.pdb"
def pdb_colours() -> dict:
return {pdb.row_id(pdb.TRACKS, r): pdb.track_fields(r)[0]["color_id"]
for r in pdb.table_rows(pdb_path.read_bytes(), pdb.TRACKS)}
before = dump(db_of(goober))
check("rekordbox's own pdb carries the same colour ids as the database",
pdb_colours() == {int(r["content_id"]): int(r["color_id"] or 0) for r in before["content"].values()},
str(pdb_colours()))
g = OneLibraryAdapter(goober)
check("an editable stick offers rekordbox's eight colours",
[s.color for s in g.capabilities().tracks.colors]
== ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"])
check("a browsed one offers none",
OneLibraryAdapter(goober, read_only=True).capabilities().tracks.colors == [])
g.set_track_color(next(x for x in g.tracks if x.color == "green").id, "green")
check("setting the colour it has is not an edit", g.dirty is False)
red = next(t for t in g.tracks if t.color == "red")
t = g.set_track_color(red.id, "blue")
check("the projection shows it at once", (t.color, t.color_hex) == ("blue", "#1F4EED"), str(t))
g.save()
changes = diff(before, dump(db_of(goober)))
check("exactly content.color_id changes (2 = Red -> 7 = Blue)",
len(changes) == 1 and changes[0][3] == {"color_id": (2, 7)}, describe(changes))
cid = int(changes[0][1]) if changes else None
check("and the pdb's track row follows", pdb_colours().get(cid) == 7, str(pdb_colours()))
g.set_track_color(red.id, None)
g.save()
check("No Color stores 0, in both",
dump(db_of(goober))["content"][changes[0][1]]["color_id"] == 0 and pdb_colours().get(cid) == 0)
check("an unknown colour is refused", _raises(lambda: g.set_track_color(red.id, "teal"), Exception))
g.close()
print() print()
print("RESULT:", "FAILED" if failed else "ALL PASSED") print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+1 -1
View File
@@ -65,7 +65,7 @@ def fingerprint(root: Path) -> str:
def rows(root: Path, sql: str): def rows(root: Path, sql: str):
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
con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db")) con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db"))
+37
View File
@@ -172,6 +172,43 @@ check("COLLECTION still byte-identical after folder delete",
check("unknown folder is 404", check("unknown folder is 404",
client.delete("/api/playlists/fld:No Such Folder").status_code == 404) client.delete("/api/playlists/fld:No Such Folder").status_code == 404)
print("== drag and drop: add with duplicates, move ==")
target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"]
first, rest = track_ids[:2], track_ids[2:4]
r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json()
check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json()
check("'ask' with a duplicate changes nothing and counts it",
r["status"] == "duplicates" and r["duplicates"] == 1
and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json()
check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1], "duplicates": "add"}).json()
check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json()
check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1)
check("capabilities say Traktor holds duplicates",
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0})
check("moving a folder answers its (path) id", r.json()["id"] == box)
check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0})
check("a folder into itself is a 400", r.status_code == 400)
r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0})
check("an unknown node is a 404", r.status_code == 404)
client.delete(f"/api/playlists/{box}")
client.post("/api/save")
check("COLLECTION still byte-identical after drops and moves",
collection_span(WORK.read_bytes()) == collection_before)
print("== original untouched ==") print("== original untouched ==")
check( check(
"original collection.nml never modified", "original collection.nml never modified",
+6 -6
View File
@@ -216,8 +216,9 @@ with tempfile.TemporaryDirectory() as d:
# writable hot cue with a padlock. # writable hot cue with a padlock.
check("ordinary hot cues are editable", check("ordinary hot cues are editable",
all(c.editable for c in tc.cues if c.role == "hotcue" and c.type != "loop")) all(c.editable for c in tc.cues if c.role == "hotcue" and c.type != "loop"))
check("memory cues are preserved but not editable", check("memory cues are editable and addressed by id",
all(not c.editable for c in tc.cues if c.role == "memory")) all(c.editable and c.id for c in tc.cues
if c.role == "memory" and c.readonly_reason is None))
check("loops are editable like any other hot cue", check("loops are editable like any other hot cue",
all(c.editable for c in tc.cues if c.type == "loop" and c.role == "hotcue")) all(c.editable for c in tc.cues if c.type == "loop" and c.role == "hotcue"))
check("an uneditable cue always says why", check("an uneditable cue always says why",
@@ -427,11 +428,10 @@ with tempfile.TemporaryDirectory() as d:
check("a Traktor-only cue type is Unsupported", check("a Traktor-only cue type is Unsupported",
_raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=1.0, _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=1.0,
cue_type="fade_in"), Unsupported)) cue_type="fade_in"), Unsupported))
# Rekordbox is the ONLY platform with memory cues, so they stay # A memory cue has no slot; set_cue is for pads only.
# preserved-but-uneditable under the two-platform promotion rule. check("set_cue refuses role=memory (memory cues have their own commands)",
check("memory cues are shown but not writable",
_raises(lambda: adapter.set_cue(cue_track.id, slot=1, start_sec=1.0, _raises(lambda: adapter.set_cue(cue_track.id, slot=1, start_sec=1.0,
cue_type="cue", role="memory"), Unsupported)) cue_type="cue", role="memory"), InvalidCommand))
# Slot 0 is the FIRST pad, not an error: it is Kind=1 natively. # Slot 0 is the FIRST pad, not an error: it is Kind=1 natively.
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue") tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue")
first = [c for c in tc.cues if c.slot == 0] first = [c for c in tc.cues if c.slot == 0]
+185
View File
@@ -31,6 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appd
from konduktor.adapters.rekordbox import discovery # noqa: E402 from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
failed = False failed = False
@@ -96,6 +97,14 @@ def diff(before: dict, after: dict, ignore_columns=("updated_at", "created_at"))
return changes return changes
def _raises(fn, exc) -> bool:
try:
fn()
except exc:
return True
return False
def describe(changes) -> str: def describe(changes) -> str:
return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)" return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)"
@@ -302,6 +311,51 @@ with tempfile.TemporaryDirectory() as d:
folder_reopened.close() folder_reopened.close()
after_folder.close() after_folder.close()
# ---- E2: moving nodes in the tree (sidebar drag and drop) -----------
print("== E2: move_playlist reorders and reparents, touching only playlist rows ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
adapter = RekordboxAdapter(work)
folder_id = adapter.create_folder("Konduktor Move Folder")
a_id = adapter.create_playlist("Konduktor Move A")
b_id = adapter.create_playlist("Konduktor Move B")
adapter.save()
adapter.close()
before = dump(work)
adapter = RekordboxAdapter(work)
check("every node offers can_move", all(n.can_move for n in adapter.playlist_tree()))
adapter.move_playlist(b_id, folder_id, 0)
adapter.move_playlist(a_id, None, 0)
tree = adapter.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
check("a playlist moved to index 0 is first at the top level", tree[0].id == a_id,
[n.name for n in tree[:3]])
try:
adapter.move_playlist(folder_id, folder_id, 0)
check("a folder cannot be moved into itself", False)
except InvalidCommand:
check("a folder cannot be moved into itself", True)
adapter.save()
changes = diff(before, dump(work))
check("only djmdPlaylist rows and the counter change",
{t for t, _, _, _ in changes} <= {"djmdPlaylist", "agentRegistry"}, describe(changes))
rows = dump(work)["djmdPlaylist"]
for parent in ("root", folder_id):
seqs = sorted(int(r["Seq"]) for r in rows.values()
if str(r["ParentID"]) == parent and not r["rb_local_deleted"])
check(f"Seq stays 1..n under {parent}", seqs == list(range(1, len(seqs) + 1)), seqs)
adapter.close()
reopened = RekordboxAdapter(work)
tree = reopened.playlist_tree()
check("the moves round-trip through a reopen",
tree[0].id == a_id
and [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
reopened.move_playlist(b_id, None, len(tree))
check("a playlist moved out of a folder lands last at the top level",
reopened.playlist_tree()[-1].id == b_id)
reopened.close()
again = final = RekordboxAdapter(work)
# ---- F: a cue write touches the cue row AND its mirror --------------- # ---- F: a cue write touches the cue row AND its mirror ---------------
print("== F: a hot cue write is localized, and keeps the mirror in step ==") print("== F: a hot cue write is localized, and keeps the mirror in step ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened]) clean_copy(REAL, work, closing=[adapter, again, final, reopened])
@@ -400,6 +454,113 @@ with tempfile.TemporaryDirectory() as d:
f"{mirror_row['rb_cue_count']} vs {len(records)}") f"{mirror_row['rb_cue_count']} vs {len(records)}")
adapter.close() adapter.close()
# ---- G2: memory cues, as rekordbox 7 writes them (kit M1, 2026-10-16) ---
print("== G2: memory cues: row shapes, colour column, mirror order, the cap of 10 ==")
import json as _json
from konduktor.adapters.rekordbox import memory_palette as _mp
from konduktor.core.adapter import InvalidCommand as _Invalid
clean_copy(REAL, work, closing=[adapter])
adapter = RekordboxAdapter(work)
mem_track = next((t for t in adapter.tracks if t.bpm), adapter.tracks[0])
for c in [c for c in adapter.track_cues(mem_track.id).cues if c.role == "memory" and c.id]:
adapter.delete_memory_cue(mem_track.id, c.id)
adapter.save()
def memory_rows(snapshot):
return {pk: r for pk, r in snapshot["djmdCue"].items()
if r["ContentID"] == mem_track.id and r["Kind"] == 0}
before = dump(work)
adapter.add_memory_cue(mem_track.id, start_sec=60.0, cue_type="cue")
adapter.add_memory_cue(mem_track.id, start_sec=20.0, cue_type="loop", length_sec=2.0)
adapter.save()
changes = diff(before, dump(work))
check("adding memory cues changes only djmdCue, contentCue and the counter",
{t for t, _, _, _ in changes} == {"djmdCue", "contentCue", "agentRegistry"},
describe(changes))
after = dump(work)
rows = sorted(memory_rows(after).values(), key=lambda r: r["InMsec"])
point = next((r for r in rows if r["OutMsec"] == -1), None)
loop = next((r for r in rows if r["OutMsec"] > 0), None)
check("a memory point cue: Kind 0, Color -1, ColorTableIndex NULL, Comment NULL",
point is not None and (point["Color"], point["ColorTableIndex"], point["Comment"])
== (-1, None, None), str(point and (point["Color"], point["ColorTableIndex"], point["Comment"])))
check("a memory loop: Color 255, ColorTableIndex 0, Comment '', ActiveLoop 0, CueMicrosec 0",
loop is not None and (loop["Color"], loop["ColorTableIndex"], loop["Comment"],
loop["ActiveLoop"], loop["CueMicrosec"]) == (255, 0, "", 0, 0),
str(loop and (loop["Color"], loop["ColorTableIndex"], loop["Comment"])))
check("its BeatLoopSize is (beats << 16) | 1",
loop is not None and loop["BeatLoopSize"] and loop["BeatLoopSize"] & 0xFFFF == 1)
mirror = next(r for r in after["contentCue"].values() if r["ContentID"] == mem_track.id)
ids_in_mirror = [str(r["ID"]) for r in _json.loads(mirror["Cues"])]
live = [r for r in after["djmdCue"].values() if r["ContentID"] == mem_track.id]
check("the mirror lists cues in ROW order, as rekordbox does — the 20 s loop "
"added second comes after the 60 s cue",
ids_in_mirror.index(str(loop["ID"])) > ids_in_mirror.index(str(point["ID"])),
str(ids_in_mirror))
check("rb_cue_count counts memory cues too", mirror["rb_cue_count"] == len(live))
cues = {c.id: c for c in adapter.track_cues(mem_track.id).cues if c.role == "memory"}
point_id = str(point["ID"])
check("a memory cue projects with its row id, editable",
point_id in cues and cues[point_id].editable)
blue = _mp.SWATCHES[6]
adapter.set_memory_cue_color(mem_track.id, point_id, blue)
adapter.save()
row = memory_rows(dump(work))[point_id]
check("a colour is the 0-based code in Color (Blue = 6), ColorTableIndex NULL",
(row["Color"], row["ColorTableIndex"]) == (6, None),
str((row["Color"], row["ColorTableIndex"])))
check("and projects back as that swatch",
next(c.color for c in adapter.track_cues(mem_track.id).cues if c.id == point_id) == blue)
adapter.set_memory_cue_color(mem_track.id, point_id, None)
adapter.save()
row = memory_rows(dump(work))[point_id]
check("No Color writes 255, as rekordbox does after a colour is cleared",
(row["Color"], row["ColorTableIndex"]) == (255, None),
str((row["Color"], row["ColorTableIndex"])))
check("rekordbox memory cues have no type to choose",
_raises(lambda: adapter.set_memory_cue_type(mem_track.id, point_id, "load"), Exception))
check("a hot-cue swatch is not a memory colour",
_raises(lambda: adapter.set_memory_cue_color(mem_track.id, point_id, "#00FF30"), _Invalid))
before = dump(work)
adapter.rename_memory_cue(mem_track.id, point_id, "This is a comment")
adapter.save()
changes = diff(before, dump(work))
cue_change = [c for c in changes if c[0] == "djmdCue"]
# pyrekordbox's commit stamps the row's USN too, as on every hot-cue write
# (rekordbox's own edits leave a cue row's USN NULL; it has accepted ours).
check("a rename changes only that row's Comment (and its USN)",
len(cue_change) == 1 and set(cue_change[0][3]) <= {"Comment", "rb_local_usn"}
and "Comment" in cue_change[0][3],
str(cue_change and cue_change[0][3]))
while sum(1 for c in adapter.track_cues(mem_track.id).cues if c.role == "memory") < 10:
adapter.add_memory_cue(mem_track.id, start_sec=float(
1 + sum(1 for c in adapter.track_cues(mem_track.id).cues if c.role == "memory")),
cue_type="cue")
adapter.save()
before = dump(work)
check("the 11th memory cue is refused (rekordbox would drop it silently)",
_raises(lambda: adapter.add_memory_cue(mem_track.id, start_sec=99.0, cue_type="cue"),
_Invalid))
adapter.save()
check("and nothing changed", not diff(before, dump(work)))
before = dump(work)
adapter.delete_memory_cue(mem_track.id, point_id)
adapter.save()
after = dump(work)
changes = [c for c in diff(before, after) if c[0] == "djmdCue"]
check("a delete removes the row outright (not rb_local_deleted)",
len(changes) == 1 and changes[0][2] == "DELETE", describe(changes))
mirror = next(r for r in after["contentCue"].values() if r["ContentID"] == mem_track.id)
check("and its mirror entry",
point_id not in {str(r["ID"]) for r in _json.loads(mirror["Cues"])})
adapter.close()
# ---- H: a grid write touches ONE tag of ONE file --------------------- # ---- H: a grid write touches ONE tag of ONE file ---------------------
print("== H: a beatgrid write is localized to the .DAT's PQTZ tag ==") print("== H: a beatgrid write is localized to the .DAT's PQTZ tag ==")
from pyrekordbox.anlz import AnlzFile from pyrekordbox.anlz import AnlzFile
@@ -791,5 +952,29 @@ with tempfile.TemporaryDirectory() as d:
len(dump(work)["djmdKey"]) == len(after["djmdKey"])) len(dump(work)["djmdKey"]) == len(after["djmdKey"]))
adapter.close() adapter.close()
print("== L: track colour is djmdContent.ColorID, one row + the counter ==")
clean_copy(REAL, work)
before = dump(work)
adapter = RekordboxAdapter(work)
t1 = adapter.tracks[0]
got = adapter.set_track_color(t1.id, "aqua")
check("the projection updates immediately", (got.color, got.color_hex) == ("aqua", "#55BBF1"), str(got))
adapter.save()
changes = diff(before, dump(work))
content = [c for c in changes if c[0] == "djmdContent"]
check("exactly the track row and the counter change",
{t for t, _, _, _ in changes} == {"djmdContent", "agentRegistry"} and len(changes) == 2,
describe(changes))
check("ColorID '6' (Aqua, 1-based into djmdColor)",
content and content[0][3].get("ColorID", (None, None))[1] == "6", str(content and content[0][3]))
before = dump(work)
adapter.set_track_color(t1.id, None)
adapter.save()
changes = diff(before, dump(work))
check("No Color writes '0'",
[c[3].get("ColorID", (None, None))[1] for c in changes if c[0] == "djmdContent"] == ["0"],
describe(changes))
adapter.close()
print("\nRESULT:", "FAILED" if failed else "ALL PASSED") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more