Compare commits

...
Author SHA1 Message Date
patben8 1464b1e211 Merge pull request #9 from MrPatben8/dev
Fixed issues on Windows, Implemented drag & drop importing, Improved STEM encoding speed
2026-10-13 17:47:09 +02:00
patben8 10f175b206 Bumped version number 2026-10-13 17:43:20 +02:00
patben8 a65ef959b2 Implemented drag to import 2026-10-13 17:42:24 +02:00
patben8 87cbd3720e Fixed STEM analysis not working on Windows 2026-10-13 10:59:22 +02:00
patben8 591f2bc791 Pararellized STEM aac encoding 2026-10-13 10:45:52 +02:00
patben8 ebe30c1128 Fixed analysis not working on windows 2026-10-12 23:49:19 +02:00
patben8 cd1914216f Fixed library options not appearing in windows 2026-10-12 23:26:33 +02:00
patben8 d10b11f8eb Merge pull request #8 from MrPatben8/dev
Fixed Rekordbox exports
2026-10-12 19:12:41 +02:00
patben8 79a8a843c5 Bumped version number 2026-10-12 19:12:09 +02:00
patben8 0204a322ff Fixed and pinned rekordbox exports 2026-10-12 19:10:20 +02:00
patben8 05051e7056 Merge pull request #7 from MrPatben8/dev
Implemented remote file exploring, fixed STEM playback and improved startup time.
2026-10-12 15:04:40 +02:00
patben8 b5dabbc8a0 Updated the readme 2026-10-12 15:02:46 +02:00
patben8 86bbb7b961 Bumped version number 2026-10-12 13:51:23 +02:00
patben8 d474c662db Fixed slow build startup time and implemented loading screen 2026-10-12 13:20:00 +02:00
patben8 a0df683fee Fixed stem playback not working in build 2026-10-12 11:31:44 +02:00
patben8 3385b794e9 Added setting for export playlist root folder toggle 2026-10-12 10:56:32 +02:00
patben8 2c352b76a1 Added konduktor settings menu 2026-10-12 10:15:14 +02:00
patben8 40630ff78e Added support for remote file exploring 2026-10-12 09:23:34 +02:00
patben8 966f3fe8c5 Bumped version number 2026-10-10 17:42:17 +02:00
patben8 a03b9056a9 Merge pull request #6 from MrPatben8/dev
Implemented dragging engine
2026-10-10 17:40:06 +02:00
patben8 26b556d975 Updated remote protocol version 2026-10-06 23:17:21 +02:00
patben8 c87444bda5 Implemented drag and drop loading 2026-10-06 23:08:34 +02:00
patben8 7ba71981c8 Implemented library rearrangement 2026-10-06 22:51:34 +02:00
patben8 89c7dade25 Tracks can be added to playlists via drag 2026-10-06 22:41:29 +02:00
patben8 b154df430a Implemented drag core and song reorganizing 2026-10-06 22:32:31 +02:00
patben8 e5c7b67626 Implemented playlist reorganizing 2026-10-06 22:25:01 +02:00
patben8 9f79f5a849 Search now includes comments 2026-10-05 23:16:12 +02:00
patben8 c8b86100f0 Track position in playlist can now be typed 2026-10-05 21:01:25 +02:00
patben8 0fac84cb73 Fixed issue with release pipeline 2026-10-04 21:57:40 +02:00
patben8 71ee877784 Merge pull request #5 from MrPatben8/dev
Implemented Key Analysis & Remote Library Management
2026-10-04 18:35:08 +02:00
patben8 920146f2c0 Bumped version number 2026-10-04 18:33:33 +02:00
patben8 ba7b662b93 Fixed port assumption 2026-10-04 17:13:24 +02:00
patben8 e5fb0f0dbb Initial implementation of remote library system 2026-10-04 17:13:24 +02:00
patben8 e8a53eee07 Added analyze dialog 2026-10-04 17:00:33 +02:00
patben8 36a6df4d3b Build analyze backend 2026-10-04 16:33:37 +02:00
patben8 72a52d3291 Reworked analysis menu 2026-10-04 16:18:43 +02:00
patben8 c3571fd054 Implemented key setting into adapters 2026-10-04 16:06:36 +02:00
patben8 b5b3dd04c3 Implemented key analysis system 2026-10-04 15:26:34 +02:00
patben8 4e9472c14a Unified prefs writing 2026-10-03 10:31:32 +02:00
patben8 957525393b Merge pull request #4 from MrPatben8/dev
Implemented STEM generation & OneLibrary editing support
2026-10-01 17:18:05 +02:00
patben8 bdc62f2c1b Added OneLibrary testing fixtures 2026-10-01 17:00:13 +02:00
patben8 7960a5a68f Implemented OneLibrary track addition and removal 2026-10-01 16:43:37 +02:00
patben8 c5280a95f2 Implemented Device Library and OneLibrary sync 2026-10-01 16:00:33 +02:00
patben8 e73fa05e1f Implemented OneLibrary cue and grid edits 2026-10-01 15:48:44 +02:00
patben8 775e94168c Begun implementing OneLibrary editing 2026-10-01 15:07:43 +02:00
213 changed files with 17555 additions and 1597 deletions

No files matched your search

+53 -3
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.
@@ -136,6 +183,9 @@ 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/…
- name: Publish release
+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.
+585 -47
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
@@ -47,6 +62,10 @@ Two independent apps that talk over HTTP:
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
(Rekordbox is a `.db`, Serato is a directory).
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers.
- `grid_edit.py` (`ReplaceGridCommands`) — the marker-level grid commands
(add / move-with-clamp / retempo / delete) for a store whose one primitive
is `replace_grid`: Rekordbox's and OneLibrary's, whose grids are per-beat
lists. Traktor keeps its own, companion-aware versions.
- `relocate.py` — **auto path remapping's search** (see `relocation.py`).
Fixes ONE thing: a stored prefix changed and the layout under it did not
(a collection built on Windows with the SSD as `X:`, opened on a Mac where
@@ -110,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
@@ -255,8 +318,9 @@ Two independent apps that talk over HTTP:
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only
platform with them — the two-platform promotion rule).
**Hot cue colour is writable** (`set_cue_color`, `PATCH
/api/tracks/cue/color`) from `palette.SWATCHES` — the 15 MEASURED swatches
of rekordbox's 16 (the teal-green is left out, not guessed); a pick must
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
wrote it as its default for a hot cue added on a stick); a pick must
be an exact swatch (`swatch_code`), unlike the exporter's nearest-hue
`code_for`. Not a breach of the promotion rule: Rekordbox, OneLibrary and
Serato all colour cues — Traktor is the odd one out, by type only, so it
@@ -295,9 +359,73 @@ Two independent apps that talk over HTTP:
`close()` disposes the SQLAlchemy engine, not just the session — otherwise
the OS file handle stays open and `master.db` cannot be replaced. `AppState`
closes the previous adapter when opening a new library.
- `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format
(AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware.
Built as the source half of a future "import a stick into Traktor" feature.
- `adapters/onelibrary/` — **editable when opened as THE library; read-only
when browsed from the sidebar's Devices** (`read_only=True`, cause `browsing`).
The cross-vendor USB export format (AlphaTheta + Algoriddim + Native
Instruments), read by CDJ-class hardware. Editing is landing in steps toward
parity with the Rekordbox adapter — track metadata, playlists, hot cues and
the beatgrid, and the `export.pdb` rebuild done and VERIFIED in rekordbox 7
(both library views matched); adding/removing tracks done (checked
in rekordbox too) and the UI ("Open for editing…" on a Devices row) — all
VERIFIED in rekordbox 7 on a real stick (2026-10-01) — decided in
[the editing discussion](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md),
which also holds what rekordbox 7 was MEASURED writing when it edits a stick
(no update counter moves, the `cue` table stays empty, a new playlist goes on
top). **The store never opens the database ON the drive**: it works on a copy
in app-data and Save writes it back whole — fingerprint check (refuses if
another app wrote the stick since open), backup to app-data, temp file beside
the database, stale `-wal`/`-shm` deleted, rename — then writes edited text
fields into the audio files' tags as rekordbox does (not the rating). Cue tags
are read by Konduktor's own `rekordbox/anlz_file.py`, NOT pyrekordbox: rekordbox
writes COMPACT cue entries when it edits (48 / 44 bytes, export: 88), and
pyrekordbox's parser raised on the 44-byte one and lost the whole `.EXT`.
**Cue and grid edits rewrite only the cue LISTS they touch, and inside them
only the entries they touch** (`anlz_file.raw_entries` keeps the rest as
rekordbox wrote them), held as edited in-memory copies of the `.DAT`/`.EXT`
that every read serves, written at Save BEFORE the database (temp + rename,
fingerprinted, backed up). Each rule reproduces rekordbox's own measured edit
byte for byte: a recolour changes only the `PCP2` colour bytes (palette code
+ RGB — rekordbox draws the CODE, so `cues.color` is `palette`, like
master.db); a new pad is APPENDED to its lists; a grid edit rewrites `PQTZ`,
BLANKS `.EXT`'s `PQT2` (`anlz_writer.blank_pqt2`), clears every loop's beat
length to 0/0, leaves `.2EX` alone, and sets `bpmx100` from the first marker.
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.
**`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
mirrored from OneLibrary (rekordbox exports both from the same ids), only the
tracks / lookup / playlist tables are candidates, a table is rewritten only if
a row changed, an unchanged row keeps rekordbox's bytes, and a changed track
row is the old row with the edited fields overwritten — so phrase strings,
`masterDbId` halves and play counts survive. A track row ends at its last
string (`pdb.track_extent`), NOT at the next row: rekordbox's heap holds stale
tails between rows. Keys and artwork are mirrored too (pdb artwork row =
`a<n>.jpg` beside OneLibrary's `b<n>`); history and `exportExt.pdb` are
untouched.
**Adding and removing tracks** (`tracks.places_audio`: the LIBRARY places
added audio, so the importer asks `place_audio` instead of the user, and the
routes check space at `audio_home()`): a file already on the stick is used in
place, anything else is copied to `Contents/<Artist>/<Album>/` (rekordbox's
layout: `UnknownArtist`/`UnknownAlbum`, file names cut to 48 characters) via
`<stick>/.konduktor-incoming/`, playable from there until Save moves it into
place; Discard deletes it, and a crashed session's incoming folder is cleared
on the next EDITABLE open (never a browsing one). Each added track is decoded
once and gets the OneLibrary exporter's own `.DAT`/`.EXT`/`.2EX`
(`OneLibraryExporter.anlz_files` builds bytes rather than writing) and art
(`art_files`), held in memory and written at Save; hot cues replay through
`set_cue`, memory cues (and a hot cue with no free pad) cross as memory cues.
The row copies a rekordbox stick row column for column (search columns NULL,
no counters) and `property.numberOfContents` follows. Removing deletes every
row naming the track (playlist entries renumbered from 1) and, AFTER the
database is saved, its audio, analysis files and unshared artwork, pruning
emptied folders. The adapter re-projects after every save, since Save moves
files. `save.managed_by_export` is set when the drive's root carries an
export set's `.konduktor-export.json`, and SaveBar warns that the next export
run replaces edits made in place.
Full research, incl. the schema, is in
[.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md);
the four things that make it unlike the Rekordbox adapter:
@@ -418,6 +546,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
@@ -464,7 +710,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
@@ -565,14 +817,30 @@ 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`). Capped at 40% of the sidebar and self-scrolling so a deep tree
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).
Capped at 40% of the sidebar and self-scrolling so a deep tree
gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in
place is **asked every time with nothing preselected** — the answer depends
on the drive — and warns that a referenced file on an external drive goes
missing on unplug. A playlist/export target adds to the collection first
and says so; it runs through `importer.run(reference=…, into_playlist=…)`),
and says so; it runs through `importer.run(reference=…, into_playlist=…)`.
A library with `tracks.places_audio` (a stick) is the exception: no
question and no destination — the dialog STATES how many files are copied
and how many stay in place (`platformCopy.placedAudioSummary`), and
`ImportDialog` drops its destination folder the same way),
`CollectionPicker` (**two steps: which PLATFORM, then which
library** — Automatic / Open last / Find manually, the last revealing a file
browser. The platform comes first because every later answer depends on it:
@@ -592,6 +860,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 Option/Alt 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 /
@@ -599,8 +882,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 opens `ShortcutsDialog` — the shortcut list is 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`. 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
@@ -619,7 +912,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 an Option-drag leaves);
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
@@ -642,6 +971,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
@@ -653,7 +994,11 @@ 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 in playlist order so its first track
lands at #N — allowed while sorted/filtered, unlike drag, because it
reorders the FULL entry list; "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`
@@ -765,18 +1110,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)
@@ -804,10 +1161,22 @@ 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.
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
@@ -824,7 +1193,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-
@@ -875,7 +1247,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`
@@ -893,6 +1267,11 @@ 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.
- `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
@@ -901,18 +1280,70 @@ serialization path.** It enforces:
Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2`
merge, and — cross-checked against the same cues in `master.db` — the dense
ANLZ slot numbering, which is the thing most likely to be silently wrong.
Also reads `fixtures/onelibrary/rekordbox-edited/` (a stick after rekordbox
itself edited it: compact cue entries) and pins browsing vs editable mode. It
opens a temp COPY of the fixture — a stray save once rewrote the checked-in one.
- `test_onelibrary_fidelity.py` — the row-level diff for OneLibrary writes, on a
temp copy of the fixture: nothing reaches the drive before Save, a no-op save
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, 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). 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
blanked `PQT2` and cleared loop beats are rekordbox's bytes exactly, and the
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
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.
- `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
file byte-identical (ids are mirrored), an edit changes only the edited
fields, a new playlist and a reorder reach it, every untouched table and
`exportExt.pdb` stay byte-identical, another app's pdb write is refused, and a
stick without one never gets one.
- `test_onelibrary_tracks.py` — adding and removing through `importer.run` on
Goober: placement (in place on the stick, else `Contents/<Artist>/<Album>/`,
Unknown*, FAT-safe names, 48 chars, suffixed on collision), the prep crossing
(pad + colour + name, memory cues, a taken pad -> memory, a detected grid),
the row's shape, art as a/b pairs, the Device Library rows; a cancel
mid-copy, a Discard and a crash leave nothing; removal deletes rows at once
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
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
@@ -920,7 +1351,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
@@ -932,6 +1363,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
@@ -948,7 +1393,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
@@ -958,6 +1407,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
@@ -1010,11 +1464,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`.
@@ -1023,14 +1505,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
@@ -1040,6 +1533,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
@@ -1047,7 +1555,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
@@ -1240,7 +1756,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
@@ -1268,15 +1785,17 @@ that number and nothing else — everything derives from it:
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).
- 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens,
projects, browses and searches: tracks, playlists, hot cues, memory cues, loops
and flexible beatgrids. Built as the readable SOURCE half of a future
**"import a OneLibrary stick into a Traktor library"** feature, which is the
motivating use case. Everything unknown about the format is on the write side
(the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the
update counters), so read-only is a deliberate boundary rather than an
unfinished one. All research — including the schema, which has no public spec —
is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- ✅ 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,
playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track
metadata (+ file tags), playlists, hot cues and the beatgrid (in the ANLZ
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
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
[the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md),
@@ -1294,7 +1813,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
@@ -1325,7 +1848,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/`,
@@ -1408,8 +1931,8 @@ that number and nothing else — everything derives from it:
rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue
from its palette CODE** (`PCP2` byte 44, before the RGB; `djmdCue.ColorTableIndex`
in master.db), not the RGB — `adapters/rekordbox/palette.py` holds the 16-swatch
table MEASURED from a rekordbox 7 export (one swatch, ~0x12 teal-green, still
unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green
table MEASURED from a rekordbox 7 export (the teal-green, 0x13 #00FF30, measured
later from a rekordbox-edited stick). Type colours map by intent (cue -> light blue 0x05, loop -> green
0x16), anything else to the nearest hue; the palette has NO white, so a grid
companion is code 0 + RGB white (what rekordbox draws for it: unverified). The
**Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7
@@ -1470,7 +1993,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.
@@ -1536,6 +2064,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
+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/"
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,32 @@
# Goober: a rekordbox-written stick, before and after rekordbox edited it
The stick Ben keeps for measuring the Pioneer formats, as rekordbox 7 left it:
11 tracks, 2 playlists, **both** libraries (`exportLibrary.db` and the legacy
`export.pdb` + `exportExt.pdb`). `test_onelibrary_anlz.py`,
`test_onelibrary_pdb.py` and `test_onelibrary_tracks.py` run against copies of it.
## What is here
- `PIONEER/rekordbox/` holds the three databases, **untouched**: bytes rekordbox
wrote (snapshot `s0`, 2026-10-01).
- `PIONEER/USBANLZ/` holds every track's `.DAT` and `.EXT`, trimmed by dropping
whole tags: only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for
byte. The waveforms are gone, and so are the `.2EX` files.
- `after/` holds the same tags after **rekordbox 7 itself** edited the stick
(snapshot `s1`, one edit per track):
- `black-bloc-recoloured.EXT`: pad C recoloured to `0x2D` `#FF0045`.
- `wtf-87bpm.DAT` / `.EXT`: "Result – WTF" changed from 174 to 87 BPM.
- `demo2-pad-e-added.EXT`: a hot cue added on pad E of "Demo Track 2".
There is no audio. The adapter resolves paths and never needs the files, so the
time base falls back to rekordbox's MP3 default, the same offset for reading and
writing.
## Why
Konduktor's edits are pinned against what rekordbox wrote for the SAME edit, not
against Konduktor's own reader. A recolour and a grid edit must reproduce
rekordbox's bytes exactly (colour bytes, the blanked `PQT2`, loop beats cleared).
The pdb tests prove that an in-place edit of a rekordbox-written `export.pdb`
leaves everything else as rekordbox wrote it. The full diff of the measurement is
in `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`.
+13
View File
@@ -56,3 +56,16 @@ implementation — open and write to it.
Not loaded by the tests; kept as documentation, and as the starting point if
Konduktor ever needs to create a drive from nothing.
## rekordbox-edited/
Analysis files from a SECOND stick (Goober), after rekordbox 7 itself edited it
(2026-10-01): a hot cue added on pad E of `demo-track-2`, and a memory cue added on
the start of `nemean`'s memory loop. Trimmed the same way as above, by dropping
whole tags: only `PPTH`, `PCOB` and `PCO2` are kept, byte for byte.
They exist for one property: rekordbox writes **compact** cue entries when it
edits (48 bytes for that hot cue, 44 with no colour for the memory cue; an export
writes 88). pyrekordbox's parser raises on the 44-byte form, which once made the
reader drop the whole `.EXT`, losing pads D-H and every colour. See
`adapters/rekordbox/anlz_file.py`.
+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",
)
+261 -47
View File
@@ -5,28 +5,30 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
* a ``TrackIndex`` — the generic READ projection built from it.
**Read-only.** Every command is refused and `capabilities.writable` is False with
cause `platform_incomplete`, so the UI never offers an edit in the first place;
the raises here are the backstop, not the mechanism.
**Editable when opened as THE library**, with parity with the Rekordbox adapter
as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
Opened `read_only` — as the sidebar's Devices do, beside the loaded library — it
reports `writable=False` with cause `browsing`, and every command is refused.
That scope is deliberate rather than provisional. The purpose of this adapter is
to make a OneLibrary drive a readable SOURCE — the half an import into another
library needs — and every genuinely unknown part of the format sits on the write
side: the `cue` table's eight MPEG frame/offset columns, whose values a player
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and
the update counters a drive uses to reconcile edits made on hardware. None of
those has to be guessed at to read a drive, and none of them should be guessed at
at all.
What a write must look like was MEASURED by diffing a stick before and after
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
playlists, hot cues and the beatgrid so far; adding and removing tracks next —
and every command not written yet is refused, with its capability flag False so
the UI never offers it.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME
from . import capabilities as caps
from . import projection
from .store import OneLibraryStore
@@ -42,9 +44,10 @@ ATTRIBUTE_SMART = 4
class OneLibraryAdapter:
platform = "onelibrary"
def __init__(self, path: Path):
def __init__(self, path: Path, *, read_only: bool = False):
self.path = Path(path)
self._store = OneLibraryStore(self.path)
self.read_only = read_only
self._store = OneLibraryStore(self.path, read_only=read_only)
self._index = TrackIndex()
self._rebuild()
@@ -60,7 +63,9 @@ class OneLibraryAdapter:
self._index.rebuild(tracks)
def _drive_path(self, row) -> str | None:
resolved = self._store.layout.resolve(getattr(row, "path", None))
# Through the store: an added track plays from its incoming copy until
# Save puts it in place.
resolved = self._store.resolve_audio(getattr(row, "path", None))
return str(resolved) if resolved is not None else None
def close(self) -> None:
@@ -72,14 +77,27 @@ class OneLibraryAdapter:
self._store.close()
def reload(self) -> None:
self._store._load()
"""Re-read the drive, DISCARDING unsaved edits."""
self._store.discard()
self._rebuild()
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale."""
from ...core.stem_file import is_stem_file
row = self._store.content(track_id)
path = self._drive_path(row)
self._index.replace(projection.to_track(row, path, stem=bool(path) and is_stem_file(path)))
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(
device_name=self._store.device_name,
version=self._store.db_version,
read_only=self.read_only,
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
# A drive an export set wrote carries the export's manifest at its root.
managed_by_export=(self._store.layout.root / MANIFEST_NAME).is_file(),
)
# ---- read ------------------------------------------------------------
@@ -146,7 +164,9 @@ class OneLibraryAdapter:
rather than an absence, and treating 0 as a real id would orphan every
top-level playlist.
"""
rows = self._store.playlists()
rows = sorted(self._store.playlists(),
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
writable = not self.read_only
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
@@ -166,13 +186,14 @@ class OneLibraryAdapter:
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
selectable=kind == "playlist",
# Read-only: every per-node flag is False, and
# Opened read-only, every flag is False and
# `capabilities.writable` tells the UI why, once.
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
can_add_tracks=writable and kind == "playlist",
can_reorder=writable and kind == "playlist",
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
parents[node_id] = "root" if parent in ("0", "", "None") else parent
@@ -203,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.
@@ -238,32 +262,147 @@ class OneLibraryAdapter:
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return False
return self._store.dirty
def save(self):
raise Unsupported(self._readonly_reason("Saving"))
self._require_writable("Saving")
outcome = self._store.save()
# Save MOVES files (an added track's audio leaves its incoming copy), so
# the projection is rebuilt from what is now on the drive.
self._rebuild()
return outcome
def snapshot(self) -> bytes:
raise Unsupported("OneLibrary drives are not versioned by Konduktor")
# ---- commands: all refused -------------------------------------------
# ---- commands -----------------------------------------------------------
def _readonly_reason(self, what: str) -> str:
if self.read_only:
return (f"{what} is not possible while the drive is open for browsing. "
"Open it for editing to change it.")
return f"{what} is not supported yet for OneLibrary drives."
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def _require_writable(self, what: str) -> None:
"""Every write passes through here, so a command added later cannot
forget that a browsing drive is read-only."""
if self.read_only:
self._refuse(what)
# ---- audio placement (`tracks.places_audio`) ----------------------------
def audio_home(self) -> Path:
return self._store.audio_home()
def place_audio(self, source: Path, track) -> Path | None:
self._require_writable("Adding tracks")
return self._store.place_audio(source, track)
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
self._refuse("Adding tracks")
"""Add tracks, each arriving ready to prep — as the Rekordbox adapter does.
A drive keeps the beatgrid, cues and waveforms in per-track analysis
files, and rekordbox shows neither grid nor cues without them, so every
file is decoded ONCE here and its `.DAT`/`.EXT`/`.2EX` built by the
OneLibrary exporter's own writer — the files rekordbox 7 was verified
to read. A file with no grid of its own gets Konduktor's.
Two phases, as in Rekordbox: FIRST the slow, cancellable part (decoding,
grid detection, building the analysis and artwork bytes) before the
library is touched; THEN the rows, with hot cues replayed through the
ordinary `set_cue` so they keep its conventions. Memory cues — and a hot
cue with no free pad — cross as memory cues, written with the files.
`audio_path` is where `place_audio` said to copy it (or the file itself,
already on the stick); Save moves copies into place.
"""
from ...core import audio_tags, grid_detect, key_detect, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
self._require_writable("Adding tracks")
exporter = OneLibraryExporter()
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
try:
rel = self._store.drive_relative(self._store.final_of(audio))
except ValueError:
raise InvalidCommand(f"{audio} is not on this drive") from None
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
hot, memory, taken = [], [], set()
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
if (cue.role == "hotcue" and cue.slot is not None
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
hot.append(cue)
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
# A file with no key of its own gets one, as it gets a grid.
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
export_track = ExportTrack(track=track, destination=audio,
cues=TrackCues(grid_markers=markers, cues=memory))
# Decoded once above; the writer must not decode it again.
export_track.waveform = lambda *, lead=0.0, m=measured: m
art = item.art or audio_tags.read_cover(audio)
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
length = track.length or (int(measured.duration) if measured else None)
prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else track.bpm, length=length)
for cue in hot:
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
cue_type="loop" if cue.length else "cue",
length_sec=cue.length or 0.0, name=cue.name)
code, _rgb = palette.code_for(cue.color)
if cue.color and code:
self._store.set_cue_color(track_id, cue.slot, code)
added.append(track_id)
self._rebuild()
return added
def remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks")
"""Remove tracks — and, on a stick, their audio and analysis files at Save
(decision 3: a stick's audio belongs to its library)."""
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
self._refuse("Converting tracks to stems")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata")
self._require_writable("Editing track metadata")
self._store.set_track_metadata(track_id, fields)
self._refresh(track_id)
return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -272,55 +411,130 @@ class OneLibraryAdapter:
return self._store.cover_art(track_id)
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists")
self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
def create_folder(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlist folders")
self._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists")
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists")
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._refuse("Editing playlists")
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
def set_cue(self, track_id: str, **kw) -> TrackCues:
self._refuse("Editing cues")
def _refresh_cues(self, track_id: str) -> TrackCues:
"""Re-project a track AND return its fresh cues — every cue/grid command
ends here, so a route can never serve a stale projection."""
self._refresh(track_id)
return self.track_cues(track_id) or TrackCues()
def _check_cue_type(self, cue_type: str) -> None:
if cue_type not in WRITABLE_CUE_TYPES:
raise Unsupported(f"OneLibrary has no cue type {cue_type!r}")
def set_cue(
self,
track_id: str,
*,
slot: int,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
role: str = "hotcue",
name: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
raise Unsupported(
"Memory cues are shown but cannot be edited — only hot cues are writable"
)
self._check_cue_type(cue_type)
self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
length_sec=length_sec, name=name)
return self._refresh_cues(track_id)
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._refuse("Editing cues")
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._refuse("Editing cues")
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's hot cue colours")
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._refuse("Deleting cues")
self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._refuse("Placing cues")
self._require_writable("Placing cues")
for cue in cues:
self._check_cue_type(getattr(cue, "type", "cue"))
self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id)
# ---- commands: beatgrid -----------------------------------------------
@staticmethod
def _markers_from(markers: list) -> list:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
return [m if isinstance(m, GridMarker) else GridMarker(start=float(m[0]), bpm=float(m[1]))
for m in markers]
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.add_grid_marker(track_id, start_sec, bpm)
return self._refresh_cues(track_id)
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.move_grid_marker(track_id, index, start_sec)
return self._refresh_cues(track_id)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.set_grid_marker_bpm(track_id, index, bpm)
return self._refresh_cues(track_id)
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.delete_grid_marker(track_id, index)
return self._refresh_cues(track_id)
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
self._require_writable("Editing the beatgrid")
self._store.replace_grid(track_id, self._markers_from(markers))
return self._refresh_cues(track_id)
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
"""An analysis result, as rekordbox's analyser would write it: nothing is
paired with a marker (the companion cue is Traktor's), so a replace."""
return self.replace_grid(track_id, markers)
def delete_grid(self, track_id: str) -> TrackCues:
self._refuse("Deleting the beatgrid")
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
raise Unsupported("OneLibrary has no beatgrid lock")
@@ -28,7 +28,8 @@ __all__ = ["BPM_EPSILON", "markers_from_beats", "beats_from_pqtz", "markers_from
def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag.
"""Per-beat ``(times_sec, bpms, beat_in_bar)`` from a parsed ANLZ file's `PQTZ` tag
(an `anlz_file.AnlzFile`).
Returns None when the file has no `PQTZ` — which is a real state, not an
error: rekordbox analyses one-shot samples too, and gives them an analysis
@@ -39,7 +40,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ":
continue
entries = getattr(getattr(tag.struct, "content", None), "entries", None)
entries = tag.entries
if not entries:
return None
times: list[float] = []
@@ -1,25 +1,27 @@
"""What a OneLibrary drive can persist: nothing, for now.
"""What a OneLibrary drive can persist.
`writable` is False with cause `platform_incomplete`. That is the distinction the
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A
cloud-synced Rekordbox library is refused permanently to protect the user's other
machines; a OneLibrary drive simply has no write path yet, and the UI must word
those two very differently.
Opened as THE library, a drive is writable, and the per-feature flags say which
edits have landed: track metadata, playlists, hot cues, the grid, and adding
and removing tracks, so the UI never offers an edit the adapter
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
loaded library — `writable` is False with cause `browsing`, which the UI words
as "open it for editing", not as a missing feature.
The per-feature flags below still report what the FORMAT supports rather than
being blanked to false, because that is what `writable=False` is for: the UI can
show a drive's cues and grid honestly, and say once, in one place, that the whole
library is read-only. Blanking them would claim OneLibrary has no hot cues.
With `writable=False` the per-feature flags still report what the FORMAT
supports rather than being blanked, because that is what the library-level flag
is for: the UI can show a drive's cues and grid honestly and say once, in one
place, that the library is read-only. Blanking them would claim OneLibrary has no
hot cues.
Two answers are worth recording now, while the evidence is in front of us, since
getting them wrong later would be a silent data bug rather than a missing
feature:
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
"palette" because `djmdCue` stores an index into a built-in table — the same
vendor, two genuinely different representations.
* cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
16 swatches and both are written. (This was first read as "free RGB" off the
RGB bytes alone; the code byte beside them is what decides.)
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
as Traktor and Rekordbox, and NOT the `separate_bank` the original
multi-platform plan assumed.
@@ -34,44 +36,59 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`).
HOTCUE_SLOTS = 8
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities:
def capabilities_for(
device_name: str | None = None,
version: str | None = None,
*,
read_only: bool = False,
editable_fields: list[str] | None = None,
managed_by_export: bool = False,
) -> Capabilities:
return Capabilities(
platform="onelibrary",
version=version,
# A roadmap gap, not a protective refusal — the UI words the two
# differently, which is the whole reason `readonly_cause` exists.
writable=False,
readonly_cause="platform_incomplete",
writable=not read_only,
readonly_cause="browsing" if read_only else None,
cues=CueCapabilities(
editable=False,
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does. They are
# projected and preserved; nothing here is editable anyway.
# OneLibrary carries memory cues, as Rekordbox does: projected and
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
memory_cues=True,
max_memory_cues=None,
types=["cue", "loop"],
color="free", # PCO2 stores RGB per cue, not a palette index
palette=[],
types=WRITABLE_CUE_TYPES,
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # PCO2 carries a per-cue comment
loops="cue_type",
),
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
# survive an export — so the format is flexible even though Konduktor
# does not write it here.
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
# The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
# No per-track grid lock exists in the format.
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # stored 0-5 directly, as in master.db
editable_fields=[],
# The Rekordbox adapter's set: `producer`/`mix` have no column.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio", "stem"],
# `artwork` gates EDITING, and a drive is read-only here. Reading
# works: `store.cover_art` follows `content.image_id` -> `image.path`.
# A stick's audio belongs to its library: added files are copied onto
# it (laid out as rekordbox does) and a removed track's file goes
# with it, at Save — so the library, not the user, places the audio.
addable=not read_only,
removable=not read_only,
key_writable=not read_only,
places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows
# `content.image_id` -> `image.path`.
artwork=False,
artwork_note=None,
),
@@ -80,13 +97,18 @@ def capabilities_for(device_name: str | None = None, version: str | None = None)
# A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules.
smart="none",
reorder=False,
reorder=True,
),
save=SaveCapabilities(
app_name="OneLibrary",
library_label=device_name or "exportLibrary.db",
# Nothing is written, so nothing can be overwritten by another app.
# Named for the DRIVE ("Save to Goober"): a person has several
# sticks, and "Save to OneLibrary" would not say which.
app_name=device_name or "OneLibrary",
library_label="exportLibrary.db",
# Another app writing the drive between open and save is CAUGHT,
# not risked: the store fingerprints the database at open and
# refuses to save over a change it did not make.
overwrite_risk="none",
managed_by_export=managed_by_export,
# A drive is a database plus N analysis files plus the audio itself,
# so there is no single blob that IS the library — the same reason
# Rekordbox libraries are not versioned.
+36 -23
View File
@@ -37,6 +37,7 @@ from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import palette
log = logging.getLogger(__name__)
@@ -47,14 +48,13 @@ NO_LOOP = 0xFFFFFFFF
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
MEMORY_SLOT = 0
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
# PCO2/PCOB entry kinds. The value is the same in both tags.
ENTRY_CUE = 1
ENTRY_LOOP = 2
def _entry_kind(value) -> int:
"""PCOB gives an enum, PCO2 an int — one number out of either."""
"""An entry's kind as an int, defaulting to a point cue if unreadable."""
try:
return int(value)
except (TypeError, ValueError):
@@ -68,8 +68,17 @@ def _color(entry) -> str | None:
real black in principle, but rekordbox uses it as "unset" and shows such a
cue in the default colour, so it is reported as no colour rather than as
black. Memory cues in the reference export are exactly this case.
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
code is reported as that swatch; a cue with code 0 and an RGB (older
exports, the reference fixture) is reported by its RGB.
"""
swatch = palette.hex_for(getattr(entry, "color_code", None))
if swatch is not None:
return swatch
try:
# None on an entry too short to carry a colour: every PCPT, and the
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
except (AttributeError, TypeError, ValueError):
return None
@@ -78,7 +87,7 @@ def _color(entry) -> str | None:
return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try:
hot_cue = int(entry.hot_cue)
@@ -111,11 +120,11 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
length=length,
slot=slot,
color=_color(entry) if with_color else None,
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
# command. `capabilities.writable` is what the UI actually gates on;
# this keeps the per-cue answer consistent with it.
editable=False,
readonly_reason="platform_managed",
# 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",
grid_marker=None,
)
@@ -130,15 +139,14 @@ def _entries(anlz, tag_type: str) -> list:
"""
out: list = []
for tag in getattr(anlz, "tags", []):
if tag.type != tag_type:
continue
content = getattr(tag.struct, "content", None)
out.extend(getattr(content, "entries", None) or [])
if tag.type == tag_type:
out.extend(tag.entries)
return out
def cues_from_anlz(dat, ext) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`.
def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`
(`rekordbox.anlz_file.AnlzFile`s).
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
with no cues at all yields an empty list rather than an error.
@@ -153,14 +161,14 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
for f in files:
pco2.extend(_entries(f, "PCO2"))
if pco2:
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
else:
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
# .EXT the rest, so either alone is an incomplete bank.
pcob: list = []
for f in files:
pcob.extend(_entries(f, "PCOB"))
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
return _dedupe(cues)
@@ -168,18 +176,23 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
"""Collapse the same cue appearing in more than one tag or file.
Identity is (role, slot, start) rather than the whole cue: the same pad can
be described by both `PCOB` and `PCO2`, and by both files, and those copies
agree on position while differing in how much detail they carry. The first
one wins, which — given PCO2 is read first — is the richest.
Identity is (role, slot, start, type, length) rather than the whole cue:
the same pad can be described by both `PCOB` and `PCO2`, and by both files,
and those copies agree on all five while differing in how much detail they
carry (colour, comment). The first one wins, which — given PCO2 is read
first — is the richest.
Type and length are part of it because two MEMORY cues may share a position:
rekordbox happily stores a memory cue on the start of a memory loop (seen on
Goober), and keying on position alone silently dropped the loop.
Ordered by position, then by slot, so the projection is stable across reads
regardless of the order the tags happened to store.
"""
seen: set[tuple[str, int | None, int]] = set()
seen: set[tuple] = set()
out: list[CuePoint] = []
for c in cues:
key = (c.role, c.slot, round(c.start * 1000))
key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
if key in seen:
continue
seen.add(key)
@@ -0,0 +1,208 @@
"""Keeping a stick's legacy Device Library (`export.pdb`) in step with its OneLibrary.
Most rekordbox sticks carry BOTH: `exportLibrary.db` (OneLibrary, newer players)
and `export.pdb` (the Device Library, older players and rekordbox's own "Device
Library" view). Cues and the grid live in the analysis files both share, so they
follow an edit by themselves; titles and playlists live in each database
separately. **rekordbox itself lets them drift**: measured on Goober
(2026-10-01), its edits updated the pdb's track metadata but not a new playlist
or a reorder. Konduktor rebuilds the pdb at Save instead (decision 2 of the
editing discussion), so a stick never shows different playlists depending on
which player reads it.
**Ids are mirrored, not assigned.** rekordbox exports both libraries from the
same ids — pdb track id = `content_id`, the artist/album/genre/label/key ids, the
playlist ids, playlist `sort` = `sequenceNo`, entries `(sequenceNo, content_id,
playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibrary
database IS the answer for every row the pdb shares with it.
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
(`pdb.PdbEditor`): only the tracks, the lookup tables (artist, album, genre,
label, key), artwork and the playlist tree and entries are candidates, a table is rewritten only if one of its rows changed,
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
with the edited fields overwritten, so everything the pdb holds that OneLibrary
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
dates — survives. History, colours, menus and `exportExt.pdb` are never touched.
"""
from __future__ import annotations
import re
import struct
from pathlib import Path
from ..rekordbox import pdb
#: Tables this rebuild owns. Everything else in the file is left as it is.
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS, pdb.KEYS,
pdb.ARTWORK, pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
def _lookup_name(table: int, row: bytes) -> str:
if table == pdb.ARTISTS:
sub, _shift, _rid, _b, ofs = struct.unpack_from("<HHIBB", row, 0)
if sub == 0x64:
ofs = struct.unpack_from("<H", row, 10)[0]
return pdb.read_dsql(row, ofs)
if table == pdb.ALBUMS:
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
return pdb.read_dsql(row, ofs)
if table == pdb.KEYS:
return pdb.read_dsql(row, 8)
return pdb.read_dsql(row, 4)
def _pdb_art_path(path: str | None) -> str:
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
def _tree_value(row: bytes) -> tuple:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
def _merge(old: list[bytes], new: dict, table: int, same) -> list[bytes] | None:
"""The table's rows: old ORDER kept, an unchanged row's old BYTES kept, new
rows appended by id. None when nothing changed (the table is not rewritten).
`new` maps row id -> (value, encode()); `same(old_row, value)` says whether
an old row already says `value`.
"""
out, changed, seen = [], False, set()
for row in old:
rid = pdb.row_id(table, row)
if rid not in new:
changed = True # removed
continue
seen.add(rid)
value, encode = new[rid]
if same(row, value):
out.append(row)
else:
out.append(encode())
changed = True
for rid in sorted((r for r in new if r not in seen), key=str):
out.append(new[rid][1]())
changed = True
return out if changed else None
def rebuild(existing: bytes, session) -> bytes | None:
"""`export.pdb` edited to match the OneLibrary database open in `session`
(the working copy, edits committed); None if it already matches."""
from sqlalchemy import text
tables: dict[int, list[bytes]] = {}
# ---- lookups ----------------------------------------------------------------
for table, sql, build in (
(pdb.ARTISTS, "SELECT artist_id, name FROM artist", pdb.artist_row),
# rekordbox's export leaves an album's artist 0 (see `pdb.album_row`).
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_row),
):
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
for i, name in session.execute(text(sql))}
merged = _merge(pdb.table_rows(existing, table), want, table,
lambda row, value, t=table: _lookup_name(t, row) == value)
if merged is not None:
tables[table] = merged
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
lambda row, value: pdb.read_dsql(row, 4) == value)
if merged is not None:
tables[pdb.ARTWORK] = merged
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid)
if cid in old_tracks:
fields, strings = pdb.track_fields(old_tracks[cid])
else:
fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
"year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""}
want[cid] = ((fields, strings),
(lambda f=fields, s=strings: pdb.track_row(f, s)))
merged = _merge(list(old_tracks.values()), want, pdb.TRACKS,
lambda row, value: _same_track(pdb.track_fields(row), value))
if merged is not None:
tables[pdb.TRACKS] = merged
# ---- playlists ----------------------------------------------------------------
want = {int(pid): ((int(parent or 0), int(seq or 0), int(pid), int(attr or 0) == 1, name or ""),
(lambda p=pid, par=parent, s=seq, n=name, a=attr:
pdb.playlist_tree_row(int(p), int(par or 0), int(s or 0), n or "",
folder=int(a or 0) == 1)))
for pid, parent, seq, name, attr in session.execute(text(
"SELECT playlist_id, playlist_id_parent, sequenceNo, name, attribute FROM playlist"))}
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_TREE), want, pdb.PLAYLIST_TREE,
lambda row, value: _tree_value(row) == value)
if merged is not None:
tables[pdb.PLAYLIST_TREE] = merged
want = {}
for pid, cid, seq in session.execute(text(
"SELECT playlist_id, content_id, sequenceNo FROM playlist_content "
"ORDER BY playlist_id, sequenceNo")):
key = (int(seq), int(cid), int(pid))
want[key] = (key, (lambda k=key: pdb.playlist_entry_row(*k)))
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_ENTRIES), want, pdb.PLAYLIST_ENTRIES,
lambda row, value: True)
if merged is not None:
tables[pdb.PLAYLIST_ENTRIES] = merged
if not tables:
return None
editor = pdb.PdbEditor(existing)
for table in _OWNED:
if table in tables:
editor.refill(table, tables[table])
return editor.render()
def _same_track(old: tuple[dict, dict], new: tuple[dict, dict]) -> bool:
"""Equal in every field that means something: `index_shift` is the row's slot
in its page, re-stamped whenever a page is written."""
(of, os_), (nf, ns) = old, new
return ({k: v for k, v in of.items() if k != "index_shift"}
== {k: v for k, v in nf.items() if k != "index_shift"} and os_ == ns)
def _fresh_track(cid: int, path, file_name, file_size, file_type, bitrate, bit_depth,
sample_rate, length, analysis, date_added, key_id, image_id) -> tuple[dict, dict]:
"""A track the pdb has never listed (one added to the stick by Konduktor), in
the shape `device_export` writes one — the values a rekordbox device export
was measured to carry (see that module)."""
from ..rekordbox.device_export import ANALYSED, BITMASK
added = str(date_added or "")[:10]
fields = {
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": int(sample_rate or 0),
"file_size": int(file_size or 0), "u2": cid + 0x600, "artwork_id": int(image_id or 0),
"key_id": int(key_id or 0), "bitrate": int(bitrate or 0), "id": cid,
"sample_depth": int(bit_depth or 0), "duration": min(int(length or 0), 0xFFFF),
"u5": ANALYSED, "u6": int(file_type or 0), "u7": 3,
}
strings = {
"kuvo_public": "ON", "autoload_hotcues": "ON", "date_added": added,
"analyze_path": analysis or "", "analyze_date": added,
"filename": file_name or Path(str(path or "")).name, "file_path": path or "",
}
return fields, strings
@@ -49,7 +49,7 @@ class OneLibraryDriver:
def _has_onelibrary_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
@@ -73,8 +73,8 @@ class OneLibraryDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path) -> OneLibraryAdapter:
return OneLibraryAdapter(path)
def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
return OneLibraryAdapter(path, read_only=read_only)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
+37 -16
View File
@@ -121,7 +121,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)
@@ -265,21 +265,21 @@ class OneLibraryExporter:
n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True)
small, medium = jpegs
files = []
for letter in ("a", "b"):
for suffix, data in (("", small), ("_m", medium)):
path = folder / f"{letter}{n}{suffix}.jpg"
path.write_bytes(data)
files.append(path)
for rel, data in art_files(n, jpegs):
path = root / rel.lstrip("/")
path.write_bytes(data)
files.append(path)
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
(n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
return n, files
# ---- the analysis files --------------------------------------------------
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them.
def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
"""The `.DAT`, `.EXT` and `.2EX` as `(suffix, bytes)`, as rekordbox 7 writes
them — built, not written, so a library adding a track to a stick can hold
them until Save (`OneLibraryStore.add_track`).
All three, and every cue list, even for a track with no cues: rekordbox
never produces a track without them, and `PCO2` — the complete list,
@@ -318,9 +318,18 @@ class OneLibraryExporter:
tags += previews
tags += W.cue_tags(cues, extended=False)
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]]
written = [W.write_anlz(dat, tags), W.write_anlz(dat.with_suffix(".EXT"), ext)]
files = [(".DAT", W.anlz_bytes(tags)), (".EXT", W.anlz_bytes(ext))]
if two_ex:
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(rel), *two_ex]))
files.append((".2EX", W.anlz_bytes([W.path_tag(rel), *two_ex])))
return files
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]:
written = []
for suffix, data in self.anlz_files(item, rel):
path = dat.with_suffix(suffix)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
written.append(path)
return written
@staticmethod
@@ -372,7 +381,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).
@@ -388,8 +398,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
@@ -418,12 +428,23 @@ 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}
def art_files(n: int, jpegs: tuple[bytes, bytes]) -> list[tuple[str, bytes]]:
"""Image `n`'s four files as `(drive-relative path, bytes)`: `a<n>`/`b<n>`
and their `_m`, byte-identical pairs, in `Artwork/00001/` (see `_write_art`).
`image.path` names the `b` file; `export.pdb`'s artwork table the `a` one."""
small, medium = jpegs
return [(f"/PIONEER/Artwork/00001/{letter}{n}{suffix}.jpg", data)
for letter in ("a", "b") for suffix, data in (("", small), ("_m", medium))]
def _file_type(path: Path) -> int:
return _FILE_TYPES.get(path.suffix.lower(), 1)
@@ -1,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:
File diff suppressed because it is too large. Load diff
+53 -13
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 ...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)
@@ -382,6 +401,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 +441,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 +470,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 +486,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:
@@ -0,0 +1,291 @@
"""Reading an ANLZ analysis file at the TAG level, by hand.
The writer half is `anlz_writer`; this is its reader. Like the writer it lives
here because the format is Pioneer's, not one product's.
**Why not `pyrekordbox`'s parser.** It decodes a cue entry with a FIXED layout,
and rekordbox does not write one. An exported entry is 88 bytes, but when
rekordbox 7 EDITS a stick it writes compact ones (measured on Goober,
2026-10-01): a hot cue added in rekordbox was a 48-byte `PCP2` (colour, no
padding), and a memory cue a 44-byte one (no colour bytes at all). pyrekordbox
raises `PaddingError` on the 44-byte form, the whole `.EXT` fails to parse, and
a reader that falls back to the `.DAT` silently loses pads D-H and every colour.
So every entry here is read at its own `len_entry`, and a field the entry is too
short to hold is simply absent.
A file is also split into its RAW tags, kept byte for byte. Editing a stick
replaces one or two tags of a file rekordbox wrote; everything else (the
waveforms, `PVBR`, tags nobody has decoded) must go back exactly as it was, and
re-serialising through a parser is how bytes get lost.
"""
from __future__ import annotations
import struct
from dataclasses import dataclass, field
#: `PMAI` · len_header · len_file · …
FILE_MAGIC = b"PMAI"
NO_LOOP = 0xFFFFFFFF
#: The cue-list kinds in `PCOB`/`PCO2`'s own header.
LIST_MEMORY = 0
LIST_HOT = 1
@dataclass
class Tag:
"""One tag, raw. `data` is the WHOLE tag: magic, both lengths, and body."""
type: str
data: bytes
_entries: list | None = field(default=None, repr=False, compare=False)
@property
def len_header(self) -> int:
return struct.unpack_from(">I", self.data, 4)[0]
@property
def list_kind(self) -> int | None:
"""`PCOB`/`PCO2`: whether this is the hot cue or the memory list."""
if self.type in ("PCOB", "PCO2") and len(self.data) >= 16:
return struct.unpack_from(">I", self.data, 12)[0]
return None
@property
def entries(self) -> list:
"""The tag's decoded entries (cues, or beats for `PQTZ`); [] otherwise."""
if self._entries is None:
decode = _DECODERS.get(self.type)
self._entries = decode(self.data) if decode else []
return self._entries
@dataclass
class AnlzFile:
"""An analysis file split into its header and raw tags."""
header: bytes
tags: list[Tag]
def to_bytes(self) -> bytes:
"""Reassemble, fixing only the header's file length."""
body = b"".join(t.data for t in self.tags)
head = bytearray(self.header)
struct.pack_into(">I", head, 8, len(head) + len(body))
return bytes(head) + body
def copy(self) -> "AnlzFile":
return AnlzFile(self.header, [Tag(t.type, t.data) for t in self.tags])
def find(self, kind: str, list_kind: int | None = None) -> int | None:
"""Index of the first `kind` tag (of that cue-list kind, if given)."""
for i, t in enumerate(self.tags):
if t.type == kind and (list_kind is None or t.list_kind == list_kind):
return i
return None
def put(self, kind: str, data: bytes, *, list_kind: int | None = None,
after: tuple[str, ...] = ()) -> None:
"""Replace the `kind` tag IN PLACE, keeping every other tag where it is.
A file without one gets it inserted after the last tag named in
`after` (rekordbox's order), else at the end.
"""
tag = Tag(kind, data)
i = self.find(kind, list_kind)
if i is not None:
self.tags[i] = tag
return
at = max((j for j, t in enumerate(self.tags) if t.type in after), default=len(self.tags) - 1)
self.tags.insert(at + 1, tag)
class AnlzError(ValueError):
pass
def parse(data: bytes) -> AnlzFile:
"""Split a file into its tags. Raises `AnlzError` on a malformed file.
Lengths are trusted only as far as the file reaches: a tag claiming more
bytes than remain ends the walk with an error rather than a short read.
"""
if len(data) < 12 or data[:4] != FILE_MAGIC:
raise AnlzError("not an ANLZ file")
len_header = struct.unpack_from(">I", data, 4)[0]
if not 12 <= len_header <= len(data):
raise AnlzError(f"bad file header length {len_header}")
tags: list[Tag] = []
off = len_header
while off < len(data):
if off + 12 > len(data):
raise AnlzError(f"truncated tag at {off}")
kind = data[off:off + 4].decode("latin-1")
len_tag = struct.unpack_from(">I", data, off + 8)[0]
if len_tag < 12 or off + len_tag > len(data):
raise AnlzError(f"bad length {len_tag} for {kind} at {off}")
tags.append(Tag(kind, data[off:off + len_tag]))
off += len_tag
return AnlzFile(header=data[:len_header], tags=tags)
def parse_file(path) -> AnlzFile:
with open(path, "rb") as f:
return parse(f.read())
# ---- cue entries ------------------------------------------------------------
@dataclass
class CueEntry:
"""One `PCPT` or `PCP2` entry. Attribute names follow pyrekordbox's, which
is what `onelibrary.cues` was written against.
`color_code` / RGB are None when the entry is too short to carry them (every
`PCPT`, and rekordbox's compact 44-byte `PCP2`).
"""
hot_cue: int
type: int
time: int
loop_time: int
comment: str = ""
loop_numerator: int = 0
loop_denominator: int = 0
color_code: int | None = None
color_red: int | None = None
color_green: int | None = None
color_blue: int | None = None
len_entry: int = 0
def raw_entries(tag: Tag) -> list[bytes]:
"""A `PCOB`/`PCO2` tag's entries as their own bytes, each at its own length —
so an entry Konduktor does not change goes back exactly as rekordbox wrote it."""
if tag.type == "PCOB":
count, first, magic = struct.unpack_from(">H", tag.data, 18)[0], 24, b"PCPT"
elif tag.type == "PCO2":
count, first, magic = struct.unpack_from(">H", tag.data, 16)[0], 20, b"PCP2"
else:
return []
return [tag.data[off:off + n] for off, n in _walk(tag.data, first, magic, count)]
def decode_entry(entry: bytes) -> CueEntry:
"""One raw `PCPT` or `PCP2` entry, decoded."""
if entry[:4] == b"PCPT":
return _pcob(struct.pack(">4sIIIHHi", b"PCOB", 24, 24 + len(entry), 0, 0, 1, -1) + entry)[0]
return _pco2(struct.pack(">4sIIIHH", b"PCO2", 20, 20 + len(entry), 0, 1, 0) + entry)[0]
def entry_hot_cue(entry: bytes) -> int:
"""A PCPT/PCP2 entry's `hot_cue`: its pad, 1-based; 0 for a memory cue."""
return struct.unpack_from(">I", entry, 12)[0]
def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> bytes | None:
"""A `PCP2` entry with ONLY its colour bytes changed — what rekordbox itself
does to recolour a cue (measured: those 4 bytes and nothing else). None if
the entry is too short to carry a colour (rekordbox's 44-byte form)."""
if len(entry) < 44:
return None
len_comment = struct.unpack_from(">I", entry, 40)[0]
at = 44 + len_comment
if at + 4 > len(entry):
return None
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
def entry_without_loop_beats(entry: bytes) -> bytes:
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
rather than recomputing it."""
if len(entry) < 40 or entry[36:40] == b"\0\0\0\0":
return entry
return entry[:36] + bytes(4) + entry[40:]
def _walk(data: bytes, first: int, magic: bytes, count: int):
"""(offset, len_entry) for each entry, trusting each entry's own length."""
off = first
for _ in range(count):
if off + 12 > len(data) or data[off:off + 4] != magic:
return
len_entry = struct.unpack_from(">I", data, off + 8)[0]
if len_entry < 12 or off + len_entry > len(data):
return
yield off, len_entry
off += len_entry
def _pcob(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H 0 · H count · i last
count = struct.unpack_from(">H", data, 18)[0]
out = []
for off, n in _walk(data, 24, b"PCPT", count):
if n < 44:
continue
# 4s · I len_header · I len_entry · I hot_cue · I status · I 0x10000 ·
# H order_first · H order_last · B kind · x · H 1000 · I time · I loop
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 28]
time, loop = struct.unpack_from(">II", data, off + 32)
out.append(CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n))
return out
def _pco2(data: bytes) -> list[CueEntry]:
# tag prefix(12) · I list kind · H count · H 0
count = struct.unpack_from(">H", data, 16)[0]
out = []
for off, n in _walk(data, 20, b"PCP2", count):
if n < 28:
continue
hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 16]
time, loop = struct.unpack_from(">II", data, off + 20)
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n)
if n >= 44:
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
colour_at = off + 44 + len_comment
if len_comment and colour_at <= off + n:
e.comment = data[off + 44:colour_at].decode("utf-16-be", "replace").rstrip("\x00")
if colour_at + 4 <= off + n:
e.color_code, e.color_red, e.color_green, e.color_blue = data[colour_at:colour_at + 4]
out.append(e)
return out
# ---- the beatgrid -----------------------------------------------------------
@dataclass
class Beat:
beat: int # 1-4, position in the bar
tempo: int # BPM x 100
time: int # ms
def _pqtz(data: bytes) -> list[Beat]:
# tag prefix(12) · I 0 · I 0x80000 · I count, then 8-byte entries
count = struct.unpack_from(">I", data, 20)[0]
first = struct.unpack_from(">I", data, 4)[0]
out = []
for i in range(count):
off = first + 8 * i
if off + 8 > len(data):
break
beat, tempo, time = struct.unpack_from(">HHI", data, off)
out.append(Beat(beat=beat, tempo=tempo, time=time))
return out
_DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
__all__ = [
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
"NO_LOOP", "Tag", "decode_entry", "entry_hot_cue", "entry_with_colour", "entry_without_loop_beats",
"parse", "parse_file", "raw_entries",
]
@@ -313,30 +313,38 @@ def flat_preview_tags() -> list[bytes]:
return preview_tags([0.0] * 400, [0.0] * 400)
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> 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:
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
Two constants in here are rekordbox's, not the documented struct's: the
`1000` after the kind (the struct calls it padding) and the `1` after the
colour id. Both appear in every entry of a real export; zeros there were a
guess, and pyrekordbox's parser would never notice one.
A `comment` (the cue's name) is UTF-16BE with a terminating NUL, and
`len_comment` counts the terminator — crate-digger's layout, which both
Konduktor's reader and pyrekordbox's agree with. No reference cue carries
one, so that detail is documented rather than measured. The entry stays the
exported 88 bytes unless the name needs more.
"""
comment = b""
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
red, green, blue = rgb or (0, 0, 0)
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind, 1000,
b"PCP2", 16, length, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
0, 1, beats or 0, 1 if beats else 0, len(comment),
0, 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 + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
PCP2_ENTRY_LEN - 48 - len(comment)
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
length - 48 - len(comment_bytes)
)
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
@@ -353,28 +361,54 @@ def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -
) + bytes(16)
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
)
def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
or new ones from `pcpt_entry`)."""
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
# shifts every following field and the reader sees garbage. The last field
# is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
# writes it.
last = -1 if cue_type == 1 else len(chosen) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob)
# writes it (an export, and rekordbox's own edits, alike).
last = -1 if cue_type == 1 else len(entries) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(entries), last) + b"".join(entries))
def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCO2` around already-built `PCP2` entries."""
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(entries), 0) + b"".join(entries))
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
return pcob_tag(cue_type, [
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
])
def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0))
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"))
for c in chosen
)
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
])
#: `PQT2` as rekordbox 7 leaves it after a grid edit: header kept, every count
#: and the beat list gone (56 bytes, the `len_header`). MEASURED on Goober
#: (2026-10-01): rekordbox does not recompute this "extended" grid when the grid
#: changes, it blanks it, and a CDJ then works from `PQTZ`.
_PQT2_HEADER = 56
def blank_pqt2(tag: bytes) -> bytes:
"""The blanked form of an existing `PQT2` tag, exactly as rekordbox writes it.
Bytes 12-24 (rekordbox's constants, `00000000 01000002 00000000` on every
file seen) are KEPT; the counts and first/last-beat fields after them are
zeroed, and the beat entries dropped.
"""
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
@@ -69,8 +69,8 @@ def capabilities_for(
max_memory_cues=None, # unlimited
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's swatches (the 15 that
# were measured, see `palette`), offered in rekordbox's own order.
# A hot cue's colour is one of rekordbox's 16 swatches (all
# measured, see `palette`), offered in rekordbox's own order.
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # djmdCue.Comment
@@ -91,6 +91,7 @@ def capabilities_for(
media_kinds=["audio", "stem"],
removable=True,
addable=True,
key_writable=True,
artwork=False,
artwork_note=None,
),
@@ -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
@@ -63,7 +63,7 @@ class RekordboxDriver:
except Exception: # noqa: BLE001
pass
def open(self, path: Path) -> RekordboxAdapter:
def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
return RekordboxAdapter(path)
def detect(self) -> list[dict]:
@@ -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.
@@ -383,9 +383,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:
@@ -9,8 +9,9 @@ The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
writes the palette's exact RGB beside each code.
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
* The teal-green between 0x0E and 0x16 was missed by that measurement, and
found later: it is **0x13 = #00FF30**, which rekordbox 7 wrote itself as the
DEFAULT colour of a hot cue added on a stick (Goober, 2026-10-01).
* 0x2B (#FF0017) was observed on a real export though it is not one of the 16
swatches; it is kept so such a colour survives a round trip exactly.
* **The palette has no white or grey.** A colourless (white/grey) cue — above
@@ -32,6 +33,7 @@ PALETTE: dict[int, tuple[int, int, int]] = {
0x05: (0x00, 0x70, 0xFF), # light blue
0x09: (0x00, 0xE0, 0xFF), # cyan
0x0E: (0x00, 0xFF, 0xA3), # teal
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
0x16: (0x1A, 0xFF, 0x00), # green
0x1A: (0x80, 0xFF, 0x00), # lime
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
@@ -94,18 +96,17 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
#: The swatches a user can pick, in rekordbox's own order — what
#: `capabilities.cues.palette` offers. 15 of rekordbox's 16: the unmeasured
#: teal-green is left out rather than offered with a guessed RGB, and 0x2B is
#: not a swatch at all (see the module note).
#: `capabilities.cues.palette` offers: all 16. 0x2B is not a swatch at all (see
#: the module note).
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
def hex_for(code: int | None) -> str | None:
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
An unknown code (the unmeasured teal-green) projects as no colour rather
than a guessed one; it is still kept on the row, since editing a cue's
position, type or name never rewrites its colour.
An unknown code projects as no colour rather than a guessed one; it is
still kept on the row, since editing a cue's position, type or name never
rewrites its colour.
"""
rgb = PALETTE.get(code) if code else None
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
+163
View File
@@ -430,3 +430,166 @@ __all__ = [
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
"playlist_tree_row", "read", "read_dsql", "template", "track_row",
]
# ---- editing an existing library -----------------------------------------------
#
# Editing a stick rekordbox wrote, rather than writing one from the template:
# only the tables whose rows change are rewritten, and inside them a row that
# does not change keeps rekordbox's own bytes. Every other table — history,
# colours, menus, artwork — stays byte-identical, and so does exportExt.pdb.
def _chain(buf: bytes, first: int, last: int) -> list[int]:
"""A table's page chain, header page first."""
pages, p = [first], first
while p != last and len(pages) < 100000:
p = struct.unpack_from("<I", buf, p * PAGE + 12)[0]
pages.append(p)
return pages
def table_rows(buf: bytes, table: int) -> list[bytes]:
"""Every present row of `table`, in page order, as its own bytes (padding
included) — a row's extent is up to the next row's heap offset, or the end
of the page's used heap."""
n_tables = struct.unpack_from("<I", buf, 8)[0]
for i in range(n_tables):
t, _empty, first, last = struct.unpack_from("<4I", buf, 28 + 16 * i)
if t != table:
continue
out = []
for p in _chain(buf, first, last)[1:]:
o = p * PAGE
if buf[o + 0x1B] & _HEADER_PAGE:
continue
n = (buf[o + 0x19] >> 5) | (buf[o + 0x1A] << 3)
used = struct.unpack_from("<H", buf, o + 0x1E)[0]
offs, present = [], []
# As `_rows` reads them: every bit of every group, since a page
# rekordbox has edited holds more row slots than its small count.
for g in range((n + 15) // 16):
base = o + PAGE - g * _GROUP
mask = struct.unpack_from("<H", buf, base - 4)[0]
for r in range(16):
if mask & (1 << r):
offs.append(struct.unpack_from("<H", buf, base - 6 - 2 * r)[0])
present.append(True)
ends = sorted(set(offs)) + [used]
for off, ok in zip(offs, present):
if ok:
end = next(e for e in ends if e > off)
row = bytes(buf[o + _HEADER + off:o + _HEADER + end])
if table == TRACKS:
row = row[:track_extent(row)]
out.append(row)
return out
return []
def _dsql_len(buf: bytes, off: int) -> int:
head = buf[off]
return (head >> 1) if head & 1 else struct.unpack_from("<H", buf, off + 1)[0]
def track_extent(row: bytes) -> int:
"""Where a track row really ends: past its last string, 4-aligned.
NOT the next row's offset: rekordbox reuses its heap, and the bytes between
a row and the next can be a stale tail of an older, longer string (seen on
Goober: `...mp3` followed by `ing.stem.m4a`)."""
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
end = max(o + _dsql_len(row, o) for o in offs)
return end + (-end % 4)
def track_fields(row: bytes) -> tuple[dict, dict]:
"""A raw track row as (`fields`, `strings`) — what `track_row` takes back."""
fields = dict(zip([n for n, _ in _TRACK_FIELDS], struct.unpack_from(_TRACK_FMT, row, 0)))
offs = struct.unpack_from(f"<{len(TRACK_STRINGS)}H", row, _TRACK_FIXED)
return fields, {name: read_dsql(row, o) for name, o in zip(TRACK_STRINGS, offs)}
def row_id(table: int, row: bytes) -> int | tuple:
"""A row's identity within its table (the triple, for playlist entries)."""
if table == TRACKS:
return track_fields(row)[0]["id"]
if table == ARTISTS:
return struct.unpack_from("<I", row, 4)[0]
if table == ALBUMS:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_TREE:
return struct.unpack_from("<I", row, 12)[0]
if table == PLAYLIST_ENTRIES:
return struct.unpack_from("<3I", row, 0)
return struct.unpack_from("<I", row, 0)[0]
class PdbEditor(PdbWriter):
"""`PdbWriter` over an EXISTING library: `refill` replaces one table's rows.
The table keeps its pages — overwritten in place, more taken from the
next-unused counter if needed, any left over unlinked and blanked (a blank
reserved page inside the file is a state rekordbox's own template has) —
and keeps its empty candidate. `render` leaves the header's
pages-with-room field as it was: rekordbox did not touch it when it edited
Goober, and it is the least understood field in the file.
"""
def __init__(self, existing: bytes):
super().__init__(existing)
self._room_field = struct.unpack_from("<I", self.buf, 16)[0]
self._blank: set[int] = set()
def refill(self, table: int, rows: list[bytes]) -> None:
slot, candidate, first, last = self.tables[table]
old = _chain(bytes(self.buf), first, last)[1:]
if candidate in old:
old.remove(candidate)
chunks = _chunk(rows) if rows else []
indices = old[:len(chunks)] + [self._alloc() for _ in chunks[len(old):]]
for p in old[len(chunks):]:
self._blank.add(p)
shift_at = _INDEX_SHIFT_AT if table in (TRACKS, ARTISTS, ALBUMS) else None
indexed = table in _INDEXED
for i, chunk in enumerate(chunks):
nxt = indices[i + 1] if i + 1 < len(indices) else candidate
fill = None
if indexed:
fill = (len(chunk) + 1, 0) if i + 1 == len(chunks) else (_NONE, _NONE)
self.sequence += 1
self.pages[indices[i]] = _data_page(indices[i], table, nxt, chunk, self.sequence,
shift_at=shift_at, fill=fill)
self._reindex(first, indices, indexed=indexed)
self.tables[table] = [slot, candidate, first, indices[-1] if indices else first]
if not indices:
# No rows: the header page points straight at the candidate again.
struct.pack_into("<I", self.buf, first * PAGE + 12, candidate)
def _reindex(self, header_page: int, data_pages: list[int], *, indexed: bool) -> None:
o = header_page * PAGE
struct.pack_into("<I", self.buf, o + 12, data_pages[0] if data_pages else
struct.unpack_from("<I", self.buf, o + 12)[0])
if indexed:
# Clear the old entries first: a table that shrank must not keep
# listing pages it no longer has.
count = struct.unpack_from("<H", self.buf, o + _HEADER + 16)[0]
for k in range(max(count, len(data_pages))):
struct.pack_into("<I", self.buf, o + _HEADER + 20 + 4 * k, 0x1FFFFFF8)
if data_pages:
pages_with_room = self.pages_with_room
self._index(header_page, data_pages, indexed=indexed)
self.pages_with_room = pages_with_room
else:
struct.pack_into("<I", self.buf, o + _HEADER + 4, 0x03FFFFFF)
if indexed:
struct.pack_into("<HH", self.buf, o + _HEADER + 16, 0, 0x1FFF)
struct.pack_into("<HH", self.buf, o + 0x20, _NONE, _NONE)
struct.pack_into("<H", self.buf, o + 0x26, 0)
def render(self) -> bytes:
out = bytearray(super().render())
struct.pack_into("<I", out, 16, self._room_field)
for p in self._blank - set(self.pages):
out[p * PAGE:(p + 1) * PAGE] = bytes(PAGE)
return bytes(out)
@@ -5,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,
}
# 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:
+137 -56
View File
@@ -45,7 +45,8 @@ from ...core.adapter import (
Unsupported,
)
from ...core.edit_journal import EditJournal
from ...core.pathmap import PathMapping
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping, stored_form
from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot
@@ -110,12 +111,14 @@ def _iso_stamp(value) -> str:
return str(value)
class RekordboxStore:
class RekordboxStore(ReplaceGridCommands):
"""One open Rekordbox library."""
def __init__(self, path: Path):
self.path = Path(path)
self._mapping = PathMapping()
# Write an added file in the library's STORED form (`pathmap.stored_form`).
self._write_stored_paths = False
self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
self._journal = EditJournal()
# Grid edits buffered until save(): ANLZ files are written to disk, so
@@ -374,6 +377,14 @@ class RekordboxStore:
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
@@ -505,6 +516,46 @@ class RekordboxStore:
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
@@ -557,6 +608,79 @@ class RekordboxStore:
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.
@@ -603,14 +727,15 @@ class RekordboxStore:
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),
@@ -632,11 +757,14 @@ class RekordboxStore:
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)
@@ -1285,53 +1413,6 @@ class RekordboxStore:
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
self._journal.record("grid", "replace" if ordered else "delete", track_id)
def delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
from ...core.model import GridMarker
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
def _flush_grids(self) -> None:
"""Write buffered grids into their ANLZ files. Called by save().
@@ -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,514 @@
"""`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_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")
+27 -1
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)
@@ -377,12 +387,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 +425,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
@@ -64,6 +64,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 +74,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",
+1 -1
View File
@@ -25,7 +25,7 @@ class TraktorDriver:
return False
return b"<NML" in head and b"VERSION=" in head
def open(self, path: Path) -> TraktorAdapter:
def open(self, path: Path, *, read_only: bool = False) -> TraktorAdapter:
return TraktorAdapter(path)
def detect(self) -> list[dict]:
+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),
+167 -17
View File
@@ -22,7 +22,6 @@ import copy
import math
import threading
import uuid as uuidlib
from dataclasses import dataclass
from pathlib import Path
from traktor_nml_utils import (
@@ -36,6 +35,7 @@ from traktor_nml_utils.models.collection import (
Entrytype,
GridType,
Infotype,
MusicalKeytype,
Locationtype,
Nodetype,
Playlisttype,
@@ -46,16 +46,17 @@ from traktor_nml_utils.models.collection import (
)
from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import InvalidCommand, SaveOutcome, StemSwapResult
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
# 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.
@@ -71,15 +72,6 @@ class PlaylistError(InvalidCommand):
"""
@dataclass
class FileTagResult:
track_id: str
file: str
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
class TraktorStore:
def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path)
@@ -87,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] = []
@@ -109,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(
@@ -164,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(
@@ -179,6 +177,7 @@ class TraktorStore:
can_contain_children=True,
can_rename=True,
can_delete=True,
can_move=True,
)
@staticmethod
@@ -352,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)
@@ -409,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.
@@ -438,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(
@@ -453,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".
@@ -479,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,
)
@@ -998,6 +1139,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:
@@ -1293,7 +1443,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(
+84 -25
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:
@@ -79,7 +92,7 @@ class AppState:
rests on, and an adapter is the thing that knows whether it is true —
so it is asserted here rather than assumed everywhere else.
"""
adapter = registry.open_library(path)
adapter = registry.open_library(path, read_only=True)
if adapter.capabilities().writable:
if hasattr(adapter, "close"):
try:
@@ -87,7 +100,7 @@ class AppState:
except Exception: # noqa: BLE001
pass
raise ValueError(
f"{path} is a writable library; only read-only sources "
f"{path} cannot be opened read-only; only a library that can "
"(such as a OneLibrary drive) can be opened as a source"
)
self.close_source()
@@ -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()
+107 -3
View File
@@ -28,6 +28,21 @@ from .pathmap import PathMapping
from .relocate import PathGroup
@dataclass
class FileTagResult:
"""One audio-file tag write a save made — the `SaveOutcome.tag_results` item.
Promoted from the Traktor store when OneLibrary became the second platform
that writes edited fields into the audio files themselves.
"""
track_id: str
file: str
ok: bool
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
detail: str = ""
@dataclass
class SaveOutcome:
"""What a save produced, in terms every platform can answer.
@@ -50,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.
@@ -78,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)
@@ -138,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."""
@@ -157,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: ...
@@ -169,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 ----------------------------------------
@@ -185,11 +269,18 @@ class LibraryAdapter(Protocol):
# is touched, so a cancel leaves it as it was. Gated on
# `capabilities().tracks.addable`.
def add_tracks(self, items: list["NewTrack"], *, checkpoint=None) -> list[str]: ...
# OPTIONAL, where `capabilities().tracks.places_audio`: the library decides
# where added audio goes. `place_audio(source, track)` returns the path the
# importer must COPY `source` to (which becomes `NewTrack.audio_path`), or
# None when the file is already where the library can use it in place;
# `audio_home()` is where that audio lands, for the free-space check.
# (A protocol member would make every adapter implement them.)
# Remove tracks from the library — and so from every playlist, since an
# entry naming a track the library no longer has is a dangling reference.
# Never touches audio files. Returns how many were removed; gated on
# `capabilities().tracks.removable`.
# Never touches audio files, except where `tracks.places_audio` (a stick's
# audio belongs to its library): there the file goes too, at Save. Returns
# how many were removed; gated on `capabilities().tracks.removable`.
def remove_tracks(self, track_ids: list[str]) -> int: ...
# Swap converted stem files into the library (see `StemSwap`), all at once:
@@ -201,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: ...
@@ -234,7 +329,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 —
@@ -274,7 +374,11 @@ class LibraryDriver(Protocol):
selects: str
def can_open(self, path: Path) -> bool: ...
def open(self, path: Path) -> LibraryAdapter: ...
# `read_only` opens a library only to READ it, alongside the loaded one (the
# sidebar's Devices). An adapter that honours it reports `writable=False`
# with cause `browsing`; one that ignores it still reports writable, and the
# caller — `AppState.open_source` — refuses it, so ignoring is safe.
def open(self, path: Path, *, read_only: bool = False) -> LibraryAdapter: ...
# OPTIONAL. What to call an opened library on screen. Only the adapter can
# answer for a platform where one library has more than one valid path —
# the filename is otherwise assumed, and that assumption is wrong for a
+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:
+41 -2
View File
@@ -22,7 +22,15 @@ from pydantic import BaseModel
# permanent refusal protecting their other machines.
# `not_in_library` is a folder of loose files being browsed: nothing there is a
# library to write to, and the way to edit one is to add it to the collection.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
# `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.
# `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"]
@@ -61,26 +69,53 @@ class TrackCapabilities(BaseModel):
editable_fields: list[str] = []
media_kinds: list[MediaKind] = ["audio"]
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way.
# audio file is never touched — except where `places_audio`: a library that
# owns where its audio lives (a stick) deletes it with the track, at Save.
removable: bool = False
# Tracks can be added to the library (`add_tracks`): an import from a
# device, or browsed files added to the collection.
addable: bool = False
# The LIBRARY decides where added audio goes (`place_audio`), so the user is
# neither asked "copy or leave in place?" nor for a destination: a OneLibrary
# stick can only point at files on itself, and lays them out as rekordbox
# does. False: the user chooses, as for a desktop collection.
places_audio: bool = False
# 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):
@@ -95,6 +130,9 @@ class SaveCapabilities(BaseModel):
library_label: str
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
history: bool = True
# The library was written by one of Konduktor's EXPORT sets, whose next run
# replaces it — so an edit made here directly is undone by the next export.
managed_by_export: bool = False
class Capabilities(BaseModel):
@@ -114,4 +152,5 @@ class Capabilities(BaseModel):
grid: GridCapabilities = GridCapabilities()
tracks: TrackCapabilities = TrackCapabilities()
playlists: PlaylistCapabilities = PlaylistCapabilities()
paths: PathCapabilities = PathCapabilities()
save: SaveCapabilities
+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]:
+69
View File
@@ -0,0 +1,69 @@
"""Marker-level beatgrid commands, for a store whose one primitive is "replace".
A platform that stores the grid as a flat list of beats (Rekordbox's `PQTZ`, and
so OneLibrary's) has no native "move this marker": every marker-level command is
a read-modify-replace of the generic marker list. Promoted here when OneLibrary
became the second store needing exactly that, so "where does a moved marker
clamp" cannot mean two things. (Traktor's store has markers natively and keeps
its own, companion-cue-aware versions.)
A store using it provides `current_markers(track_id)` and
`replace_grid(track_id, markers)`.
"""
from __future__ import annotations
from .adapter import InvalidCommand, NotFound
from .model import GridMarker
class ReplaceGridCommands:
def current_markers(self, track_id: str) -> list[GridMarker]: # pragma: no cover
raise NotImplementedError
def replace_grid(self, track_id: str, markers: list[GridMarker]) -> None: # pragma: no cover
raise NotImplementedError
def delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
+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.
+7 -1
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()
@@ -194,6 +197,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 +214,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]
+2 -2
View File
@@ -44,8 +44,8 @@ def driver_for(path: Path) -> LibraryDriver:
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
def open_library(path: Path):
return driver_for(path).open(path)
def open_library(path: Path, *, read_only: bool = False):
return driver_for(path).open(path, read_only=read_only)
def describe(path: Path) -> dict:
+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,
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff. Show more