Compare commits

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

No files matched your search

+93 -4
View File
@@ -55,10 +55,11 @@ jobs:
with:
python-version: "3.12"
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
# --- Step 1: freeze the FastAPI backend into a onedir sidecar folder ---
# build_sidecar.* stages it as
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
# which tauri.conf.json's externalBin bundles into the app.
# frontend/src-tauri/binaries/konduktor-sidecar/
# which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) /
# tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`.
- name: Install backend deps
working-directory: backend
run: |
@@ -114,6 +115,52 @@ jobs:
if-no-files-found: error
path: installer/*
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
# can name the tag that matches the app it is opened from.
server-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # push to ghcr.io
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and image name
id: meta
run: |
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
# GHCR names must be lower-case; the owner may not be.
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
env:
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
with:
context: .
file: server/Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
${{ steps.meta.outputs.image }}:latest
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
# Gather both platforms' installers and publish them as a single new Release.
# Runs once, after both builds succeed, so the two matrix jobs never race to
# create the same tag/release.
@@ -122,6 +169,7 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write # required to create the tag + release
pull-requests: read # to read the merged PR's patch notes
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -136,14 +184,55 @@ jobs:
- name: Download installers from both builds
uses: actions/download-artifact@v4
with:
# Only the installers: the run also holds server-image's Docker build
# record, which is not a release asset (and once failed to download).
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
# Release notes from the "Patch notes" section of the PR that merged this
# commit into main (dev → main merges carry many features in one PR, so
# its title alone says little). Written under "What's Changed", the
# heading the app's update dialog reads. No PR (a manual run, a direct
# push) or no such section → GitHub's generated notes, as before.
- name: Patch notes from the merged PR
id: notes
env:
GH_TOKEN: ${{ github.token }}
run: |
gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \
--jq '[.[] | select(.base.ref == "main" and .merged_at != null)][0].body // ""' \
> pr-body.md || : > pr-body.md
python3 - <<'EOF'
import os, re
body = open("pr-body.md", encoding="utf-8").read().replace("\r\n", "\n")
body = re.sub(r"<!--.*?-->", "", body, flags=re.S)
section, level = [], None
for line in body.split("\n"):
m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line)
if level is None:
if m and re.fullmatch(r"patch[\s-]?notes:?", m.group(2), re.I):
level = len(m.group(1))
elif m and len(m.group(1)) <= level:
break
else:
section.append(line)
notes = "\n".join(section).strip()
found = bool(notes)
if found:
with open("release-notes.md", "w", encoding="utf-8") as f:
f.write("## What's Changed\n\n" + notes + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as out:
out.write(f"found={'true' if found else 'false'}\n")
print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.")
EOF
- name: Publish release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
target_commitish: ${{ github.sha }}
generate_release_notes: true # auto changelog from commits/PRs since last release
body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }}
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
fail_on_unmatched_files: true
files: artifacts/**/*
+101 -29
View File
@@ -1,21 +1,27 @@
# Building Konduktor for Windows
The desktop app can't be cross-compiled — a Windows build must be produced **on
Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
The desktop app can't be cross-compiled. A Windows build must be produced **on
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately
on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)).
This mirrors the macOS build exactly; only the toolchain install and the
sidecar-build command differ.
The recipe is the same as on macOS. Only the toolchain install and the
sidecar-build command differ. CI does exactly this on `windows-latest`
([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build
disagrees with CI, check that workflow first.
## One-time setup
1. **Rust** — install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
1. **Rust**: install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
development with C++" from the Visual Studio Build Tools installer.
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
4. **Node 18+** — <https://nodejs.org>.
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
get the Evergreen runtime from Microsoft (Tauri's installer can also
bootstrap it).
3. **Python 3.11–3.14**: <https://python.org> (tick "Add to PATH"). CI builds
with **3.12**, the safest choice.
4. **Node 20.19+ or 22.12+**: <https://nodejs.org>. Vite 8 refuses older
versions, so Node 18 no longer works. CI uses Node 20.
Then, from the repo root:
@@ -33,49 +39,115 @@ npm install
cd ..
```
## Build
If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is
disabled on this system"), either allow local scripts once with
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with
`powershell -ExecutionPolicy Bypass -File .\dev.ps1`.
## Develop (no build)
```powershell
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
```
Then open <http://localhost:5173> in a browser. `dev.ps1` is the Windows
counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules`
from the setup above. It runs the Python source, not the frozen sidecar, so it
can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file
drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this
still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend
changes need `build_sidecar.ps1` first.
### Tests
`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't
run as-is on Windows. Run a suite directly with the venv's Python instead:
```powershell
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
cd backend
.\.venv\Scripts\Activate.ps1 # if not already active
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
.\.venv\Scripts\python.exe test_save_fidelity.py
```
## Build
One command does both steps and lists the installers it produced:
```powershell
.\build.ps1 # sidecar + app
.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
.\build.ps1 --debug # any other argument is passed on to `tauri build`
```
By hand, that is:
```powershell
# 1) Freeze + stage the backend sidecar
cd backend
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
cd ..
# 2) Build the app
# 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend
npx tauri build
```
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
gotcha 4 in [CLAUDE.md](CLAUDE.md).
## Output
Installers land in:
```
frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
frontend\src-tauri\target\release\bundle\nsis\Konduktor_<version>_x64-setup.exe
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
```
Either one installs the app (bundling the sidecar `.exe` alongside it).
`<version>` is the `version` in [frontend/package.json](frontend/package.json),
the app's only version source. Either installer works. Releases ship only the
NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource
folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
`sidecar\konduktor-sidecar.exe`.
## Rebuilding after changes
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
(its `beforeBuildCommand` rebuilds the web app).
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build`). Frontend-only changes just need
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
## Not part of this build: the stem engine
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
released on its own channel by
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
and `windows-x64-cuda`). The app downloads it at runtime into a short
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
limit. You don't need it to build or run the app.
## Known Windows caveats
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
(Signing is a future step.)
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
launch shows a "Windows protected your PC" prompt. Click **More info → Run
anyway**.
- **Mixed content is already handled.** The webview is forced to the `http`
custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
Leave that setting as-is.
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
without a visible window; if a console flashes on launch, tell me and we'll add
the `CREATE_NO_WINDOW` spawn flag.
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
- **The sidecar is a console app, but no console appears.** It's frozen with
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
flashes.
- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its
stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS
DLL, which hung the first analysis, so it waits on the parent process instead
(`backend/sidecar.py`). Keep this in mind before touching that watcher.
- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads
AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` /
`.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg.
- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run.
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
+588 -53
View File
@@ -35,6 +35,21 @@ Two independent apps that talk over HTTP:
- `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the
error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422),
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
the UI can gate controls instead of branching on the platform.
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
@@ -114,11 +129,55 @@ Two independent apps that talk over HTTP:
`backend/bench_grid_detect.py` scores it against any library's
single-marker grids and reports that constant separately from detection
error (29 Rekordbox references: old 1/29 BPMs, new 27/29).
Either half can be HELD — the Analyze dialog's BPM / Grid ticks:
`bpm=` keeps that tempo (no search, no round snap, no re-octave) and
finds only the phase; `anchor=` detects the tempo and returns the anchor
untouched, `drift_ms` then measuring how well the kept anchor fits.
`bench_grid_detect.py --hold bpm|anchor` scores each alone (2026-10-04,
15 local refs: phase given the right BPM 15/15; tempo given the right
anchor 14/15, the same miss as full analysis).
- `grid_plan.py` — **what an analysis does to one track's grid**, as one
pure function (`plan_grid` → `GridStep`) so the batch, the dialog's
counts and the tests agree. BPM+Grid = full, an existing grid replaced
only with Replace ticked; BPM alone keeps the first marker's anchor; Grid
alone keeps its BPM (else the track's TEMPO). With ONE tick, Replace does
not apply (adjusting is the point) and a track with nothing to keep is
analysed in full; a flexible grid is skipped, never flattened; locked is
always skipped. `main._analyse_grid` writes each through the hand-edit
command for the same thing — `set_grid_marker_bpm(0)` / `move_grid_marker(0)`
— so companions, marker names and time bases behave as for a hand edit.
- `key_detect.py` + `key_model.npz` — **musical key detection**: a small
CNN (Korzeniowski & Widmer 2017 — five 5x5 convs, a per-frame dense layer
over the WHOLE pitch axis, since a key is not pitch-invariant, logits
averaged over time), an ensemble of three, run in NUMPY — torch only
trains it (`backend/train_key_model.py`, engine venv), the backend never
imports it. Input is a 7-octave CQT at 36 bins/octave (C1–C8); the net
sees C2–C7, the spare octaves are for pitch-shift augmentation. Trained
on GiantSteps MTG, scored on the separate GiantSteps key set
(`bench_key_detect.py`): **69.4% exact, 83.4% harmonically mixable**;
key templates (Krumhansl/Temperley/KeyFinder/EDM) topped out at 49.5% on
the same features. ~0.6 s per track beside the decode. Always returns a
key for music (confidence tracks accuracy, but even the lowest band is
~10x chance); None only for silence / under 5 s. The datasets are NOT on
the machine by default — fetch steps are in the training script.
- `musical_key.py` — the generic key (Camelot wheel 1-12 + mode) and the
three notations libraries STORE: `camelot` (8A), `open_key` (1m — Traktor's
default, Open Key n = Camelot n+7) and `musical` (Am, spelt as rekordbox
spells its own rows: flats for Db/Eb/Ab/Bb, F#). `parse` accepts all
three (and "Amin", "F# minor"), because a library holds what imported
tags said: a rekordbox stick's key table had "12A" beside "Abm".
- `stem_file.py` + `tag_copy.py` — **writing a native-instruments STEM
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,
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
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
@@ -256,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.
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.
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only
platform with them — the two-platform promotion rule).
**Memory cues are editable** (`add_memory_cue` / `rename_` /
`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
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
@@ -333,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
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.
A track with no analysis files refuses cue/grid edits. Memory cues stay
preserved-but-uneditable.
A track with no analysis files refuses cue/grid edits.
**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
every Save (rekordbox's own edits let its playlists drift — measured). The
stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are
@@ -487,6 +568,124 @@ Two independent apps that talk over HTTP:
open / save / discard (and, next, a stem batch's swap step).
History is app-level: the adapter returns the bytes it wrote plus a summary,
and `AppState.save()` versions them. Every write path must go through it.
**Where** it is versioned is the open library's `services` (`services.py`):
`LocalServices` is the history repo in this computer's app-data, keyed by
path (what it always was); a remote library's live on its server. Routes
reach history through `STATE.services` / `STATE.restore_version`, never the
`history` module with `STATE.path`. `open_hooks` run at the end of every
open (and restore) — how the server re-applies its configured path mapping.
- **Remote libraries** (decided 2026-10-01/02 —
[the discussion](.claude/discussions/discuss-remote-library-2026-10-01.md)):
the whole library on the user's NAS, a Konduktor SERVER in a container
holding it, the desktop app opening it as "Remote". Three pieces:
- `remote_protocol.py` — the wire contract BOTH sides import: the
`LibraryAdapter` protocol itself as RPC (`RPC` table, `MUTATING` flag,
`EXCLUDED` with a reason for every member that does not travel —
`test_remote_protocol.py` fails on a protocol member that is neither),
args/results (de)serialised by pydantic `TypeAdapter`s built from the
protocol's own hints (a misspelt argument is refused, not defaulted),
`API_VERSION` (same major, server minor ≥ client's), the lease
(`LEASE_SECONDS` 120 / `HEARTBEAT_SECONDS` 15), `WireNewTrack` and the
prepared-analysis `.npz` packing. Bytes never travel as JSON.
- `server/` — `python -m konduktor.server` (the container's command;
`server/Dockerfile`, `compose.yaml`, `.env.example`). NOT `main.py`
behind a password. `config.py` reads the env (`KONDUKTOR_PLATFORM`
checked against the file, `_LIBRARY`, `_CONTENT`, `_USERNAME`,
`_PASSWORD`, `_PATH_MAP` "stored => here; …") and fails fast with one
line. `app.py`: HTTP Basic on every route; `/v1/hello`, `session/*`,
`rpc/{method}` (every answer carries `rev` plus the tracks it `changed`
/ `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED
to the content folder — resolve then `is_relative_to`, so neither `..`
nor a symlink escapes — never overwriting, `-2` suffixes, per-session
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
the adapter's plus `tracks.audio_destination="library"`,
`reference=False`, `paths.remappable=False`, `overwrite_risk="none"`.
`session.py`: ONE holder; a 409 names who holds it (machine, since,
running batch) and `takeover` replaces it; the old token is 423 from
then on; a lapsed lease is renewed silently for the SAME client if
nobody took it. Unsaved edits are the native model's, not the
session's: the next holder inherits them and `pending_edits`
(`last_editor` + the adapter's optional `edit_summary()`) asks them to
save or discard. A container restart loses them — accepted.
**Lightweight by decision: the server never decodes audio** — its
image ships `requirements-server.txt` without librosa / scikit-learn /
PyAV, and `test_layering.py` checks importing it pulls none in
(`stem_file._audio_stream_count` counts `soun` traks when PyAV is
absent). With a path mapping configured the server calls the
adapter's optional `set_write_stored_paths(True)`: a file added (or a
stem file swapped in) through the mapping is written in the library's
STORED form (`pathmap.stored_form`), so the collection keeps one
convention and still opens where it was made.
- `adapters/remote/` — the client, imports no platform adapter.
`RemoteAdapter` IS a `LibraryAdapter`: the frontend, export, import and
batches never learn a library is remote. It mirrors the projection in a
local `TrackIndex` (same query code), folds each command's `changed`
into it, and re-fetches on any `rev` gap. **`audio_path` downloads**
into the shared `cache.py` (keyed by the server's `AudioFacts` — path,
size, mtime — partial-then-rename, LRU under `remoteCacheBytes`, the
recently used never evicted); anything that needs only a file's
IDENTITY asks the new protocol member **`audio_facts`**, which never
downloads (`exporter.plan`, `importer._existing_files`). `client.py`
tries the address that last worked, then the others (primary →
fallback) on CONNECT failures only, and maps status codes back onto the
adapter error classes (423 → `SessionLost`, unreachable → `Unavailable`,
503 in `main.py`). `session.py` heartbeats (reporting the running batch)
and moves `connected / reconnecting / offline / taken_over`; anything
but connected/reconnecting makes `capabilities()` read-only with cause
`taken_over` / `offline`, and a 423 on any command flips it at once;
taken over cancels this computer's batches (`_on_remote_change`).
`config.py`: saved remotes in prefs (`remotes`, plus a stable
`remoteClientId`), passwords in the OS keychain via `keyring`
(`use_password_store` is the test seam). `services.py`: history, export
sets (`exports.use_store`, keyed by `remote:<server id>` so nothing on
this computer is mistaken for the server's) and the stems ledger
(`RemotePending`) all on the server. Imports UPLOAD
(`importer.uploads_audio` → `upload_audio`, cleaned up on failure; free
space from the server) into a folder the user picks on the server;
Rekordbox's add analysis — waveform, grid AND key — is computed HERE
(`core/add_analysis.prepare` with the lead the upload reports, sent as
`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
(`/v1/stems/plan`, its `convert.plan`), this computer downloads,
separates and encodes, uploads each verified file (`/v1/stems/stage`,
sha-256 checked, kept on the server as a LEFTOVER), and the server runs
the ordinary `convert._end_step` under its mutation lock with its own
ledger (`/v1/stems/publish`). Cancel abandons this run's uploads; a
takeover cannot, so they stay and the next run reuses them. The preview
adds `transfer` (download / upload / measured speed) and space lines for
both machines.
UI: the picker's platform list ends with **Remote** (`selects:
"remote"`) → `RemotePicker` (saved remotes; the form saves only after
`handshake` — a wrong password or version refuses, an unreachable
fallback alone does not; the in-use → Take over and the leftover-edits
Save / Discard / Decide-later prompts happen before the library shows).
`App` polls `['state']` every 5 s for a remote (`remote` in `EditState`),
re-reads capabilities on a change and toasts it; `StatusBar` shows the
connection. `FileBrowser`/`FolderPicker` take `listing="library"` for the
server's folders; Import / Add Files / Convert to Stems use it when
`tracks.audio_destination === 'library'` (folders remembered per remote:
`remoteImportFolders`, `remoteStemFolders`). Settings → Remote audio is
the cache. Path remapping hides on `paths.remappable === false`.
- `library_id.py` — a **stable identity for a library that survives it being
moved**. Everything else keys off the OS path (`history` hashes it, `prefs`
stores it), which is fine for things a user shrugs at losing and NOT fine for
@@ -533,7 +732,13 @@ Two independent apps that talk over HTTP:
"Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss.
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
dir). Last-opened collection (global AND per-platform), library column
layout, prep-deck zoom, import destination. Best-effort.
layout, prep-deck zoom, import destination. Best-effort, but **every
read-modify-write holds `_LOCK` and every write is atomic**
(`paths.write_json`): the UI sends several PATCHes at once on launch, and
unlocked, with a truncating write, a reader caught the file empty and wrote
back only its own key — wiping every pref, the column layout included. A
file that will not parse is moved to `userprefs.json.corrupt`, never
silently overwritten. New helpers that read then write must take the lock.
- `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`.
- `main.py` — thin FastAPI routes (all under `/api`), talking only to the
adapter. Starts **unloaded**; the library is chosen at runtime via
@@ -634,9 +839,17 @@ Two independent apps that talk over HTTP:
expandable Local Storage. A drive carrying a OneLibrary library opens as a
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
table, read-only via `readonly_cause: 'not_in_library'`, with files the
collection already holds checked off in the # column (`TrackTable`'s
`marked`). A browsed device is read-only (cause `browsing`); **"Open for
table, with files the collection already holds checked off in the #
column (`TrackTable`'s `marked`). **A held file's row IS the collection
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
a device whose caps say `browsing` — opens it as THE library via App's
`openForEditing` (unsaved-edits confirm, source closed, library opened).
@@ -669,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
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.
**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`
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 /
@@ -676,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
user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard
· Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer;
browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when
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),
browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx`
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
devices. TanStack Table + **virtualized** grid; per-row play button,
configurable columns, header sorting, inline double-click editing, and
@@ -696,7 +934,43 @@ Two independent apps that talk over HTTP:
not dnd-kit sortable**: a SortableContext around the virtualizer loops on its
flushSync-driven measurement — which is why playlists were once a separate,
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 =
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
@@ -719,6 +993,18 @@ Two independent apps that talk over HTTP:
original files" while conversions are pending (decided: the consequence is
shown where Save is pressed). `Toast` takes an optional `action`;
`StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares.
`AnalyzeDialog` (the context menu's **Analyze…**, decided 2026-10-04:
BPM / Grid / Key ticks, remembered as `analyzeWhat`, each disabled with a
reason where the library cannot store it — offered when EITHER grids or
keys are writable; the Replace questions are inside the dialog, never a
second popup, and never remembered: the grid's only when BPM AND Grid are
ticked, since with one tick adjusting the grid is the point. Every count
and the "Analyze N" button come from `/api/tracks/analyze/preview`, i.e.
the backend's own `plan_grid`. The finished job's toast says what was
written and skipped, by reason. The deck's one-click Analyze writes the
key too, and App hands the deck the fresh copy of its track whenever the
view it came from refetches — the deck otherwise held a load-time
snapshot, so neither an analysed key nor an Edit Tags change reached it),
`AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
slot, a per-slot Replace tick for occupied slots — never remembered, since
overwriting is a decision about THIS track — and the template itself
@@ -730,7 +1016,14 @@ Two independent apps that talk over HTTP:
`ContextMenu` (supports `▸` submenus, section headings, separators and
checkbox items that toggle without closing — the header row's right-click
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,
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
@@ -758,7 +1051,7 @@ Two independent apps that talk over HTTP:
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).
`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
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
@@ -769,11 +1062,14 @@ Two independent apps that talk over HTTP:
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
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
by `PrepStrip` so it survives track switches and persists) over
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll,
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
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
(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
**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
@@ -797,6 +1093,20 @@ Two independent apps that talk over HTTP:
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
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
choices, a colour swatch grid + Default where `cues.color` is `palette` —
`ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone
@@ -827,9 +1137,12 @@ Two independent apps that talk over HTTP:
`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`,
`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
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`, and
memory-cue *editing* (one-platform features stay preserved-but-uneditable).
since a platform may allow renaming but not deleting. Memory cues: the deck's
Hot / Mem toggle shows on `cues.memory_cues`, + Memory refuses past
`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).
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
columns (defs, default widths/visibility/order, the Columns-menu list, the
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
@@ -842,18 +1155,30 @@ Two independent apps that talk over HTTP:
via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against
defaults so newly-added columns still appear). The prep deck's main-waveform
zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the
shared `['prefs']` query).
shared `['prefs']` query). Continuously-changing prefs (columns, zoom,
`beatSize`) are written through ONE debounced writer, `lib/prefs.ts`
(`usePrefsWriter` / `queuePrefs`): changes merge into one PATCH, sent in
order, and the queue outlives unmounts; `QuitGuard` calls `flushPrefs()`
before quitting. Do not give a new pref its own timer.
## Commands
```bash
./dev.sh # start both servers (see README for one-time setup)
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
# Backend
cd backend && source .venv/bin/activate
uvicorn konduktor.main:app --reload --port 8000
# point at another file: KONDUKTOR_NML=/path/to/collection.nml uvicorn ...
# A Konduktor SERVER (a remote library) from source — configured by env, see
# server/.env.example; the container runs the same command:
KONDUKTOR_PLATFORM=traktor KONDUKTOR_LIBRARY=/path/collection.nml \
KONDUKTOR_CONTENT=/path/music KONDUKTOR_USERNAME=dj KONDUKTOR_PASSWORD=pw \
python -m konduktor.server # listens on :8765
docker build -f server/Dockerfile -t konduktor-server . # from the repo root
# Frontend
cd frontend
npm run dev # dev server (proxies /api -> :8000)
@@ -881,10 +1206,32 @@ serialization path.** It enforces:
— onto a staying track's path, or two differently-keyed entries for one file
— which the preview reports first, while a chain (A onto B's old path, B
onward) and a pre-existing duplicate are allowed, each track's staged art
and edits following the TRACK (H4).
and edits following the TRACK (H4). And **`set_key`** (N): on a keyed
entry only its INFO and MUSICAL_KEY lines change; an unkeyed one gains the
KEY attribute and one `<MUSICAL_KEY>` between LOUDNESS and CUE_V2 in
Traktor's layout; the encoding matches the real collection; a Camelot
collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the
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).
The guard that catches serialization regressions like the lxml reformatting bug.
- `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
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
@@ -901,7 +1248,10 @@ serialization path.** It enforces:
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
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
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-
@@ -952,7 +1302,9 @@ serialization path.** It enforces:
against SQLite). Asserts a no-op save changes zero rows; a one-field edit
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
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
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
@@ -970,6 +1322,17 @@ serialization path.** It enforces:
(pad, colour), loop and memory cue cross as themselves; and removing it
deletes its analysis files. `test_folders.py` drives the same through
`/api/folder/add` on a Rekordbox copy, and a non-addable library 422s.
And **`set_key`** (K): a key the library has changes exactly the track row
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
spelling, `Seq` NULL, its own USN (so through the ORM; a raw insert is
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.
Unlike the Rekordbox tests it needs **nothing installed and nothing plugged
in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed
@@ -986,9 +1349,13 @@ serialization path.** It enforces:
changes zero rows, a title edit exactly `content.title` (no counter, as
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
`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,
the drive never held open, file tags written (title yes, rating no).
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
the stick names it; a missing one adds a key row in rekordbox's spelling;
on Goober, "12A" projects a key and setting 12A reuses that row.
- `test_onelibrary_anlz.py` — cue and grid edits in the ANLZ files. First
against **rekordbox's own edit** of the same thing
(`fixtures/onelibrary-goober/after/`): a recolour's `PCO2` and a grid edit's
@@ -996,10 +1363,15 @@ serialization path.** It enforces:
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
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
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
`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
@@ -1016,16 +1388,30 @@ serialization path.** It enforces:
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
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
byte-identically, that the job registry runs/fails/cancels, and that a
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
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
return, octave choice, and the loud off-beat hat and syncopated bassline that
each fooled one band on real music. Accuracy on REAL music is
each fooled one band on real music. Holding either half: a held BPM comes
back untouched (never snapped or re-octaved, a wrong one reports drift) with
the phase still found through the hat/bass traps; a held anchor comes back
untouched with the tempo detected, an off-beat one reported as drift. And
`plan_grid`'s every rule. Accuracy on REAL music is
`bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio).
- `test_key_detect.py` — key detection on SYNTHETIC cadences in all 24 keys
(I-IV-V-I / i-iv-V-i — a pop I-V-vi-IV is fairly called minor by an EDM
model), loudness / sample-rate invariance, None for silence, and the numpy
convolution against a direct implementation. Accuracy on real music is
`bench_key_detect.py`'s job (GiantSteps + any folder of key-tagged files).
- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse`
on SYNTHETIC audio with known sections (the intro with a kick is not a drop;
no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
@@ -1033,7 +1419,7 @@ serialization path.** It enforces:
collection — the previous implementation's route returned 500 on every call
for a week while its helper's tests passed.
- `test_grid_batch.py` — **batch analysis** from the context menu, both
`jobs.py` jobs shown in the status bar: Analyze Grid & BPM
`jobs.py` jobs shown in the status bar: Analyze… (BPM / Grid / Key)
(`POST /api/tracks/grid/auto-batch`) and Auto Hotcues…
(`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the
batch-only decisions: locked grids are skipped always, existing grids unless
@@ -1045,6 +1431,20 @@ serialization path.** It enforces:
returns its result; opening another library cancels the run. Each shares its
helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track
button.
Also BPM alone / Grid alone through `_analyse_grid` on a real Traktor copy:
the detector is asked to hold the right half, BPM alone retempos the marker
in place with its beat-1 cue untouched, Grid alone moves it (cue dragged
along) at the same tempo, and a TEMPO-only track gets one marker at it.
And **Analyze** (`POST /api/tracks/analyze` + `/analyze/preview`, the
dialog's BPM / Grid / Key; `grid/auto-batch` is now an alias of it with
BPM+Grid): nothing ticked 400s; Key alone sets keyless tracks, skips keyed
ones unless `replace_key`, never touches a grid; the preview's counts match
the run's (BPM alone: single grids adjusted, flexible skipped, bare in
full); a skipped track is never decoded and grid+key share ONE decode; a
grid that cannot be fitted still gets its key; the deck's Analyze writes
the key too and never fails on it. The decode is `main._decode_for_analysis`
(the seam the fakes replace); `test_key_detect.py` runs the route once with
the REAL decode and detectors on a generated F-minor 124 BPM WAV.
- `test_bulk_remove.py` — the context menu's **Remove ▸** routes
(`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`):
locked grids are kept, clearing hotcues empties the whole bank (loops and the
@@ -1061,7 +1461,11 @@ serialization path.** It enforces:
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
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
replaced was invisible: `/api/library/options` flattened every driver's
detections and returned `[0]`, so a plugged-in USB stick could be offered as
@@ -1071,6 +1475,11 @@ serialization path.** It enforces:
as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the
answer, and prefs are redirected to a temp file so a test can never rewrite
the user's last-opened library.
- `test_prefs.py` — `userprefs.json` under concurrent writes: 200 bursts of
simultaneous patches (plus a reader) keep every key and every patch; the
last-collection and path-mapping helpers lose nothing either; an unreadable
file is moved aside, not overwritten. Against the old unlocked code it fails
on the first trial.
- `test_exports.py` — export sets against a temp copy of the real collection.
Pins the things that would fail SILENTLY: a live reference picks up a playlist
edited AFTER curation; contents dedupe across playlists and loose tracks; a
@@ -1123,11 +1532,39 @@ serialization path.** It enforces:
reopen), and a running batch has stopped by the time discard returns; on
Rekordbox (temp copy, skipped when absent) the library is clean afterwards and
a later save writes nothing that was thrown away; read-only libraries 409.
- `test_remote_protocol.py` — pure: every `LibraryAdapter` member is an RPC or
excluded with a reason, every command is `MUTATING`, args/results survive
JSON by the protocol's types (tuples, dataclasses, `None`), a misspelt or
missing argument is refused, a prepared analysis crosses intact, the
version rule.
- `test_remote_server.py` — the server's own routes on a temp copy of the
collection with a FAKE clock: config refusals, 401s, one computer at a time
(423 without the token, 409 naming the holder and its batch, takeover kills
the old token, an expired lease frees it, the same client renews), leftover
edits named, save + history on the server, discard, confinement (`..`,
symlinks), uploads never overwrite and delete only their own, Range audio.
- `test_remote_adapter.py` — END TO END: a real server in a thread, the app's
routes opening it. Handshake refusals, fallback, the mirror, Save touching
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
stored in the mapping's stored form, takeover → read-only at once,
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:
the plan's transfer and two-machine space, Replace parks and swaps ON THE
SERVER (saved file untouched until Save, which deletes the parked
original), Discard restores, Cancel deletes only this run's uploads, a
takeover's uploads are reused without the engine.
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
imports another platform's library (checked on real imports via AST, so merely
naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately
**share** `pyrekordbox`: the rule is "no adapter reaches for a rival vendor's
library", and a shared dependency is not a breach.
library", and a shared dependency is not a breach. Also: `adapters/remote`
imports no platform adapter, and importing `konduktor.server` pulls in no
librosa / scikit-learn / torch / numba / PyAV.
Also validate the backend interactively at `http://localhost:8000/docs` and the
frontend at `http://localhost:5173`.
@@ -1136,14 +1573,25 @@ frontend at `http://localhost:5173`.
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
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins the
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin.
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
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
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` →
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`;
the Rekordbox adapter uses the new names. `db6` still works as a deprecated
alias and is **removed in 0.6.0**.
`onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
(`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
`models`, `BLOB` in `masterdb.database`).
**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
writes a timestamped `.bak` first (into a `backups/` folder next to the
collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the
@@ -1153,6 +1601,21 @@ frontend at `http://localhost:5173`.
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
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
@@ -1160,7 +1623,15 @@ frontend at `http://localhost:5173`.
e.g. `Macintosh HD/:Music/:one.mp3`. This is how playlist entries
(`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this.
- **Rating** = `RANKING / 51`, giving 0–5 stars (`_rating_stars`).
- **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation).
- **Key** = two fields. `INFO@KEY` is the display text Traktor shows and tags
files with, in the user's notation (Open Key `"10m"` in the real
collection); `<MUSICAL_KEY VALUE>` is the analysed key, pitch class + 12 for
minor (`12` = C minor = `10m`; 6,628 of 6,641 entries carrying both agree).
1,354 entries have ONLY `MUSICAL_KEY` — analysed, never given text — so
`projection.entry_key` falls back to it (rendered Open Key). `set_key` and
`add_entry` write BOTH, the text in the collection's majority notation
(`TraktorStore.key_notation()`; an empty collection — an export — takes a
Traktor-native source's own, so Traktor→Traktor keeps the user's).
- **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
(flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
@@ -1182,6 +1653,16 @@ frontend at `http://localhost:5173`.
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`
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`
is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and
have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`;
@@ -1353,7 +1834,8 @@ that number and nothing else — everything derives from it:
(`waveform.decode` → `analyse_samples` + `grid_detect`), in a first phase
that may be cancelled through `checkpoint` before the library is touched;
a file with no grid of its own gets Konduktor's (decided: arrive ready to
prep). Then `RekordboxStore.add_track` writes the row the way Rekordbox's
prep), and one with no key of its own a detected key
(`key_detect.with_detected_key`, from the same decode; OneLibrary too). Then `RekordboxStore.add_track` writes the row the way Rekordbox's
own add was MEASURED to (file facts, `DateCreated` from the file's birth
time, this library's device) and the grid/cues replay through
`replace_grid`/`set_cue`/`add_memory_cue` — memory cues and colours cross
@@ -1378,9 +1860,11 @@ that number and nothing else — everything derives from it:
that swap so `SaveBar` still saves collection edits. While a device'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
library. Lossiness follows the settled rule: memory cues become hot cues in
spare pads (earliest first), cue colour is dropped (Traktor derives it from
type).
library. Lossiness follows the settled rule: memory cues stay memory cues
(Traktor's `HOTCUE="-1"`; until 2026-10-16 they were promoted to spare
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
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,
@@ -1389,8 +1873,7 @@ that number and nothing else — everything derives from it:
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
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,
stem conversion. All format research — including the schema, which has no
rekordbox 7. Same gaps as Rekordbox: cover-art writing, 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).
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
are settled; see
@@ -1409,7 +1892,11 @@ that number and nothing else — everything derives from it:
**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.
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
real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`,
`<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a
@@ -1440,7 +1927,7 @@ that number and nothing else — everything derives from it:
deliberately NOT in the fixture, since they carry the machine's name and
UUIDs; those are generated fresh per export.
- **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.
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
@@ -1549,7 +2036,8 @@ that number and nothing else — everything derives from it:
0x2C060E. **Parity with the OneLibrary target is done and verified in
Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`,
`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
`_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes
cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with
@@ -1585,7 +2073,12 @@ that number and nothing else — everything derives from it:
**Key notation crosses via the wheel**, never by copying the string:
`projection.render_key()` is the inverse of `parse_key`, shared by both Pioneer
targets, so Traktor's `"10m"` becomes `"Cm"` rather than a literal `"10m"` in a
Pioneer library. **Caveat**: `djmdContent.FolderPath` is an ABSOLUTE host path,
Pioneer library. Both are now `core/musical_key`; until 2026-10-04
`render_key` spelt with SHARPS ("G#m", "D#", "C#m") where rekordbox's own rows
say "Abm", "Eb", "Dbm" — measured from the key rows rekordbox 7 created in
the local library. In-place writes (`set_key`, adds) find a key row by
MEANING, so a library's existing "12A" or "G#m" row is reused, never
duplicated. **Caveat**: `djmdContent.FolderPath` is an ABSOLUTE host path,
so unlike Traktor and OneLibrary a Rekordbox export is not portable by copying
the folder. Still unwritten and documented as unknown: OneLibrary's waveform
tags and the `cue` table's MPEG seek columns.
@@ -1651,6 +2144,16 @@ that number and nothing else — everything derives from it:
yet**, since nothing can be written. Note the OneLibrary work already demonstrated
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
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
(TrueNAS) holds a Traktor or Rekordbox library; the app opens it as
"Remote": browse, prep, edit, Save (versioned on the server), export sticks,
import by upload, Convert to Stems — all with analysis and separation on the
laptop. One computer at a time, with takeover. See "Remote libraries" under
Architecture. Not yet: verified on a real TrueNAS (the image is published by
CI's `server-image` job), a web UI served by the server (decided: not now).
- ⬜ Serato adapter
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
@@ -1743,6 +2246,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
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.
- `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
band, the beatgrid (per-segment white beats/brighter downbeats, plus marker
lines — gold for the one governing the playhead, accent otherwise, with the
+125 -197
View File
@@ -1,213 +1,141 @@
# Konduktor
<p align="center">
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
</p>
**A fast, modern home for your Traktor collection.**
<h1 align="center">Konduktor</h1>
Konduktor is a lightweight desktop-style app for DJs who run **Native
Instruments Traktor** (Pro 4 / NML v20). It opens your existing
`collection.nml`, gives you a beautiful dark library to explore, and lets you
build playlists and prep tracks — without launching the whole heavyweight
Traktor app just to tidy up your tags or drop a few cue points.
<p align="center">
<b>Prep your tracks and run your DJ libraries in one fast app.</b><br>
Traktor, Rekordbox, or the USB stick in your pocket.
</p>
Your collection stays exactly where it is. Konduktor reads and writes the same
file Traktor uses, so everything you do shows up next time you open Traktor.
<p align="center">
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
</p>
![Konduktor: the prep deck with a track loaded, above a playlist](docs/screenshots/library.png)
Konduktor opens the library you already have, in the format it already uses.
You can tidy tags, build playlists, set grids and cues, and pack a USB stick
for the gig without launching your full DJ software. When you open your DJ
software again, everything you changed is there.
---
## Why you'll like it
## One app for every library
- **Instant, searchable library.** Your whole collection loads into a snappy,
virtualized grid. Search, filter by genre / key / BPM / rating, and sort by
any column — all instant, no waiting.
- **Make it yours.** Show only the columns you care about, drag them into the
order you like, and resize them to fit. Your layout is remembered.
- **Edit tags without the ceremony.** Double-click any field to fix a title or
genre on the spot, click the stars to rate a track, or right-click for a full
tag + cover-art editor. Great for quick one-off fixes.
- **Playlists, the easy way.** Create, rename, and delete playlists, then
drag-and-drop to reorder or add tracks.
- **A real prep deck.** Load any track into the deck at the top and:
- play it with a **frequency-colored waveform** (Traktor-style Spectrum look),
scrolling under a fixed playhead with zoom in/out
- scratch it by dragging the waveform
- see and adjust the **beatgrid** and BPM
- set, jump to, and delete **hotcues** (with a color-coded 8-slot bar)
- build **loops** in fixed beat sizes, tied into the hotcue system
- use keyboard shortcuts: **Space** to play/pause, **1–8** to fire hotcues,
**Shift+1–8** to clear them
- **Your data is safe.** Every save makes a timestamped backup first, and only
ever touches the parts you changed — the rest of the file stays byte-for-byte
identical.
<img src="docs/screenshots/platforms.png" align="right" width="420" alt="Choosing a platform: Rekordbox, Traktor, OneLibrary or Remote">
- **Traktor** collections.
- **Rekordbox** libraries.
- **OneLibrary** USB sticks, the format CDJs read. Plug one in to browse it,
preview tracks off it, import them, or edit the stick directly.
- **Remote** libraries: keep your whole library and music on a home server and
open it from any laptop ([set up a server](docs/REMOTE-SERVER.md)).
- **Any folder or drive**: browse loose audio files, preview them, and add
them to your library.
Your library is never converted into a Konduktor database. Saves write back to
the original file and change only what you edited.
<br clear="right">
## A real prep deck
![The prep deck in beatgrid editing mode](docs/screenshots/deck.png)
- A scrolling waveform, coloured by frequency, with zoom, scratching and an
overview of the whole track.
- Eight hotcue pads with names, types and colours, plus beat loops, beat jump
and tap tempo.
- **Beatgrid editing**, including grids with tempo changes. Nudge, retempo,
halve or double without opening your DJ software.
- Keyboard shortcuts for the whole deck: Space to play, 1–8 for hotcues,
arrow keys to jump or move a loop.
## Stems, built in
![A stem file in the deck: drums, bass, synths and vocals each in their own lane](docs/screenshots/stems.png)
**Play stem files as stems.** Load a stem file and the deck splits into
drums, bass, synths and vocals, each drawn in its own lane. Click a lane's
button to mute it, Alt/Option-click to solo it, or use Q W E R.
**Convert to Stems.** In a Traktor collection, right-click any tracks and
choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and
beatgrid intact.
- The separation runs on your own computer, so your music isn't sent to an
online service.
- Replace the originals, or save the stems to a folder and add them as new
tracks.
- Convert a whole playlist in one go.
## Let it do the boring parts
| Auto Hotcues | Analyze |
|:---:|:---:|
| ![Auto Hotcues: choose an event for each pad](docs/screenshots/auto-hotcues.png) | ![Analyze: BPM, grid and key](docs/screenshots/analyze.png) |
| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. |
## Export to USB for CDJs, or other platforms
<img src="docs/screenshots/export.png" align="right" width="380" alt="An export set for OneLibrary, Traktor and Rekordbox">
Make an **export** in the sidebar, drag playlists onto it, and press Export.
One stick can carry a Traktor collection, a OneLibrary library for current
CDJs and a Rekordbox Device Library for older players, all sharing **one copy
of the audio**.
- Hotcues, memory cues, loops, grids, keys and cover art are converted for
each platform.
- Playlists stay linked: edit a playlist, re-export, and the stick catches up.
- Re-exports copy only what changed, so updating a stick is quick.
- Konduktor only ever clears a folder that it wrote itself.
<br clear="right">
## Your library is safe
- **Saves are surgical.** A Traktor save changes only the entries you edited.
The rest of the file stays byte-for-byte identical.
- **Backups and history.** Every Traktor save makes a backup first and is kept
in a version history that you can restore from in the app.
- **Nothing is written until you press Save.** Discard changes throws away
everything you did since your last save.
- Tag edits are also written into the audio files themselves, so other apps
see them too.
## And also
- A fast library with search, filters, sorting and columns you can rearrange,
even with thousands of tracks.
- Edit tags inline or in a full tag and cover-art editor.
- Drag and drop tracks onto playlists, exports or the deck, and drag playlists
to reorganise them.
- If you open a Traktor collection on a different computer or drive,
Konduktor finds the missing files for you.
---
## Getting started
## Get Konduktor
Konduktor runs as two small local servers (a Python backend and a web
frontend). Do the one-time setup, then start them — the same steps work on
macOS, Linux, and Windows.
Download the latest build from
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows.
### 1. Install (once)
> **First launch:** builds aren't notarised yet, so your OS will warn you the
> first time.
> **macOS:** right-click the app, choose **Open**, then **Open** again. If it
> still refuses, run `xattr -cr /Applications/Konduktor.app` once.
> **Windows:** click **More info → Run anyway**.
**Backend** — needs Python 3.11+. Create a virtual environment and install the
dependencies:
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
> `collection.nml` when it quits, which would overwrite your changes.
```bash
cd backend
python3 -m venv .venv # Windows: python -m venv .venv
```
Want to run it from source or build it yourself? See
[docs/BUILDING.md](docs/BUILDING.md).
Activate it, then install:
## License
```bash
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
cd ..
```
**Frontend** — needs Node 18+ (same on every platform):
```bash
cd frontend
npm install
cd ..
```
### 2. Run it (development)
Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`).
**macOS / Linux** — one command starts both:
```bash
./dev.sh
```
**Windows** — start each server in its own terminal:
```powershell
# Terminal 1 — backend
cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000
# Terminal 2 — frontend
cd frontend; npm run dev
```
Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a
server). This is the fastest way to try Konduktor or hack on it — the frontend
hot-reloads as you edit. To package a real double-clickable app instead, see
[Build a standalone app](#build-a-standalone-app-production) below.
### 3. Open your collection
On launch, Konduktor offers to:
- **Automatically** open the collection from your latest installed Traktor,
- reopen the **last collection** you used, or
- **browse** for a `collection.nml` yourself.
That's it — you're in.
---
## Build a standalone app (production)
Prefer a real double-clickable app over running the dev servers? Konduktor
packages into a native desktop app (via **Tauri**) that bundles the Python
backend as a sidecar — no terminal, no servers to start by hand.
### Extra prerequisites
On top of the Python 3.11+ and Node 18+ from above:
- **Rust** — install from <https://rustup.rs> (the app shell is Tauri/Rust).
- **PyInstaller** — into the backend venv:
`pip install -r backend/requirements-build.txt`
- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see
[BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup.
The build is a two-step recipe on both platforms: **freeze the backend into a
sidecar binary**, then **build the app**. The only difference is which sidecar
script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its
own OS (the app can't be cross-compiled).
### macOS / Linux
```bash
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd ..
# 2) Build the app
cd frontend && npx tauri build
```
The installer lands at
`frontend/src-tauri/target/release/bundle/dmg/Konduktor_<version>_aarch64.dmg`
(with the `.app` beside it).
### Windows
```powershell
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd ..
# 2) Build the app
cd frontend; npx tauri build
```
The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
walkthrough and Windows-specific notes.
> **First launch — getting past the OS security prompt.** Builds are
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
> the OS flags them the first time. This is expected — the app isn't damaged.
>
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
> quarantines — clear the quarantine flag once from Terminal:
> ```bash
> xattr -cr /Applications/Konduktor.app
> ```
> - **Windows:** click **More info → Run anyway** past SmartScreen.
>
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
> optimizer and the installer, giving you a runnable app in seconds — handy while
> iterating.
### Rebuilding after changes
Changed **backend** Python? Re-run the sidecar script for your OS
(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`.
Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you.
---
## Saving back to Traktor
Playlist edits, tag changes, and prep tweaks all apply live in the app. When
you're happy, hit **Save to Traktor** to write them to `collection.nml`.
> ⚠️ **Close Traktor before saving.** Traktor rewrites `collection.nml` when it
> quits, so if it's open it will overwrite your changes. Konduktor always writes
> a backup first (into a `backups/` folder next to your collection), but closing
> Traktor first is the safe habit.
Want to experiment risk-free? Point Konduktor at a *copy* of your collection and
play around.
---
## Good to know
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
and speaks Traktor's real file format — no import/export, no separate database.
- Run it in your browser from source, or package it into a native desktop app
(macOS `.dmg` / Windows `.msi`) that bundles the backend — see
[Build a standalone app](#build-a-standalone-app-production). A mobile version
is on the horizon.
- Under the hood: **FastAPI** (Python) backend + **React / TypeScript / Vite**
frontend. Curious about internals or contributing? See
[CLAUDE.md](CLAUDE.md) for the architecture and conventions.
[AGPL-3.0](LICENSE)
+7 -1
View File
@@ -6,6 +6,8 @@ compare rather than a pass/fail. Every open is read-only — nothing is saved.
python bench_grid_detect.py # the local Rekordbox library
python bench_grid_detect.py path/to/collection.nml path/to/master.db
python bench_grid_detect.py --legacy # score the old librosa beat_track
python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM
python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor
The reference is each track's own grid, and only single-marker grids are used:
a multi-marker grid is either a real tempo change (which a constant-tempo
@@ -102,6 +104,9 @@ def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("libraries", nargs="*", type=Path)
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
ap.add_argument("--hold", choices=("bpm", "anchor"),
help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's "
"'Grid' tick — phase is all that is scored) or its anchor ('BPM')")
args = ap.parse_args()
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
@@ -119,7 +124,8 @@ def main() -> int:
for name, audio, r0, rb in refs:
t0 = time.perf_counter()
try:
res = detect(str(audio))
hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
res = detect(str(audio), **hold)
except Exception as ex: # a failure is a data point, not a crash
print(f" FAIL {name[:48]:48} {ex}")
rows.append(None)
+172
View File
@@ -0,0 +1,172 @@
"""Benchmark key detection (`core/key_detect.py`).
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
compare rather than a pass/fail.
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
python bench_key_detect.py ~/Music # files with a key TAG
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
and the number to quote; the model never trained on it (see
`train_key_model.py`). A folder's key tags were written by some other
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
source) count once, by title.
Errors are classed the MIREX way, because they are not equally wrong for a
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
"""
from __future__ import annotations
import argparse
import os
import re
import sys
import warnings
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
warnings.filterwarnings("ignore")
from konduktor.core import key_detect, musical_key # noqa: E402
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
"""How a detected (wheel, mode) relates to the reference."""
(dw, dm), (rw, rm) = det, ref
if (dw, dm) == (rw, rm):
return "exact"
if dw == rw:
return "relative"
if dm == rm and (dw - rw) % 12 in (1, 11):
return "fifth"
if dm != rm:
major, minor = (dw, rw) if dm == "major" else (rw, dw)
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
return "parallel"
return "other"
def parse_any(text: str) -> tuple[int, str] | None:
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
w, m = musical_key.parse(text)
return (w, m) if w else None
def _tag_key(path: Path) -> tuple[str, str] | None:
import mutagen
try:
f = mutagen.File(path)
except Exception:
return None
if not f or not f.tags:
return None
t = f.tags
def has(name: str) -> bool:
try:
return name in t
except ValueError: # a Vorbis comment refuses an MP4-style atom name
return False
key = title = None
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
if has(name):
v = t[name]
v = v.text[0] if hasattr(v, "text") else v[0]
key = v.decode() if isinstance(v, bytes) else str(v)
break
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
if has(name):
v = t[name]
title = str(v.text[0] if hasattr(v, "text") else v[0])
break
return (key, title or path.stem) if key else None
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
seen, out = set(), []
for root in roots:
for dp, dirs, files in os.walk(root):
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
for name in sorted(files):
p = Path(dp) / name
if p.suffix.lower() not in AUDIO or name.startswith("."):
continue
tagged = _tag_key(p)
if not tagged or not (ref := parse_any(tagged[0])):
continue
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
if title not in seen:
seen.add(title)
out.append((p, ref, tagged[1]))
return out
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
out = []
for f in sorted((gs / "annotations/key").glob("*.key")):
audio = gs / "audio" / f"{f.stem}.mp3"
ref = parse_any(f.read_text()) # "C minor"
if audio.exists() and ref:
out.append((audio, ref, f.stem))
return out
def _detect(path: Path):
warnings.filterwarnings("ignore")
try:
r = key_detect.detect_key(str(path))
except Exception as ex: # an undecodable file is reported, not fatal
return None, str(ex)
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
def run(refs, label: str, verbose: bool) -> None:
with ProcessPoolExecutor() as ex:
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
rels, misses = [], []
for (path, ref, title), (det, err) in zip(refs, results):
if det is None:
print(f" could not analyse {title}: {err or 'silent / too short'}")
continue
rel = relation(det[:2], ref)
rels.append(rel)
if rel != "exact":
misses.append((title, ref, det, rel))
n = len(rels)
if not n:
print(f"{label}: nothing to score")
return
c = Counter(rels)
print(f"\n{label}: {n} tracks")
for k in WEIGHT:
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
if verbose:
for title, ref, det, rel in misses:
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
if __name__ == "__main__":
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
a = ap.parse_args()
if not a.folders and not a.giantsteps:
ap.error("give --giantsteps and/or folders")
if a.giantsteps:
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
if a.folders:
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
sys.exit(0)
+17 -10
View File
@@ -1,6 +1,7 @@
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
# tauri.conf.json bundles as a resource folder (`sidecar\` in the app).
# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\
#
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
# cd backend
@@ -15,13 +16,19 @@ Set-Location $Root
$Py = Join-Path $Root ".venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { $Py = "python" }
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
# native command's stderr into an error record, which "Stop" makes fatal on the
# first INFO line — so relax it for this call and judge by the exit code.
$ErrorActionPreference = "Continue"
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
$ErrorActionPreference = "Stop"
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
Write-Host "Built: $Root\dist\konduktor-sidecar\"
# Stage for Tauri: name with the host target triple + .exe so the shell plugin
# resolves it. (rustc must be on PATH.)
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
$Staged = Join-Path $Dest "konduktor-sidecar"
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
Write-Host "Staged: $Staged\"
+19 -23
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Build the frozen backend sidecar (single-file binary) with PyInstaller and
# stage it for Tauri as binaries/konduktor-sidecar-<target-triple>.
# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/…
# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage
# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which
# tauri.conf.json bundles as a resource folder (`sidecar/` in the app).
# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/
#
# One-time: pip install -r requirements-build.txt (into the backend venv).
set -euo pipefail
@@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
PY="${PY:-.venv/bin/python}"
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
echo "Built: $ROOT/dist/konduktor-sidecar"
echo "Built: $ROOT/dist/konduktor-sidecar/"
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
# fails with "different Team IDs" and the sidecar dies on launch (which makes
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this binary without re-signing it.
# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc
# signs the executable AND its collected libraries (Python, the .so/.dylib
# files) with a matching identity. Re-signing only some of them desyncs the
# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on
# launch (the app then shows "Konduktor couldn't start"). The app bundle is
# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this folder as a resource without re-signing it.
# Stage for Tauri: the sidecar must be named with the host target triple so the
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
if command -v rustc >/dev/null 2>&1; then
TRIPLE="$(rustc -vV | sed -n 's/host: //p')"
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE"
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
else
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
fi
# Stage for Tauri. Replace the whole folder so no file from an older build
# survives; `cp -R` keeps PyInstaller's symlinks as symlinks.
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
rm -rf "$DEST/konduktor-sidecar"
cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
echo "Staged: $DEST/konduktor-sidecar/"
@@ -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`.
+29 -5
View File
@@ -1,6 +1,14 @@
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
# build). Produces a single-file binary that serves the FastAPI API on a free
# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the
# executable plus `_internal/` — that serves the FastAPI API on a free loopback
# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
#
# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390
# native libraries) into a NEW temp folder on every launch, and macOS checks
# every library it has not seen before (XProtect / syspolicyd) as it is
# dlopen()ed, keyed per file — so every launch paid ~10 s before the window
# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once
# seen). Installed as a folder inside the app, they are checked once.
#
# The tricky bits this handles:
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
@@ -10,7 +18,7 @@
# - python-multipart is imported as `multipart` by starlette → hidden import
# - dulwich (version-history backups) imports git backends dynamically →
# collect_submodules('dulwich')
from PyInstaller.utils.hooks import collect_submodules, collect_all
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
hiddenimports = []
datas = []
@@ -31,6 +39,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"):
# Imported by name, not statically discoverable.
hiddenimports += ["multipart", "anyio"]
# A remote library's password lives in the OS keychain through `keyring`, which
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
# — so both the modules AND the package metadata that names them must ship.
hiddenimports += collect_submodules("keyring")
datas += copy_metadata("keyring")
# Bundle the canonical version file so konduktor.__version__ can read it at
# runtime from sys._MEIPASS (frontend/package.json is the single source of the
# app version — see konduktor/__init__.py). Path is relative to this spec.
@@ -54,6 +68,8 @@ datas += [
("konduktor/stems/engine.json", "konduktor/stems"),
("konduktor/stems/weights.json", "konduktor/stems"),
]
# The key-detection network's weights (konduktor/core/key_detect.py).
datas += [("konduktor/core/key_model.npz", "konduktor/core")]
a = Analysis(
["sidecar.py"],
@@ -74,9 +90,8 @@ pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
exclude_binaries=True,
name="konduktor-sidecar",
debug=False,
bootloader_ignore_signals=False,
@@ -89,3 +104,12 @@ exe = EXE(
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=False,
name="konduktor-sidecar",
)
@@ -21,12 +21,12 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from ..rekordbox import palette
from ..rekordbox import memory_palette, palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME
from . import capabilities as caps
@@ -193,6 +193,7 @@ class OneLibraryAdapter:
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
parents[node_id] = "root" if parent in ("0", "", "None") else parent
@@ -223,6 +224,9 @@ class OneLibraryAdapter:
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
"""Ignored: a drive's paths are relative to wherever it is mounted.
@@ -312,7 +316,7 @@ class OneLibraryAdapter:
`audio_path` is where `place_audio` said to copy it (or the file itself,
already on the stick); Save moves copies into place.
"""
from ...core import audio_tags, grid_detect, waveform
from ...core import audio_tags, grid_detect, key_detect, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
@@ -348,21 +352,23 @@ class OneLibraryAdapter:
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
export_track = ExportTrack(track=item.track, destination=audio,
# A file with no key of its own gets one, as it gets a grid.
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
export_track = ExportTrack(track=track, destination=audio,
cues=TrackCues(grid_markers=markers, cues=memory))
# Decoded once above; the writer must not decode it again.
export_track.waveform = lambda *, lead=0.0, m=measured: m
art = item.art or audio_tags.read_cover(audio)
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
length = item.track.length or (int(measured.duration) if measured else None)
prepared.append((item, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
length = track.length or (int(measured.duration) if measured else None)
prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, audio, rel, anlz, jpegs, markers, hot, length in prepared:
for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, item.track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else item.track.bpm, length=length)
audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else track.bpm, length=length)
for cue in hot:
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
cue_type="loop" if cue.length else "cue",
@@ -392,6 +398,12 @@ class OneLibraryAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -414,6 +426,10 @@ class OneLibraryAdapter:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
@@ -441,10 +457,8 @@ class OneLibraryAdapter:
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
raise Unsupported(
"Memory cues are shown but cannot be edited — only hot cues are writable"
)
# A memory cue has no slot to set; it has its own commands.
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
self._check_cue_type(cue_type)
self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
length_sec=length_sec, name=name)
@@ -478,6 +492,53 @@ class OneLibraryAdapter:
self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id)
# ---- commands: memory cues --------------------------------------------
@staticmethod
def _memory_byte(color: str | None) -> int:
if color is None:
return 0
code = memory_palette.code_for(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's memory cue colours")
return memory_palette.anlz_byte(code)
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.add_memory_cue(track_id, start_sec=start_sec, cue_type=cue_type,
length_sec=length_sec, name=name,
color_id=self._memory_byte(color))
return self._refresh_cues(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh_cues(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
# rekordbox has one point type, so there is nothing to choose; a memory
# cue is a cue or a loop by its length.
raise Unsupported("rekordbox memory cues have no type to change")
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.set_memory_cue_color(track_id, cue_id, self._memory_byte(color))
return self._refresh_cues(track_id)
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh_cues(track_id)
# ---- commands: beatgrid -----------------------------------------------
@staticmethod
def _markers_from(markers: list) -> list:
@@ -36,8 +36,8 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ..rekordbox import memory_palette, palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`).
@@ -61,10 +61,12 @@ def capabilities_for(
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does: projected and
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
# Memory cues, editable as in Rekordbox — in the ANLZ files, the
# way rekordbox 7 edits them on a stick (measured, kit M2).
memory_cues=True,
max_memory_cues=None,
max_memory_cues=MAX_MEMORY_CUES,
memory_color="palette",
memory_palette=list(memory_palette.SWATCHES),
types=WRITABLE_CUE_TYPES,
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
@@ -84,6 +86,7 @@ def capabilities_for(
# with it, at Save — so the library, not the user, places the audio.
addable=not read_only,
removable=not read_only,
key_writable=not read_only,
places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows
+24 -7
View File
@@ -37,7 +37,7 @@ from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import palette
from ..rekordbox import memory_palette, palette
log = logging.getLogger(__name__)
@@ -112,6 +112,13 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
slot = None if role == "memory" else hot_cue - 1
comment = getattr(entry, "comment", None)
if role == "memory":
# A memory cue's colour is byte 28 (`memory_palette`), not the hot-cue
# code + RGB tail, which stays zero on one.
color = (memory_palette.hex_for(memory_palette.from_anlz_byte(
int(getattr(entry, "color_id", 0) or 0))) if with_color else None)
else:
color = _color(entry) if with_color else None
return CuePoint(
name=(str(comment) or None) if comment else None,
type="loop" if length > 0 else "cue",
@@ -119,16 +126,26 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
start=start_ms / 1000.0,
length=length,
slot=slot,
color=_color(entry) if with_color else None,
# Hot cues are editable on a drive opened for editing (the caller says
# so). MEMORY cues never are — preserved-but-uneditable, as in the
# Rekordbox adapter (the two-platform rule).
editable=editable and role == "hotcue",
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
color=color,
# Editable on a drive opened for editing (the caller says so), memory
# cues included; browsing a device is read-only.
editable=editable,
readonly_reason=None if editable else "platform_managed",
grid_marker=None,
id=memory_cue_id(entry) if role == "memory" else None,
)
def memory_cue_id(entry) -> str:
"""A memory cue's `CuePoint.id`: its STORED position, kind and loop end.
Content-derived, so it is the same on every read and in both lists (`PCOB`
in the .DAT, `PCO2` in the .EXT, which order the same cues differently);
an index would not be. Two memory cues identical in all three are one cue
to `_dedupe` already, so the first match is the one meant."""
return f"m:{int(entry.time)}:{_entry_kind(getattr(entry, 'type', ENTRY_CUE))}:{int(getattr(entry, 'loop_time', NO_LOOP))}"
def _entries(anlz, tag_type: str) -> list:
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
@@ -49,7 +49,7 @@ class OneLibraryDriver:
def _has_onelibrary_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
+32 -14
View File
@@ -44,7 +44,8 @@ from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, palette, timebase
from ..rekordbox import artwork, memory_palette, palette, timebase
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key
from .capabilities import capabilities_for
@@ -121,7 +122,7 @@ class OneLibraryExporter:
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
@@ -359,15 +360,29 @@ class OneLibraryExporter:
too far along.
"""
out: list[dict] = []
for cue in (item.cues.cues if item.cues else []):
memory = 0
for cue in sorted(item.cues.cues if item.cues else [], key=lambda c: c.start):
is_loop = cue.type == "loop" or cue.length > 0
# A hot cue carries what Konduktor SHOWS — stored colour, else the
# type's (blue cue, green loop) — as a rekordbox palette CODE, which
# is what rekordbox draws from; "unset" draws its own defaults. A
# memory cue keeps rekordbox's own "unset".
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue))
is_memory = cue.role == "memory" or cue.slot is None
if is_memory:
# rekordbox keeps 10 (earliest first; the rest are dropped, per
# the lossiness rule). A memory cue's colour is PCP2 byte 28 from
# its own 8-colour palette — what Konduktor SHOWS (stored, else
# the type's), as for a hot cue; the hot-cue code + RGB stay zero.
if memory >= MAX_MEMORY_CUES:
continue
memory += 1
code, rgb = 0, (0, 0, 0)
color_id = memory_palette.anlz_byte(memory_palette.nearest_code(effective_color(cue)))
else:
# What Konduktor SHOWS — stored colour, else the type's (blue cue,
# green loop) — as a rekordbox palette CODE, which is what
# rekordbox draws from; "unset" draws its own defaults.
code, rgb = palette.code_for(effective_color(cue))
color_id = 0
out.append({
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1,
"color_id": color_id,
"hot_cue": 0 if is_memory else cue.slot + 1,
"kind": 2 if is_loop else 1,
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
@@ -381,7 +396,8 @@ class OneLibraryExporter:
# ---- playlists -----------------------------------------------------------
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
"""One folder named after the export, with the tree preserved under it.
"""The tree preserved — at the top level (parent NULL), or with
`payload.root_folder` under one folder named after the export.
`playlist` is a flat table with `playlist_id_parent`, so folders and
playlists are the same row kind told apart by `attribute` (1 = folder).
@@ -397,8 +413,8 @@ class OneLibraryExporter:
)
return next_id[0]
root = add(payload.name, None, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
root = add(payload.name, None, folder=True) if payload.root_folder else None
folders: dict[tuple[str, ...], int | None] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -427,8 +443,10 @@ class OneLibraryExporter:
)
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
#: both still write 4.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12}
@@ -0,0 +1,102 @@
"""Memory-cue edits on a track's two analysis files, the way rekordbox 7 makes them.
Pure functions over parsed `AnlzFile`s, so they are pinned byte for byte
against rekordbox's own edits (`fixtures/onelibrary-memory-edits`, kit M2,
2026-10-16) without a drive; the store adds the drive, the time base and Save.
A stick keeps memory cues ONLY in the analysis files — the database and both
pdbs keep every row — in two lists kept in OPPOSITE orders:
* `.DAT` `PCOB` memory: a new cue is PREPENDED, and the whole list is
relinked (`anlz_writer.relinked_memory_pcpts`: status 0, prev/next
indexes) on any add or delete; header field = count − 1.
* `.EXT` `PCO2` memory: a new cue is APPENDED in the compact 44-byte form;
every other entry keeps its bytes. The `.EXT`'s own `PCOB` memory list
stays empty.
A colour is `PCP2` byte 28 and a name the `PCP2` comment; neither touches the
`.DAT`. A cue is addressed by `cues.memory_cue_id` (stored time, kind, loop
end), which is the same in both lists.
"""
from __future__ import annotations
from ..rekordbox import anlz_file
from ..rekordbox import anlz_writer as W
from .cues import memory_cue_id
DAT_ORDER = ("PPTH", "PVBR", "PQTZ", "PWAV", "PWV2", "PCOB")
EXT_ORDER = ("PPTH", "PWV3", "PCOB", "PCO2")
def entries(f: anlz_file.AnlzFile, kind: str) -> list[bytes]:
"""The raw entries of a file's `kind` (PCOB / PCO2) MEMORY list."""
i = f.find(kind, anlz_file.LIST_MEMORY)
return anlz_file.raw_entries(f.tags[i]) if i is not None else []
def count(ext: anlz_file.AnlzFile) -> int:
return len(entries(ext, "PCO2"))
def _matches(entry: bytes, cue_id: str) -> bool:
return memory_cue_id(anlz_file.decode_entry(entry)) == cue_id
def _put(dat, ext, pcob: list[bytes] | None, pco2: list[bytes] | None) -> None:
if pcob is not None:
dat.put("PCOB", W.pcob_tag(anlz_file.LIST_MEMORY, W.relinked_memory_pcpts(pcob)),
list_kind=anlz_file.LIST_MEMORY, after=DAT_ORDER)
if pco2 is not None:
ext.put("PCO2", W.pco2_tag(anlz_file.LIST_MEMORY, pco2),
list_kind=anlz_file.LIST_MEMORY, after=EXT_ORDER)
def add(dat, ext, *, kind: int, time_ms: int, loop_ms: int | None, beats: int | None,
name: str | None = None, color_id: int = 0) -> None:
"""Add one memory cue (kind 1 cue, 2 loop): prepended to the `.DAT`'s list,
appended — compact unless named — to the `.EXT`'s."""
pcp2 = W.pcp2_compact_entry(kind=kind, time_ms=time_ms, loop_ms=loop_ms,
beats=beats, color_id=color_id)
if name:
pcp2 = anlz_file.entry_with_comment(pcp2, name)
pcpt = W.pcpt_entry(hot_cue=0, kind=kind, time_ms=time_ms, loop_ms=loop_ms)
_put(dat, ext, [pcpt] + entries(dat, "PCOB"), entries(ext, "PCO2") + [pcp2])
def _index(ext, cue_id: str) -> tuple[list[bytes], int | None]:
pco2 = entries(ext, "PCO2")
return pco2, next((n for n, e in enumerate(pco2) if _matches(e, cue_id)), None)
def rename(ext, cue_id: str, name: str | None) -> bool:
"""Rename in the `.EXT` only; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_comment(pco2[i], name)
_put(None, ext, None, pco2)
return True
def recolour(ext, cue_id: str, color_id: int) -> bool:
"""Byte 28 of the cue's `PCP2` entry, nothing else; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_color_id(pco2[i], color_id)
_put(None, ext, None, pco2)
return True
def delete(dat, ext, cue_id: str) -> bool:
"""Out of both lists (the `.DAT`'s relinked); False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
del pco2[i]
pcob = entries(dat, "PCOB")
j = next((n for n, e in enumerate(pcob) if _matches(e, cue_id)), None)
if j is not None:
del pcob[j]
_put(dat, ext, pcob if j is not None else None, pco2)
return True
@@ -1,6 +1,6 @@
"""OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed:
@@ -114,7 +114,7 @@ def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
`cues` are already generic — see `store.cues` for why that boundary sits
where it does — so this is the assembly point rather than a translation.
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
`capabilities.writable` says so at the library level.
Each cue already says whether it is editable (the store knows whether the
drive was opened for editing or is only being browsed).
"""
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
+141 -20
View File
@@ -1,7 +1,7 @@
"""The retained native model for a OneLibrary drive.
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
with a **different and universal key**: every OneLibrary drive from every vendor
@@ -54,8 +54,9 @@ from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.model import CuePoint
from ... import paths
from . import beatgrid, cues as cue_reader
from . import beatgrid, cues as cue_reader, memory_cues
from ..rekordbox import anlz_file, palette, timebase
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox import anlz_writer as W
from ..rekordbox import beatgrid as rb_beatgrid
from .layout import DriveLayout
@@ -133,8 +134,8 @@ class OneLibraryStore(ReplaceGridCommands):
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating", "release_date"}
# Written into the audio file's own tags at Save, as rekordbox does when it
# edits a stick (measured: the title reached the MP3's TIT2, the rating did
# not). Everything editable except the rating.
FILE_TAG_FIELDS = EDITABLE_FIELDS - {"rating"}
# not). Everything editable except the rating, plus the key `set_key` sets.
FILE_TAG_FIELDS = (EDITABLE_FIELDS - {"rating"}) | {"key"}
def __init__(self, path: Path, *, read_only: bool = False):
layout = DriveLayout.locate(Path(path))
@@ -170,10 +171,10 @@ class OneLibraryStore(ReplaceGridCommands):
def _load(self) -> None:
"""Copy the drive's database into app-data and open the copy."""
try:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
except ImportError as ex: # pragma: no cover — dependency missing
raise LibraryNotSupported(
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
"Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
) from ex
_clear_stale_work()
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
@@ -186,7 +187,7 @@ class OneLibraryStore(ReplaceGridCommands):
sidecar = self.path.with_name(self.path.name + suffix)
if sidecar.is_file() and sidecar.stat().st_size:
shutil.copyfile(sidecar, working.with_name(working.name + suffix))
db = DeviceLibraryPlus(str(working))
db = OneLibrary(str(working))
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
shutil.rmtree(work, ignore_errors=True)
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
@@ -206,7 +207,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""Release the working copy and delete it.
The drive itself is never held open (see the module docstring); the copy
is, and `DeviceLibraryPlus.close()` only unregisters events, so the
is, and `OneLibrary.close()` only unregisters events, so the
session and engine are closed here explicitly.
"""
db, self._db = self._db, None
@@ -316,7 +317,7 @@ class OneLibraryStore(ReplaceGridCommands):
image_id = getattr(self.content(track_id), "image_id", None)
if not image_id:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
@@ -456,7 +457,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""
if not name:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
model = getattr(models, model_name)
pk = f"{model.__tablename__}_id"
@@ -490,6 +491,34 @@ class OneLibraryStore(ReplaceGridCommands):
pass
raise InvalidCommand(f"Release date must be a year or YYYY-MM-DD, got {text!r}")
def _key_id(self, wheel: int | None, mode: str | None) -> int | None:
"""The `key` row for a key, found by what it MEANS: a stick's table holds
rekordbox's names ("Abm") beside imported tag text ("12A" — the goober
fixture has both), so a rendered-name match would duplicate a key the
stick already has. A new key gets rekordbox's own spelling."""
if wheel is None or mode is None:
return None
from pyrekordbox.onelibrary import models
from ..rekordbox.projection import parse_key, render_key
for k in self._require_db().query(models.Key).all():
if parse_key(k.name) == (wheel, mode):
return int(k.key_id)
return self._lookup_id("Key", render_key(wheel, mode))
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
db = self._require_db()
row = self.content(track_id)
before = row.key_id
row.key_id = self._key_id(wheel, mode)
self._journal.record("track", "set", track_id, "key", before, row.key_id)
# A foreign key: flush + expire, or re-projecting reads the old name.
db.flush()
db.session.expire(row)
def set_track_metadata(self, track_id: str, fields: dict) -> None:
from sqlalchemy import text
@@ -539,7 +568,7 @@ class OneLibraryStore(ReplaceGridCommands):
# ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str):
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
try:
pid = int(node_id)
@@ -551,14 +580,14 @@ class OneLibraryStore(ReplaceGridCommands):
return row
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
rows = [r for r in rows if r.playlist_id != excluding]
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
name = (name or "").strip()
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
@@ -603,7 +632,7 @@ class OneLibraryStore(ReplaceGridCommands):
def delete_playlist(self, node_id: str) -> None:
"""Delete a playlist, or a folder WITH everything in it, and close the gap
its `sequenceNo` leaves among its siblings."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
row = self._playlist(node_id)
@@ -624,9 +653,48 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children, renumbering
`sequenceNo` from 0 in both parents as create and delete do. The
Device Library's playlist tree follows at Save (`device_library`
mirrors parent and sort from these rows)."""
db = self._require_db()
row = self._playlist(node_id)
dest = 0
if parent_id:
folder = self._playlist(parent_id)
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
raise InvalidCommand("A playlist can only be moved into a folder")
dest = int(folder.playlist_id)
ancestor = folder
while ancestor is not None:
if int(ancestor.playlist_id) == int(row.playlist_id):
raise InvalidCommand("A folder cannot be moved into itself")
up = int(ancestor.playlist_id_parent or 0)
ancestor = self._playlist(str(up)) if up else None
source = int(row.playlist_id_parent or 0)
siblings = self._siblings(dest, excluding=row.playlist_id)
index = max(0, min(int(index), len(siblings)))
order = siblings[:index] + [row] + siblings[index:]
if source == dest and [r.playlist_id for r in order] == [
r.playlist_id for r in self._siblings(dest)
]:
return str(row.playlist_id)
row.playlist_id_parent = dest
for n, r in enumerate(order):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
if source != dest:
for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
db.flush()
self._journal.record("playlist", "move", row.name)
return str(row.playlist_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in order, numbered from 1 (measured)."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
playlist = self._playlist(node_id)
@@ -849,6 +917,60 @@ class OneLibraryStore(ReplaceGridCommands):
self._replace_hot(track_id, hot, None, None)
self._journal.record("cue", "delete", track_id, f"slot:{slot}")
# ---- memory cues -------------------------------------------------------
# The list edits — and what rekordbox was measured doing — are in
# `memory_cues`; here: the drive, the time base, the cap and the journal.
MAX_MEMORY_CUES = MAX_MEMORY_CUES # rekordbox stops storing at 10, silently (measured)
def _memory_files(self, track_id: str):
dat, ext = self._editing(track_id)
self._ensure_pco2(dat, ext)
return dat, ext
def add_memory_cue(self, track_id: str, *, start_sec: float, cue_type: str,
length_sec: float = 0.0, name: str | None = None,
color_id: int = 0) -> None:
"""Add a memory cue (a memory loop with a length) the way rekordbox does.
`color_id` is `PCP2` byte 28 (`memory_palette.anlz_byte`), 0 = none."""
from .export import _loop_beats
if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track")
dat, ext = self._memory_files(track_id)
if memory_cues.count(ext) >= self.MAX_MEMORY_CUES:
raise InvalidCommand(
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
)
is_loop = cue_type == "loop" and length_sec > 0
off = self._offset(track_id)
time_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000))
loop_ms = int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000)) if is_loop else None
grid = self.anlz_grid(track_id)
beats = (_loop_beats(start_sec, length_sec, list(zip(grid[2], grid[1], grid[0])))
if is_loop and grid else None)
memory_cues.add(dat, ext, kind=2 if is_loop else 1, time_ms=time_ms, loop_ms=loop_ms,
beats=beats, name=name, color_id=color_id)
self._journal.record("cue", "add", track_id, "memory")
def _memory_edit(self, track_id: str, cue_id: str, op: str, edit) -> None:
dat, ext = self._memory_files(track_id)
if not edit(dat, ext):
raise NotFound(f"No memory cue {cue_id!r} on this track")
self._journal.record("cue", op, track_id, "memory")
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
self._memory_edit(track_id, cue_id, "modify",
lambda _d, ext: memory_cues.rename(ext, cue_id, name))
def set_memory_cue_color(self, track_id: str, cue_id: str, color_id: int) -> None:
self._memory_edit(track_id, cue_id, "modify",
lambda _d, ext: memory_cues.recolour(ext, cue_id, color_id))
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
self._memory_edit(track_id, cue_id, "delete",
lambda dat, ext: memory_cues.delete(dat, ext, cue_id))
def hot_slots(self, track_id: str) -> set[int]:
"""Occupied 0-based slots (pending edits included)."""
return {c.slot for c in self.cues(track_id) if c.role == "hotcue" and c.slot is not None}
@@ -1026,7 +1148,6 @@ class OneLibraryStore(ReplaceGridCommands):
"""
from sqlalchemy import text
from ..rekordbox.projection import render_key
from .export import ANALYSED_BITS, CONTENT_LINK, _audio_format, _file_type, _kbps, art_files
if rel in (self._by_id or {}) or any(self.track_id(r) == rel for r in self.iter_content()):
@@ -1070,7 +1191,7 @@ class OneLibraryStore(ReplaceGridCommands):
"album": lookup("Album", track.album), "genre": lookup("Genre", track.genre),
"label": lookup("Label", track.label),
# Rendered from the parsed wheel: a source's "10m" means nothing here.
"key": lookup("Key", render_key(track.key_wheel, track.key_mode)),
"key": self._key_id(track.key_wheel, track.key_mode),
"image": image_id, "comment": track.comment or "",
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
@@ -1312,9 +1433,9 @@ class OneLibraryStore(ReplaceGridCommands):
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
def _reopen_working(self, work: Path) -> None:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work
self._db, self._work = OneLibrary(str(work / self.path.name)), work
self._content_cache = None
self._by_id = None
@@ -1375,7 +1496,7 @@ class OneLibraryStore(ReplaceGridCommands):
t = projection.to_track(self.content(track_id))
return {"title": t.title, "artist": t.artist, "album": t.album, "genre": t.genre,
"label": t.label, "remixer": t.remixer, "comment": t.comment,
"release_date": t.release_date}
"release_date": t.release_date, "key": t.key}
def _prune_empty(folder: Path, *, stop: Path) -> None:
+114 -26
View File
@@ -21,13 +21,14 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import palette, projection, timebase
from . import memory_palette, palette, projection, timebase
from ...core import add_analysis
from .store import RekordboxStore
@@ -171,6 +172,7 @@ class RekordboxAdapter:
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
@@ -202,6 +204,9 @@ class RekordboxAdapter:
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
# The FILE decides a track's media kind, and the mapping moves files.
@@ -215,6 +220,10 @@ class RekordboxAdapter:
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def set_write_stored_paths(self, enabled: bool) -> None:
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
self._store.set_write_stored_paths(enabled)
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
@@ -245,6 +254,12 @@ class RekordboxAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
@@ -262,6 +277,10 @@ class RekordboxAdapter:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
@@ -284,12 +303,8 @@ class RekordboxAdapter:
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# Rekordbox is the ONLY platform with memory cues, so under the
# two-platform promotion rule they stay preserved-but-uneditable:
# they are projected and shown, never written.
raise Unsupported(
"Memory cues are shown but cannot be edited — only hot cues are writable"
)
# A memory cue has no slot to set; it has its own commands.
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
self._check_cue_type(cue_type)
self._store.set_cue(
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
@@ -320,6 +335,53 @@ class RekordboxAdapter:
self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id)
# ---- commands: memory cues --------------------------------------------
def _memory_code(self, color: str | None) -> int | None:
if color is None:
return None
code = memory_palette.code_for(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's memory cue colours")
return code
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.add_memory_cue(
track_id, start_sec=start_sec, cue_type=cue_type, length_sec=length_sec,
name=name, color_code=self._memory_code(color),
)
return self._refresh_cues(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh_cues(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
# rekordbox has one point type, so there is nothing to choose; a memory
# cue is a cue or a loop by its length.
raise Unsupported("rekordbox memory cues have no type to change")
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.set_memory_cue_color(track_id, cue_id, self._memory_code(color))
return self._refresh_cues(track_id)
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh_cues(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._require_writable("Placing cues")
for cue in cues:
@@ -382,6 +444,12 @@ class RekordboxAdapter:
def dirty(self) -> bool:
return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._journal.summary()
def save(self):
self._require_writable("Saving")
return self._store.save()
@@ -416,6 +484,14 @@ class RekordboxAdapter:
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
def analysis_lead(self, audio: Path) -> float:
"""The time-base lead `add_tracks` measures a file's waveform with —
rekordbox's clock against the decoded audio, read from the file's
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
not analyse what it adds has none, and whoever prepares an analysis
for this one (a client of a server-held library) asks for it."""
return timebase.offset(Path(audio))
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
@@ -437,7 +513,7 @@ class RekordboxAdapter:
bank or already taken becomes a memory cue at the same position rather
than being dropped.
"""
from ...core import audio_tags, grid_detect, waveform
from ...core import audio_tags
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
@@ -453,22 +529,29 @@ class RekordboxAdapter:
if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}")
held.add(str(audio))
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
if item.analysis is not None:
# Measured by whoever added it — a library held by a server is
# never asked to decode audio (see `PreparedAnalysis`).
analysed = item.analysis
if not markers:
markers = list(analysed.markers)
else:
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
detect=not markers,
detect_key=item.track.key_wheel is None)
markers = markers or list(analysed.markers)
measured = analysed.measured
# A file with no key of its own gets one, as it gets a grid
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
track = add_analysis.with_key(item.track, analysed.key)
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, audio, measured, markers, art[0] if art else None))
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
added: list[str] = []
for item, audio, measured, markers, art in prepared:
for item, track, audio, measured, markers, art in prepared:
track_id = self._store.add_track(
audio, item.track, measured=measured, with_grid=bool(markers), art=art)
audio, track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), (),
stem=self._store.is_stem(track_id)))
if markers:
@@ -481,20 +564,25 @@ class RekordboxAdapter:
def _place_imported_cues(self, track_id: str, cues) -> None:
"""Hot cues on their own pads; memory cues — and a hot cue with no
free pad — as memory cues. Colour as the nearest palette swatch."""
free pad — as memory cues, up to rekordbox's 10 (earliest first; the
rest are dropped, per the lossiness rule). Colour as the nearest swatch
of the palette the cue lands in: a hot cue's 16, a memory cue's 8."""
taken: set[int] = set()
memory = 0
for cue in sorted(cues.cues or [], key=lambda c: c.start):
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
code, _rgb = palette.code_for(cue.color)
common = dict(start_sec=cue.start, cue_type=cue_type,
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), color_code=code or None)
name=getattr(cue, "name", None))
slot = cue.slot if cue.role == "hotcue" else None
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
self._store.set_cue(track_id, slot=slot, **common)
code, _rgb = palette.code_for(cue.color)
self._store.set_cue(track_id, slot=slot, color_code=code or None, **common)
taken.add(slot)
else:
self._store.add_memory_cue(track_id, **common)
elif memory < self._store.MAX_MEMORY_CUES:
self._store.add_memory_cue(
track_id, color_code=memory_palette.nearest_code(cue.color), **common)
memory += 1
def remove_tracks(self, track_ids: list[str]) -> int:
# What goes with a track was measured in Rekordbox 7 — see the store.
@@ -158,6 +158,9 @@ class CueEntry:
color_green: int | None = None
color_blue: int | None = None
len_entry: int = 0
#: `PCP2` byte 28: a MEMORY cue's colour, 1-based, 0 = none (also present
#: in the compact 44-byte form, which has no hot-cue colour tail).
color_id: int = 0
def raw_entries(tag: Tag) -> list[bytes]:
@@ -197,6 +200,35 @@ def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> byt
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
def entry_color_id(entry: bytes) -> int:
"""A `PCP2` entry's byte 28 — a MEMORY cue's colour, 1-based, 0 = none."""
return entry[28] if len(entry) > 28 and entry[:4] == b"PCP2" else 0
def entry_with_color_id(entry: bytes, value: int) -> bytes:
"""A `PCP2` entry with ONLY byte 28 changed — what rekordbox does to recolour
a memory cue (measured: that one byte, in any entry length, compact too)."""
return entry[:28] + bytes([value & 0xFF]) + entry[29:]
def entry_with_comment(entry: bytes, name: str | None) -> bytes:
"""A `PCP2` entry renamed, every other byte kept.
Measured on a memory loop (rekordbox 7, 2026-10-16): the comment goes in at
byte 44 as UTF-16BE plus a NUL, `len_comment` (byte 40) counts it, and the
entry GROWS by exactly that much — 88 -> 100 for "Loopy" — the colour tail
and padding following it unchanged. A compact 44-byte entry has no tail, so
it first takes a full entry's (4 colour bytes + 40 zeros); that case is
unmeasured."""
if len(entry) < 44:
raise AnlzError("A PCP2 entry shorter than 44 bytes has no comment field")
old_len = struct.unpack_from(">I", entry, 40)[0]
tail = entry[44 + old_len:] if len(entry) > 44 else bytes(44)
comment = (name.encode("utf-16-be") + b"\0\0") if name else b""
head = entry[:8] + struct.pack(">I", 44 + len(comment) + len(tail)) + entry[12:40]
return head + struct.pack(">I", len(comment)) + comment + tail
def entry_without_loop_beats(entry: bytes) -> bytes:
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
@@ -245,7 +277,8 @@ def _pco2(data: bytes) -> list[CueEntry]:
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 16]
time, loop = struct.unpack_from(">II", data, off + 20)
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n,
color_id=data[off + 28] if n > 28 else 0)
if n >= 44:
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
colour_at = off + 44 + len_comment
@@ -315,7 +315,7 @@ def flat_preview_tags() -> list[bytes]:
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
comment: str | None = None) -> bytes:
comment: str | None = None, color_id: int = 0) -> bytes:
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
Two constants in here are rekordbox's, not the documented struct's: the
@@ -328,6 +328,9 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
Konduktor's reader and pyrekordbox's agree with. No reference cue carries
one, so that detail is documented rather than measured. The entry stays the
exported 88 bytes unless the name needs more.
`color_id` is byte 28: a MEMORY cue's colour, 1-based (`memory_palette`),
0 = none. A hot cue's colour is the code + RGB tail instead.
"""
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
red, green, blue = rgb or (0, 0, 0)
@@ -336,7 +339,7 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, length, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
0, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
# The colour is the palette CODE, then RGB: rekordbox draws from the code
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
@@ -344,6 +347,41 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
)
#: rekordbox's COMPACT `PCP2` entry: the first 44 bytes of a full one — no
#: comment and no colour tail. What rekordbox 7 appends when it ADDS a memory cue
#: on a stick (measured 2026-10-16, `fixtures/onelibrary-memory-edits`).
PCP2_COMPACT_LEN = 44
def pcp2_compact_entry(*, kind: int, time_ms: int, loop_ms: int | None,
beats: int | None, color_id: int = 0, hot_cue: int = 0) -> bytes:
"""A compact 44-byte `PCP2` entry, byte for byte as rekordbox 7 writes one
for a memory cue it adds: the same fields as `pcp2_entry` up to
`len_comment` (0), including the `1000` and the `1` after byte 28."""
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, PCP2_COMPACT_LEN, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, 0,
)
def relinked_memory_pcpts(entries: list[bytes]) -> list[bytes]:
"""A `PCOB` MEMORY list's entries with their link fields rewritten, as
rekordbox 7 leaves them after ANY add or delete (measured 2026-10-16,
`fixtures/onelibrary-memory-edits`): status (bytes 16-19) 0, and bytes 24-27 the
previous / next entry's INDEX IN THE LIST, 0xFFFF at either end — so every
entry changes when one is added or removed. rekordbox's exports agree on any
list of two or more; a lone exported entry is status 4, 0xFFFF/0xFFFF."""
n = len(entries)
out = []
for i, e in enumerate(entries):
prev = i - 1 if i > 0 else 0xFFFF
nxt = i + 1 if i < n - 1 else 0xFFFF
out.append(e[:16] + struct.pack(">I", 0) + e[20:24] + struct.pack(">HH", prev, nxt) + e[28:])
return out
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
@@ -378,18 +416,25 @@ def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
return pcob_tag(cue_type, [
entries = [
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
])
]
if cue_type == 0 and len(entries) > 1:
# A memory list of two or more is linked, status 0 — what rekordbox's
# own exports (two test sticks) and edits hold. A lone entry keeps the
# status 4 / 0xFFFF form the reference export pins.
entries = relinked_memory_pcpts(entries)
return pcob_tag(cue_type, entries)
def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
return pco2_tag(cue_type, [
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0), comment=c.get("comment"))
code=c.get("code", 0), comment=c.get("comment"),
color_id=c.get("color_id", 0))
for c in chosen
])
@@ -30,8 +30,8 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import palette
from .cue_types import WRITABLE_CUE_TYPES
from . import memory_palette, palette
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps
@@ -55,18 +55,19 @@ def capabilities_for(
writable=not cloud_synced,
readonly_cause="cloud_synced" if cloud_synced else None,
cues=CueCapabilities(
# Hot cues are writable: djmdCue rows plus the contentCue JSON
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
# Rekordbox is the only platform that has them, and the two-platform
# promotion rule says a one-platform concept does not become an
# editing feature.
# Hot AND memory cues are writable: djmdCue rows plus the
# contentCue JSON mirror, kept in step (memory cues: measured
# 2026-10-16, kit M1).
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# Rekordbox is the only platform with memory cues, so they are
# projected and PRESERVED but not editable (two-platform rule).
memory_cues=True,
max_memory_cues=None, # unlimited
# rekordbox stops storing at 10, silently; the store refuses the 11th.
max_memory_cues=MAX_MEMORY_CUES,
# A memory cue's colour is its own 8-colour palette (`Color`, not
# `ColorTableIndex`) — see `memory_palette`.
memory_color="palette",
memory_palette=list(memory_palette.SWATCHES),
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's 16 swatches (all
@@ -91,6 +92,7 @@ def capabilities_for(
media_kinds=["audio", "stem"],
removable=True,
addable=True,
key_writable=True,
artwork=False,
artwork_note=None,
),
@@ -36,6 +36,10 @@ has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
from __future__ import annotations
MEMORY_KIND = 0
#: rekordbox stores at most this many memory cues per track — on the computer
#: AND on a stick — and enforces it SILENTLY (measured 2026-10-16: MEMORY simply
#: stops storing), so Konduktor refuses the next one itself, with a reason.
MAX_MEMORY_CUES = 10
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
CUE_TYPES = ["cue", "loop"]
@@ -198,8 +198,9 @@ class RekordboxDeviceExporter:
@staticmethod
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
"""The tree under one folder named after the export, as the other
targets build it. `sort_order` is a node's position among its siblings."""
"""The tree as the other targets build it — at the top level (parent
0), or with `payload.root_folder` under one folder named after the
export. `sort_order` is a node's position among its siblings."""
tree: list[bytes] = []
entries: list[bytes] = []
next_id = [0]
@@ -220,7 +221,7 @@ class RekordboxDeviceExporter:
index += 1
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
root = add(payload.name, 0, folder=True)
root = add(payload.name, 0, folder=True) if payload.root_folder else 0
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
+23 -13
View File
@@ -58,7 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from . import new_content, palette
from . import memory_palette, new_content, palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
@@ -125,7 +125,7 @@ class RekordboxExporter:
)
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
# OneLibrary drive uses a universal key shared across vendors, and
# master.db does not. Mixing them up produces a database Rekordbox
# cannot open, and pyrekordbox rejects the wrong one outright.
@@ -199,24 +199,31 @@ class RekordboxExporter:
from .adapter import RekordboxAdapter
adapter = RekordboxAdapter(library)
# The store, not the adapter's commands: the adapter refuses memory cues
# (editing them in a user's library is off-limits) and takes no colour.
# Building a NEW library is neither an edit nor lossy by choice, so the
# exporter writes both — through the same `_write_cue` every edit uses.
# The store, not the adapter's commands: the adapter's set_cue takes no
# colour and its memory-cue command takes only a swatch. A NEW library
# maps any source colour to the nearest one instead — through the same
# `_write_cue` every edit uses.
store = adapter._store
try:
for item in payload.tracks:
track_id = ids.get(item.source_id)
if track_id is None or not item.cues:
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:
# rekordbox's own "unset" for a memory cue with no colour.
code, _rgb = palette.code_for(cue.color)
# rekordbox keeps 10 (earliest first; the rest are
# dropped, per the lossiness rule). Colour: what
# Konduktor SHOWS — stored, else the type's — as the
# nearest of the memory palette's 8, as for a hot cue.
if memory >= store.MAX_MEMORY_CUES:
continue
store.add_memory_cue(
track_id, start_sec=cue.start, cue_type=cue.type,
length_sec=cue.length, name=cue.name, color_code=code or None,
length_sec=cue.length, name=cue.name,
color_code=memory_palette.nearest_code(effective_color(cue)),
)
memory += 1
continue
# What Konduktor SHOWS — stored colour, else the type's (blue
# cue, green loop) — as a palette code, which is what
@@ -383,9 +390,12 @@ class RekordboxExporter:
# ---- playlists ---------------------------------------------------------------
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
"""The tree, under one folder named after the export."""
root = db.create_playlist_folder(payload.name)
db.flush()
"""The tree — at the top level, or with `payload.root_folder` under one
folder named after the export (None = the top level)."""
root = None
if payload.root_folder:
root = db.create_playlist_folder(payload.name)
db.flush()
folders: dict[tuple[str, ...], object] = {(): root}
for playlist in payload.playlists:
@@ -0,0 +1,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
@@ -5,65 +5,32 @@ The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
"""
from __future__ import annotations
import re
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, palette, timebase
from .cue_types import cue_type, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
# Open Key notation. Parsing that is platform knowledge and belongs here.
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
# Camelot wheel position for each pitch class, per mode.
_CAMELOT_MINOR = {
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
"F": 4, "C": 5, "G": 6, "D": 7,
}
_CAMELOT_MAJOR = {
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
"F": 7,
}
from . import beatgrid, memory_palette, palette, timebase
from .cue_types import cue_type, kind_for, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
# holds whatever text a track's key TAG carried when it was imported, so a real
# stick has "12A" beside "Abm". Parsing therefore accepts every notation.
def parse_key(key: str | None) -> tuple[int | None, str | None]:
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
if not key:
return None, None
m = _KEY_RE.match(key.strip())
if not m:
return None, None
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
pitch = letter + (accidental.replace("B", "b") if accidental else "")
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
n = table.get(pitch)
return (n, "minor" if minor else "major") if n else (None, None)
"""(Camelot wheel position 1-12, mode) for a key name in any notation."""
return musical_key.parse(key)
# The inverse, for EXPORT. A track arriving from Traktor carries `key` as
# The inverse, for writing. A track arriving from Traktor carries `key` as
# Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed
# position — so writing the string verbatim into a Pioneer library would show
# "10m" where the deck expects "Abm". Rendering from the wheel is the only
# correct crossing. Shared with the OneLibrary exporter: same vendor, same
# notation, and two tables would drift.
_MINOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MINOR.items()))}
_MAJOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MAJOR.items()))}
# "10m" where the deck expects "Cm". Rendering from the wheel is the only
# correct crossing. Shared by the adapter and both Pioneer exporters.
def render_key(wheel: int | None, mode: str | None) -> str | None:
"""A Pioneer-style key name ("Abm", "F") for a Camelot position + mode.
"""A Pioneer key name ("Abm", "F") for a Camelot position + mode, spelt as
rekordbox spells its own (flats; see `core/musical_key`).
Returns None when the position is unknown, which is honest: a made-up key is
worse than a blank one, and Pioneer software shows blanks without complaint.
"""
if not wheel or not (1 <= wheel <= 12):
return None
if mode == "minor":
name = _MINOR_NAMES.get(wheel)
return f"{name}m" if name else None
return _MAJOR_NAMES.get(wheel)
return musical_key.render(wheel, mode, "musical")
def _iso_date(value) -> str | None:
@@ -173,10 +140,10 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
`editable` says whether the adapter will accept a command on THIS cue, which
is the only thing the UI gates on. Every hot cue is editable, loops included.
**Memory cues are not**: Rekordbox is the only platform that has them, so
under the two-platform promotion rule they are shown and never written. A cue
sitting on the reserved `Kind` occupies no pad and is projected the same way,
because that is how Rekordbox itself displays one.
So is every memory cue (`Kind` 0), addressed by its row id (`CuePoint.id`)
since it has no pad. A cue sitting on the reserved `Kind` 4 occupies no pad
either and is SHOWN as a memory cue, because that is how Rekordbox itself
displays one — but it is not one, so it is not editable.
"""
markers: list[GridMarker] = []
if grid is not None:
@@ -191,7 +158,9 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
length = 0.0
if out_msec is not None and out_msec > 0:
length = max(0.0, (out_msec - in_msec) / 1000.0)
editable = role == "hotcue"
memory = role == "memory"
# Kind 4 (reserved) displays as a memory cue but is not one.
editable = not memory or getattr(c, "Kind", None) == kind_for("memory", None)
cues.append(
CuePoint(
name=(getattr(c, "Comment", None) or None),
@@ -202,15 +171,27 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
start=timebase.from_pioneer(in_msec / 1000.0, time_offset),
length=length,
slot=slot,
color=_cue_color(c),
color=_memory_cue_color(c) if memory else _cue_color(c),
editable=editable,
readonly_reason=None if editable else "platform_managed",
grid_marker=None,
# A memory cue is addressed by its row id (`CuePoint.id`).
id=str(c.ID) if memory and editable and getattr(c, "ID", None) is not None else None,
)
)
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
def _memory_cue_color(row) -> str | None:
"""A memory cue keeps its 0-based `memory_palette` code in `Color` (-1 and
255 = none). A row Konduktor wrote before that was measured carries a
hot-cue code in `ColorTableIndex` instead; read it rather than lose it."""
colour = memory_palette.hex_for(getattr(row, "Color", None))
if colour is None and (getattr(row, "OutMsec", -1) or -1) <= 0:
colour = palette.hex_for(getattr(row, "ColorTableIndex", None))
return colour
def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
+222 -18
View File
@@ -46,9 +46,9 @@ from ...core.adapter import (
)
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping
from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot
from ...core.pathmap import PathMapping, stored_form
from . import memory_palette, timebase
from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__)
@@ -117,6 +117,8 @@ class RekordboxStore(ReplaceGridCommands):
def __init__(self, path: Path):
self.path = Path(path)
self._mapping = PathMapping()
# Write an added file in the library's STORED form (`pathmap.stored_form`).
self._write_stored_paths = False
self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
self._journal = EditJournal()
# Grid edits buffered until save(): ANLZ files are written to disk, so
@@ -375,6 +377,14 @@ class RekordboxStore(ReplaceGridCommands):
def set_path_mapping(self, mapping: PathMapping) -> None:
self._mapping = mapping or PathMapping()
def set_write_stored_paths(self, enabled: bool) -> None:
self._write_stored_paths = bool(enabled)
def _stored(self, audio: Path) -> Path:
if not self._write_stored_paths:
return Path(audio)
return stored_form(Path(audio), [self._mapping])
def is_stem(self, track_id: str) -> bool:
"""Whether the track's FILE is a native-instruments stem file — read
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
@@ -506,6 +516,46 @@ class RekordboxStore(ReplaceGridCommands):
self._db.flush()
self._db.session.expire(row)
# ---- writes: musical key ---------------------------------------------
def _key_id(self, wheel: int | None, mode: str | None) -> str | None:
"""The `djmdKey` row for a key, found by what it MEANS, not its text.
A library's key table holds rekordbox's own names ("Abm") and whatever
key tags imported ("12A"), so matching on a rendered name would add a
second row for a key the library already has. Only a key it has never
seen gets a row — created as rekordbox creates its own (measured on the
local library, which rekordbox fills lazily as it analyses): named in
its spelling, `Seq` NULL, and through the ORM so `commit()` stamps the
row's `rb_local_usn` like any other change. (The exporters' raw insert
would leave it unstamped.)"""
from .projection import parse_key, render_key
if wheel is None or mode is None:
return None
for k in self._db.query(self._tables.DjmdKey).all():
if parse_key(k.ScaleName) == (wheel, mode):
return str(k.ID)
row = self._tables.DjmdKey(
ID=str(uuid.uuid4().int % 2_147_483_647),
ScaleName=render_key(wheel, mode),
UUID=str(uuid.uuid4()),
)
self._db.add(row)
self._db.flush()
return str(row.ID)
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
row = self.content(track_id)
before = row.KeyID
row.KeyID = self._key_id(wheel, mode)
self._journal.record("track", "set", track_id, "key", before, row.KeyID)
# A foreign key, like artist: flush + expire, or the re-projection
# reads the old key back through the cached relationship.
self._db.flush()
self._db.session.expire(row)
# ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str):
t = self._tables
@@ -558,6 +608,79 @@ class RekordboxStore(ReplaceGridCommands):
self._db.delete_playlist(row)
self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s visible children.
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
parent", so nothing can be moved to the top level with it. The same
writes are made here — `ParentID`, the moved row's `updated_at`, and
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
share the table and the numbering, so `index` is placed relative to
the VISIBLE siblings and the hidden ones keep their order around it."""
import datetime
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
t = self._tables
row = self._playlist(node_id)
dest = self._playlist(parent_id) if parent_id else None
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
raise InvalidCommand("A playlist can only be moved into a folder")
ancestor = dest
while ancestor is not None:
if str(ancestor.ID) == str(row.ID):
raise InvalidCommand("A folder cannot be moved into itself")
up = str(ancestor.ParentID or "root")
ancestor = None if up in ("root", "0", "") else self._playlist(up)
def children(key: str) -> list:
return (
self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.ParentID == key)
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdPlaylist.Seq)
.all()
)
old_key = str(row.ParentID or "root")
new_key = str(dest.ID) if dest is not None else "root"
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
index = max(0, min(int(index), len(visible)))
if index < len(visible):
at = siblings.index(visible[index])
else:
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
order = siblings[:at] + [row] + siblings[at:]
if old_key == new_key and [str(c.ID) for c in order] == [
str(c.ID) for c in children(new_key)
]:
return str(row.ID)
row.ParentID = new_key
with self._db.registry.disabled():
row.updated_at = datetime.datetime.now()
for n, c in enumerate(order, start=1):
if c.Seq != n:
c.Seq = n
if old_key != new_key:
for n, c in enumerate(
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
):
if c.Seq != n:
c.Seq = n
xml = getattr(self._db, "playlist_xml", None)
if xml is not None:
try:
xml.update(row.ID, parent_id=new_key)
except ValueError:
pass # a playlist the XML never listed: nothing to keep in step
self._db.flush()
self._journal.record("playlist", "move", row.Name)
return str(row.ID)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in the given order.
@@ -604,14 +727,15 @@ class RekordboxStore(ReplaceGridCommands):
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
in the `.DAT` for `replace_grid` to fill."""
from . import new_content
from .projection import render_key
audio = Path(audio)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
t = self._tables
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count():
raise InvalidCommand(f"The library already holds {audio}")
stored = self._stored(audio)
for form in {str(audio), str(stored)}:
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=form).count():
raise InvalidCommand(f"The library already holds {audio}")
facts = _file_facts(audio)
content = self._db.add_content(
str(audio),
@@ -633,11 +757,14 @@ class RekordboxStore(ReplaceGridCommands):
content.AlbumID = new_content.lookup(self._db, "album", track.album)
content.GenreID = new_content.lookup(self._db, "genre", track.genre)
content.LabelID = new_content.lookup(self._db, "label", track.label)
# Rendered from the wheel, never copied: the source's notation is not
# Rekordbox's ("10m" is "Cm" here).
content.KeyID = new_content.lookup(
self._db, "key", render_key(track.key_wheel, track.key_mode))
# From the wheel, never the source's text: its notation is not
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
content.ContentLink = new_content.CONTENT_LINK
if stored != audio:
# pyrekordbox reads the file where it IS; the row names it as the
# library stores every other path (the server's mapping, inverted).
content.FolderPath = str(stored)
track_uuid = str(content.UUID)
rel = new_content.anlz_rel(track_uuid)
@@ -1020,6 +1147,25 @@ class RekordboxStore(ReplaceGridCommands):
)
self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}")
MAX_MEMORY_CUES = MAX_MEMORY_CUES # see `cue_types`
def memory_cue_rows(self, track_id: str) -> list:
"""A track's memory cues (`Kind` 0), in row order."""
t = self._tables
return list(
self._db.session.query(t.DjmdCue)
.filter(t.DjmdCue.ContentID == str(track_id))
.filter(t.DjmdCue.Kind == kind_for("memory", None))
.filter(t.DjmdCue.rb_local_deleted == 0)
)
def _memory_cue_row(self, track_id: str, cue_id: str):
"""The memory cue whose `djmdCue.ID` is `cue_id` (`CuePoint.id`)."""
row = next((c for c in self.memory_cue_rows(track_id) if str(c.ID) == str(cue_id)), None)
if row is None:
raise NotFound(f"No memory cue {cue_id!r} on this track")
return row
def add_memory_cue(
self,
track_id: str,
@@ -1029,23 +1175,59 @@ class RekordboxStore(ReplaceGridCommands):
length_sec: float = 0.0,
name: str | None = None,
color_code: int | None = None,
enforce_cap: bool = True,
) -> None:
"""Add a MEMORY cue (`Kind` 0) — for the exporter building a new library.
"""Add a MEMORY cue (`Kind` 0); a memory loop when `length_sec` > 0.
The adapter never calls this: editing memory cues in a user's library
stays refused under the two-platform promotion rule. A new export is not
an edit, and dropping the source's memory cues would lose prep.
`color_code` is a 0-based `memory_palette` code — NOT a hot-cue palette
code: a memory cue keeps its colour in `Color`, not `ColorTableIndex`.
`enforce_cap` refuses the 11th (an edit); the exporter, building a
library from a source that may hold more, trims before calling.
"""
if enforce_cap and len(self.memory_cue_rows(track_id)) >= self.MAX_MEMORY_CUES:
raise InvalidCommand(
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
)
self._write_cue(
track_id, None, kind=kind_for("memory", None), start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
)
self._journal.record("cue", "add", track_id, "memory")
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
"""A memory cue's name is rekordbox's `Comment`; only that column changes."""
cue = self._memory_cue_row(track_id, cue_id)
is_loop = (cue.OutMsec or 0) > 0
# An unnamed memory LOOP is '' (measured); an unnamed point cue NULL.
cue.Comment = name or ("" if is_loop else None)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, "memory")
def set_memory_cue_color(self, track_id: str, cue_id: str, color_code: int | None) -> None:
"""Recolour a memory cue; None = rekordbox's "No Color" (255, measured)."""
cue = self._memory_cue_row(track_id, cue_id)
self._apply_memory_color(cue, color_code, (cue.OutMsec or 0) > 0, cleared=True)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, "memory")
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
"""Delete the row outright, as rekordbox does (never `rb_local_deleted`)."""
cue = self._memory_cue_row(track_id, cue_id)
self._db.delete(cue)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "delete", track_id, "memory")
def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str,
length_sec: float, name: str | None, color_code: int | None) -> None:
"""Fill one `djmdCue` row (a new one when `cue` is None) and resync the
`contentCue` mirror — the single definition of a cue row's fields."""
`contentCue` mirror — the single definition of a cue row's fields.
`color_code` is a hot-cue palette code on a hot cue and a 0-based
`memory_palette` code on a memory cue (`Kind` 0): the two keep their
colour in different columns."""
if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track")
row = self.content(track_id)
@@ -1090,8 +1272,13 @@ class RekordboxStore(ReplaceGridCommands):
cue.BeatLoopSize = None
cue.ActiveLoop = None
cue.CueMicrosec = None
self._apply_color(cue, color_code, is_loop)
cue.Comment = name or None
if kind == kind_for("memory", None):
self._apply_memory_color(cue, color_code, is_loop)
# Measured: an unnamed memory LOOP has Comment '', a point cue NULL.
cue.Comment = name or ("" if is_loop else None)
else:
self._apply_color(cue, color_code, is_loop)
cue.Comment = name or None
self._db.flush()
self._sync_content_cue(track_id)
@@ -1113,6 +1300,21 @@ class RekordboxStore(ReplaceGridCommands):
cue.Color = -1
cue.ColorTableIndex = None
@staticmethod
def _apply_memory_color(cue, code: int | None, is_loop: bool, *, cleared: bool = False) -> None:
"""A MEMORY cue's colour columns (measured 2026-10-16, kit M1): the
0-based `memory_palette` code in `Color`, `ColorTableIndex` untouched by
colour — NULL on a point cue, 0 on a loop (rekordbox's loop marker).
Uncoloured is -1 on a new point cue, 255 on a loop and on any cue set
back to "No Color" (`cleared`)."""
cue.ColorTableIndex = 0 if is_loop else None
if code is not None:
cue.Color = int(code)
elif cleared or is_loop:
cue.Color = memory_palette.CLEARED
else:
cue.Color = -1
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
colour columns, so the position does not take a time-base round trip."""
@@ -1181,11 +1383,13 @@ class RekordboxStore(ReplaceGridCommands):
"""
t = self._tables
row = self.content(track_id)
# In ROW order, as rekordbox writes it (measured: a memory cue added at
# 1:55 is listed after older ones at 2:04 and 3:26), not by position.
cues = (
self._db.session.query(t.DjmdCue)
.filter(t.DjmdCue.ContentID == str(track_id))
.filter(t.DjmdCue.rb_local_deleted == 0)
.order_by(t.DjmdCue.InMsec)
.order_by(text("djmdCue.rowid"))
.all()
)
fields = (
@@ -0,0 +1,99 @@
"""Remote libraries: a library held by a Konduktor server, opened from here.
NOT a registered driver: a remote is not a file `can_open` could probe, and it
is chosen from the picker's own "Remote" step, by the saved remote's id. What
opening one returns is everything `AppState.open_remote` installs — the
adapter, the services that keep history and export sets on the server, and the
session that keeps this computer's hold on it.
Imports no platform adapter (`test_layering.py`): what platform the server
holds is the server's business, and reaches this side only as capabilities.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from ... import exports
from . import config
from .adapter import RemoteAdapter
from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch
from .services import RemotePending, RemoteServices, RemoteSetStore
from .session import RemoteSession
__all__ = [
"AuthFailed", "InUse", "Opened", "RemoteAdapter", "SessionLost", "Unreachable",
"VersionMismatch", "handshake", "open_remote",
]
@dataclass
class Opened:
remote: config.Remote
path: Path
adapter: RemoteAdapter
services: RemoteServices
session: RemoteSession
library_id: str
pending: object | None
#: Edits another computer left unsaved: {machine, summary}, or None.
pending_edits: dict | None
def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=None,
password: str | None = None, cache=None) -> Opened:
"""Connect, take the session, and mirror the library. Raises `InUse` when
another computer holds it (and `takeover` is not set), `AuthFailed`,
`VersionMismatch` or `Unreachable` — all before anything is installed."""
secret = password if password is not None else config.password(remote.id)
if not secret:
raise AuthFailed("No password is saved for this remote — edit it to enter one")
client = RemoteClient(remote, secret)
try:
client_id = config.client_id()
hello = client.hello(client_id)
machine = config.machine_name()
acquired = client.acquire(client_id, machine, takeover=takeover)
session = RemoteSession(client, batch_probe=batch_probe, identity=(client_id, machine))
adapter = RemoteAdapter(client, session, hello, cache=cache)
session.on_reacquired = adapter.refresh
except Exception:
client.release()
client.close()
raise
# The server's id for the library, namespaced: this computer's export-set
# store for it is the SERVER (`RemoteSetStore`), and nothing this computer
# keeps under the server's own id may be mistaken for it.
library_id = f"remote:{hello['library_id']}"
exports.use_store(library_id, RemoteSetStore(client))
session.start()
return Opened(
remote=remote, path=Path(hello.get("path") or remote.name), adapter=adapter,
services=RemoteServices(client), session=session, library_id=library_id,
pending=RemotePending(client), pending_edits=acquired.get("pending_edits"),
)
def handshake(remote: config.Remote, password: str) -> list[dict]:
"""Try each of the remote's addresses on its own: what a Save of the
remote's settings reports. Each result is {address, url, ok, error, kind},
`kind` one of ok / unreachable / auth / version / other."""
results = []
for label, url in remote.addresses():
single = config.Remote(id=remote.id, name=remote.name, host=url, username=remote.username)
client = RemoteClient(single, password, timeout=8.0)
try:
info = client.hello()
results.append({"address": label, "url": url, "ok": True, "error": None, "kind": "ok",
"name": info.get("name"), "platform": info.get("platform")})
except Unreachable as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "unreachable"})
except AuthFailed as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "auth"})
except VersionMismatch as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "version"})
except Exception as ex: # noqa: BLE001 — anything else is that address's answer
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "other"})
finally:
client.close()
return results
@@ -0,0 +1,530 @@
"""`RemoteAdapter`: a library held by a Konduktor server, as a `LibraryAdapter`.
Everything above the adapter layer — routes, export, import, batches, the UI —
works on a remote library unchanged, because this IS the adapter: the server
holds the native model (`konduktor.server`), and every command travels to it
over `remote_protocol`.
* **The projection is mirrored here.** The server's tracks are fetched once
into a local `TrackIndex`, and each command's answer carries the tracks it
changed — so filtering, sorting, facets and stats are as instant as on a
local library, and use the SAME query code (`core/query.py`). Every answer
carries the server's revision; a gap (an answer out of order, a reconnect)
re-fetches the whole projection rather than guessing.
* **`audio_path` downloads.** It must return a readable file on THIS
computer, so it fetches the track into the shared cache (`cache.py`).
Anything that only needs to know WHICH file a track is asks `audio_facts`,
which never downloads.
* **Read-only when the session is not ours** — taken over, or the server out
of reach — through `capabilities()`, so the UI gates itself as it does for
any read-only library. A command the server refuses for that reason (423)
turns the session `taken_over` on the spot, not at the next heartbeat.
"""
from __future__ import annotations
import base64
import threading
from pathlib import Path
from ... import remote_protocol as rp
from ...core.adapter import (
AudioFacts,
FileTagResult,
NotFound,
SaveOutcome,
Unavailable,
Unsupported,
)
from ...core.capabilities import Capabilities
from ...core.query import TrackIndex
from .cache import RemoteAudioCache, StaleFacts
from .cache import shared as shared_cache
from .client import RemoteClient, SessionLost
from .folder import ServerFile, ServerFiles
from .session import RemoteSession
_NOT_HERE = "A remote library's paths are the server's configuration"
class RemoteAdapter:
def __init__(self, client: RemoteClient, session: RemoteSession, hello: dict, *,
cache: RemoteAudioCache | None = None):
self.platform = hello["platform"]
self.path = Path(hello.get("path") or "")
self.hello = hello
self.client = client
self.session = session
self.cache = cache or shared_cache()
self._index = TrackIndex()
self._lock = threading.RLock()
self._rev: int | None = None
self._caps: tuple[int, Capabilities] | None = None
self._facts: dict[str, AudioFacts] = {}
#: Server path of an upload → (the local file it came from, its analysis lead).
self._uploads: dict[str, tuple[Path, float | None]] = {}
#: Content-folder files a listing returned, by their server path.
self._listed: dict[str, ServerFile] = {}
#: `str(Path(p))` → `p` for every server path this side has turned into
#: a `Path` (an upload's target, a listed file): on Windows that
#: conversion rewrites the separators, and the server must get its own
#: spelling back.
self._server_paths: dict[str, str] = {}
self._dirty = bool(hello.get("dirty"))
self._load()
# ---- following the server ---------------------------------------------------
def _load(self) -> None:
envelope = self.client.rpc("tracks")
with self._lock:
self._index.rebuild(list(envelope["result"]))
self._rev = envelope["rev"]
self._facts.clear()
self._caps = None
def _apply(self, envelope: dict) -> None:
"""Fold a command's answer into the mirror — or re-fetch on any gap."""
with self._lock:
rev = envelope.get("rev")
if envelope.get("reset") or self._rev is None or rev != self._rev + 1:
in_order = False
else:
in_order = True
from ...core.model import Track
removed = set(envelope.get("removed") or [])
if removed:
self._index.rebuild([t for t in self._index.tracks if t.id not in removed])
for raw in envelope.get("changed") or []:
track = Track.model_validate(raw)
self._index.add(track)
self._facts.pop(track.id, None)
for track_id in removed:
self._facts.pop(track_id, None)
self._rev = rev
if not in_order:
self._load()
def _call(self, method: str, /, **args):
try:
envelope = self.client.rpc(method, **args)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
if rp.RPC[method].mutating:
self.session.reached()
self._apply(envelope)
return envelope["result"]
def refresh(self) -> None:
"""Re-read everything from the server (after a restore, a reconnect)."""
self._load()
# ---- identity -----------------------------------------------------------------
def capabilities(self) -> Capabilities:
with self._lock:
cached = self._caps
if cached is None or cached[0] != self._rev:
try:
caps = self._call("capabilities")
except Unavailable:
# Out of reach: the last answer, read-only (below) — the UI
# must still render, and gate every edit.
if cached is None:
raise
caps = cached[1]
else:
with self._lock:
self._caps = (self._rev, caps)
else:
caps = cached[1]
if self.session.writable:
return caps
return caps.model_copy(update={"writable": False, "readonly_cause": self.session.readonly_cause})
def reload(self) -> None:
# The server is what holds (and drops) the edits — `AppState.discard`
# asks it to discard first; this is the mirror following.
self._load()
# ---- read projection (the mirror) -------------------------------------------
@property
def tracks(self):
return self._index.tracks
def track(self, track_id: str):
return self._index.get(track_id)
def query_tracks(self, **kw):
return self._index.query_tracks(**kw)
def facets(self):
return self._index.facets()
def stats(self, playlist_count: int):
return self._index.stats(playlist_count)
# ---- read projection (the server) -------------------------------------------
def playlist_tree(self):
return self._call("playlist_tree")
def playlist_count(self) -> int:
return self._call("playlist_count")
def playlist_entries(self, node_id: str):
return self._call("playlist_entries", node_id=node_id)
def playlist_tracks(self, node_id: str):
entries = self.playlist_entries(node_id)
if entries is None:
return None
return [t for k in entries if (t := self._index.get(k)) is not None]
def track_cues(self, track_id: str):
return self._call("track_cues", track_id=track_id)
@property
def dirty(self) -> bool:
try:
self._dirty = self._call("dirty")
except Unavailable:
pass # out of reach: what it was
return self._dirty
# ---- commands -------------------------------------------------------------------
def create_playlist(self, name, parent_id=None):
return self._call("create_playlist", name=name, parent_id=parent_id)
def create_folder(self, name, parent_id=None):
return self._call("create_folder", name=name, parent_id=parent_id)
def rename_playlist(self, node_id, name):
return self._call("rename_playlist", node_id=node_id, name=name)
def delete_playlist(self, node_id):
return self._call("delete_playlist", node_id=node_id)
def move_playlist(self, node_id, parent_id, index):
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
def set_playlist_entries(self, node_id, track_ids):
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
def remove_tracks(self, track_ids):
return self._call("remove_tracks", track_ids=list(track_ids))
def set_track_metadata(self, track_id, fields):
return self._call("set_track_metadata", track_id=track_id, fields=fields)
def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
def set_cue_type(self, track_id, slot, cue_type):
return self._call("set_cue_type", track_id=track_id, slot=slot, cue_type=cue_type)
def set_cue_color(self, track_id, slot, color):
return self._call("set_cue_color", track_id=track_id, slot=slot, color=color)
def delete_cue(self, track_id, slot):
return self._call("delete_cue", track_id=track_id, slot=slot)
def place_cues(self, track_id, cues, *, overwrite=False):
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
def add_memory_cue(self, track_id, *, start_sec, cue_type, length_sec=0.0, name=None, color=None):
return self._call("add_memory_cue", track_id=track_id, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color=color)
def rename_memory_cue(self, track_id, cue_id, name):
return self._call("rename_memory_cue", track_id=track_id, cue_id=cue_id, name=name)
def set_memory_cue_type(self, track_id, cue_id, cue_type):
return self._call("set_memory_cue_type", track_id=track_id, cue_id=cue_id, cue_type=cue_type)
def set_memory_cue_color(self, track_id, cue_id, color):
return self._call("set_memory_cue_color", track_id=track_id, cue_id=cue_id, color=color)
def delete_memory_cue(self, track_id, cue_id):
return self._call("delete_memory_cue", track_id=track_id, cue_id=cue_id)
def add_grid_marker(self, track_id, start_sec, bpm=None):
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
def move_grid_marker(self, track_id, index, start_sec):
return self._call("move_grid_marker", track_id=track_id, index=index, start_sec=start_sec)
def set_grid_marker_bpm(self, track_id, index, bpm):
return self._call("set_grid_marker_bpm", track_id=track_id, index=index, bpm=bpm)
def delete_grid_marker(self, track_id, index):
return self._call("delete_grid_marker", track_id=track_id, index=index)
def replace_grid(self, track_id, markers):
return self._call("replace_grid", track_id=track_id, markers=_pairs(markers))
def set_analysed_grid(self, track_id, markers):
return self._call("set_analysed_grid", track_id=track_id, markers=_pairs(markers))
def delete_grid(self, track_id):
return self._call("delete_grid", track_id=track_id)
def set_grid_lock(self, track_id, locked):
return self._call("set_grid_lock", track_id=track_id, locked=locked)
# ---- adding tracks ------------------------------------------------------------------
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
"""Send `source` into `folder` on the server; the path it landed at (a
taken name gets `-2`…, as a local copy does). What a local import's
file copy becomes when the library's destination is the server's."""
try:
landed = self.client.upload(Path(source), folder, name, progress=progress)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
self._server_paths[str(Path(landed["path"]))] = landed["path"]
return Path(landed["path"])
def free_space(self, path: str) -> int:
"""Free space on the SERVER's disk at `path` (an import's destination)."""
return self.client.fs_space(path)
def delete_upload(self, path) -> None:
"""Undo `upload_audio` (a cancelled or failed import)."""
key = self._server_key(path)
self._uploads.pop(key, None)
self.client.delete_upload(key)
def _server_key(self, path) -> str:
text = str(path)
return self._server_paths.get(text, text)
def add_tracks(self, items, *, checkpoint=None):
"""Add uploaded files. Where the platform analyses what it adds (the
server said so with an analysis lead), the analysis is done HERE, on
the copy this computer uploaded — the server never decodes audio."""
from ...core import add_analysis
wire = []
total = len(items)
keys = [self._server_key(item.audio_path) for item in items]
# Files already in the content folder (added in place): the server says
# whether the platform analyses, and only then is the file fetched.
in_place = [k for k, item in zip(keys, items)
if item.analysis is None and k not in self._uploads and k in self._listed]
leads = self.client.folder_leads(in_place) if in_place else {}
for n, (item, key) in enumerate(zip(items, keys), start=1):
source, lead = self._uploads.get(key, (None, None))
analysis = item.analysis
if analysis is None and source is None and leads.get(key) is not None:
lead = leads[key]
if checkpoint is not None:
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
source = self.folder_audio(key)
if analysis is None and lead is not None and source is not None:
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
has_grid = bool(item.cues and item.cues.grid_markers)
analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid,
detect_key=item.track.key_wheel is None)
art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \
if item.art else None
wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art,
analysis=rp.pack_analysis(analysis)))
if checkpoint is not None:
checkpoint(f"Adding {total} track{'' if total == 1 else 's'} on the server",
step=total, of=total)
try:
envelope = self.client.rpc("add_tracks", items=wire, timeout=None)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._apply(envelope)
for key in keys:
self._uploads.pop(key, None)
return envelope["result"]
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
raise Unsupported("A remote library's stem files are swapped in on the server")
# ---- Convert to Stems (the library side lives on the server) ---------------------
# `stems/remote_convert.py` drives these: the server plans and swaps, this
# computer separates. See the server's stem routes for why.
def stems_plan(self, body: dict) -> dict:
return self.client.stems_plan(body)
def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int,
duration: float, progress=None) -> dict:
import hashlib
digest = hashlib.sha256()
with open(local, "rb") as f:
while chunk := f.read(1 << 20):
digest.update(chunk)
try:
return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(),
bit_rate=bit_rate, duration=duration, progress=progress)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
def abandon_stems(self, targets: list[str]) -> None:
self.client.stems_abandon(targets)
def publish_stems(self, items: list[dict], options: dict) -> dict:
try:
result = self.client.stems_publish(items, options)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._load() # ids changed (repoint) or entries were added
return result
# ---- metadata / art ------------------------------------------------------------------
def set_cover_art(self, track_id, data, mime):
try:
envelope = self.client.put_art(track_id, data, mime)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._apply({**envelope, "removed": [], "reset": False})
def cover_art(self, track_id):
return self.client.art(track_id)
# ---- audio ------------------------------------------------------------------------------
def audio_facts(self, track_ids):
wanted = list(dict.fromkeys(track_ids))
with self._lock:
missing = [t for t in wanted if t not in self._facts]
if missing:
found = {}
for start in range(0, len(missing), 2000):
found.update(self._call("audio_facts", track_ids=missing[start:start + 2000]))
with self._lock:
self._facts.update(found)
with self._lock:
return {t: self._facts[t] for t in wanted if t in self._facts}
def audio_path(self, track_id, *, progress=None):
"""A local copy of the track's audio, downloaded if this computer has
none of this version. None when the server has no file for it."""
for attempt in range(2):
facts = self.audio_facts([track_id]).get(track_id)
if facts is None:
return None
cached = self.cache.get(facts)
if cached is not None:
return cached
try:
return self.cache.fetch(
facts, lambda partial: self.client.download(track_id, partial, progress=progress))
except StaleFacts:
with self._lock:
self._facts.pop(track_id, None)
if attempt:
raise
return None
def cached_audio(self, track_id) -> Path | None:
"""The local copy if there already is one — never downloads."""
facts = self.audio_facts([track_id]).get(track_id)
return self.cache.get(facts) if facts else None
# ---- the content folder, browsed --------------------------------------------------
def folder_listing(self, path: str | None) -> ServerFiles:
"""The audio directly inside a content folder (None: the folder itself),
as the server lists it — and remembered, so a file can then be played
or added by its path."""
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
with self._lock:
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
self._listed.update(listing.files)
self._server_paths.update({str(Path(k)): k for k in listing.files})
return listing
def listed_files(self, paths) -> ServerFiles | None:
"""The listed files among `paths` as one source (they may come from
several folders); None when none of them was listed."""
with self._lock:
found = [self._listed[p] for p in paths if p in self._listed]
return ServerFiles(self, found[0].folder, found) if found else None
def folder_audio(self, path: str, *, progress=None) -> Path:
"""A local copy of a listed file, downloaded into the shared cache —
keyed by the same facts as a library track's, so a file that is both
downloads once."""
for attempt in range(2):
with self._lock:
found = self._listed.get(path)
if found is None:
raise NotFound("File not found — browse to its folder first")
cached = self.cache.get(found.facts)
if cached is not None:
return cached
try:
return self.cache.fetch(
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
except StaleFacts:
if attempt:
raise
self.folder_listing(found.folder) # changed on the server: re-read it
raise NotFound(path)
# ---- paths: the server's business ------------------------------------------------
def set_path_mapping(self, mapping):
raise Unsupported(_NOT_HERE)
def set_session_mappings(self, mappings):
raise Unsupported(_NOT_HERE)
def unresolved_path_groups(self):
return []
def path_prefix_suggestions(self):
raise Unsupported(_NOT_HERE)
def remap_preview(self, mapping):
raise Unsupported(_NOT_HERE)
def remap_locations(self, mapping):
raise Unsupported(_NOT_HERE)
# ---- save ----------------------------------------------------------------------------
def save(self):
try:
result = self.client.save()
except SessionLost as ex:
self.session.lost(ex.holder)
raise
outcome = SaveOutcome(
summary=result.get("summary") or "",
snapshot=None,
tag_results=[FileTagResult(**r) for r in result.get("tag_results") or []],
)
# Versioned on the server; `RemoteServices.commit_save` hands it on.
outcome.commit = result.get("commit")
self._load()
return outcome
def snapshot(self) -> bytes:
raise Unsupported("A remote library's version history is kept on the server")
def close(self) -> None:
self.session.stop()
self.client.release()
self.client.close()
def _pairs(markers) -> list[tuple[float, float]]:
out = []
for m in markers:
if hasattr(m, "start"):
out.append((float(m.start), float(m.bpm)))
else:
start, bpm = m
out.append((float(start), float(bpm)))
return out
+194
View File
@@ -0,0 +1,194 @@
"""This computer's copies of a remote library's audio.
Everything that needs a track's audio as a FILE runs here, not on the server —
the deck's decode, grid and cue analysis, stem separation and extraction, an
export's copy onto a stick. One cache serves them all, so a track analysed and
then exported downloads once.
* **Keyed by what the server says the file IS** — its path there, size and
mtime (`AudioFacts`) — never by when it was fetched: an edited file (Save
writes tags into it) is a new entry, and the same file fetched again after
an eviction, or by another computer exporting the same set, is recognised.
* **A partial, renamed into place**, so a cut connection never leaves a
truncated file under a real entry's name, and a download whose size does
not match the facts is refused rather than kept.
* **Least recently used, under a cap** (`remoteCacheBytes` in prefs). The
entry just written and anything touched in the last few minutes are never
the ones evicted: they are being played or copied right now.
"""
from __future__ import annotations
import hashlib
import os
import shutil
import threading
import time
from pathlib import Path
from ... import paths, prefs
from ...core.adapter import AudioFacts, Unavailable
DEFAULT_CAP = 10 * 1024 ** 3
_RECENT = 300.0 # seconds: an entry touched this recently is in use
_PART = ".part"
class StaleFacts(Unavailable):
"""The server's file changed between asking about it and downloading it."""
def cache_root() -> Path:
return paths.app_data_dir() / "remote-cache"
def cap_bytes() -> int:
try:
value = int(prefs.load_prefs().get("remoteCacheBytes") or DEFAULT_CAP)
except (TypeError, ValueError):
value = DEFAULT_CAP
return max(value, 256 * 1024 ** 2)
class RemoteAudioCache:
def __init__(self, root: Path | None = None, *, cap=None, clock=time.time):
self.root = Path(root) if root is not None else cache_root()
self._cap = cap if cap is not None else cap_bytes
self._clock = clock
self._locks: dict[str, threading.Lock] = {}
self._guard = threading.Lock()
#: Recent download speeds (bytes/s), newest last — for time estimates.
self._speeds: list[float] = []
# ---- naming ----------------------------------------------------------------
@staticmethod
def key(facts: AudioFacts) -> str:
text = f"{facts.key}|{facts.size}|{facts.mtime_ns}"
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:32]
def path_for(self, facts: AudioFacts) -> Path:
# The original's suffix, so a MIME type and a decoder's guess still work.
suffix = Path(facts.key.replace("\\", "/")).suffix.lower()
return self.root / f"{self.key(facts)}{suffix}"
def _lock_for(self, key: str) -> threading.Lock:
with self._guard:
return self._locks.setdefault(key, threading.Lock())
# ---- use -------------------------------------------------------------------
def get(self, facts: AudioFacts) -> Path | None:
path = self.path_for(facts)
if path.is_file():
self._touch(path)
return path
return None
def fetch(self, facts: AudioFacts, download) -> Path:
"""The cached copy, downloading it first if needed. `download(partial)`
writes the file and returns the server's `{size, mtime_ns}` for it."""
path = self.path_for(facts)
with self._lock_for(path.name):
if path.is_file():
self._touch(path)
return path
self.root.mkdir(parents=True, exist_ok=True)
partial = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}{_PART}")
started = time.monotonic()
try:
meta = download(partial) or {}
got = partial.stat().st_size
if got != facts.size or (meta.get("size") and meta["size"] != facts.size):
raise StaleFacts(f"{Path(facts.key).name} changed on the server while downloading")
os.replace(partial, path)
finally:
partial.unlink(missing_ok=True)
elapsed = max(time.monotonic() - started, 1e-3)
if facts.size > 1 << 20:
self._speeds = (self._speeds + [facts.size / elapsed])[-8:]
self._touch(path)
self.prune(keep={path})
return path
def speed(self) -> float | None:
"""A recent download speed in bytes/s, or None before the first."""
if not self._speeds:
return None
ordered = sorted(self._speeds)
return ordered[len(ordered) // 2]
def _touch(self, path: Path) -> None:
now = self._clock()
try:
os.utime(path, (now, now))
except OSError:
pass
# ---- housekeeping ------------------------------------------------------------
def _entries(self) -> list[tuple[float, int, Path]]:
out = []
if not self.root.is_dir():
return out
for p in self.root.iterdir():
if p.name.endswith(_PART) or not p.is_file():
continue
try:
st = p.stat()
except OSError:
continue
out.append((st.st_mtime, st.st_size, p))
return out
def prune(self, keep: set[Path] | None = None) -> int:
"""Evict least-recently-used entries until under the cap. Returns bytes freed."""
cap = self._cap() if callable(self._cap) else self._cap
entries = sorted(self._entries())
total = sum(size for _, size, _ in entries)
freed = 0
now = self._clock()
for used, size, p in entries:
if total <= cap:
break
if (keep and p in keep) or now - used < _RECENT:
continue
try:
p.unlink()
except OSError:
continue # held open (Windows): next time
total -= size
freed += size
return freed
def usage(self) -> dict:
entries = self._entries()
cap = self._cap() if callable(self._cap) else self._cap
return {"bytes": sum(s for _, s, _ in entries), "files": len(entries), "cap": cap,
"free": _free(self.root)}
def clear(self) -> int:
freed = 0
for _, size, p in self._entries():
try:
p.unlink()
freed += size
except OSError:
pass
return freed
def _free(folder: Path) -> int:
probe = folder
while not probe.exists() and probe != probe.parent:
probe = probe.parent
try:
return shutil.disk_usage(probe).free
except OSError:
return 0
_shared: RemoteAudioCache | None = None
def shared() -> RemoteAudioCache:
global _shared
if _shared is None:
_shared = RemoteAudioCache()
return _shared
+325
View File
@@ -0,0 +1,325 @@
"""Talking to a Konduktor server: addresses, sign-in, and the error vocabulary.
Every request tries the address that last worked, then the others in the
remote's order (primary, then fallback) — so a laptop that leaves the house
moves from the LAN address to the VPN one without being asked, and back again.
Only a CONNECT failure moves on: the request never reached that server, so
sending it to the other one cannot apply it twice. A request that reached a
server and then failed is that server's answer.
The server's refusals come back as the adapter's own error classes (the same
status codes `main.py` maps them from), so a route on this computer reports a
remote library's refusal exactly as it would a local one's.
"""
from __future__ import annotations
import logging
import threading
from pathlib import Path
import httpx
from ... import remote_protocol as rp
from ...core.adapter import (
AdapterError,
InvalidCommand,
LibraryNotSupported,
NotFound,
Unavailable,
Unsupported,
)
from .config import Remote
log = logging.getLogger(__name__)
_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
class Unreachable(Unavailable):
"""No address of the remote answered."""
class AuthFailed(LibraryNotSupported):
"""The server refused the username or password."""
class VersionMismatch(LibraryNotSupported):
def __init__(self, update: str, server_version: str):
side = "Konduktor on this computer" if update == "app" else "the Konduktor server"
super().__init__(
f"This server speaks a different version of Konduktor's protocol "
f"(server {server_version}): update {side}."
)
self.update = update
class InUse(AdapterError):
"""Another computer holds the session: `holder` = {machine, since, batch}."""
def __init__(self, holder: dict):
super().__init__(f"In use by {holder.get('machine') or 'another computer'}")
self.holder = holder
class SessionLost(Unavailable):
"""This computer no longer holds the session (another one took over)."""
def __init__(self, holder: dict | None):
who = (holder or {}).get("machine")
super().__init__(
f"{who} has taken over this library — it is read-only here" if who
else "This computer no longer holds the library's session"
)
self.holder = holder
def _detail(response: httpx.Response):
try:
return response.json().get("detail")
except Exception: # noqa: BLE001
return response.text[:300]
class RemoteClient:
def __init__(self, remote: Remote, password: str, *, timeout: float = 30.0):
self.remote = remote
self._addresses = remote.addresses()
self._active: int | None = None
self.token: str | None = None
self._lock = threading.Lock()
self._http = httpx.Client(
auth=(remote.username, password),
timeout=httpx.Timeout(timeout, connect=4.0),
follow_redirects=False,
)
def close(self) -> None:
self._http.close()
@property
def via(self) -> str | None:
"""Which address is in use: "primary" / "fallback" (None until one answers)."""
return None if self._active is None else self._addresses[self._active][0]
# ---- transport ----------------------------------------------------------------
def _order(self) -> list[int]:
everything = list(range(len(self._addresses)))
if self._active is None:
return everything
return [self._active] + [i for i in everything if i != self._active]
def request(self, method: str, path: str, *, retry: bool = True, session: bool = True,
**kw) -> httpx.Response:
headers = dict(kw.pop("headers", None) or {})
if session and self.token:
headers[rp.SESSION_HEADER] = self.token
order = self._order() if retry else ([self._active] if self._active is not None else [0])
last: Exception | None = None
for i in order:
base = self._addresses[i][1]
try:
response = self._http.request(method, base + path, headers=headers, **kw)
except _CONNECT_ERRORS as ex:
last = ex
continue
except httpx.TimeoutException as ex:
self._active = i
raise Unreachable(f"The server at {base} stopped answering") from ex
except httpx.TransportError as ex:
last = ex
continue
self._active = i
return self.check(response)
names = " or ".join(b for _, b in (self._addresses[i] for i in order))
raise Unreachable(f"Cannot reach the server at {names}") from last
def stream(self, method: str, path: str, **kw):
"""A streaming request on the address in use (a download)."""
headers = dict(kw.pop("headers", None) or {})
if self.token:
headers[rp.SESSION_HEADER] = self.token
# Pick the address first with a cheap call, so the stream itself is not
# the request that discovers the primary is gone.
if self._active is None:
self.request("GET", "/v1/hello", session=False)
base = self._addresses[self._active][1]
return self._http.stream(method, base + path, headers=headers, **kw)
@staticmethod
def check(response: httpx.Response) -> httpx.Response:
status = response.status_code
if status < 400:
return response
detail = _detail(response)
if status == 401:
raise AuthFailed("The server refused the username or password")
if status == 423:
raise SessionLost((detail or {}).get("holder") if isinstance(detail, dict) else None)
if status == 409 and isinstance(detail, dict) and detail.get("code") == "in_use":
raise InUse(detail)
text = detail if isinstance(detail, str) else (detail or {}).get("message", str(detail))
cls = {404: NotFound, 400: InvalidCommand, 422: Unsupported, 503: Unavailable}.get(status)
if cls is not None:
raise cls(text)
raise AdapterError(f"The server answered {status}: {text}")
# ---- handshake + session ----------------------------------------------------------
def hello(self, client_id: str | None = None) -> dict:
info = self.request("GET", "/v1/hello", params={"client_id": client_id} if client_id else None,
session=False).json()
server_version = tuple(info.get("api_version") or (0, 0))
update = rp.compatible(rp.API_VERSION, (int(server_version[0]), int(server_version[1])))
if update:
raise VersionMismatch(update, info.get("app_version") or ".".join(map(str, server_version)))
return info
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> dict:
body = self.request("POST", "/v1/session/acquire", session=False,
json={"client_id": client_id, "machine": machine, "takeover": takeover}).json()
self.token = body["token"]
return body
def heartbeat(self, batch: str | None) -> dict:
return self.request("POST", "/v1/session/heartbeat", json={"batch": batch}).json()
def release(self, *, timeout: float | None = None) -> None:
if not self.token:
return
try:
kw = {"timeout": timeout} if timeout is not None else {}
self.request("POST", "/v1/session/release", retry=False, **kw)
except AdapterError:
pass
self.token = None
# ---- the protocol -------------------------------------------------------------------
def rpc(self, method: str, /, *, timeout=..., **args) -> dict:
"""Call one protocol method; the envelope `{result, rev, changed, removed, reset}`
with `result` already deserialised."""
kw = {} if timeout is ... else {"timeout": timeout}
body = self.request("POST", f"/v1/rpc/{method}", json={"args": rp.dump_args(method, args)}, **kw).json()
body["result"] = rp.load_result(method, body.get("result"))
return body
# ---- bytes -----------------------------------------------------------------------------
def download(self, track_id: str, target: Path, *, progress=None) -> dict:
"""Stream a track's audio into `target`; its server-side size and mtime."""
with self.stream("GET", "/v1/audio", params={"track_id": track_id}, timeout=None) as response:
if response.status_code >= 400:
response.read()
self.check(response)
with open(target, "wb") as out:
for chunk in response.iter_bytes(1 << 20):
out.write(chunk)
if progress is not None:
progress(len(chunk))
return {
"size": int(response.headers.get("X-Konduktor-Size") or 0),
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
}
def upload(self, source: Path, folder: str, name: str, *, progress=None) -> dict:
def body():
with open(source, "rb") as f:
while chunk := f.read(1 << 20):
if progress is not None:
progress(len(chunk))
yield chunk
return self.request("POST", "/v1/upload", params={"dir": folder, "name": name},
content=body(), retry=False, timeout=None).json()
def delete_upload(self, path: str) -> None:
self.request("DELETE", "/v1/upload", params={"path": path})
def art(self, track_id: str) -> tuple[bytes, str] | None:
try:
r = self.request("GET", "/v1/art", params={"track_id": track_id})
except NotFound:
return None
return r.content, r.headers.get("content-type", "image/jpeg").split(";")[0]
def put_art(self, track_id: str, data: bytes, mime: str) -> dict:
return self.request("PUT", "/v1/art", params={"track_id": track_id, "mime": mime},
content=data).json()
def fs_list(self, path: str | None) -> dict:
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
def folder_tracks(self, path: str | None) -> dict:
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
timeout=None).json()
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
"""Stream a listed content-folder file into `target` (as `download`)."""
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
if response.status_code >= 400:
response.read()
self.check(response)
with open(target, "wb") as out:
for chunk in response.iter_bytes(1 << 20):
out.write(chunk)
if progress is not None:
progress(len(chunk))
return {
"size": int(response.headers.get("X-Konduktor-Size") or 0),
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
}
def fs_space(self, path: str | None) -> int:
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
# ---- Convert to Stems ----------------------------------------------------------------
def stems_plan(self, body: dict) -> dict:
return self.request("POST", "/v1/stems/plan", json=body, timeout=None).json()
def stems_stage(self, track_id: str, target: str, source: Path, *, sha256: str,
bit_rate: int, duration: float, progress=None) -> dict:
def body():
with open(source, "rb") as f:
while chunk := f.read(1 << 20):
if progress is not None:
progress(len(chunk))
yield chunk
return self.request(
"PUT", "/v1/stems/stage",
params={"track_id": track_id, "target": target, "sha256": sha256,
"bit_rate": bit_rate, "duration": duration},
content=body(), retry=False, timeout=None,
).json()
def stems_abandon(self, targets: list[str]) -> None:
self.request("POST", "/v1/stems/abandon", json={"targets": targets})
def stems_publish(self, items: list[dict], options: dict) -> dict:
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
timeout=None).json()
def stems_pending(self) -> dict:
return self.request("GET", "/v1/stems/pending").json()
# ---- save / history / export sets -------------------------------------------------
def save(self) -> dict:
return self.request("POST", "/v1/save", timeout=None).json()
def discard(self) -> dict:
return self.request("POST", "/v1/discard", timeout=None).json()
def history(self) -> list[dict]:
return self.request("GET", "/v1/history").json()
def restore(self, commit_id: str) -> dict:
return self.request("POST", f"/v1/history/{commit_id}/restore", timeout=None).json()
def clear_history(self) -> None:
self.request("DELETE", "/v1/history")
def export_sets(self) -> dict:
return self.request("GET", "/v1/export-sets").json()
def put_export_sets(self, doc: dict) -> None:
self.request("PUT", "/v1/export-sets", json=doc)
+199
View File
@@ -0,0 +1,199 @@
"""Saved remotes: the servers this computer knows how to reach.
A remote is where a Konduktor server is (an address, an optional port, and a
fallback address — typically the LAN address first and a VPN one second) and
who to sign in as. Everything but the password is a plain preference
(`userprefs.json`, key `remotes`); the password lives in the OS keychain
(macOS Keychain, Windows Credential Manager) through `keyring`, never in a JSON
file beside the app's other data.
This computer also has a stable `client_id`, which is how a server tells "the
same laptop back from sleep" (renew its session silently) from "another
computer" (offer a takeover).
"""
from __future__ import annotations
import socket
import uuid
from dataclasses import asdict, dataclass
from ... import prefs
DEFAULT_PORT = 8765
_PREFS_KEY = "remotes"
_CLIENT_KEY = "remoteClientId"
_KEYRING_SERVICE = "Konduktor"
@dataclass
class Remote:
id: str
name: str
host: str
port: int | None = None
fallback_host: str | None = None
fallback_port: int | None = None
username: str = ""
def addresses(self) -> list[tuple[str, str]]:
"""`(label, base url)`, primary first — the order every connect tries.
Each address keeps its OWN port. The fallback once borrowed the
primary's, so a reverse-proxied fallback (`konduktor.example.net`,
served on 443) was tried at `:8765` because the LAN address named it.
"""
out = [("primary", _base(self.host, self.port))]
if self.fallback_host:
out.append(("fallback", _base(self.fallback_host, self.fallback_port)))
return out
def public(self) -> dict:
return asdict(self)
def _base(host: str, port: int | None) -> str:
"""An address as typed → a base URL. A full URL (`https://…`, the way to
reach a server behind the user's own reverse proxy) is taken exactly as
given, port and all; anything else is plain HTTP on its port, else 8765."""
host = host.strip()
if host.startswith("http://") or host.startswith("https://"):
return host.rstrip("/")
bare, inline = split_host(host)
if inline is not None:
host, port = bare, port or inline
if ":" in host and not host.startswith("["):
host = f"[{host}]" # an IPv6 literal
return f"http://{host}:{port or DEFAULT_PORT}"
def split_host(text: str) -> tuple[str, int | None]:
"""`"nas.local:9000"` → `("nas.local", 9000)`; a bare host keeps no port."""
text = (text or "").strip()
if text.startswith("http://") or text.startswith("https://"):
return text, None
if text.count(":") == 1:
host, _, port = text.partition(":")
if port.isdigit():
return host, int(port)
return text, None
# ---- the list ------------------------------------------------------------------
def remotes() -> list[Remote]:
raw = prefs.load_prefs().get(_PREFS_KEY) or []
out = []
for item in raw if isinstance(raw, list) else []:
try:
out.append(Remote(**{k: item.get(k) for k in Remote.__dataclass_fields__ if k in item}))
except TypeError:
continue
return out
def get(remote_id: str) -> Remote | None:
return next((r for r in remotes() if r.id == remote_id), None)
def save(remote: Remote) -> Remote:
items = [r for r in remotes() if r.id != remote.id] + [remote]
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
return remote
def delete(remote_id: str) -> bool:
before = remotes()
items = [r for r in before if r.id != remote_id]
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
forget_password(remote_id)
return len(items) != len(before)
def new_id() -> str:
return uuid.uuid4().hex[:12]
# ---- this computer ---------------------------------------------------------------
def client_id() -> str:
current = prefs.load_prefs().get(_CLIENT_KEY)
if isinstance(current, str) and current:
return current
fresh = uuid.uuid4().hex
prefs.update_prefs({_CLIENT_KEY: fresh})
return fresh
def machine_name() -> str:
"""What another computer is told holds the library ("Ben's MacBook")."""
try:
import subprocess
import sys
if sys.platform == "darwin":
name = subprocess.run(["scutil", "--get", "ComputerName"], capture_output=True,
text=True, timeout=2).stdout.strip()
if name:
return name
except Exception: # noqa: BLE001
pass
name = socket.gethostname()
return name[:-6] if name.endswith(".local") else name
# ---- the password ------------------------------------------------------------------
# A seam for tests (and any machine without a keychain): `use_password_store`.
class _Keyring:
def get(self, account: str) -> str | None:
import keyring
return keyring.get_password(_KEYRING_SERVICE, account)
def set(self, account: str, password: str) -> None:
import keyring
keyring.set_password(_KEYRING_SERVICE, account, password)
def delete(self, account: str) -> None:
import keyring
from keyring.errors import PasswordDeleteError
try:
keyring.delete_password(_KEYRING_SERVICE, account)
except PasswordDeleteError:
pass
_store = _Keyring()
def use_password_store(store) -> None:
"""Replace the keychain (`get`/`set`/`delete` by account) — tests only."""
global _store
_store = store if store is not None else _Keyring()
def _account(remote_id: str) -> str:
return f"remote:{remote_id}"
def password(remote_id: str) -> str | None:
try:
return _store.get(_account(remote_id))
except Exception: # noqa: BLE001 — a locked keychain reads as "no password"
return None
def set_password(remote_id: str, value: str) -> None:
_store.set(_account(remote_id), value)
def forget_password(remote_id: str) -> None:
try:
_store.delete(_account(remote_id))
except Exception: # noqa: BLE001
pass
+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
@@ -0,0 +1,85 @@
"""A remote library's app-level bookkeeping — kept on the server, beside it.
Version history, export sets and the stems ledger belong with the library, not
with whichever computer opened it: they are what every computer that opens it
should see. So for a remote library these are calls to the server, and this
computer's app-data holds none of them (`services.py` is the local half).
"""
from __future__ import annotations
from ...core.adapter import NotFound
from ...history import HistoryEntry
from .client import RemoteClient
class RemoteServices:
remote = True
def __init__(self, client: RemoteClient):
self.client = client
def baseline(self) -> None:
pass # the server records its own "as I found it" version when it opens
def commit_save(self, adapter, outcome) -> str | None:
# The server versioned the save itself; its commit rides on the outcome.
return getattr(outcome, "commit", None)
def history(self) -> list[HistoryEntry]:
return [HistoryEntry(**e) for e in self.client.history()]
def restore(self, commit_id: str) -> bool:
try:
self.client.restore(commit_id)
except NotFound:
return False
return True
def clear_history(self) -> None:
self.client.clear_history()
def discard(self) -> None:
self.client.discard()
class RemoteSetStore:
"""`exports.use_store`'s store for a remote library: its sets, on the server."""
def __init__(self, client: RemoteClient):
self.client = client
def read(self) -> dict:
return self.client.export_sets()
def write(self, doc: dict) -> None:
self.client.put_export_sets(doc)
class RemotePending:
"""`AppState.pending` for a remote library: the SERVER keeps the ledger of
converted tracks awaiting Save (and commits, restores and recovers it
itself), so on this computer there is nothing to commit or restore — only
the server's summary to report, and its "blocking" to honour."""
items: list = []
def __init__(self, client: RemoteClient):
self.client = client
def summary(self) -> dict:
try:
return self.client.stems_pending()
except Exception: # noqa: BLE001 — out of reach: nothing known to be pending
return {"tracks": 0, "parked": 0, "bytes": 0}
def blocking(self) -> bool:
return bool(self.summary().get("tracks"))
def swapped(self) -> list:
return []
def restore(self) -> int:
return 0
def commit(self) -> dict:
return {}
@@ -0,0 +1,159 @@
"""This computer's hold on a remote library's session.
The server lets ONE computer edit at a time (`server/session.py`); this keeps
this computer's hold alive with a heartbeat every `HEARTBEAT_SECONDS`, and is
the one place that knows how this computer stands:
connected — holding the session; edits go through
reconnecting — a heartbeat failed to reach the server; edits still try
(each request walks the addresses again)
offline — several in a row failed; read-only until one gets through
taken_over — another computer took the session; read-only, for good
Coming back from `reconnecting` or `offline` needs no new sign-in: the server
renews a lapsed lease for the computer that held it, as long as nobody else
has taken it meanwhile — and says so (423) if somebody has.
The heartbeat names the batch running here, so a computer asking to take over
is told what it would cancel. Being taken over cancels it (`on_change`).
"""
from __future__ import annotations
import logging
import threading
from ...core.adapter import Unavailable
from ...remote_protocol import HEARTBEAT_SECONDS
from .client import RemoteClient, SessionLost
log = logging.getLogger(__name__)
#: Missed heartbeats in a row before `reconnecting` becomes `offline`.
OFFLINE_AFTER = 3
class RemoteSession:
def __init__(self, client: RemoteClient, *, batch_probe=None, interval: float = HEARTBEAT_SECONDS,
identity: tuple[str, str] | None = None):
self.client = client
self.interval = interval
self._batch_probe = batch_probe or (lambda: None)
#: (client_id, machine) — to take the session back when the server has
#: forgotten it (a restart) and nobody else holds it.
self.identity = identity
self.state = "connected"
self.machine: str | None = None # who took it over
#: The last thing worth telling the user that is not a state ("the
#: server restarted"), with a counter so the UI shows each once.
self.notice: str | None = None
self.notices = 0
#: Called after the session was taken back: the library must be re-read.
self.on_reacquired = None
self._failures = 0
self._listeners: list = []
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._lock = threading.Lock()
# ---- facts ---------------------------------------------------------------------
@property
def writable(self) -> bool:
return self.state in ("connected", "reconnecting")
@property
def readonly_cause(self) -> str | None:
return {"taken_over": "taken_over", "offline": "offline"}.get(self.state)
def describe(self) -> dict:
return {"state": self.state, "via": self.client.via if self.state != "offline" else None,
"machine": self.machine, "notice": self.notice, "notices": self.notices}
def on_change(self, listener) -> None:
"""`listener(state)` after every change of state (from the heartbeat thread)."""
self._listeners.append(listener)
# ---- running -------------------------------------------------------------------
def start(self) -> None:
if self._thread is None:
self._thread = threading.Thread(target=self._run, name="konduktor-remote-heartbeat",
daemon=True)
self._thread.start()
def stop(self) -> None:
self._stop.set()
def _run(self) -> None:
while not self._stop.wait(self.interval):
if self.state == "taken_over":
return
self.beat()
def beat(self) -> None:
try:
self.client.heartbeat(self._batch_probe())
except SessionLost as ex:
self.lost(ex.holder)
return
except Unavailable:
self._failures += 1
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
return
except Exception: # noqa: BLE001 — a bad answer is a missed beat, not a crash
log.exception("heartbeat failed")
self._failures += 1
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
return
self._failures = 0
self._set("connected")
def _take_back(self) -> bool:
"""The server no longer knows this computer's token and nobody holds the
session — it restarted (unsaved edits went with it, an accepted loss).
Take the session back without asking, unless the library now holds
someone ELSE's unsaved edits: those deserve the Save / Discard question
that reopening asks, so then this stays read-only."""
if self.identity is None:
return False
try:
got = self.client.acquire(*self.identity)
except Exception: # noqa: BLE001 — someone got there first, or no server
return False
if got.get("pending_edits"):
self.client.release()
return False
if self.on_reacquired is not None:
try:
self.on_reacquired()
except Exception: # noqa: BLE001
log.exception("re-reading the library after a reconnect failed")
self.notice = "The server restarted — any edits not yet saved there were lost"
self.notices += 1
self._failures = 0
self._set("connected")
return True
def lost(self, holder: dict | None) -> None:
"""Another computer holds the session — from a heartbeat, or a command
the server refused with 423. Nobody holding it means the server forgot
this computer's token (a restart): take it back if that is safe."""
if holder is None and self.state != "taken_over" and self._take_back():
return
self.machine = (holder or {}).get("machine")
self._set("taken_over")
def reached(self) -> None:
"""A request got through: whatever the heartbeat last saw, the server is there."""
if self.state in ("reconnecting", "offline"):
self._failures = 0
self._set("connected")
def _set(self, state: str) -> None:
with self._lock:
if state == self.state:
return
self.state = state
for listener in list(self._listeners):
try:
listener(state)
except Exception: # noqa: BLE001
log.exception("remote session listener failed")
+101 -21
View File
@@ -15,7 +15,7 @@ from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
from ...core.adapter import InvalidCommand, NotFound, Unsupported
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping
@@ -131,6 +131,10 @@ class TraktorAdapter:
with _translate():
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
with _translate():
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents. The adapter resolves each id to its
native entry kind, so callers never see Traktor's STEM/TRACK split."""
@@ -146,6 +150,12 @@ class TraktorAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
with _translate():
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
with _translate():
self._store.set_track_art(track_id, data, mime)
@@ -187,10 +197,11 @@ class TraktorAdapter:
Lossiness follows the settled rule — degrade to the nearest equivalent,
drop only where none exists:
* **Memory cues become hot cues in spare slots.** Traktor has no
memory cues, and every Traktor cue occupies a slot. Filling the
leftovers preserves the positions a DJ actually marked; when the
bank is full the rest are dropped, because there is nowhere left.
* **Memory cues stay memory cues** — Traktor's cues on no pad
(HOTCUE="-1"), decided 2026-10-16 once Traktor was measured keeping
them. They used to be promoted to spare pads.
* **A hot cue whose pad is taken** moves to a spare pad, else becomes a
memory cue — never dropped.
* **Cue colour is dropped.** Traktor derives a cue's colour from its
type, so a free RGB value has nowhere to go.
@@ -240,29 +251,43 @@ class TraktorAdapter:
self._place_imported_cue(track_id, cue.slot, cue)
taken.add(cue.slot)
# Everything without a pad of its own competes for what is left: memory
# cues, which Traktor has no equivalent for, and any hot cue whose pad
# was already occupied. Earliest first, so that when the bank runs out
# it is the late cues that are lost rather than an arbitrary set — and
# a displaced hot cue is moved rather than dropped, because losing one
# silently is much worse than having it turn up on the wrong pad.
leftovers = displaced + [c for c in (cues.cues or []) if c.role != "hotcue"]
# A hot cue whose pad was taken (or is past the bank) moves to a spare
# pad, earliest first, because muscle memory is most of what a hot cue
# layout is; once the bank is full it becomes a memory cue rather than
# being lost. Memory cues cross as memory cues.
spare = (s for s in range(slots) if s not in taken)
for cue in sorted(leftovers, key=lambda c: c.start):
for cue in sorted(displaced, key=lambda c: c.start):
slot = next(spare, None)
if slot is None:
break # bank full: the rest are dropped, per the lossiness rule
self._place_imported_cue(track_id, slot, cue)
self._place_imported_memory_cue(track_id, cue)
else:
self._place_imported_cue(track_id, slot, cue)
for cue in sorted((c for c in (cues.cues or []) if c.role != "hotcue" or c.slot is None),
key=lambda c: c.start):
self._place_imported_memory_cue(track_id, cue)
@staticmethod
def _imported_type(cue) -> str:
"""A loop stays a loop; Traktor's own point types (fade, load) survive."""
if getattr(cue, "length", 0):
return "loop"
return cue.type if cue.type in ("cue", "fade_in", "fade_out", "load") else "cue"
def _place_imported_cue(self, track_id: str, slot: int, cue) -> None:
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
if cue_type not in CUE_TYPE_TO_NATIVE:
return
self.set_cue(
track_id,
slot=slot,
start_sec=cue.start,
cue_type=cue_type,
cue_type=self._imported_type(cue),
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None),
)
def _place_imported_memory_cue(self, track_id: str, cue) -> None:
self.add_memory_cue(
track_id,
start_sec=cue.start,
cue_type=self._imported_type(cue),
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None),
)
@@ -286,8 +311,8 @@ class TraktorAdapter:
name: str | None = None,
) -> TrackCues:
if role != "hotcue":
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot.
raise Unsupported("Traktor cues always occupy a hotcue slot")
# A memory cue has no slot to set; it has its own commands.
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
with _translate():
self._store.set_hotcue(
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
@@ -308,6 +333,45 @@ class TraktorAdapter:
self._store.delete_hotcue(track_id, slot)
return self._refresh(track_id)
# ---- memory cues: cues on no pad (HOTCUE="-1") ----------------------------
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
# Traktor colours a cue by its type, so a colour has nowhere to go; an
# import passes none, and the capabilities offer none.
if color is not None:
raise Unsupported("Traktor colours cues by their type")
with _translate():
self._store.add_memory_cue(
track_id, start_sec, self._native_cue_type(cue_type), length_sec, name
)
return self._refresh(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
with _translate():
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
with _translate():
self._store.set_memory_cue_type(track_id, cue_id, self._native_cue_type(cue_type))
return self._refresh(track_id)
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
raise Unsupported("Traktor colours cues by their type")
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
with _translate():
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
native = [
SimpleNamespace(
@@ -377,12 +441,22 @@ class TraktorAdapter:
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
self._store.set_session_mappings(mappings)
def set_write_stored_paths(self, enabled: bool) -> None:
"""OPTIONAL: write a file added through the path mapping in the
library's STORED form (see `pathmap.stored_form`). A Konduktor server
holding a collection made on another computer turns this on, so a
track uploaded there is stored as that computer would have stored it."""
self._store.set_write_stored_paths(enabled)
def unresolved_path_groups(self) -> list[PathGroup]:
return self._store.unresolved_path_groups()
@@ -405,6 +479,12 @@ class TraktorAdapter:
def dirty(self) -> bool:
return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._edit_summary()
def save(self):
outcome = self._store.save()
self._rebuild() # save() re-parses, so every object identity changed
@@ -46,8 +46,11 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable=True,
hotcue_slots=8,
slot_labels="number",
# Traktor has no memory cues — every cue occupies a bank slot.
memory_cues=False,
# Memory cues are CUE_V2s on no pad (HOTCUE="-1"), any type, no
# limit (measured in Traktor 4.5, 2026-10-16). No colour: by type.
memory_cues=True,
max_memory_cues=None,
memory_color="none",
types=CUE_TYPES,
# Traktor colours a cue by its TYPE; the only COLOR it stores is a
# grid marker's white companion, so there is nothing to pick.
@@ -64,6 +67,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
removable=True,
addable=True,
stem_convertible=True,
key_writable=True,
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both.
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
@@ -73,7 +77,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
"need a manual Import Cover Art to show up."
),
),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
playlists=PlaylistCapabilities(
folders=True, smart="read_only", reorder=True,
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
# itself adds a track twice when asked.
duplicates=True,
),
save=SaveCapabilities(
app_name="Traktor",
library_label="collection.nml",
+5 -9
View File
@@ -106,14 +106,10 @@ class TraktorExporter:
return WrittenLibrary(library=library)
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
"""Recreate the tree under one folder named after the export.
Nested under the export's own name for the same reason import nests a
drive's playlists under the drive's name: a collection swapped onto
another machine should say where its playlists came from.
"""
root = adapter.create_folder(payload.name)
folders: dict[tuple[str, ...], str] = {(): root}
"""Recreate the tree — at the top level, or with `payload.root_folder`
under one folder named after the export (None = the top level)."""
root = adapter.create_folder(payload.name) if payload.root_folder else None
folders: dict[tuple[str, ...], str | None] = {(): root}
for playlist in payload.playlists:
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
@@ -128,7 +124,7 @@ class TraktorExporter:
adapter.set_playlist_entries(node_id, loose)
@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."""
for depth in range(1, len(path) + 1):
branch = path[:depth]
@@ -7,15 +7,14 @@ from __future__ import annotations
import re
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase
from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
# depending on a user preference — so the library can contain either. Parsing
# notation is platform knowledge and belongs here, not in the UI.
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
# depending on a user preference, and INFO@KEY also holds whatever a file's key
# tag said ("Gm", "Amin") — so every notation is parsed (`core/musical_key`).
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
# "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
# timestamp's date part is the date).
@@ -23,23 +22,42 @@ _ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$")
def parse_key(key: str | None) -> tuple[int | None, str | None]:
"""(Camelot wheel position 1-12, mode) for a Traktor display key.
"""(Camelot wheel position 1-12, mode) for a Traktor key string."""
return musical_key.parse(key)
Open Key numbers the wheel seven semitones round from Camelot, so
Open Key 1 == Camelot 8 (both are C major / A minor).
"""
if not key:
def musical_key_value(wheel: int, mode: str) -> int:
"""`<MUSICAL_KEY VALUE>`: the tonic's pitch class (C = 0), plus 12 for minor
— read off the real collection, where 12 pairs with "10m" (C minor) and 21
with "1m" (A minor) on every entry carrying both."""
return musical_key.pitch_class_of(wheel, mode) + (12 if mode == "minor" else 0)
def _from_musical_key(value: int | None) -> tuple[int | None, str | None]:
if value is None or not 0 <= value <= 23:
return None, None
k = key.strip()
if m := _CAMELOT.match(k):
n = int(m.group(1))
if 1 <= n <= 12:
return n, "minor" if m.group(2).lower() == "a" else "major"
if m := _OPEN_KEY.match(k):
n = int(m.group(1))
if 1 <= n <= 12:
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
return None, None
mode = "minor" if value >= 12 else "major"
return musical_key.wheel_of(value % 12, mode), mode
def entry_key(e) -> tuple[str | None, int | None, str | None]:
"""(display string, wheel, mode) for an ENTRY.
INFO@KEY is the text Traktor shows and writes to the file's tag; the
analysed key itself is `<MUSICAL_KEY>`. 1,354 of the real collection's
8,485 entries carry only the latter — analysed, with every value 0-23
present, just never given a text — and Traktor shows a key for them, so
they fall back to it, rendered in Open Key (Traktor's own default).
"""
info = e.info
text = info.key if info else None
wheel, mode = parse_key(text)
if wheel is None:
mk = e.musical_key.value_attribute if e.musical_key is not None else None
wheel, mode = _from_musical_key(mk)
if wheel is not None and not text:
text = musical_key.render(wheel, mode, "open_key")
return text, wheel, mode
def iso_date(value: str | None) -> str | None:
@@ -122,7 +140,7 @@ def to_track(e) -> Track:
),
key=lambda chip: chip.slot,
)
wheel, mode = parse_key(info.key if info else None)
key_text, wheel, mode = entry_key(e)
return Track(
id=primary_key(loc) if loc else (e.title or ""),
artist=e.artist,
@@ -137,7 +155,7 @@ def to_track(e) -> Track:
# Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING).
comment2=info.rating if info else None,
bpm=beatgrid.effective_bpm(e),
key=info.key if info else None,
key=key_text,
key_wheel=wheel,
key_mode=mode,
rating=_rating_stars(info.ranking if info else None),
@@ -157,6 +175,43 @@ def to_track(e) -> Track:
)
#: Traktor's NAME for a cue nobody named.
UNNAMED = "n.n."
def is_memory_cue(c) -> bool:
"""A cue on no pad that is not a grid marker — Traktor's memory cue.
Traktor stores it as an ordinary CUE_V2 with HOTCUE="-1", any type, drawn
on the waveform and reached with the cue panel's ‹ › (measured in Traktor
4.5, 2026-10-16). A grid marker is ALSO HOTCUE="-1"; its <GRID> child is
what tells them apart — never its name or position.
"""
return getattr(c, "grid", None) is None and (c.hotcue is None or c.hotcue < 0)
def memory_cue_id(c, n: int) -> str:
"""`CuePoint.id` for a memory cue: its stored START, TYPE and LEN, plus `n`
— how many identical memory cues come before it (Traktor allows several at
one START). Content-derived, so it is the same on every read."""
return f"m:{c.start or 0.0:.6f}:{c.type}:{c.len or 0.0:.6f}:{n}"
def with_memory_ids(entry) -> list:
"""(cue, its memory id or None) for every CUE_V2 of an entry, in order."""
seen: dict[str, int] = {}
out = []
for c in entry.cue_v2 or []:
if not is_memory_cue(c):
out.append((c, None))
continue
base = memory_cue_id(c, 0)
n = seen.get(base, 0)
seen[base] = n + 1
out.append((c, memory_cue_id(c, n)))
return out
def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
"""Project an ENTRY's beatgrid + cues.
@@ -182,20 +237,30 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
)
for i, m in enumerate(markers)
]
# A pad MAP put on a memory cue leaves the memory cue in place at the same
# START (measured in Traktor 4.5); Traktor draws ONE marker, so the pad
# stands for both (decided 2026-10-16).
pad_starts = {c.start for c in entry.cue_v2 or []
if getattr(c, "grid", None) is None and c.hotcue is not None and c.hotcue >= 0}
cues = []
for c in entry.cue_v2 or []:
for c, memory_id in with_memory_ids(entry):
if getattr(c, "grid", None) is not None:
continue # a grid marker is projected as a beatgrid marker, not a cue
if memory_id is not None and c.start in pad_starts:
continue
marker = marker_of.get(id(c))
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
cues.append(
CuePoint(
name=c.name,
# "n.n." is the name Traktor gives every cue the user did not
# name — a placeholder, not a name, so it crosses as none
# (it once landed in rekordbox as a comment reading "n.n.").
name=None if c.name in (None, "", UNNAMED) else c.name,
# An unknown TYPE is projected as a plain cue rather than dropped:
# preserving a cue we cannot name beats hiding it from the user.
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
# Every Traktor cue lives in the hotcue bank.
role="hotcue",
# A cue on no pad (HOTCUE="-1") is a memory cue.
role="hotcue" if slot is not None else "memory",
start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
length=(c.len or 0.0) / 1000.0,
slot=slot,
@@ -203,6 +268,7 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
editable=True,
readonly_reason=None,
grid_marker=marker,
id=memory_id,
)
)
return TrackCues(
+248 -21
View File
@@ -35,6 +35,7 @@ from traktor_nml_utils.models.collection import (
Entrytype,
GridType,
Infotype,
MusicalKeytype,
Locationtype,
Nodetype,
Playlisttype,
@@ -48,13 +49,14 @@ from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
from ...core.pathmap import PathMapping, stored_form
from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode
from . import beatgrid, timebase
from .locations import os_path_to_location, resolve_path
from .projection import iso_date, traktor_date
from ...core import musical_key
from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
# this email is what makes the stars show up in Traktor itself.
@@ -77,6 +79,9 @@ class TraktorStore:
self.dirty = False
# Active OS-path prefix remapping (empty = identity). Survives _load().
self._path_mapping = PathMapping()
# Write a file added through a mapping in the library's STORED form
# (`pathmap.stored_form`) — a Konduktor server sets this.
self._write_stored_paths = False
# Mappings the user confirmed in the open-time missing-files check.
# Session-only: never saved, re-derived on every open.
self._session_mappings: list[PathMapping] = []
@@ -99,6 +104,7 @@ class TraktorStore:
self._journal = EditJournal()
# track_id -> (image_bytes, mime) of staged replacement cover art
self._track_art: dict[str, tuple[bytes, str]] = {}
self._notation: str | None = None
self.dirty = False
def _note(
@@ -154,11 +160,13 @@ class TraktorStore:
can_reorder=True,
can_rename=True,
can_delete=True,
can_move=True,
)
if ntype == "SMARTLIST" or node.smartplaylist is not None:
# Rule-based, so it has no static entry list to show or edit.
return PlaylistNode(
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart"
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
can_move=True,
)
path = parent_path + [name]
return PlaylistNode(
@@ -169,6 +177,7 @@ class TraktorStore:
can_contain_children=True,
can_rename=True,
can_delete=True,
can_move=True,
)
@staticmethod
@@ -342,6 +351,79 @@ class TraktorStore:
self._note("playlist-delete", node.name)
self.dirty = True
def _find_node(self, node_id: str) -> Nodetype:
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
smart playlist's `sl:` path (its folder path plus its own name)."""
if node_id.startswith("fld:"):
return self._find_folder(node_id)
if node_id.startswith("sl:"):
*folders, name = node_id[len("sl:"):].split("/")
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
match = next(
(c for c in self._children(parent)
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
None,
)
if match is None:
raise PlaylistError(f"Smart playlist not found: {node_id}")
return match
node = self._find_playlist_node(node_id)
if node is None:
raise PlaylistError(f"Playlist not found: {node_id}")
return node
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children (counted without
it) and return its id afterwards — a folder's and a smart playlist's id
is their path of names, so moving one changes it (and its subtree's).
A folder or smart playlist landing beside a namesake of its own kind is
refused, as rename refuses it: the two paths would be one, and one of
them unaddressable. Playlists are UUIDs, so their names may repeat."""
with self._lock:
node = self._find_node(node_id)
if node is self._root():
raise PlaylistError("Cannot move the root folder")
dest = self._find_folder(parent_id)
if dest is node or any(n is dest for n in self._iter_nodes(node)):
raise PlaylistError("A folder cannot be moved into itself")
is_folder = node.playlist is None and node.smartplaylist is None and (
node.type or "FOLDER") == "FOLDER"
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
if is_folder or is_smart:
kind = "folder" if is_folder else "smart playlist"
for c in self._children(dest):
same_kind = (
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
and c.smartplaylist is None
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
if c is not node and same_kind and c.name == node.name:
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
source = self._find_parent_of(node)
if source is None:
raise PlaylistError("Cannot move a top-level node")
siblings = [c for c in self._children(dest) if c is not node]
index = max(0, min(int(index), len(siblings)))
if source is dest and self._children(dest).index(node) == index:
return self._node_id(node, parent_id) # already there
source.subnodes.node.remove(node)
source.subnodes.count = len(source.subnodes.node)
if dest.subnodes is None:
dest.subnodes = Subnodestype(node=[], count=0)
dest.subnodes.node.insert(index, node)
dest.subnodes.count = len(dest.subnodes.node)
self._note("playlist-move", node.name)
self.dirty = True
return self._node_id(node, parent_id)
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
if node.playlist is not None:
return node.playlist.uuid
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
with self._lock:
node = self._find_playlist_node(playlist_uuid)
@@ -399,6 +481,69 @@ class TraktorStore:
self._journal.record("track", "set", track_id, k)
self.dirty = True
# ---- musical key ----------------------------------------------------
def _collection_notation(self) -> str | None:
"""The notation this collection's INFO@KEY values are written in — a
Traktor preference (Open Key / Camelot / musical) the NML does not
record, so it is read off the keys themselves; the majority wins. None
when the collection holds no keys — never cached, since adding entries
to an empty collection (an export) is exactly when it changes. Once
known it is kept for the session: every key Konduktor writes is in it,
so it can only move if one could out-vote thousands."""
from collections import Counter
if self._notation is not None:
return self._notation
seen = Counter(
musical_key.notation_of(e.info.key)
for e in self._nml.collection.entry
if e.info is not None and e.info.key
)
seen.pop(None, None)
self._notation = seen.most_common(1)[0][0] if seen else None
return self._notation
def key_notation(self) -> str:
"""`_collection_notation`, or Open Key (Traktor's default) when there
are no keys to go by. A key in another notation would display fine but
read as foreign beside its neighbours."""
return self._collection_notation() or "open_key"
def _added_key_text(self, track) -> str | None:
"""INFO@KEY for an entry `add_entry` creates: rendered from the wheel in
this collection's notation, never copied — a Pioneer source says "Abm",
which reads as foreign beside "9m". A collection with no keys yet (an
export's fresh skeleton) takes a Traktor-native source's own notation,
so Traktor -> Traktor keeps the user's (the export decision). Text that
names no key is kept as it was: dropping it would lose information."""
text = getattr(track, "key", None) or None
wheel, mode = getattr(track, "key_wheel", None), getattr(track, "key_mode", None)
if not (wheel and mode):
return text
notation = self._collection_notation()
if notation is None:
own = musical_key.notation_of(text)
notation = own if own in ("open_key", "camelot") else "open_key"
return musical_key.render(wheel, mode, notation)
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
"""Set a track's key as Traktor's analysis writes one: the display
text in INFO@KEY (in the collection's notation; also what reaches the
file's tag at Save) AND the analysed value in `<MUSICAL_KEY>`."""
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
if entry.info is None:
entry.info = Infotype()
before = entry.info.key
entry.info.key = musical_key.render(wheel, mode, self.key_notation())
entry.musical_key = MusicalKeytype(value_attribute=musical_key_value(wheel, mode))
self._journal.record("track", "set", track_id, "key", before, entry.info.key)
self.dirty = True
# ---- adding tracks --------------------------------------------------
def add_entry(self, track, audio_path: Path) -> str:
"""Append a brand-new ENTRY for `audio_path` and return its track id.
@@ -428,7 +573,7 @@ class TraktorStore:
# Read before the lock: it opens the file.
stems = nml_stems_for(audio_path)
with self._lock:
volume, dir_, file = os_path_to_location(Path(audio_path))
volume, dir_, file = os_path_to_location(self._stored(Path(audio_path)))
key = f"{volume}{dir_}{file}"
if key in self._entry_by_key:
raise PlaylistError(
@@ -443,7 +588,7 @@ class TraktorStore:
remixer=getattr(track, "remixer", None) or None,
producer=getattr(track, "producer", None) or None,
mix=getattr(track, "mix", None) or None,
key=getattr(track, "key", None) or None,
key=self._added_key_text(track),
bitrate=getattr(track, "bitrate", None) or None,
playcount=getattr(track, "playcount", None) or None,
# The generic model carries ISO dates; Traktor writes "YYYY/M/D".
@@ -469,6 +614,12 @@ class TraktorStore:
# projected BPM so a track with no grid still shows a tempo;
# `replace_grid` overwrites it from the markers when they land.
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
# The analysed key, as Traktor's own analysis stores it.
musical_key=(
MusicalKeytype(value_attribute=musical_key_value(track.key_wheel, track.key_mode))
if getattr(track, "key_wheel", None) and getattr(track, "key_mode", None)
else None
),
cue_v2=[],
stems=Stemstype(stems=stems) if stems else None,
)
@@ -619,21 +770,7 @@ class TraktorStore:
if name is not None:
existing.name = name
else:
if entry.cue_v2 is None:
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
name=name or "n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
len=len_ms,
repeats=-1,
hotcue=slot,
color=None,
grid=None,
)
)
self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, slot, name))
# "add" only when it's a genuinely new hotcue; repositioning/retyping
# an existing slot is a "modify" (keeps the net add/remove count honest).
self._note(
@@ -665,6 +802,87 @@ class TraktorStore:
name=getattr(spec, "name", None),
)
@staticmethod
def _new_cue(cue_type: int, start_ms: float, len_ms: float, hotcue: int,
name: str | None) -> CueV2Type:
"""A CUE_V2 as Traktor writes one by hand — on a pad, or on none
(`hotcue` -1, a memory cue: the same element, measured in Traktor 4.5)."""
return CueV2Type(
name=name or "n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
len=len_ms,
repeats=-1,
hotcue=hotcue,
color=None,
grid=None,
)
@staticmethod
def _insert_cue(entry: Entrytype, cue: CueV2Type) -> None:
"""Insert a new cue at its place BY START, after every cue at or before
it — Traktor keeps CUE_V2 sorted by START (8485/8485 reference entries,
and its own saves), so a later Traktor save moves nothing. Nothing else
moves either, unlike a re-sort of an entry another tool left unsorted."""
if entry.cue_v2 is None:
entry.cue_v2 = []
at = len(entry.cue_v2)
while at > 0 and (entry.cue_v2[at - 1].start or 0.0) > (cue.start or 0.0):
at -= 1
entry.cue_v2.insert(at, cue)
# ---- memory cues: CUE_V2 on no pad (HOTCUE="-1"), not a grid marker -----
# Measured in Traktor 4.5 (2026-10-16, kit M3): any type, no limit, drawn
# on the waveform and reached with the cue panel's ‹ ›, a name shown in the
# cue panel — and a cue written here survives Traktor's own save byte for
# byte. Addressed by `projection.memory_cue_id`.
def _memory_cue(self, entry: Entrytype, cue_id: str) -> CueV2Type:
cue = next((c for c, mid in with_memory_ids(entry) if mid == cue_id), None)
if cue is None:
raise PlaylistError(f"Memory cue {cue_id!r} not found on this track")
return cue
def add_memory_cue(self, track_id: str, start_sec: float, cue_type: int,
length_sec: float = 0.0, name: str | None = None) -> None:
if cue_type not in self.CREATABLE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
len_ms = max(0.0, length_sec * 1000.0)
self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, -1, name))
self._note("hotcue", "add", track_id, "memory")
self.dirty = True
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
self._memory_cue(entry, cue_id).name = name or "n.n."
self._note("hotcue", "modify", track_id, "memory")
self.dirty = True
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: int) -> None:
"""A point type only, as for a hot cue: a loop is not retyped."""
if cue_type not in self.POINT_CUE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
cue = self._memory_cue(entry, cue_id)
if cue.type not in self.POINT_CUE_TYPES:
raise PlaylistError("A memory loop keeps its type")
cue.type = cue_type
self._note("hotcue", "modify", track_id, "memory")
self.dirty = True
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
cue = self._memory_cue(entry, cue_id)
entry.cue_v2 = [c for c in entry.cue_v2 if c is not cue]
self._note("hotcue", "delete", track_id, "memory")
self.dirty = True
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
if cue_type not in self.POINT_CUE_TYPES:
@@ -988,6 +1206,15 @@ class TraktorStore:
with self._lock:
self._path_mapping = mapping
def set_write_stored_paths(self, enabled: bool) -> None:
self._write_stored_paths = bool(enabled)
def _stored(self, os_path: Path) -> Path:
"""Where a NEW entry points, as the collection stores paths."""
if not self._write_stored_paths:
return Path(os_path)
return stored_form(Path(os_path), [self._path_mapping, *self._session_mappings])
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
"""Set the mappings confirmed for this session (applied at resolve time)."""
with self._lock:
@@ -1283,7 +1510,7 @@ class TraktorStore:
if swap.mode not in ("repoint", "add"):
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
seen_ids.add(swap.track_id)
loc = os_path_to_location(Path(swap.stem_path))
loc = os_path_to_location(self._stored(Path(swap.stem_path)))
new_key = "".join(x or "" for x in loc)
if new_key in self._entry_by_key or new_key in new_keys:
raise PlaylistError(
+82 -23
View File
@@ -28,11 +28,12 @@ import os
import threading
from pathlib import Path
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
from . import adapters, library_id, prefs # noqa: F401 — registers adapters
from .core import registry
from .core.adapter import LibraryAdapter
from .core.pathmap import PathMapping
from .relocation import RelocationCheck
from .services import LibraryServices, LocalServices
class AppState:
@@ -61,6 +62,18 @@ class AppState:
# and what the last open's crash recovery did about any left over.
self.pending = None
self.recovery: dict | None = None
# Where this library's history (and, for a remote, its export sets and
# ledger) are kept — see `services.py`.
self.services: LibraryServices | None = None
# The open remote's connection (`adapters/remote/session.py`), or None
# for a library on this computer.
self.remote = None
# …and the saved remote it was opened through (`adapters/remote/config.py`).
self.remote_config = None
# Called with the adapter at the end of every open (and so after a
# restore, which reopens): how a Konduktor SERVER re-applies the path
# mapping its configuration names, which lives in no prefs file.
self.open_hooks: list = []
@property
def loaded(self) -> bool:
@@ -120,16 +133,7 @@ class AppState:
# write-ahead log beside a file another process replaces is how a SQLite
# library gets corrupted. Only close once the new one has parsed, so a
# failed open leaves the current library intact.
previous = self.adapter
# Leaving a library discards its unsaved edits (the UI has confirmed), so
# a stem conversion's parked originals go back under their own names.
if self.pending is not None and self.pending.items:
self.pending.restore()
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
except Exception: # noqa: BLE001 — a failed close must not block the open
pass
self._release_previous()
# Apply this library's saved OS-path remapping (per-machine, keyed by the
# library's local path) so runtime translation is live on open.
saved = prefs.get_path_mapping(str(path))
@@ -161,9 +165,55 @@ class AppState:
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(adapter)
# Version history: record an "as I found it" baseline (deduped, so
# re-opening an unchanged library is a no-op). Best-effort.
history.ensure_baseline(path)
self.services = LocalServices(path)
self.services.baseline()
for hook in self.open_hooks:
hook(adapter)
def _release_previous(self) -> None:
previous = self.adapter
# Leaving a library discards its unsaved edits (the UI has confirmed), so
# a stem conversion's parked originals go back under their own names.
if self.pending is not None and self.pending.items:
self.pending.restore()
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
except Exception: # noqa: BLE001 — a failed close must not block the open
pass
if self.remote is not None and self.library_id:
# A remote library's export sets were the server's; stop asking it.
from . import exports
exports.use_store(self.library_id, None)
self.adapter = None
self.remote = None
self.remote_config = None
def open_remote(self, opened) -> None:
"""Make an already-connected remote library THE library.
`opened` is what `adapters.remote.open_remote` returns: the adapter, its
services and session, and the server's identity for the library. The
connection (handshake, version check, session) is made BEFORE this, so
a refusal leaves the current library intact, as a failed parse does.
"""
with self.mutation:
self._release_previous()
self.path = opened.path
self.adapter = opened.adapter
self.services = opened.services
self.remote = opened.session
self.remote_config = opened.remote
# The server's id for the library: export sets are keyed by it, and
# they live on the server too, so every computer sees the same ones.
self.library_id = opened.library_id
# The server keeps its own ledger of converted tracks; nothing of a
# remote library's lives in this computer's.
self.pending = opened.pending
self.recovery = None
# A remote library's files are not on this computer's drives.
self.relocation = None
def save(self):
"""Write the library, then record the saved bytes in version history.
@@ -178,15 +228,7 @@ class AppState:
def _save(self):
outcome = self.adapter.save()
# Not every platform is versioned. A library that is more than one file
# has no single blob that IS the library, and it says so through its
# capabilities rather than this module knowing which platforms those are.
versioned = self.adapter.capabilities().save.history
commit = None
if versioned and outcome.snapshot is not None:
commit = history.commit(
self.path, outcome.snapshot, outcome.summary, __version__
)
commit = self.services.commit_save(self.adapter, outcome)
# The swap is now on disk: what it replaced can go. After the library
# write, so a failed save deletes nothing; here rather than in the save
# route, because import and path remap save too.
@@ -209,8 +251,25 @@ class AppState:
with self.mutation:
if self.pending is not None and self.pending.items:
self.pending.restore()
if self.services is not None and self.services.remote:
# The server holds the edits; it is what drops them.
self.services.discard()
self.adapter.reload()
def restore_version(self, commit_id: str) -> bool:
"""Write a past version back as a new save and re-read the library.
False when the version is unknown."""
assert self.adapter is not None and self.services is not None
with self.mutation:
if not self.services.restore(commit_id):
return False
if self.services.remote:
# The server reopened its own library; follow it.
self.adapter.reload()
else:
self._open(self.path) # rebuild read + edit models from the restored file
return True
STATE = AppState()
+101
View File
@@ -65,6 +65,60 @@ class SaveOutcome:
tag_results: list = field(default_factory=list)
@dataclass(frozen=True)
class AudioFacts:
"""One track's audio file as its library's host sees it — WITHOUT reading it.
`key` is the file's path on the machine that holds it (a string, because on
a remote library that is not this machine), `size` and `mtime_ns` its stat.
Together they name one version of one file: what an export's manifest
records, what the analysis cache keys on, and how a downloaded copy is
recognised. Callers that only need a file's IDENTITY ask for these rather
than `audio_path`, which on a remote library means downloading it.
"""
key: str
size: int
mtime_ns: int
def local_audio_facts(adapter, track_ids) -> dict[str, AudioFacts]:
"""`audio_facts` for a library whose files are on this machine: stat each
`audio_path`. A track whose file is missing is left out."""
out: dict[str, AudioFacts] = {}
for track_id in track_ids:
try:
path = adapter.audio_path(track_id)
if path is None:
continue
st = Path(path).stat()
except (OSError, AdapterError):
continue
if not Path(path).is_file():
continue
out[track_id] = AudioFacts(key=str(path), size=st.st_size, mtime_ns=st.st_mtime_ns)
return out
@dataclass
class PreparedAnalysis:
"""What adding a track would otherwise decode the file to learn.
A platform that must ANALYSE what it adds (Rekordbox: the waveform and grid
live in its ANLZ files) decodes each file in `add_tracks`. When the library
lives on a server that never decodes audio, the client does that work on
its own copy and the result travels with the track. `measured` is a
`core.waveform.Analysis` measured with the file's own time-base lead,
`markers` the detected grid (empty: none found) and `key` the detected
`core.key_detect.KeyResult` (None: not asked for, or none found). Absent,
the adapter decodes as before.
"""
measured: object
markers: list = field(default_factory=list)
key: object | None = None
@dataclass
class NewTrack:
"""A track to ADD to a library, described generically.
@@ -93,6 +147,9 @@ class NewTrack:
# For a platform that keeps its own copy of the art (Rekordbox); one that
# reads the file's tags (Traktor) ignores it.
art: tuple[bytes, str] | None = None
# Precomputed analysis for a platform that would otherwise decode the file
# (see `PreparedAnalysis`); ignored by one that does not analyse.
analysis: PreparedAnalysis | None = None
@dataclass(frozen=True)
@@ -153,6 +210,11 @@ class Unsupported(AdapterError):
"""The platform cannot represent this edit at all."""
class Unavailable(AdapterError):
"""The library's host cannot be reached, or no longer lets this computer
write (a library held by a server, taken over by another computer)."""
@runtime_checkable
class LibraryAdapter(Protocol):
"""One open library. Stateful; exactly one is loaded at a time."""
@@ -172,6 +234,7 @@ class LibraryAdapter(Protocol):
def facets(self) -> Facets: ...
def stats(self, playlist_count: int) -> Stats: ...
def playlist_tree(self) -> list[PlaylistNode]: ...
def playlist_count(self) -> int: ...
def playlist_entries(self, node_id: str) -> list[str] | None: ...
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
def track_cues(self, track_id: str) -> TrackCues | None: ...
@@ -184,6 +247,12 @@ class LibraryAdapter(Protocol):
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
def rename_playlist(self, node_id: str, name: str) -> None: ...
def delete_playlist(self, node_id: str) -> None: ...
# Move a node (playlist, folder or smart playlist) to `index` among
# `parent_id`'s children (None = the top level), counted with the moved
# node left out. Returns the node's id AFTER the move: an id is opaque, and
# on a platform that addresses a folder by its path it changes. A folder
# cannot go into itself or a descendant (InvalidCommand).
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
# ---- commands: adding tracks ----------------------------------------
@@ -223,6 +292,10 @@ class LibraryAdapter(Protocol):
# ---- commands: track metadata / art ---------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
# The musical key, as a Camelot wheel position (1-12) + mode — what key
# analysis writes. Each platform renders it in its own notation (and its own
# analysed-key field, where it has one). Gated on `tracks.key_writable`.
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ...
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
@@ -245,6 +318,29 @@ class LibraryAdapter(Protocol):
def delete_cue(self, track_id: str, slot: int) -> 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 ---------------------------------------------
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: ...
@@ -256,7 +352,12 @@ class LibraryAdapter(Protocol):
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
# ---- audio / paths ---------------------------------------------------
# A READABLE file on this machine — which, for a library held by a server,
# means downloading it. Anything that only needs to know WHICH file a track
# is (an export plan, "is this already in the library?") asks `audio_facts`
# instead, which never reads the file and never downloads.
def audio_path(self, track_id: str) -> Path | None: ...
def audio_facts(self, track_ids: list[str]) -> dict[str, AudioFacts]: ...
def set_path_mapping(self, mapping: PathMapping) -> None: ...
# The open-time missing-files check (`core/relocate.py`): the stored volumes
# in which NO track resolves, and the mappings the user confirmed for them —
+52
View File
@@ -0,0 +1,52 @@
"""The analysis a platform that ANALYSES what it adds needs for one new track.
Rekordbox draws a new track's waveform and grid from its ANLZ files, so adding a
track means decoding it once: the waveform measured on the platform's own clock
(`lead`, read from the file's header by that platform) plus a detected grid and
key when the track brings none. One definition, used both by the adapter (a library on
this computer) and by the client of a library held by a server — which never
decodes audio, so the client measures its own copy and sends the result
(`PreparedAnalysis`) with the track.
"""
from __future__ import annotations
import logging
from pathlib import Path
from .adapter import PreparedAnalysis
from .model import GridMarker
def prepare(path: Path, *, lead: float, detect: bool = True,
detect_key: bool = False) -> PreparedAnalysis:
"""Decode `path` once: its waveform at `lead`, and (with `detect`) a grid,
(with `detect_key`) a key."""
from . import grid_detect, waveform
samples = waveform.decode(Path(path))
measured = waveform.analyse_samples(samples, lead=lead)
markers: list[GridMarker] = []
if detect and samples is not None:
try:
found = grid_detect.detect_grid(str(path), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
key = None
if detect_key and samples is not None:
from . import key_detect
try:
key = key_detect.detect_key_samples(samples, waveform.SR)
except Exception: # noqa: BLE001 - a missing key is not worth failing an add over
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
return PreparedAnalysis(measured=measured, markers=markers, key=key)
def with_key(track, key):
"""`track` (a generic `Track`) with the detected `key` if it has none of its
own. A key the track already carries (its tags, its source library) is
never second-guessed."""
if key is None or getattr(track, "key_wheel", None) is not None:
return track
return track.model_copy(update={"key": key.name, "key_wheel": key.wheel, "key_mode": key.mode})
+9 -2
View File
@@ -22,7 +22,10 @@ DEFAULT_POPM_EMAIL = "no@email"
# The safe, editable metadata we sync to files (the adapter's editable field set).
# rating is 0–5 stars.
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
# comment, mix, release_date, rating
# comment, mix, release_date, rating, key
# `key` is written as the library holds it ("9m", "Abm") into the frame DJ
# software reads: ID3 TKEY, MP4/FLAC `initialkey` — where Traktor writes its
# own (every key-tagged file on the dev machine has it there).
@dataclass
@@ -170,6 +173,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
TDRC,
TIT2,
TIT3,
TKEY,
TPE1,
TPE4,
TPUB,
@@ -185,6 +189,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
"remixer": TPE4,
"mix": TIT3,
"release_date": TDRC,
"key": TKEY,
}
for field, frame in simple.items():
if field in meta:
@@ -262,7 +267,8 @@ def _write_mp4(path: Path, meta: TagMeta) -> None:
else:
t[atom] = [val]
# No standard MP4 atoms for these — use iTunes-style freeform atoms.
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"}
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX",
"key": "initialkey"}
for field, name in freeform.items():
if field in meta:
key = f"----:com.apple.iTunes:{name}"
@@ -297,6 +303,7 @@ def _write_flac(path: Path, meta: TagMeta) -> None:
"comment": "comment",
"mix": "mixname",
"release_date": "date",
"key": "initialkey",
}
for field, vc in mapping.items():
if field in meta:
+37 -3
View File
@@ -25,7 +25,12 @@ from pydantic import BaseModel
# `browsing` is an editable library opened only to READ alongside the loaded one
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
# as THE library, which one SaveBar and one dirty state can then follow.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"]
# `taken_over` is a library held by a server that another computer has taken
# over; `offline` one whose server cannot be reached. Both are temporary, and
# both mean "nothing you do here can be saved" until the session is back.
ReadonlyCause = Literal[
"platform_incomplete", "cloud_synced", "not_in_library", "browsing", "taken_over", "offline",
]
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
@@ -40,10 +45,17 @@ class CueCapabilities(BaseModel):
editable: bool = False
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
slot_labels: Literal["number", "letter"] = "number"
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
# but not editable anywhere yet (the two-platform promotion rule).
# Cues on no pad, listed in time order and called CDJ-style (decided
# 2026-10-16). Editable wherever `editable` is: every platform that has them
# can store them (Rekordbox, OneLibrary, and Traktor's HOTCUE="-1").
memory_cues: bool = False
# Per track; None = no limit. rekordbox stops storing at 10 WITHOUT saying
# so, so the adapter refuses the 11th itself.
max_memory_cues: int | None = None
# A memory cue's colour is its own palette, not `palette` (rekordbox offers
# 8 colours for memory cues against 16 for hot cues).
memory_color: Literal["none", "palette"] = "none"
memory_palette: list[str] = []
types: list[CueType] = ["cue"]
color: Literal["none", "free", "palette"] = "none"
palette: list[str] = []
@@ -78,18 +90,39 @@ class TrackCapabilities(BaseModel):
# Tracks can be converted to native-instruments STEM files, which this
# platform plays as stems (`apply_stem_swaps`).
stem_convertible: bool = False
# The musical key can be set (`set_key`) — what key analysis writes. Not
# in `editable_fields`: a key is a wheel position, not free text.
key_writable: bool = False
# The audio files this library can hold, as lower-case suffixes. What a
# browsed folder offers to add — a file the library would refuse, or that
# the DJ app cannot play, is not worth listing as addable.
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
artwork: bool = False
artwork_note: str | None = None
# Whose filesystem an import destination is on. "host": this computer's,
# browsed with the ordinary file browser. "library": the machine that holds
# the library (a server), whose folders are listed through the library —
# added audio is UPLOADED there.
audio_destination: Literal["host", "library"] = "host"
# Whether added files can be left where they are ("reference") rather than
# copied. False where the library cannot see this computer's files at all.
reference: bool = True
class PlaylistCapabilities(BaseModel):
folders: bool = False
smart: Literal["none", "read_only"] = "none"
reorder: bool = False
# A playlist can hold the same track more than once. Where it cannot, a
# drop of tracks already there skips them rather than asking.
duplicates: bool = False
class PathCapabilities(BaseModel):
# Path mapping, path rewriting and the open-time missing-files check apply.
# False for a library held by a server: its mapping is the server's own
# configuration, and this computer's drives are not where its files are.
remappable: bool = True
class SaveCapabilities(BaseModel):
@@ -126,4 +159,5 @@ class Capabilities(BaseModel):
grid: GridCapabilities = GridCapabilities()
tracks: TrackCapabilities = TrackCapabilities()
playlists: PlaylistCapabilities = PlaylistCapabilities()
paths: PathCapabilities = PathCapabilities()
save: SaveCapabilities
+2 -3
View File
@@ -25,9 +25,8 @@ MEMORY_COLOR = "#9AA1B2" # grey
def effective_color(cue: CuePoint) -> str:
"""`#RRGGBB` — the stored colour, or the type's."""
"""`#RRGGBB` — the stored colour, or the type's: hot and memory cues alike
(a memory cue's type colours it too, decided 2026-10-16)."""
if cue.color:
return cue.color.upper()
if cue.role == "memory":
return MEMORY_COLOR
return TYPE_COLORS.get(cue.type, MEMORY_COLOR)
+16 -12
View File
@@ -167,21 +167,23 @@ class EditJournal:
else:
parts.append(f"{verb} {len(names)} {noun}s")
# --- hotcues: net change in count, scoped by how many tracks were touched ---
hc_add = hc_del = 0
hc_tracks: set[str] = set()
# --- cues: net change in count, scoped by how many tracks were touched.
# Memory cues (detail "memory") are counted apart from hotcues, so a
# session of memory-cue edits is not described as hotcue work.
counts = {kind: [0, 0, set()] for kind in ("hotcue", "memory cue")}
grid_edit: set[str] = set()
grid_del: set[str] = set()
lock_on: set[str] = set()
lock_off: set[str] = set()
for c in self.changes:
if c.scope == "cue":
bucket = counts["memory cue" if c.detail == "memory" else "hotcue"]
if c.target:
hc_tracks.add(c.target)
bucket[2].add(c.target)
if c.op == "add":
hc_add += 1
bucket[0] += 1
elif c.op == "delete":
hc_del += 1
bucket[1] += 1
elif c.scope == "grid":
# "delete" is the ONLY deletion op. Everything else — including
# ops added later — counts as an edit, because mis-labelling an
@@ -190,15 +192,17 @@ class EditJournal:
elif c.scope == "lock":
(lock_on if c.op == "on" else lock_off).add(c.target or "")
if hc_tracks:
net = hc_add - hc_del
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else ""
for noun, (added, deleted, touched) in counts.items():
if not touched:
continue
net = added - deleted
scope = f" across {tracks(len(touched))}" if len(touched) > 1 else ""
if net > 0:
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}")
parts.append(f"added {net} {noun}{'' if net == 1 else 's'}{scope}")
elif net < 0:
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}")
parts.append(f"removed {-net} {noun}{'' if -net == 1 else 's'}{scope}")
else: # net zero but there was activity (moves / retypes / add-then-delete)
parts.append(f"adjusted hotcues{scope}")
parts.append(f"adjusted {noun}s{scope}")
# --- beatgrids & lock: per-track counts ---
if grid_edit:
+7 -1
View File
@@ -94,8 +94,14 @@ class ExportPayload:
tracks: list[ExportTrack] = field(default_factory=list)
playlists: list[ExportPlaylist] = field(default_factory=list)
#: The export's name, used for the folder its playlists are nested under.
#: The export's name, used for the folder its playlists are nested under
#: when `root_folder` is set.
name: str = "Export"
#: Nest the whole playlist tree (and "Other") in one folder named `name`.
#: Off — the default, a Konduktor setting — the playlists sit at the
#: library's top level: an export is a library of its own, so a folder
#: saying where it came from is one more click at the gig.
root_folder: bool = False
#: Called by a writer before each slow step (e.g. decoding a track for its
#: waveform) with a message for the status bar, and — for a per-track loop —
#: `step` of `of`, which drives the progress bar. RAISES when the user has
+107 -6
View File
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
Three rules:
* **This folder only.** Subfolders are not scanned — the tree is how you get to
them — so a click on a drive root never walks the whole drive.
them — so a click on a drive root never walks the whole drive. A folder
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
* **A track id is the file's absolute path.** It is the one identity a loose
file has, and it is what the audio route checks a request against.
* **Tags are read once per folder state.** Reading tags opens every file, which
@@ -26,6 +28,7 @@ from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass, field
from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
@@ -150,6 +153,11 @@ class FolderSource:
def audio_path(self, track_id: str) -> Path | None:
return Path(track_id) if track_id in self._by_id else None
def audio_facts(self, track_ids: list[str]):
from .adapter import local_audio_facts
return local_audio_facts(self, track_ids)
def playlist_tree(self) -> list[PlaylistNode]:
return []
@@ -160,17 +168,88 @@ class FolderSource:
return capabilities_for(self.path)
# A drop of a whole drive must not read tags for hours: past this many audio
# files the rest are left out and the answer says so.
MAX_DROPPED = 20_000
@dataclass
class Dropped:
"""What a drop onto the window resolved to."""
tracks: list[Track] = field(default_factory=list)
# Dropped FILES that are not audio this library can hold (or are gone).
# Non-audio inside a dropped folder is not counted: an album folder's
# cover and cue sheet are not something the user asked to add.
skipped: int = 0
# More than MAX_DROPPED audio files: the rest were left out.
truncated: bool = False
class FolderScanner:
"""Scans folders on request, caching each until its contents change.
Also the gatekeeper for streaming: `source_for_file` answers only for a file
found by a scan, so the audio route cannot be used to read an arbitrary path
off the disk — only audio the user has browsed to.
found by a scan — or dropped onto the window by the user — so the audio
route cannot be used to read an arbitrary path off the disk, only audio the
user has browsed to or handed over.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
# Files dropped one by one: their folder was never scanned (and is not
# cached as if it had been — a partial listing would hide its other
# files from the sidebar), so each is held on its own.
self._files: dict[str, Track] = {}
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
and OS-housekeeping folders left out, as the tree leaves them out),
files as themselves. Every audio file found becomes addable and
playable through the folder routes, exactly as if it had been browsed."""
wanted = {f.lower() for f in formats}
out = Dropped()
seen: set[str] = set()
def take(tracks: list[Track]) -> bool:
for t in tracks:
if t.id in seen:
continue
if len(out.tracks) >= limit:
out.truncated = True
return False
seen.add(t.id)
out.tracks.append(t)
return True
for raw in paths:
path = Path(raw).expanduser()
if path.is_dir():
for folder in _walk(path):
if not audio_files(folder, formats):
continue
if not take(self.scan(folder, formats).tracks):
return out
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
track = self._file_track(path)
if not take([track]):
return out
else:
out.skipped += 1
return out
def _file_track(self, path: Path) -> Track:
key = str(path)
with self._lock:
hit = self._cache.get(str(path.parent))
known = hit[2].track(key) if hit is not None else None
if known is not None:
return known
track = read_track(path)
with self._lock:
self._files[key] = track
return track
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
folder = Path(folder)
@@ -193,10 +272,32 @@ class FolderScanner:
folder = str(Path(track_id).parent)
with self._lock:
hit = self._cache.get(folder)
if hit is None or hit[2].track(track_id) is None:
return None
return hit[2]
loose = self._files.get(track_id)
if hit is not None and hit[2].track(track_id) is not None:
return hit[2]
if loose is not None:
return FolderSource(Path(folder), [loose])
return None
def clear(self) -> None:
with self._lock:
self._cache.clear()
self._files.clear()
def _walk(root: Path):
"""`root` and every visible folder under it, depth first, sorted by name."""
yield root
try:
with os.scandir(root) as it:
subs = []
for entry in it:
try:
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
subs.append(Path(entry.path))
except OSError:
continue
except OSError:
return
for sub in sorted(subs, key=lambda p: p.name.lower()):
yield from _walk(sub)
+52 -13
View File
@@ -213,24 +213,71 @@ def detect_grid(
*,
y: np.ndarray | None = None,
sr: int = _SR,
bpm: float | None = None,
anchor: float | None = None,
) -> GridResult:
"""Detect a track's constant tempo and first beat.
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly.
Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot).
Either half can be held fixed — the Analyze dialog's BPM and Grid ticks:
- ``bpm`` given ("Grid" alone): that tempo is KEPT — no search, no
round-BPM snap — and only where its beats fall is found. For a BPM the
user trusts (typed, or a store's) and a grid that sits off the beat.
- ``anchor`` given ("BPM" alone): the tempo is detected and the anchor
returned as given, so the grid's downbeat stays where the user put it.
``drift_ms`` is then measured against THAT anchor: large means the kept
anchor does not sit on the detected beat.
"""
if bpm is not None and anchor is not None:
raise ValueError("Hold the BPM or the anchor, not both — there would be nothing to detect")
if bpm is not None and not (20.0 <= bpm <= 400.0):
raise ValueError(f"Not a usable BPM: {bpm}")
if y is None:
import librosa
y, sr = librosa.load(audio_path, sr=sr, mono=True)
from . import waveform
y, sr = waveform.load(audio_path, sr=sr)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / sr
if duration < 1.5:
raise ValueError("Track is too short to detect a tempo")
lo, hi = bpm_range
low = _onset(_band_env(y, sr, 30.0, 150.0))
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3))
if bpm is not None:
period = 60.0 / bpm
if not np.isfinite(attack).all() or attack.max() <= 0:
raise ValueError("No onsets found")
phase = _phase(low, attack, period)
return GridResult(
bpm=float(bpm),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(_drift(attack, bpm, phase) * 1000.0, 1),
)
found_bpm, phase, drift = _detect_tempo(y, sr, low, attack, bpm_range, duration)
period = 60.0 / found_bpm
if anchor is not None:
return GridResult(
bpm=round(found_bpm, 4),
anchor=float(anchor),
duration=duration,
drift_ms=round(_drift(attack, found_bpm, float(anchor) % period) * 1000.0, 1),
)
return GridResult(
bpm=round(found_bpm, 4),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(drift * 1000.0, 1),
)
def _detect_tempo(y, sr, low, attack, bpm_range, duration) -> tuple[float, float, float]:
"""(bpm, phase, drift) — the tempo search, octave rule and round snap."""
lo, hi = bpm_range
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
o_tempo = low + mid + 0.5 * full
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0:
@@ -260,15 +307,7 @@ def detect_grid(
bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
phase = _phase(low, attack, 60.0 / bpm)
drift = _drift(attack, bpm, phase)
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration)
period = 60.0 / bpm
return GridResult(
bpm=round(bpm, 4),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(drift * 1000.0, 1),
)
return _snap_round(low, attack, bpm, phase, drift, duration)
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]:
+63
View File
@@ -0,0 +1,63 @@
"""What an analysis does to one track's grid, given the BPM / Grid ticks.
One pure function, so the batch, the dialog's counts and the tests cannot come
to mean different things. Decided with the user (2026-10-04, see
`.claude/discussions/discuss-key-analysis-2026-10-04.md`):
- BPM + Grid: a full analysis. A track that already has a grid is replaced
only when the user ticked "Replace" — a grid may hold hand edits.
- BPM alone: re-detect the tempo, KEEP the anchor (the first marker).
- Grid alone: KEEP the BPM, find only where the beats fall.
- With one tick, adjusting the existing grid is the point, so "Replace" does
not apply; a track with nothing to keep (no grid / no BPM) is analysed in
full rather than skipped — one tick never leaves a track worse off.
- A multi-marker (flexible) grid is skipped by BPM alone and Grid alone: its
tempo changes are exactly what one constant tempo would flatten.
- A locked grid is skipped whatever is ticked.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal, Sequence
Action = Literal["none", "full", "bpm", "phase", "skip"]
SkipReason = Literal["locked", "existing", "flexible"]
@dataclass(frozen=True)
class GridStep:
action: Action
reason: SkipReason | None = None
hold_bpm: float | None = None # "phase": the tempo kept
hold_anchor: float | None = None # "bpm": the anchor kept (seconds)
def plan_grid(
*,
bpm: bool,
grid: bool,
markers: Sequence, # the track's grid markers (`.start`, `.bpm`), any order
track_bpm: float | None,
locked: bool,
replace_existing: bool,
) -> GridStep:
if not (bpm or grid):
return GridStep("none")
if locked:
return GridStep("skip", "locked")
ordered = sorted(markers, key=lambda m: m.start)
if bpm and grid:
if ordered and not replace_existing:
return GridStep("skip", "existing")
return GridStep("full")
if len(ordered) > 1:
return GridStep("skip", "flexible")
if bpm: # BPM alone
if not ordered:
return GridStep("full")
return GridStep("bpm", hold_anchor=float(ordered[0].start))
# Grid alone
held = float(ordered[0].bpm) if ordered else (float(track_bpm) if track_bpm else None)
if not held or held <= 0:
return GridStep("full")
return GridStep("phase", hold_bpm=held)
+184
View File
@@ -0,0 +1,184 @@
"""Musical key detection: a small convolutional network, run in numpy.
Why a network and not key profiles. The classic method — fold the spectrum
into a 12-bin chroma vector and correlate it with a major / minor template —
was benchmarked first on GiantSteps (604 Beatport previews, keys corrected by
hand), over Krumhansl, Temperley, Sha'ath (KeyFinder) and Faraldo's EDM
templates and every combination of octave range, compression and harmonic
filtering tried: the best got 49.5% exactly right. A template sees only how
much of each pitch class there is; a network also sees WHERE in pitch it is
(the bass line, the pad, the lead) and learns from data what states a key.
The model follows Korzeniowski & Widmer, "End-to-end musical key estimation
using a convolutional neural network" (EUSIPCO 2017): five 5x5 convolutions,
then a per-frame dense layer over the whole pitch axis — a key is NOT
pitch-invariant, so nothing pools over frequency — then 24 logits averaged
over the track. ~76 k weights per network; `key_model.npz` holds an ensemble
of three (logits averaged), trained by `backend/train_key_model.py` on the
SEPARATE GiantSteps MTG dataset. torch is used only to train: the backend
never imports it.
Measured (`bench_key_detect.py`, 2026-10-04): GiantSteps 69.4% exact, 83.4%
harmonically mixable (exact, a fifth, or the relative key), MIREX 0.758 —
about the published figure for this design. Against the key tags of 47 local
files (Traktor's analysis, not ground truth) it agrees on 62%, 77% mixable.
`confidence` tracks correctness (82% exact above 0.7, ~40% below 0.4) but even
a low one is ten times better than chance, so a key is always returned for
music; only silence and clips under 5 s get None.
Cost on a 6.7-minute track: CQT 0.1 s, the three networks 0.5 s — beside the
decode, which the grid analysis shares.
"""
from __future__ import annotations
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Literal
import numpy as np
from . import musical_key
SR = 22050
HOP = 4096 # ~5.4 frames/s: key is a slow property
BINS_PER_OCTAVE = 36 # three per semitone, so a detuned track still lands in one
FMIN_NOTE = "C1"
OCTAVES = 7 # C1..C8: the input window plus room to pitch-shift it
# The network's input: C2..C7 (65 Hz - 2.1 kHz), where bass lines, pads and
# leads state the key. The octave either side is only there so training can
# shift the window by up to six semitones.
WINDOW = (36, 216)
_MODEL = Path(__file__).with_name("key_model.npz")
_TIME_CHUNK = 256 # frames per im2col block: bounds memory to tens of MB
PITCH_NAMES = musical_key.SPELLING
@dataclass(frozen=True)
class KeyResult:
pitch_class: int # tonic, 0 = C
mode: Literal["major", "minor"]
wheel: int # Camelot position 1-12, the generic model's key
confidence: float # the network's probability for this key, 0-1
@property
def name(self) -> str:
return PITCH_NAMES[self.pitch_class] + ("m" if self.mode == "minor" else "")
def camelot_wheel(pitch_class: int, mode: str) -> int:
"""Camelot position: C major = 8B, A minor = 8A; one step = a fifth."""
return musical_key.wheel_of(pitch_class, mode)
def features(y: np.ndarray, sr: int = SR) -> np.ndarray:
"""Log-magnitude constant-Q spectrogram, (OCTAVES * 36, frames), float32.
Normalised to the track's own loudest bin, so a quiet master and a loud
one give the same picture. Training calls this same function."""
import librosa
if sr != SR:
y = librosa.resample(y, orig_sr=sr, target_sr=SR)
C = np.abs(librosa.cqt(
y, sr=SR, hop_length=HOP, fmin=librosa.note_to_hz(FMIN_NOTE),
n_bins=OCTAVES * BINS_PER_OCTAVE, bins_per_octave=BINS_PER_OCTAVE, tuning=0.0,
))
peak = float(C.max()) or 1.0
return np.log1p(1000.0 * C / peak).astype(np.float32)
@lru_cache(maxsize=1)
def _members() -> list[dict[str, np.ndarray]]:
"""The ensemble: `key_model.npz` holds N networks as `m<i>.<param>`, plus
`pool` (frequency bins averaged before the dense layer; 1 = none)."""
with np.load(_MODEL) as z:
flat = {k: z[k] for k in z.files}
pool = int(flat.pop("pool"))
members: dict[int, dict[str, np.ndarray]] = {}
for k, v in flat.items():
i, name = k.split(".", 1)
members.setdefault(int(i[1:]), {})[name] = v.astype(np.float32)
for m in members.values():
m["pool"] = np.array(pool)
return [members[i] for i in sorted(members)]
def _elu(x: np.ndarray) -> np.ndarray:
return np.where(x > 0, x, np.expm1(np.minimum(x, 0)))
def _conv5(x: np.ndarray, w: np.ndarray, b: np.ndarray) -> np.ndarray:
"""'same' 5x5 convolution (cross-correlation, as torch's Conv2d).
x: (cin, F, T), w: (cout, cin, 5, 5) -> (cout, F, T)."""
cin, f, t = x.shape
xp = np.pad(x, ((0, 0), (2, 2), (2, 2)))
out = np.empty((w.shape[0], f, t), np.float32)
for t0 in range(0, t, _TIME_CHUNK):
t1 = min(t, t0 + _TIME_CHUNK)
view = np.lib.stride_tricks.sliding_window_view(xp[:, :, t0:t1 + 4], (5, 5), axis=(1, 2))
out[:, :, t0:t1] = np.tensordot(w, view, axes=([1, 2, 3], [0, 3, 4]))
return out + b[:, None, None]
def _network(x: np.ndarray, w: dict[str, np.ndarray]) -> np.ndarray:
"""One member's 24 logits, averaged over time. x: (1, F, T)."""
n = sum(1 for k in w if k.startswith("conv") and k.endswith(".weight"))
for i in range(n):
x = _elu(_conv5(x, w[f"conv{i}.weight"], w[f"conv{i}.bias"]))
pool = int(w["pool"]) # average within a semitone
if pool > 1:
f = x.shape[1] // pool * pool
x = x[:, :f].reshape(x.shape[0], f // pool, pool, -1).mean(axis=2)
dw = w["dense.weight"][..., 0] # (hid, ch, F)
h = _elu(np.tensordot(dw, x, axes=([1, 2], [0, 1])) + w["dense.bias"][:, None])
out = w["out.weight"][:, :, 0, 0] @ h + w["out.bias"][:, None] # (24, T)
return out.mean(axis=1)
def logits(spec: np.ndarray) -> np.ndarray:
"""The ensemble's 24 logits — major C..B, then minor C..B — for a
`features()` spectrogram: each member's, averaged."""
x = spec[WINDOW[0]:WINDOW[1]][None]
return np.mean([_network(x, w) for w in _members()], axis=0)
def detect_key_samples(y: np.ndarray, sr: int) -> KeyResult | None:
"""The key of decoded mono audio, or None for silence / too short to say."""
if y.size < sr * 5 or not np.any(y):
return None
z = logits(features(y, sr)).astype(np.float64)
p = np.exp(z - z.max())
p /= p.sum()
k = int(np.argmax(p))
pc, mode = k % 12, ("minor" if k >= 12 else "major")
return KeyResult(pc, mode, camelot_wheel(pc, mode), float(p[k]))
def with_detected_key(track, y: np.ndarray | None, sr: int):
"""`track` (a generic `Track`) with a detected key if it has none of its
own — for a file being ADDED, which is decoded anyway. A key the track
already carries (its tags, its source library) is never second-guessed,
and a detection failure leaves the track as it was: a missing key is not
worth failing an add over."""
if getattr(track, "key_wheel", None) is not None or y is None:
return track
try:
found = detect_key_samples(y, sr)
except Exception: # noqa: BLE001
import logging
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
return track
if found is None:
return track
return track.model_copy(update={"key": found.name, "key_wheel": found.wheel, "key_mode": found.mode})
def detect_key(audio_path: str) -> KeyResult | None:
from . import waveform
y, sr = waveform.load(audio_path, sr=SR)
return detect_key_samples(y, sr)
Binary file not shown.
+13 -3
View File
@@ -130,6 +130,9 @@ class PlaylistNode(BaseModel):
can_rename: bool = False
can_delete: bool = False
can_contain_children: bool = False # a valid parent for a new playlist
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
# its siblings or moved into another folder.
can_move: bool = False
PlaylistNode.model_rebuild()
@@ -141,8 +144,8 @@ PlaylistNode.model_rebuild()
class CuePoint(BaseModel):
name: str | None = None
type: CueType = "cue"
# "memory" cues have no bank slot. Only Rekordbox has them, so they are
# modelled and preserved but not yet editable anywhere.
# A "memory" cue has no bank slot: Rekordbox's / OneLibrary's memory cues,
# Traktor's cues on no pad (HOTCUE="-1"). Addressed by `id`, not `slot`.
role: CueRole = "hotcue"
start: float # seconds
length: float # seconds (>0 for loops)
@@ -155,6 +158,10 @@ class CuePoint(BaseModel):
# Index of the grid marker this cue mirrors, where the platform pairs them.
# A display hint only; None on platforms that do not.
grid_marker: int | None = None
# The handle the memory-cue commands take (None on a hot cue, which is
# addressed by slot). Opaque and adapter-defined; an edit of THIS cue may
# change it, which is fine because every command returns fresh TrackCues.
id: str | None = None
class GridMarker(BaseModel):
@@ -194,6 +201,9 @@ class LibraryInfo(BaseModel):
path: str
display_name: str # short label for the status bar
version: str | None = None
# Set when the library is held by a server: {id, name, via} of the saved
# remote it was opened through. None for a library on this computer.
remote: dict | None = None
class PlatformOption(BaseModel):
@@ -208,7 +218,7 @@ class PlatformOption(BaseModel):
platform: str
name: str
library_label: str
selects: Literal["file", "directory"] = "file"
selects: Literal["file", "directory", "remote"] = "file"
installed: bool = False
#: How many libraries this platform has right now; `installed` is `found > 0`.
found: int = 0
+95
View File
@@ -0,0 +1,95 @@
"""Musical keys: the generic form and the notations DJ software writes.
The generic model carries a key as a Camelot wheel position (1-12) plus a mode
(`Track.key_wheel` / `key_mode`); one step round the wheel is a fifth, and the
minor key on a number is the relative of the major one. Each platform STORES a
key in its own notation, and a library also holds whatever another tool put
there — a rekordbox stick's key table carries "12A" beside "Abm" when tracks
arrived with Camelot tags. So parsing accepts every notation, and rendering is
always explicit about which one it writes.
Notations:
- "camelot": 8A / 8B (Mixed In Key's wheel; A = minor)
- "open_key": 1m / 1d (Traktor's default; Open Key 1 = Camelot 8)
- "musical": Am / C, with rekordbox's spelling: flats for Db Eb Ab Bb, and
F# — measured from the key rows rekordbox 7 itself created (Abm, Dbm, Ebm,
Eb; the six-sharp key was not among them).
"""
from __future__ import annotations
import re
from typing import Literal
Mode = Literal["major", "minor"]
Notation = Literal["camelot", "open_key", "musical"]
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
_MUSICAL = re.compile(r"^([A-G])\s*([#b♯♭]?)\s*(m|min|minor|maj|major)?$", re.I)
_PITCH = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
SPELLING = ("C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
def wheel_of(pitch_class: int, mode: Mode) -> int:
"""Camelot position of a tonic: C major = 8B, A minor = 8A."""
return (((7 * pitch_class) % 12 + (7 if mode == "major" else 4)) % 12) + 1
def pitch_class_of(wheel: int, mode: Mode) -> int:
"""The tonic (0 = C) at a Camelot position — `wheel_of`'s inverse."""
return (7 * ((wheel - 1) - (7 if mode == "major" else 4))) % 12
def parse(text: str | None) -> tuple[int | None, Mode | None]:
"""(wheel, mode) for a key in any notation; (None, None) if unreadable.
A bare number-and-letter is ambiguous only in principle: Camelot uses A/B
and Open Key m/d, so the letter says which."""
if not text:
return None, None
s = text.strip()
if m := _CAMELOT.match(s):
n = int(m.group(1))
if 1 <= n <= 12:
return n, "minor" if m.group(2).lower() == "a" else "major"
return None, None
if m := _OPEN_KEY.match(s):
n = int(m.group(1))
if 1 <= n <= 12:
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
return None, None
if m := _MUSICAL.match(s):
letter, accidental, quality = m.group(1).upper(), m.group(2), (m.group(3) or "")
pc = _PITCH[letter] + {"#": 1, "♯": 1, "b": -1, "♭": -1}.get(accidental, 0)
# "m" alone is minor; "maj"/"major" major; "min"/"minor" minor.
q = quality.lower()
mode: Mode = "minor" if q in ("m", "min", "minor") else "major"
return wheel_of(pc % 12, mode), mode
return None, None
def render(wheel: int | None, mode: str | None, notation: Notation) -> str | None:
"""A key in `notation`, or None when the position is unknown — a made-up
key is worse than a blank one."""
if not wheel or not (1 <= wheel <= 12) or mode not in ("major", "minor"):
return None
if notation == "camelot":
return f"{wheel}{'A' if mode == 'minor' else 'B'}"
if notation == "open_key":
return f"{((wheel + 4) % 12) + 1}{'m' if mode == 'minor' else 'd'}"
return SPELLING[pitch_class_of(wheel, mode)] + ("m" if mode == "minor" else "")
def notation_of(text: str | None) -> Notation | None:
"""Which notation a stored key string is written in."""
if not text:
return None
s = text.strip()
if _CAMELOT.match(s):
return "camelot"
if _OPEN_KEY.match(s):
return "open_key"
if _MUSICAL.match(s):
return "musical"
return None
+22
View File
@@ -54,6 +54,10 @@ class PathMapping:
return True
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
def inverted(self) -> "PathMapping":
"""The mapping back: a path HERE → the form the library stores."""
return PathMapping(self.to_prefix, self.from_prefix)
def apply(self, os_path: Path) -> Path:
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
path unchanged when it doesn't match (non-matching tracks untouched)."""
@@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str:
else:
break
return "/".join(common)
def stored_form(os_path: Path, mappings) -> Path:
"""`os_path` as the library STORES its paths, when it sits under where one
of `mappings` points (the first that does).
A library opened through a mapping (a server holding a collection made on
another computer) stores every path in the other computer's form. A file
added through that mapping is written in the same form, so the library
keeps ONE convention — and still opens, mapping and all, where it was made.
"""
for mapping in mappings:
if mapping is None or mapping.empty:
continue
back = mapping.inverted()
if back.matches(os_path):
return back.apply(os_path)
return os_path
+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())
or (t.title and ql in t.title.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:
items = [t for t in items if t.genre == genre]
+125 -28
View File
@@ -37,15 +37,17 @@ from __future__ import annotations
import fractions
import json
import queue
import struct
import sys
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
import numpy as np
from . import mp4_edit, tag_copy
from . import mp4_edit, pyav, tag_copy
SR = 44100
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."""
import av
with av.open(str(path), metadata_errors="ignore") as container:
with pyav.open_input(path) as container:
stream = container.streams.audio[0]
codec = stream.codec_context.name
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)
#: 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,
checkpoint: Callable[[], None] | None) -> None:
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the
muxer never buffers a whole stream (which it would if they came one after
another)."""
checkpoint: Callable[[], None] | None,
progress: Callable[[float], None] | None = None) -> None:
"""Encode the AAC streams on one thread EACH and mux them on this one, IN
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
n = tracks[0].shape[1]
tb = fractions.Fraction(1, SR)
offsets = range(0, n, FRAME)
stop = threading.Event()
threads: list[threading.Thread] = []
container = av.open(fp, "w", format="ipod")
try:
streams = []
@@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
if k:
s.disposition = 0 # present, not enabled: a plain player plays the mix
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 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)
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:
# 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()
@@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]]
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`.
`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
writes a `*.konduktor-partial` and renames it once the batch commits — since
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)
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)
with open(target, "wb") as fp:
_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)
tags = tag_copy.copy_tags(source_path, target)
verify(target, source)
@@ -356,17 +423,14 @@ def stem_layout(path: Path | str) -> list[dict] | None:
MP3 entries in the real collection carry that element."""
import json
import av
path = Path(path)
try:
raw = read_stem_box(path)
if raw is None:
return None
return None # not a stem file: nothing to count, no decoder needed
stems = json.loads(raw).get("stems") or []
with av.open(str(path), metadata_errors="ignore") as c:
streams = len(c.streams.audio)
except (OSError, ValueError, av.FFmpegError):
streams = _audio_stream_count(path)
except (OSError, ValueError):
return None
if not stems or streams < 1 + len(stems):
return None
@@ -374,6 +438,39 @@ def stem_layout(path: Path | str) -> list[dict] | None:
for i, s in enumerate(stems)]
def _audio_stream_count(path: Path) -> int:
"""How many audio streams an MP4 holds. Through PyAV where it is installed;
otherwise (the Konduktor SERVER ships without it — it never decodes) by
counting the `trak`s whose handler is `soun`, which is what PyAV counts."""
try:
import av
except ImportError:
av = None
if av is not None:
try:
with pyav.open_input(path) as c:
return len(c.streams.audio)
except av.FFmpegError as ex:
raise ValueError(str(ex))
size = path.stat().st_size
count = 0
with open(path, "rb") as f:
moov = _find(f, 0, size, b"moov")
if moov is None:
return 0
for kind, body, end in mp4_edit._boxes(f, moov[1], moov[2]):
if kind != b"trak":
continue
mdia = _find(f, body, end, b"mdia")
hdlr = _find(f, mdia[1], mdia[2], b"hdlr") if mdia else None
if hdlr is None:
continue
f.seek(hdlr[1] + 8) # version/flags (4) + pre_defined (4), then the type
if f.read(4) == b"soun":
count += 1
return count
def _traktor_json(v) -> str:
if isinstance(v, bool):
return "true" if v else "false"
@@ -423,7 +520,7 @@ def extract_stream(path: Path | str, stream: int, fp) -> None:
"""
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):
raise StemFileError(f"The file has no audio stream {stream}")
ist = inp.streams.audio[stream]
+2 -2
View File
@@ -273,8 +273,8 @@ def analyse(
if not markers:
raise ValueError("Set a beatgrid first")
if y is None:
import librosa
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
from . import waveform
y, _ = waveform.load(audio_path, sr=_SR)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / _SR
beats, bar0 = grid_beats(markers, duration)
+20 -10
View File
@@ -84,8 +84,8 @@ class Analysis:
return self.columns.duration
def _decode_pyav(path: Path) -> np.ndarray:
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray:
"""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
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
with av.open(str(path)) as container:
from . import pyav
with pyav.open_input(path) as container:
stream = container.streams.audio[0]
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
resampler = av.AudioResampler(format="flt", layout="mono", rate=sr)
chunks = []
for frame in container.decode(stream):
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:])]
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:
return _decode_pyav(path)
return _decode_pyav(Path(path), sr), sr
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
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)
return y
y, _ = librosa.load(str(path), sr=sr, mono=True)
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
log.warning("could not decode %s for a waveform: %s", path, ex)
return None
+22 -16
View File
@@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan:
resolved = exports.resolve(adapter, export_set)
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
# The source is the adapter's `audio_path`, never `Track.filepath`: that is
# a DISPLAY path, which on Traktor omits the volume and ignores the active
# The source is the adapter's file, never `Track.filepath`: that is a
# DISPLAY path, which on Traktor omits the volume and ignores the active
# path mapping — so every track off the boot volume (or on a remapped
# Windows drive) read as missing and the export was "empty".
sources = {t.id: adapter.audio_path(t.id) for t in tracks}
# Windows drive) read as missing and the export was "empty". Its FACTS,
# not `audio_path`: planning must not read a file, and on a library held
# by a server reading one means downloading it. `run` fetches each file
# only when it copies it.
facts = adapter.audio_facts([t.id for t in tracks])
sources = {tid: Path(f.key) for tid, f in facts.items()}
# Mirror relative to the deepest shared folder, so the export carries the
# user's structure without carrying their home directory.
@@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan:
previous = _previous_copies(destination)
claimed: set[Path] = set()
for track in tracks:
source = sources[track.id]
exists = False
size = mtime_ns = 0
try:
exists = bool(source and source.is_file())
if exists:
st = source.stat()
size, mtime_ns = st.st_size, st.st_mtime_ns
except OSError:
exists = False
source = sources.get(track.id)
fact = facts.get(track.id)
exists = fact is not None
size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0)
planned = PlannedTrack(
track_id=track.id,
title=track.title or (source.name if source else track.id),
@@ -435,9 +433,13 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
# ---- 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.
`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 —
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
@@ -519,7 +521,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
done += n
handle.progress(done=done)
copy_file(planned.source_path, partial, handle, advance)
# The file to READ: on this machine that is the source itself;
# on a library held by a server, a downloaded copy of it.
local = adapter.audio_path(planned.track_id) or planned.source_path
copy_file(local, partial, handle, advance)
os.replace(partial, target)
payload_tracks.append(
ExportTrack(
@@ -544,6 +549,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
payload = ExportPayload(
name=export_set.name,
root_folder=root_folder,
tracks=payload_tracks,
playlists=built.playlists,
checkpoint=checkpoint,
+34 -3
View File
@@ -123,8 +123,39 @@ def _store_path(library_id: str) -> Path:
return paths.app_data_dir() / "exports" / f"{library_id}.json"
# A library whose sets are kept somewhere other than this computer's app-data —
# a library held by a server keeps them beside itself, so every computer that
# opens it sees the same sets. Each store reads and writes the WHOLE document
# (`{"library_id", "sets"}`); everything else here is unchanged by where it is.
_STORES: dict[str, object] = {}
def use_store(library_id: str, store) -> None:
"""Keep `library_id`'s sets in `store` (`read() -> dict`, `write(dict)`);
None returns them to this computer's app-data."""
if store is None:
_STORES.pop(library_id, None)
else:
_STORES[library_id] = store
def _read_doc(library_id: str) -> dict:
store = _STORES.get(library_id)
if store is not None:
return store.read()
return paths.read_json(_store_path(library_id), {})
def _write_doc(library_id: str, doc: dict) -> None:
store = _STORES.get(library_id)
if store is not None:
store.write(doc)
else:
paths.write_json(_store_path(library_id), doc)
def _load(library_id: str) -> dict[str, ExportSet]:
data = paths.read_json(_store_path(library_id), {})
data = _read_doc(library_id)
raw = data.get("sets") if isinstance(data, dict) else None
out: dict[str, ExportSet] = {}
if isinstance(raw, dict):
@@ -158,8 +189,8 @@ def _targets(values: dict) -> list[str]:
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
paths.write_json(
_store_path(library_id),
_write_doc(
library_id,
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
)
+80 -11
View File
@@ -112,18 +112,19 @@ def _key(path: Path) -> str:
def _existing_files(dest) -> dict[str, str]:
"""Every audio file the destination points at → its track id.
Resolved through the adapter's own `audio_path`, which is the only answer
Resolved through the adapter's own `audio_facts`, which is the only answer
that includes the volume and the active path mapping; the projected
`filepath` is a display string and is not good enough to match on.
`filepath` is a display string and is not good enough to match on. Facts,
not `audio_path`: on a library held by a server that would download every
file it has.
"""
out: dict[str, str] = {}
for track in dest.tracks:
try:
path = dest.audio_path(track.id)
except Exception: # noqa: BLE001
path = None
if path is not None:
out.setdefault(_key(path), track.id)
try:
facts = dest.audio_facts([t.id for t in dest.tracks])
except Exception: # noqa: BLE001
return out
for track_id, fact in facts.items():
out.setdefault(_key(Path(fact.key)), track_id)
return out
@@ -190,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids
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:
for nid, name in _all_playlists(source):
if nid == node_id:
@@ -216,7 +241,16 @@ def _all_playlists(source) -> list[tuple[str, str]]:
return out
def free_bytes(path: Path) -> int | None:
def free_bytes(path: Path, dest=None) -> int | None:
"""Free space where the audio will land. On the DESTINATION's machine: a
library held by a server reports its own disk (`free_space`), since the
path names a folder there, not here."""
remote_free = getattr(dest, "free_space", None) if dest is not None and uploads_audio(dest) else None
if remote_free is not None:
try:
return remote_free(str(path))
except Exception: # noqa: BLE001 — unknown is not "full"
return None
try:
target = path if path.exists() else path.parent
return shutil.disk_usage(target).free
@@ -224,6 +258,15 @@ def free_bytes(path: Path) -> int | None:
return None
def uploads_audio(dest) -> bool:
"""Whether added audio is SENT to the machine holding the library (a
server) rather than copied on this one — `tracks.audio_destination`."""
try:
return dest.capabilities().tracks.audio_destination == "library" and hasattr(dest, "upload_audio")
except Exception: # noqa: BLE001
return False
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
"""A free filename in `folder`, suffixing on collision.
@@ -298,7 +341,13 @@ def run(
"""
destination = plan.destination
places = places_audio(dest)
if not reference and not places:
# A library held by a server: each file is UPLOADED into `destination`,
# a folder on the server, instead of copied here. Nothing can be left in
# place — the server cannot see this computer's files.
uploads = not places and uploads_audio(dest)
if uploads and reference and not getattr(source, "on_library_host", False):
raise ValueError("A remote library cannot reference files on this computer")
if not reference and not places and not uploads:
assert destination is not None
destination.mkdir(parents=True, exist_ok=True)
@@ -312,6 +361,8 @@ def run(
# from it leaves the half-written file behind — which then makes the next
# attempt suffix around a file that is not really there.
created: list[Path] = []
# Files sent to the server, which a failure asks it to delete again.
uploaded: list[Path] = []
taken: set[str] = set()
moved = 0
@@ -333,6 +384,19 @@ def run(
elif reference:
copied.append((planned, planned.source_path))
continue
elif uploads:
handle.progress(message=f"Uploading {planned.title}")
def sent(n: int) -> None:
handle.raise_if_cancelled() # mid-file: the server drops the partial
bump(n)
# The server never overwrites: a taken name comes back `-2`…
target = dest.upload_audio(planned.source_path, str(destination),
planned.source_path.name, progress=sent)
uploaded.append(target)
copied.append((planned, target))
continue
else:
target = _unique_target(destination, planned.source_path.name, taken)
handle.progress(message=f"Copying {planned.title}")
@@ -409,6 +473,11 @@ def run(
target.unlink(missing_ok=True)
except OSError:
log.debug("could not clean up %s", target, exc_info=True)
for target in uploaded:
try:
dest.delete_upload(target) # refused once the library names it
except Exception: # noqa: BLE001
log.debug("could not clean up upload %s", target, exc_info=True)
raise
+705 -88
View File
File diff suppressed because it is too large. Load diff
+68 -31
View File
@@ -3,10 +3,19 @@
A self-contained JSON file in the app's per-OS user-writable data dir (see
``paths.app_data_dir``) so it survives a frozen/packaged build and works the same
on every platform. Best-effort: any I/O error degrades to "no prefs".
**Every read-modify-write holds ``_LOCK`` and every write is atomic.** FastAPI
runs ``PATCH /api/prefs`` on a thread pool, and the UI sends several at once on
launch. Unlocked, with ``write_text`` truncating before it wrote, a reader could
catch the file empty, take it for "no prefs" and write back only its own key —
wiping everything else (measured: 249 of 300 trials of three concurrent patches).
A file that exists but will not parse is moved aside before it is replaced, so
it is never silently overwritten.
"""
from __future__ import annotations
import json
import threading
from pathlib import Path
from . import paths
@@ -16,6 +25,9 @@ from . import paths
_PREFS_PATH = paths.app_data_dir() / "userprefs.json"
_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
# Reentrant: the helpers below read and write inside one critical section.
_LOCK = threading.RLock()
def _migrate_legacy() -> None:
"""One-time: if the new file is absent but a legacy package-relative one
@@ -27,29 +39,52 @@ def _migrate_legacy() -> None:
pass
def load_prefs() -> dict:
def _read(*, for_write: bool) -> dict:
"""The stored prefs, or {} if there are none or they cannot be read.
With ``for_write``, a file that exists but is not a JSON object is renamed
to ``userprefs.json.corrupt`` first, since the caller is about to replace it.
"""
try:
_migrate_legacy()
data = json.loads(_PREFS_PATH.read_text())
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
text = _PREFS_PATH.read_text()
except OSError:
return {}
try:
data = json.loads(text)
if isinstance(data, dict):
return data
except ValueError:
pass
if for_write:
try:
_PREFS_PATH.replace(_PREFS_PATH.with_name(_PREFS_PATH.name + ".corrupt"))
except OSError:
pass
return {}
def load_prefs() -> dict:
with _LOCK:
return _read(for_write=False)
def save_prefs(prefs: dict) -> None:
try:
_PREFS_PATH.write_text(json.dumps(prefs, indent=2))
except OSError:
pass # non-fatal — prefs are a convenience, not a requirement
with _LOCK:
try:
paths.write_json(_PREFS_PATH, prefs)
except OSError:
pass # non-fatal — prefs are a convenience, not a requirement
def update_prefs(patch: dict) -> dict:
"""Shallow-merge `patch` into the stored prefs and persist. Returns the
full updated prefs dict."""
prefs = load_prefs()
prefs.update(patch)
save_prefs(prefs)
return prefs
with _LOCK:
prefs = _read(for_write=True)
prefs.update(patch)
save_prefs(prefs)
return prefs
def get_path_mapping(collection_path: str) -> dict | None:
@@ -69,16 +104,17 @@ def set_path_mapping(
collection_path: str, from_prefix: str | None, to_prefix: str | None
) -> None:
"""Persist (or, when either prefix is blank, clear) a collection's mapping."""
prefs = load_prefs()
mappings = prefs.get("path_mappings")
if not isinstance(mappings, dict):
mappings = {}
if from_prefix and to_prefix:
mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
else:
mappings.pop(collection_path, None)
prefs["path_mappings"] = mappings
save_prefs(prefs)
with _LOCK:
prefs = _read(for_write=True)
mappings = prefs.get("path_mappings")
if not isinstance(mappings, dict):
mappings = {}
if from_prefix and to_prefix:
mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
else:
mappings.pop(collection_path, None)
prefs["path_mappings"] = mappings
save_prefs(prefs)
def get_last_collection(platform: str | None = None) -> str | None:
@@ -105,12 +141,13 @@ def get_last_collection(platform: str | None = None) -> str | None:
def set_last_collection(path: str, platform: str | None = None) -> None:
"""Record a library as the last opened, globally and for its platform."""
prefs = load_prefs()
prefs["last_collection"] = path
if platform:
by_platform = prefs.get("last_collection_by_platform")
if not isinstance(by_platform, dict):
by_platform = {}
by_platform[platform] = path
prefs["last_collection_by_platform"] = by_platform
save_prefs(prefs)
with _LOCK:
prefs = _read(for_write=True)
prefs["last_collection"] = path
if platform:
by_platform = prefs.get("last_collection_by_platform")
if not isinstance(by_platform, dict):
by_platform = {}
by_platform[platform] = path
prefs["last_collection_by_platform"] = by_platform
save_prefs(prefs)
+275
View File
@@ -0,0 +1,275 @@
"""The wire contract between a Konduktor SERVER and the app that opens it.
A library held by a server (`konduktor.server`, a container on the user's NAS)
is opened on a laptop through `adapters/remote`'s `RemoteAdapter`, which speaks
THIS protocol to the server. Both sides import this module, so the method list,
which commands need the session, and the version they speak cannot drift apart.
The protocol is the `LibraryAdapter` protocol itself, not the UI's `/api`
routes: commands in, projections out. Every member of `LibraryAdapter` is
either in `RPC` or in `EXCLUDED` with the reason it does not travel —
`test_remote_protocol.py` fails the moment a new protocol member is neither, so
a command added later cannot silently be missing from remote libraries.
Arguments and results are (de)serialised with pydantic `TypeAdapter`s built
from the protocol's own type hints; the model classes are pydantic already and
the dataclasses convert. Bytes never travel as JSON — art, audio and uploads
have routes of their own.
"""
from __future__ import annotations
import base64
import inspect
import io
import typing
from dataclasses import dataclass
from functools import lru_cache
from typing import Any
from pydantic import BaseModel, TypeAdapter
from .core.adapter import LibraryAdapter
from .core.model import AutoHotcue, Track, TrackCues
#: (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
#: method, the major for anything an older client would misread.
#: 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`.
API_VERSION: tuple[int, int] = (1, 3)
#: 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
#: address; short enough that moving to another computer after closing a lid
#: rarely needs a takeover (decided 2026-10-02).
LEASE_SECONDS = 120.0
HEARTBEAT_SECONDS = 15.0
#: The header that carries the session token on every command.
SESSION_HEADER = "X-Konduktor-Session"
def compatible(client: tuple[int, int], server: tuple[int, int]) -> str | None:
"""None when `client` can talk to `server`; otherwise which side to update."""
if client[0] != server[0]:
return "app" if server[0] > client[0] else "server"
if server[1] < client[1]:
return "server"
return None
@dataclass(frozen=True)
class Method:
name: str
#: Changes the library — needs the session token, bumps the revision.
mutating: bool
#: A property on the protocol rather than a method (`tracks`, `dirty`).
prop: bool = False
#: Parameter types where the protocol's hint is too loose to validate.
overrides: tuple[tuple[str, Any], ...] = ()
_READ = (
"capabilities", "track", "query_tracks", "facets", "stats", "playlist_tree",
"playlist_count", "playlist_entries", "playlist_tracks", "track_cues", "audio_facts",
)
_MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "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",
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
)
RPC: dict[str, Method] = {
**{n: Method(n, False) for n in _READ},
"tracks": Method("tracks", False, prop=True),
"dirty": Method("dirty", False, prop=True),
**{n: Method(n, True) for n in _MUTATING},
}
RPC["place_cues"] = Method("place_cues", True, overrides=(("cues", list[AutoHotcue]),))
#: Protocol members that do not travel as RPC, and why.
EXCLUDED: dict[str, str] = {
"reload": "POST /v1/discard — a discard on the server is what drops its edits",
"save": "POST /v1/save — the server saves, versions and backs up beside the library",
"snapshot": "version history lives on the server",
"audio_path": "GET /v1/audio — a server path names no file on this computer",
"cover_art": "GET /v1/art — bytes",
"set_cover_art": "PUT /v1/art — bytes",
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
"set_path_mapping": "the server's path mapping is its own configuration",
"set_session_mappings": "the missing-files check searches THIS computer's drives",
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
"path_prefix_suggestions": "paths.remappable is false for a remote library",
"remap_preview": "paths.remappable is false for a remote library",
"remap_locations": "paths.remappable is false for a remote library",
}
def protocol_members() -> set[str]:
"""Every method and property `LibraryAdapter` declares (not its attributes)."""
out = set()
for name, value in vars(LibraryAdapter).items():
if name.startswith("_"):
continue
if inspect.isfunction(value) or isinstance(value, property):
out.add(name)
return out
def _callable(name: str):
member = getattr(LibraryAdapter, name)
return member.fget if isinstance(member, property) else member
@lru_cache(maxsize=None)
def _hints(name: str) -> dict[str, Any]:
hints = typing.get_type_hints(_callable(name))
method = RPC[name]
hints.update(dict(method.overrides))
return hints
@lru_cache(maxsize=None)
def _params(name: str) -> tuple[tuple[str, Any, Any], ...]:
"""(name, type, default) for each parameter the RPC takes."""
if name == "query_tracks":
# `**kw` on the protocol: the index's own signature is the real one.
from .core.query import TrackIndex
sig = inspect.signature(TrackIndex.query_tracks)
hints = typing.get_type_hints(TrackIndex.query_tracks)
else:
sig = inspect.signature(_callable(name))
hints = _hints(name)
out = []
for p in sig.parameters.values():
if p.name == "self" or p.kind in (p.VAR_KEYWORD, p.VAR_POSITIONAL):
continue
if name == "add_tracks" and p.name == "checkpoint":
continue # a callable; the server reports progress instead
hint = hints.get(p.name, Any)
if name == "add_tracks" and p.name == "items":
hint = list[WireNewTrack]
out.append((p.name, hint, p.default))
return tuple(out)
@lru_cache(maxsize=None)
def _adapter(hint) -> TypeAdapter:
return TypeAdapter(hint)
def dump_args(name: str, args: dict) -> dict:
"""Arguments → JSON-able, by the protocol's own types."""
out = {}
for pname, hint, _default in _params(name):
if pname in args:
out[pname] = _adapter(hint).dump_python(args[pname], mode="json")
return out
def load_args(name: str, raw: dict) -> dict:
"""JSON → validated arguments. Unknown names are refused rather than
ignored: a misspelt argument silently taking its default is a wrong edit."""
params = {p: (h, d) for p, h, d in _params(name)}
unknown = set(raw) - set(params)
if unknown:
raise ValueError(f"{name}: unknown argument(s) {sorted(unknown)}")
out = {}
for pname, (hint, default) in params.items():
if pname in raw:
out[pname] = _adapter(hint).validate_python(raw[pname])
elif default is inspect.Parameter.empty:
raise ValueError(f"{name}: missing argument {pname!r}")
return out
def _result_hint(name: str):
if name == "add_tracks":
return list[str]
return _hints(name).get("return", Any)
def dump_result(name: str, value) -> Any:
return _adapter(_result_hint(name)).dump_python(value, mode="json")
def load_result(name: str, raw) -> Any:
return _adapter(_result_hint(name)).validate_python(raw)
# ---- adding tracks -------------------------------------------------------------
class WireArt(BaseModel):
data: str # base64
mime: str
class WireNewTrack(BaseModel):
"""`NewTrack` as it crosses the wire. `audio_path` is a path ON THE SERVER —
the client uploaded the file first (`POST /v1/upload`), exactly as a local
import copies it first. The analysis is the client's (the server never
decodes audio)."""
track: Track
audio_path: str
cues: TrackCues | None = None
art: WireArt | None = None
analysis: str | None = None # base64 `.npz`, see `pack_analysis`
def pack_analysis(prepared) -> str | None:
"""A `PreparedAnalysis` → base64 `.npz` (float32: what the writers use)."""
if prepared is None or prepared.measured is None:
return None
import numpy as np
m = prepared.measured
buf = io.BytesIO()
markers = np.array([[g.start, g.bpm] for g in prepared.markers], dtype=np.float64).reshape(-1, 2)
np.savez(
buf,
rms=np.asarray(m.columns.rms, dtype=np.float32),
brightness=np.asarray(m.columns.brightness, dtype=np.float32),
columns_duration=np.float64(m.columns.duration),
bands=np.asarray(m.frames.bands, dtype=np.float32),
frames_duration=np.float64(m.frames.duration),
markers=markers,
**({} if prepared.key is None else {
"key": np.array([prepared.key.pitch_class, prepared.key.wheel,
prepared.key.mode == "minor", prepared.key.confidence], dtype=np.float64)}),
)
return base64.b64encode(buf.getvalue()).decode("ascii")
def unpack_analysis(text: str | None):
"""The inverse of `pack_analysis` → `PreparedAnalysis` (or None)."""
if not text:
return None
import numpy as np
from .core import waveform
from .core.adapter import PreparedAnalysis
from .core.model import GridMarker
with np.load(io.BytesIO(base64.b64decode(text))) as z:
measured = waveform.Analysis(
columns=waveform.Columns(rms=z["rms"], brightness=z["brightness"],
duration=float(z["columns_duration"])),
frames=waveform.Frames(bands=z["bands"], duration=float(z["frames_duration"])),
)
markers = [GridMarker(start=float(s), bpm=float(b)) for s, b in z["markers"]]
key = None
if "key" in z:
from .core.key_detect import KeyResult
pitch, wheel, minor, confidence = z["key"]
key = KeyResult(pitch_class=int(pitch), mode="minor" if minor else "major",
wheel=int(wheel), confidence=float(confidence))
return PreparedAnalysis(measured=measured, markers=markers, key=key)
+133 -2
View File
@@ -21,6 +21,20 @@ class SetEntries(BaseModel):
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):
track_id: str
fields: dict[str, str | int | None]
@@ -133,6 +147,40 @@ class AutoGridRequest(BaseModel):
track_id: str
class AnalyzeRequest(BaseModel):
"""The Analyze dialog's choices. BPM and Grid are independent halves of a
beatgrid (`core/grid_plan`); `replace_grid` only guards a FULL re-analysis
(both ticked), since with one tick adjusting the grid is the point.
`replace_key` lets detection overwrite a key the track already has."""
track_ids: list[str]
bpm: bool = True
grid: bool = True
key: bool = False
replace_grid: bool = False
replace_key: bool = False
class AnalyzePreview(BaseModel):
"""What an Analyze run WOULD do, for the dialog. Counted from the
projection, so on a platform whose marker counts are lazy (Rekordbox,
OneLibrary: 1 for any track with a BPM) a flexible grid is only found when
the run reads the real grid — it is then skipped and reported."""
total: int
tracks_to_analyze: int = 0 # tracks with anything to do (grid and key overlap)
# Grid: what `plan_grid` decides per track — full / bpm / phase / skipped.
grid_full: int = 0
grid_bpm: int = 0
grid_phase: int = 0
grid_locked: int = 0
grid_existing: int = 0 # skipped: has a grid, Replace not ticked
grid_flexible: int = 0
with_grid: int = 0 # unlocked tracks that have a grid (the Replace tick's count)
# Key.
key_set: int = 0
key_existing: int = 0 # skipped: has a key, Replace not ticked
with_key: int = 0 # tracks that have a key (the Replace tick's count)
class AutoGridBatchRequest(BaseModel):
track_ids: list[str]
# False skips tracks that already have a grid. Locked grids are skipped
@@ -152,6 +200,33 @@ class SetCueColor(BaseModel):
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):
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
target: str | None = None
@@ -187,6 +262,8 @@ class EditState(BaseModel):
stem_job: str | None = None
# What this open's crash recovery did about an interrupted conversion.
stem_recovery: dict | None = None
# A remote library's connection: {state, via, machine}. None when local.
remote: dict | None = None
# ---- collection selection ----
@@ -200,12 +277,34 @@ class CollectionStatus(BaseModel):
# Identity of the loaded library, so the UI can name it without parsing the
# path (a Serato library is a directory, not a file).
library: LibraryInfo | None = None
# Opening a remote library: the unsaved edits another computer left there,
# {machine, summary} — the user chooses to save or discard them.
pending_edits: dict | None = None
class OpenCollection(BaseModel):
path: str
class RemoteIn(BaseModel):
"""A remote's settings as the picker's form sends them. `password` may be
omitted on an edit, which keeps the saved one."""
name: str
host: str
port: int | None = None
fallback_host: str | None = None
fallback_port: int | None = None
username: str
password: str | None = None
class OpenRemote(BaseModel):
remote_id: str
# Take the session from the computer holding it (the user confirmed).
takeover: bool = False
class CollectionCandidate(BaseModel):
path: str
label: str # folder name, e.g. "Traktor 4.5.0"
@@ -435,6 +534,11 @@ class ImportRequest(BaseModel):
# 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.
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):
@@ -444,11 +548,15 @@ class Drive(BaseModel):
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
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
path: str
kind: Literal["local", "external"]
kind: Literal["local", "external", "server"]
library: SourceCandidate | None = None
@@ -456,14 +564,37 @@ class FolderTracks(BaseModel):
"""The audio files directly inside one folder, projected as tracks."""
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]
# Ids (= absolute paths) of the files the collection already points at.
# Collection ids of the rows that are collection tracks.
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
# drive is unplugged, which the add dialog has to say.
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):
"""Add browsed files to the collection, and optionally to a playlist/export.
+2
View File
@@ -0,0 +1,2 @@
"""Konduktor's server: one library, held on the machine where its audio lives,
opened from the desktop app as a "Remote" library. See `app.py`."""
+37
View File
@@ -0,0 +1,37 @@
"""`python -m konduktor.server` — what the container runs.
Configuration is the environment (see `config.py`); a bad setting stops here
with one clear line instead of serving a library that half-works.
"""
from __future__ import annotations
import logging
import sys
import uvicorn
from .config import ConfigError, from_env
def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
try:
config = from_env()
except ConfigError as ex:
print(f"konduktor-server: {ex}", file=sys.stderr)
return 2
from .app import Server, create_app
server = Server(config)
try:
server.open()
except ConfigError as ex:
print(f"konduktor-server: {ex}", file=sys.stderr)
return 2
uvicorn.run(create_app(server), host=config.host, port=config.port,
log_level="info", proxy_headers=True)
return 0
if __name__ == "__main__":
sys.exit(main())
+729
View File
@@ -0,0 +1,729 @@
"""The Konduktor SERVER: one library, held where its audio lives.
Runs in a container on the user's NAS (`server/Dockerfile`) and is opened from
the desktop app as a "Remote" library. It is deliberately NOT `main.py` behind a
password: the UI's routes would become a public contract, and half of them are
about THIS computer (its drives, its stem engine, its sticks). What it serves is
the `LibraryAdapter` protocol itself (`remote_protocol.py`), plus the few things
that are bytes — audio, art, uploads — and the app-level bookkeeping that lives
beside the library: save + backups + version history, export sets, the stems
ledger.
Lightweight by decision: the server never DECODES audio. Analysis, waveforms and
stem separation all run on the computer that opened the library; what arrives
here are the results, as ordinary commands. Its work is file IO, the native
model, tags, and header reads.
One computer at a time (`session.py`): every command carries the session token,
and anything that changes the library without it is answered 423 with who holds
it.
"""
from __future__ import annotations
import logging
import mimetypes
import os
import secrets
import shutil
import threading
from pathlib import Path
from fastapi import Body, Depends, FastAPI, Header, HTTPException, Query, Request, Response
from fastapi.responses import FileResponse, JSONResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from .. import __version__, exports
from .. import remote_protocol as rp
from ..app_state import AppState
from ..core import registry
from ..core.adapter import (
AdapterError,
InvalidCommand,
LibraryNotSupported,
NewTrack,
NotFound,
Unsupported,
)
from ..core.folder import FolderScanner
from ..core.places import is_os_housekeeping
from .config import ConfigError, ServerConfig
from .session import InUse, Lost, SessionLock
log = logging.getLogger("konduktor.server")
#: Upload partials, published by a rename that never overwrites.
PARTIAL_SUFFIX = ".konduktor-upload"
_CHUNK = 1 << 20
class Server:
"""The open library, its session, and the revision counter clients follow."""
def __init__(self, config: ServerConfig, *, state: AppState | None = None,
lock: SessionLock | None = None):
self.config = config
self.state = state if state is not None else _default_state()
self.lock = lock or SessionLock()
self.rev = 0
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 ---------------------------------------------------------------
def open(self) -> None:
cfg = self.config
try:
driver = registry.driver_for(cfg.library)
except LibraryNotSupported as ex:
raise ConfigError(f"KONDUKTOR_LIBRARY: {ex}")
if driver.platform != cfg.platform:
raise ConfigError(
f"KONDUKTOR_PLATFORM is {cfg.platform!r} but {cfg.library} is a "
f"{driver.display_name} library"
)
self.state.open_hooks.append(self._configure)
self.state.open(cfg.library)
def _configure(self, adapter) -> None:
"""After every (re)open: the configured path mapping, and no missing-files
search of a container's empty drives."""
maps = self.config.path_maps
if maps:
adapter.set_path_mapping(maps[0])
adapter.set_session_mappings(list(maps[1:]))
# A file uploaded here is stored as the library stores every other
# path — so it still opens, mapping and all, where it was made.
write_stored = getattr(adapter, "set_write_stored_paths", None)
if write_stored is not None:
write_stored(True)
self.state.relocation = None
@property
def adapter(self):
if self.state.adapter is None:
raise HTTPException(503, "The library is not open")
return self.state.adapter
def bump(self) -> int:
with self._rev_lock:
self.rev += 1
return self.rev
# ---- facts -------------------------------------------------------------------
def capabilities(self):
"""The adapter's own, plus what being held by a server changes."""
caps = self.adapter.capabilities().model_copy(deep=True)
caps.tracks.audio_destination = "library"
caps.tracks.reference = False
caps.paths.remappable = False
# Nothing runs a DJ app against a library on a NAS while it is being
# saved: the "close Traktor first" warning would only confuse.
caps.save.overwrite_risk = "none"
return caps
def name(self) -> str:
return self.config.name or self.config.library.stem
def pending_edits(self, client_id: str | None = None) -> dict | None:
"""The unsaved edits someone else left, for the computer arriving."""
adapter = self.adapter
if not adapter.dirty:
return None
editor = self.lock.last_editor or {}
if client_id and editor.get("client_id") == client_id:
return None
summary = getattr(adapter, "edit_summary", None)
return {
"machine": editor.get("machine"),
"summary": (summary() if summary else "") or "unsaved changes",
}
def confine(self, raw: str | None) -> Path:
"""A path inside the content folder, or 400. Resolved first, so neither
`..` nor a symlink can lead out of it."""
root = self.config.content
candidate = Path(raw) if raw else root
if not candidate.is_absolute():
candidate = root / candidate
resolved = candidate.resolve()
if resolved != root and not resolved.is_relative_to(root):
raise HTTPException(400, f"{raw} is outside the library's content folder")
return resolved
def _default_state() -> AppState:
# The process-wide STATE: a server holds one library, and the stem end step
# reaches for `app_state.STATE.mutation` like the desktop app's does.
from ..app_state import STATE
return STATE
def create_app(server: Server) -> FastAPI:
cfg = server.config
security = HTTPBasic(realm="Konduktor")
def auth(creds: HTTPBasicCredentials = Depends(security)) -> None:
user_ok = secrets.compare_digest(creds.username.encode(), cfg.username.encode())
pass_ok = secrets.compare_digest(creds.password.encode(), cfg.password.encode())
if not (user_ok and pass_ok):
raise HTTPException(401, "Wrong username or password",
headers={"WWW-Authenticate": 'Basic realm="Konduktor"'})
app = FastAPI(title="Konduktor server", version=__version__, dependencies=[Depends(auth)])
app.state.server = server
@app.exception_handler(AdapterError)
def _adapter_error(_request, exc: AdapterError):
status = {NotFound: 404, InvalidCommand: 400, Unsupported: 422,
LibraryNotSupported: 400}.get(type(exc), 400)
return JSONResponse(status_code=status, content={"detail": str(exc)})
def session(token: str | None = Header(None, alias=rp.SESSION_HEADER)):
try:
return server.lock.check(token)
except Lost as ex:
raise HTTPException(423, {
"code": "taken_over", "message": str(ex), "holder": server.lock.describe(),
})
# ---- handshake + session -----------------------------------------------------
@app.get("/v1/hello")
def hello(client_id: str | None = None) -> dict:
state = server.state
caps = server.capabilities()
return {
"api_version": list(rp.API_VERSION),
"app_version": __version__,
"platform": caps.platform,
"app_name": caps.save.app_name,
"library_label": caps.save.library_label,
"name": server.name(),
"path": str(state.path),
"library_id": state.library_id,
"holder": server.lock.describe(),
"dirty": server.adapter.dirty,
"pending_edits": server.pending_edits(client_id),
"rev": server.rev,
}
@app.post("/v1/session/acquire")
def acquire(body: dict = Body(...)) -> dict:
client_id = str(body.get("client_id") or "")
machine = str(body.get("machine") or "another computer")
if not client_id:
raise HTTPException(400, "client_id is required")
try:
holder = server.lock.acquire(client_id, machine, takeover=bool(body.get("takeover")))
except InUse as ex:
h = ex.holder
raise HTTPException(409, {"code": "in_use", "machine": h.machine,
"since": h.since, "batch": h.batch})
return {
"token": holder.token,
"lease": server.lock.lease,
"heartbeat": rp.HEARTBEAT_SECONDS,
"pending_edits": server.pending_edits(client_id),
"rev": server.rev,
}
@app.post("/v1/session/heartbeat")
def heartbeat(body: dict = Body(default={}),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
try:
server.lock.heartbeat(token, body.get("batch"))
except Lost as ex:
raise HTTPException(423, {"code": "taken_over", "message": str(ex),
"holder": server.lock.describe()})
return {"rev": server.rev, "dirty": server.adapter.dirty}
@app.post("/v1/session/release")
def release(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
server.lock.release(token)
return {"status": "released"}
# ---- the protocol ------------------------------------------------------------
@app.post("/v1/rpc/{name}")
def rpc(name: str, body: dict = Body(default={}),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
method = rp.RPC.get(name)
if method is None:
raise HTTPException(404, f"No such method: {name}")
holder = session(token) if method.mutating else None
try:
args = rp.load_args(name, body.get("args") or {})
except ValueError as ex:
raise HTTPException(400, str(ex))
adapter = server.adapter
changed: list = []
removed: list[str] = []
reset = False
if name == "capabilities":
value = server.capabilities()
elif name == "add_tracks":
with server.state.mutation:
value = adapter.add_tracks([_new_track(server, w) for w in args["items"]])
changed = [t for i in value if (t := adapter.track(i)) is not None]
elif method.prop:
value = getattr(adapter, name)
else:
value = getattr(adapter, name)(**args)
if method.mutating:
if name == "remove_tracks":
removed = list(args["track_ids"])
elif "track_id" in args:
track = adapter.track(args["track_id"])
if track is None:
removed = [args["track_id"]]
else:
changed = [track]
server.lock.touch(holder)
rev = server.bump()
else:
rev = server.rev
return {
"result": rp.dump_result(name, value),
"rev": rev,
"changed": [t.model_dump(mode="json") for t in changed],
"removed": removed,
"reset": reset,
}
# ---- bytes -------------------------------------------------------------------
@app.get("/v1/audio")
def audio(track_id: str):
path = server.adapter.audio_path(track_id)
if path is None or not Path(path).is_file():
raise HTTPException(404, "The audio file is missing")
st = Path(path).stat()
media = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
return FileResponse(path, media_type=media, headers={
"X-Konduktor-Size": str(st.st_size),
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
})
@app.get("/v1/art")
def art(track_id: str):
found = server.adapter.cover_art(track_id)
if not found:
raise HTTPException(404, "No cover art")
data, mime = found
return Response(content=data, media_type=mime)
@app.put("/v1/art")
async def put_art(request: Request, track_id: str, mime: str,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
holder = session(token)
data = await request.body()
server.adapter.set_cover_art(track_id, data, mime)
server.lock.touch(holder)
track = server.adapter.track(track_id)
return {"rev": server.bump(), "changed": [track.model_dump(mode="json")] if track else []}
@app.post("/v1/upload")
async def upload(request: Request, dir: str, name: str,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""Receive one audio file into `dir` (created if needed) under the content
folder. Never overwrites: a name already taken gets `-2`, `-3`, … as a
local import's copy does. The partial is renamed in only when complete,
so a cut connection leaves no half file under a real name."""
holder = session(token)
folder = server.confine(dir)
clean = _safe_name(name)
folder.mkdir(parents=True, exist_ok=True)
partial = folder / f".{clean}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}"
try:
with open(partial, "wb") as out:
async for chunk in request.stream():
out.write(chunk)
target = _publish(partial, folder / clean)
finally:
partial.unlink(missing_ok=True)
holder.uploads.add(str(target))
st = target.stat()
# A platform that analyses what it adds measures on its own clock, read
# from the file's header — which only the server can read. The client
# measures with this (`PreparedAnalysis`); None: nothing to measure.
lead = getattr(server.adapter, "analysis_lead", None)
return {"path": str(target), "size": st.st_size, "mtime_ns": st.st_mtime_ns,
"analysis_lead": lead(target) if lead else None}
@app.delete("/v1/upload")
def delete_upload(path: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""Remove a file THIS session uploaded and the library does not name —
how a cancelled or failed import cleans up after itself."""
holder = session(token)
target = server.confine(path)
if str(target) not in holder.uploads:
raise HTTPException(403, "Only a file this session uploaded can be removed")
adapter = server.adapter
named = {f.key for f in adapter.audio_facts([t.id for t in adapter.tracks]).values()}
if str(target) in named:
raise HTTPException(409, "The library names that file")
target.unlink(missing_ok=True)
holder.uploads.discard(str(target))
return {"status": "deleted"}
# ---- the content folder ------------------------------------------------------
@app.get("/v1/fs/list")
def fs_list(path: str | None = None) -> dict:
folder = server.confine(path)
if not folder.is_dir():
raise HTTPException(404, f"Not a folder: {folder}")
entries = []
try:
children = sorted(folder.iterdir(), key=lambda p: p.name.lower())
except OSError as ex:
raise HTTPException(400, f"Cannot list {folder}: {ex}")
for child in children:
if child.name.startswith(".") or is_os_housekeeping(child.name):
continue
try:
is_dir = child.is_dir()
except OSError:
continue
entries.append({"name": child.name, "path": str(child), "is_dir": is_dir})
root = server.config.content
return {
"path": str(folder),
"parent": None if folder == root else str(folder.parent),
"root": str(root),
"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")
def fs_space(path: str | None = None) -> dict:
folder = server.confine(path)
probe = folder
while not probe.exists() and probe != server.config.content:
probe = probe.parent
return {"free": shutil.disk_usage(probe).free}
# ---- save / discard / history ------------------------------------------------
@app.post("/v1/save")
def save(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
adapter = server.adapter
if not adapter.dirty:
return {"saved": False, "commit": None, "summary": "",
"tag_results": [], "playlists": adapter.playlist_count(), "rev": server.rev}
outcome, commit = server.state.save()
server.lock.clear_editor()
return {
"saved": True,
"commit": commit,
"summary": outcome.summary,
"tag_results": [r.__dict__ for r in outcome.tag_results],
"playlists": adapter.playlist_count(),
"rev": server.bump(),
}
@app.post("/v1/discard")
def discard(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
server.state.discard()
server._configure(server.adapter)
server.lock.clear_editor()
return {"rev": server.bump()}
@app.get("/v1/history")
def history() -> list[dict]:
return [e.__dict__ for e in server.state.services.history()]
@app.post("/v1/history/{commit_id}/restore")
def restore(commit_id: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
if not server.state.restore_version(commit_id):
raise HTTPException(404, f"Version not found: {commit_id}")
server.lock.clear_editor()
return {"rev": server.bump()}
@app.delete("/v1/history")
def clear_history(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
server.state.services.clear_history()
return {"status": "cleared"}
# ---- export sets -------------------------------------------------------------
@app.get("/v1/export-sets")
def get_export_sets() -> dict:
return exports._read_doc(server.state.library_id)
@app.put("/v1/export-sets")
def put_export_sets(doc: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
if not isinstance(doc.get("sets"), dict):
raise HTTPException(400, "Expected {'sets': {...}}")
exports._write_doc(server.state.library_id,
{"library_id": server.state.library_id, "sets": doc["sets"]})
return {"status": "saved"}
# ---- Convert to Stems: the library side ---------------------------------------
# The SEPARATION runs on the computer that opened the library (the server
# never decodes audio); what lives here is everything about the FILES and the
# library: where each stem file goes, what is skipped and why, the verified
# files it uploads (kept as leftovers until the batch's end step, so a
# takeover mid-batch loses nothing — the next run reuses them), and the end
# step itself, under the library's mutation lock, with the server's ledger.
def stem_options(body: dict):
from ..stems import convert
destination = body.get("destination")
if body.get("mode") == "destination":
if not destination:
raise HTTPException(400, "Choose a destination folder")
destination = server.confine(destination)
return convert.Options(
mode=body.get("mode") or "replace", destination=Path(destination) if destination else None,
collection=body.get("collection") or "repoint", playlist_id=body.get("playlist_id"),
new_playlist=body.get("new_playlist"),
)
@app.post("/v1/stems/plan")
def stems_plan(body: dict = Body(...)) -> dict:
from ..stems import convert
adapter = server.adapter
caps = adapter.capabilities()
if not caps.tracks.stem_convertible:
raise HTTPException(422, "This library cannot hold stem files")
try:
planned = convert.plan(adapter, list(body.get("track_ids") or []), stem_options(body),
server.state.pending)
except convert.ConvertError as ex:
raise HTTPException(400, str(ex))
out = planned.as_dict()
out["items"] = [{
"track_id": p.track_id, "title": p.title, "source": str(p.source), "target": str(p.target),
"seconds": p.seconds, "source_size": p.source.stat().st_size if p.source.exists() else 0,
"reuse": p.reuse["written"] if p.reuse else None,
} for p in planned.items]
return out
def stem_item(track_id: str, target: str) -> tuple[Path, Path]:
"""The source and target a stem upload / publish names, checked against
the library rather than trusted: a target outside the content folder, or
one not named after its own track's file, is refused."""
from ..core import stem_file as sf
source = server.adapter.audio_path(track_id)
if source is None or not Path(source).is_file():
raise HTTPException(404, "The track's audio file is missing")
dest = server.confine(target)
if dest.name != sf.stem_target_name(Path(source).name):
raise HTTPException(400, f"{dest.name} is not the stem file of {Path(source).name}")
return Path(source), dest
@app.put("/v1/stems/stage")
async def stems_stage(request: Request, track_id: str, target: str, sha256: str,
bit_rate: int, duration: float,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
import hashlib
from ..stems.pending import partial_name, source_facts
session(token)
source, dest = stem_item(track_id, target)
if dest.exists():
raise HTTPException(409, f"A stem file already exists: {dest.name}")
dest.parent.mkdir(parents=True, exist_ok=True)
partial = partial_name(dest)
incoming = dest.with_name(f".{dest.name}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}")
digest = hashlib.sha256()
size = 0
try:
with open(incoming, "wb") as out:
async for chunk in request.stream():
out.write(chunk)
digest.update(chunk)
size += len(chunk)
if digest.hexdigest() != sha256.lower():
raise HTTPException(400, "The stem file arrived damaged (checksum mismatch)")
os.replace(incoming, partial)
finally:
incoming.unlink(missing_ok=True)
pending = server.state.pending
with pending._lock:
pending.leftovers = [lo for lo in pending.leftovers if lo["partial"] != str(partial)]
pending.leftovers.append({
"source": str(source), "facts": source_facts(source), "partial": str(partial),
"written": {"bit_rate": bit_rate, "duration": duration, "size": size},
})
pending._write()
return {"partial": str(partial), "size": size}
@app.post("/v1/stems/abandon")
def stems_abandon(body: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""A cancelled batch: delete the files it uploaded (a cancel deletes
only new files, as on this computer)."""
from ..stems.pending import partial_name
session(token)
pending = server.state.pending
wanted = {str(partial_name(server.confine(t))) for t in body.get("targets") or []}
for lo in [lo for lo in pending.leftovers if lo["partial"] in wanted]:
pending.forget_leftover(lo, delete=True)
return {"status": "abandoned"}
@app.post("/v1/stems/publish")
def stems_publish(body: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""The batch's END STEP, here where the files are: publish each staged
stem file, park originals (Replace), swap every entry at once."""
from ..core import stem_file as sf
from ..stems import convert
from ..stems.pending import partial_name
holder = session(token)
opts = stem_options(body.get("options") or {})
pending = server.state.pending
result = {"converted": [], "renamed": {}, "added": {}, "failed": [], "clamped": {}}
with server.state.mutation:
finished = []
for entry in body.get("items") or []:
source, dest = stem_item(entry["track_id"], entry["target"])
partial = partial_name(dest)
lo = next((x for x in pending.leftovers if x["partial"] == str(partial)), None)
track = server.adapter.track(entry["track_id"])
title = convert._title(track)
if lo is None or not partial.is_file():
result["failed"].append({"track_id": entry["track_id"], "title": title,
"reason": "the converted file never reached the server"})
continue
written = lo["written"]
pitem = pending.add({"track_id": entry["track_id"], "mode": opts.collection,
"source": str(source), "stem": str(dest), "state": "converted",
"facts": lo.get("facts"), "written": written})
pending.forget_leftover(lo, delete=False)
planned = convert.Planned(entry["track_id"], title, source, dest, float(written["duration"]))
finished.append((planned, pitem, sf.Written(path=partial, bit_rate=int(written["bit_rate"]),
duration=float(written["duration"]),
size=int(written["size"]), tags={})))
convert._end_step(server.adapter, finished, opts, pending, result)
server.lock.touch(holder)
result["rev"] = server.bump()
return result
@app.get("/v1/stems/pending")
def stems_pending() -> dict:
pending = server.state.pending
return pending.summary() if pending is not None else {"tracks": 0, "parked": 0, "bytes": 0}
return app
def _safe_name(name: str) -> str:
clean = os.path.basename((name or "").replace("\\", "/")).strip()
if not clean or clean in (".", "..") or clean.startswith("."):
raise HTTPException(400, f"Not a usable file name: {name!r}")
return clean
def _publish(partial: Path, wanted: Path) -> Path:
"""Rename `partial` to `wanted`, or `wanted-2`… — never over an existing file
(a hard link fails rather than replaces)."""
stem, suffix = wanted.stem, wanted.suffix
# `.stem.m4a` keeps its double suffix together.
if stem.endswith(".stem"):
stem, suffix = stem[: -len(".stem")], ".stem" + suffix
n = 1
while True:
target = wanted if n == 1 else wanted.with_name(f"{stem}-{n}{suffix}")
try:
os.link(partial, target)
return target
except FileExistsError:
n += 1
def _new_track(server: Server, wire: rp.WireNewTrack) -> NewTrack:
import base64
path = server.confine(wire.audio_path)
art = (base64.b64decode(wire.art.data), wire.art.mime) if wire.art else None
return NewTrack(track=wire.track, audio_path=path, cues=wire.cues, art=art,
analysis=rp.unpack_analysis(wire.analysis))
# ---- entry points ------------------------------------------------------------------
def create_from_env() -> FastAPI:
"""`uvicorn --factory konduktor.server.app:create_from_env`."""
from .config import from_env
server = Server(from_env())
server.open()
log.info("Serving %s (%s) to remote clients", server.config.library, server.config.platform)
return create_app(server)
+101
View File
@@ -0,0 +1,101 @@
"""The server's configuration: the container's environment (its `.env`).
Everything is read once at start and checked before the library is opened, and
a bad setting stops the container with ONE clear line rather than a library
that half-works: a missing content folder would otherwise show up as every
track "missing", and an empty password as an open door.
KONDUKTOR_PLATFORM traktor | rekordbox — checked against the library file
KONDUKTOR_LIBRARY the library file (collection.nml / master.db)
KONDUKTOR_CONTENT the folder holding the audio; uploads and the folder
browser are confined to it
KONDUKTOR_USERNAME the one account
KONDUKTOR_PASSWORD
KONDUKTOR_PATH_MAP optional: "stored => here", e.g.
"/Users/ben/Music => /music"; several separated by ";".
Applied for the session only — the library keeps its
stored paths, so it still opens on the computer it
was made on.
KONDUKTOR_NAME optional: what the library is called on screen
KONDUKTOR_DATA_DIR where history, export sets and the ledger live
(read by `paths.app_data_dir`)
KONDUKTOR_HOST / KONDUKTOR_PORT where to listen (0.0.0.0:8765)
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from ..core.pathmap import PathMapping
PLATFORMS = ("traktor", "rekordbox")
class ConfigError(Exception):
pass
@dataclass(frozen=True)
class ServerConfig:
platform: str
library: Path
content: Path
username: str
password: str
path_maps: tuple[PathMapping, ...] = field(default_factory=tuple)
name: str = ""
host: str = "0.0.0.0"
port: int = 8765
def parse_path_maps(text: str | None) -> tuple[PathMapping, ...]:
"""`"a => b; c => d"` → mappings. Raises `ConfigError` on a malformed one."""
out = []
for part in (text or "").split(";"):
part = part.strip()
if not part:
continue
if "=>" not in part:
raise ConfigError(f"KONDUKTOR_PATH_MAP: expected 'stored => here', got {part!r}")
src, dst = (s.strip() for s in part.split("=>", 1))
mapping = PathMapping.make(src, dst)
if mapping.empty:
raise ConfigError(f"KONDUKTOR_PATH_MAP: both sides are needed in {part!r}")
out.append(mapping)
return tuple(out)
def from_env(env=None) -> ServerConfig:
env = os.environ if env is None else env
def need(key: str) -> str:
value = (env.get(key) or "").strip()
if not value:
raise ConfigError(f"{key} is not set")
return value
platform = need("KONDUKTOR_PLATFORM").lower()
if platform not in PLATFORMS:
raise ConfigError(f"KONDUKTOR_PLATFORM must be one of {', '.join(PLATFORMS)}, not {platform!r}")
library = Path(need("KONDUKTOR_LIBRARY"))
if not library.exists():
raise ConfigError(f"KONDUKTOR_LIBRARY: {library} does not exist")
content = Path(need("KONDUKTOR_CONTENT"))
if not content.is_dir():
raise ConfigError(f"KONDUKTOR_CONTENT: {content} is not a folder")
username = need("KONDUKTOR_USERNAME")
password = env.get("KONDUKTOR_PASSWORD") or ""
if not password:
raise ConfigError("KONDUKTOR_PASSWORD is not set")
try:
port = int(env.get("KONDUKTOR_PORT") or 8765)
except ValueError:
raise ConfigError("KONDUKTOR_PORT must be a number")
return ServerConfig(
platform=platform, library=library, content=content.resolve(),
username=username, password=password,
path_maps=parse_path_maps(env.get("KONDUKTOR_PATH_MAP")),
name=(env.get("KONDUKTOR_NAME") or "").strip(),
host=(env.get("KONDUKTOR_HOST") or "0.0.0.0").strip(), port=port,
)
+133
View File
@@ -0,0 +1,133 @@
"""One computer at a time: the server's session lock.
A library held by a server is edited by ONE computer at a time (decided: a
shared or merged session was rejected). That computer holds the session; every
command carries its token, and anything else is told who holds it.
* **A lease, renewed by heartbeat.** The holder's app sends one every
`HEARTBEAT_SECONDS`; `LEASE_SECONDS` without one and the session is free.
A crashed laptop or a closed lid therefore never locks the library for
good, and a Wi-Fi blip does not lose it.
* **Takeover** is how a second computer gets in before the lease runs out:
it is told who holds the session (and what batch is running there) and may
take it. The old token is refused from then on, which is how the displaced
computer finds out.
* **The same computer coming back** — after sleep, after a reconnect through
its fallback address — renews its expired lease silently, as long as
nobody else has taken the session meanwhile.
Unsaved edits are NOT the session's: they live in the one native model the
server holds, so whoever holds the session next inherits them (and is asked to
save or discard them — `last_editor` says whose they were).
"""
from __future__ import annotations
import secrets
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from ..remote_protocol import LEASE_SECONDS
@dataclass
class Holder:
token: str
client_id: str
machine: str
since: str # ISO 8601, UTC
last_seen: float # on the lock's clock
batch: str | None = None # the kind of batch job running there, if any
uploads: set[str] = field(default_factory=set)
class InUse(Exception):
"""Another computer holds the session."""
def __init__(self, holder: Holder):
super().__init__(f"In use by {holder.machine}")
self.holder = holder
class Lost(Exception):
"""This token no longer holds the session."""
def __init__(self, holder: Holder | None):
super().__init__("Another computer has taken over this library" if holder
else "This computer no longer holds the session")
self.holder = holder
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
class SessionLock:
def __init__(self, *, lease: float = LEASE_SECONDS, clock=time.monotonic):
self.lease = lease
self._clock = clock
self._lock = threading.Lock()
self._holder: Holder | None = None
#: The machine whose commands made the unsaved edits (see `touch`).
self.last_editor: dict | None = None
# ---- reading --------------------------------------------------------------
def _live(self, holder: Holder | None) -> bool:
return holder is not None and self._clock() - holder.last_seen < self.lease
def holder(self) -> Holder | None:
"""Who holds the session right now (None: free, or the lease ran out)."""
with self._lock:
return self._holder if self._live(self._holder) else None
def describe(self) -> dict | None:
h = self.holder()
return None if h is None else {"machine": h.machine, "since": h.since, "batch": h.batch}
# ---- changing -------------------------------------------------------------
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> Holder:
"""Hold the session. Raises `InUse` when another computer holds it and
`takeover` is not set. The same client re-acquiring keeps its uploads."""
with self._lock:
current = self._holder
live = self._live(current)
if live and current.client_id != client_id and not takeover:
raise InUse(current)
uploads = current.uploads if current is not None and current.client_id == client_id else set()
self._holder = Holder(
token=secrets.token_urlsafe(24), client_id=client_id, machine=machine,
since=_now_iso(), last_seen=self._clock(), uploads=uploads,
)
return self._holder
def check(self, token: str | None) -> Holder:
"""The holder this token names, renewing its lease. Raises `Lost`.
A token whose lease ran out is still honoured when nobody else has
taken the session since — the same computer back from sleep."""
with self._lock:
current = self._holder
if current is None or not token or not secrets.compare_digest(current.token, token):
raise Lost(current if self._live(current) else None)
current.last_seen = self._clock()
return current
def heartbeat(self, token: str | None, batch: str | None) -> Holder:
holder = self.check(token)
holder.batch = batch
return holder
def release(self, token: str | None) -> None:
with self._lock:
current = self._holder
if current is not None and token and secrets.compare_digest(current.token, token):
self._holder = None
def touch(self, holder: Holder) -> None:
"""Record that `holder` made an edit — whose the unsaved ones are."""
self.last_editor = {"client_id": holder.client_id, "machine": holder.machine}
def clear_editor(self) -> None:
"""After a save or discard, nobody's edits are pending."""
self.last_editor = None
+70
View File
@@ -0,0 +1,70 @@
"""The app-level bookkeeping around ONE open library, wherever it is kept.
Version history belongs to the app, not the adapter (see `app_state.py`), and
until a library could live on a server it could only mean one thing: a git repo
in this computer's app-data, keyed by the library's local path. A library held
by a server is versioned THERE, beside the file it describes — so the open
library carries the services that know where its history lives, and the routes
ask them rather than the history module directly.
`LocalServices` is the whole of what used to be inline: nothing about a library
on this computer changes. The remote implementation lives with the remote
adapter (`adapters/remote/services.py`).
"""
from __future__ import annotations
from pathlib import Path
from typing import Protocol
from . import __version__, history
from .core import registry
class LibraryServices(Protocol):
#: Whether this library is held by a server (its history lives there).
remote: bool
def baseline(self) -> None: ...
def commit_save(self, adapter, outcome) -> str | None: ...
def history(self) -> list[history.HistoryEntry]: ...
def restore(self, commit_id: str) -> bool: ...
def clear_history(self) -> None: ...
class LocalServices:
"""History in this computer's app-data, keyed by the library's path."""
remote = False
def __init__(self, path: Path):
self.path = path
def baseline(self) -> None:
# An "as I found it" version (deduped, so re-opening an unchanged
# library is a no-op). Best-effort.
history.ensure_baseline(self.path)
def commit_save(self, adapter, outcome) -> str | None:
# Not every platform is versioned. A library that is more than one file
# has no single blob that IS the library, and it says so through its
# capabilities rather than this module knowing which platforms those are.
if adapter.capabilities().save.history and outcome.snapshot is not None:
return history.commit(self.path, outcome.snapshot, outcome.summary, __version__)
return None
def history(self) -> list[history.HistoryEntry]:
return history.list_history(self.path)
def restore(self, commit_id: str) -> bool:
"""Write a past version back as a NEW forward save. False if unknown.
The caller reopens the library afterwards."""
data = history.read_version(self.path, commit_id)
if data is None:
return False
# The adapter's driver owns writing its own format back, even for a restore.
registry.driver_for(self.path).restore(self.path, data)
history.commit(self.path, data, f"Restored version {commit_id[:8]}", __version__)
return True
def clear_history(self) -> None:
history.clear_history(self.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
#: Shares of ONE track's conversion time, for the status bar's within-track
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode +
#: verify ~4 s for a 4-minute track).
_DECODE_SHARE = 0.03
_SEPARATE_SHARE = 0.90
#: Shares of ONE track's conversion time (decode, separate; encoding + verifying
#: take the rest), for the status bar's within-track progress, by AAC encoder.
#: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate
#: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute
#: 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):
@@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
work = work_root() / f"batch-{id(handle):x}"
finished: list[tuple[Planned, dict, sf.Written]] = []
needs_engine = any(p.reuse is None for p in items)
encoder = sf.default_encoder()
if needs_engine and not mgr.ready():
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)})
item.target.parent.mkdir(parents=True, exist_ok=True)
# Of a TRACK's time, separation is nearly all (~90 % on MPS);
# decoding before it and encoding + verifying after share the rest.
# Of a TRACK's time, separation is nearly all; decoding before it
# and encoding + verifying after share the rest.
decode_share, separate_share = track_shares(encoder)
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} %")
def separate(pcm):
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)
done_at = _DECODE_SHARE + _SEPARATE_SHARE
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
return stems
handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %")
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(status="decoding 0 %")
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):
partial.unlink(missing_ok=True)
pending.drop([pitem])
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff. Show more