Compare commits

..
Author SHA1 Message Date
patben8 0fac84cb73 Fixed issue with release pipeline 2026-10-04 21:57:40 +02:00
patben8 71ee877784 Merge pull request #5 from MrPatben8/dev
Implemented Key Analysis & Remote Library Management
2026-10-04 18:35:08 +02:00
patben8 920146f2c0 Bumped version number 2026-10-04 18:33:33 +02:00
patben8 ba7b662b93 Fixed port assumption 2026-10-04 17:13:24 +02:00
patben8 e5fb0f0dbb Initial implementation of remote library system 2026-10-04 17:13:24 +02:00
patben8 e8a53eee07 Added analyze dialog 2026-10-04 17:00:33 +02:00
patben8 36a6df4d3b Build analyze backend 2026-10-04 16:33:37 +02:00
patben8 72a52d3291 Reworked analysis menu 2026-10-04 16:18:43 +02:00
patben8 c3571fd054 Implemented key setting into adapters 2026-10-04 16:06:36 +02:00
patben8 b5b3dd04c3 Implemented key analysis system 2026-10-04 15:26:34 +02:00
patben8 4e9472c14a Unified prefs writing 2026-10-03 10:31:32 +02:00
patben8 957525393b Merge pull request #4 from MrPatben8/dev
Implemented STEM generation & OneLibrary editing support
2026-10-01 17:18:05 +02:00
patben8 bdc62f2c1b Added OneLibrary testing fixtures 2026-10-01 17:00:13 +02:00
patben8 7960a5a68f Implemented OneLibrary track addition and removal 2026-10-01 16:43:37 +02:00
patben8 c5280a95f2 Implemented Device Library and OneLibrary sync 2026-10-01 16:00:33 +02:00
patben8 e73fa05e1f Implemented OneLibrary cue and grid edits 2026-10-01 15:48:44 +02:00
patben8 775e94168c Begun implementing OneLibrary editing 2026-10-01 15:07:43 +02:00
patben8 2784879872 Added a clear button for the search bar 2026-10-01 13:32:54 +02:00
patben8 702e5d86a6 Stem tracks are now correctly labeled in the song list 2026-10-01 13:25:13 +02:00
patben8 d7f8768d4c Implemented importing into Rekordbox 2026-10-01 13:12:10 +02:00
patben8 5c193e0ab7 Fixed Stem track importing. Added remove from collection for Rekordbox 2026-10-01 11:42:55 +02:00
patben8 badf12b991 Improved progress status section layout 2026-10-01 10:55:09 +02:00
patben8 ecc0e4c8df Implemented STEM playback 2026-10-01 10:55:09 +02:00
patben8 ae03a93f98 Implemented front end for stem conversion 2026-10-01 10:55:09 +02:00
patben8 c560876c02 Implemented stem conversion API 2026-10-01 10:55:09 +02:00
patben8 e805635383 More stem engine implementation
# Conflicts:
#	backend/konduktor/schemas.py
2026-10-01 10:55:09 +02:00
patben8 27471a82cd Implemented demucs engine 2026-10-01 10:54:27 +02:00
patben8 28b705173e Implemented Discard changes button 2026-10-01 10:54:27 +02:00
patben8 681add852a Implemented foundation of STEM support 2026-10-01 10:54:27 +02:00
patben8 376569ec75 Fixed track collision bug 2026-10-01 10:54:27 +02:00
patben8 b5b0fa91fe Refined Rekordbox timing fix 2026-10-01 10:54:27 +02:00
patben8 34b18893ef Refined traktor timing fix 2026-10-01 10:54:27 +02:00
patben8 2c02019bb2 Implemented traktor utility fixes 2026-10-01 10:54:27 +02:00
patben8 08c53e1150 Added support for coloring Rekordbox hotcues 2026-10-01 10:54:14 +02:00
184 changed files with 18542 additions and 1090 deletions

No files matched your search

+49
View File
@@ -114,6 +114,52 @@ jobs:
if-no-files-found: error if-no-files-found: error
path: installer/* path: installer/*
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
# can name the tag that matches the app it is opened from.
server-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # push to ghcr.io
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and image name
id: meta
run: |
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
# GHCR names must be lower-case; the owner may not be.
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
env:
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
with:
context: .
file: server/Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
${{ steps.meta.outputs.image }}:latest
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
# Gather both platforms' installers and publish them as a single new Release. # Gather both platforms' installers and publish them as a single new Release.
# Runs once, after both builds succeed, so the two matrix jobs never race to # Runs once, after both builds succeed, so the two matrix jobs never race to
# create the same tag/release. # create the same tag/release.
@@ -136,6 +182,9 @@ jobs:
- name: Download installers from both builds - name: Download installers from both builds
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
# Only the installers: the run also holds server-image's Docker build
# record, which is not a release asset (and once failed to download).
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/… path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
- name: Publish release - name: Publish release
+590 -35
View File
@@ -47,6 +47,10 @@ Two independent apps that talk over HTTP:
- `registry.py` — adapter selection by **`can_open()` probe**, not extension - `registry.py` — adapter selection by **`can_open()` probe**, not extension
(Rekordbox is a `.db`, Serato is a directory). (Rekordbox is a `.db`, Serato is a directory).
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers. - `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`). - `relocate.py` — **auto path remapping's search** (see `relocation.py`).
Fixes ONE thing: a stored prefix changed and the layout under it did not 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 (a collection built on Windows with the SSD as `X:`, opened on a Mac where
@@ -110,6 +114,43 @@ Two independent apps that talk over HTTP:
`backend/bench_grid_detect.py` scores it against any library's `backend/bench_grid_detect.py` scores it against any library's
single-marker grids and reports that constant separately from detection single-marker grids and reports that constant separately from detection
error (29 Rekordbox references: old 1/29 BPMs, new 27/29). 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 - `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 file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz
streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0, streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
@@ -158,7 +199,8 @@ Two independent apps that talk over HTTP:
only a file a scan found is streamed, so `/api/folder/tracks/audio` cannot only a file a scan found is streamed, so `/api/folder/tracks/audio` cannot
read an arbitrary path. Tagged keys are deliberately dropped (every read an arbitrary path. Tagged keys are deliberately dropped (every
notation there is). The listed suffixes are the collection's notation there is). The listed suffixes are the collection's
`tracks.audio_formats` capability. `tracks.audio_formats` capability. A stem file lists as
`media_kind: "stem"` (its `stem` box, read at scan time).
- `adapters/traktor/` — everything that knows NML exists. - `adapters/traktor/` — everything that knows NML exists.
- `store.py` (`TraktorStore`) — the retained native model: owns the parsed - `store.py` (`TraktorStore`) — the retained native model: owns the parsed
dataclass NML, applies every edit, renders + saves. See "Write path". dataclass NML, applies every edit, renders + saves. See "Write path".
@@ -253,6 +295,21 @@ Two independent apps that talk over HTTP:
bank. Point cues AND loops both write; `cue_types` owns the translation. bank. Point cues AND loops both write; `cue_types` owns the translation.
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only **Memory cues stay preserved-but-uneditable** (Rekordbox is the only
platform with them — the two-platform promotion rule). platform with them — the two-platform promotion rule).
**Hot cue colour is writable** (`set_cue_color`, `PATCH
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
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
reports `color="none"`. **The colour belongs to the PAD**: `set_cue` with
no colour keeps the slot's existing code, so rename, type change and an
Auto Hotcues Replace keep it; only Delete or "Default" clear it. Both
columns go through `RekordboxStore._apply_color` (coloured: code +
`Color=-1`; uncoloured loop: `255/0`; uncoloured cue: `-1/NULL`). An
unknown code projects as no colour but stays on the row. Uncoloured cues
still DRAW in Konduktor's type colours, not rekordbox's green/orange
defaults (decided 2026-10-01: those defaults are unmeasured).
- **Saving warns but does not block when Rekordbox is running.** - **Saving warns but does not block when Rekordbox is running.**
`pyrekordbox.commit()` refuses outright, and its check is process-wide `pyrekordbox.commit()` refuses outright, and its check is process-wide
rather than per-file, so `RekordboxStore._commit()` suppresses that veto rather than per-file, so `RekordboxStore._commit()` suppresses that veto
@@ -280,9 +337,73 @@ Two independent apps that talk over HTTP:
`close()` disposes the SQLAlchemy engine, not just the session — otherwise `close()` disposes the SQLAlchemy engine, not just the session — otherwise
the OS file handle stays open and `master.db` cannot be replaced. `AppState` the OS file handle stays open and `master.db` cannot be replaced. `AppState`
closes the previous adapter when opening a new library. closes the previous adapter when opening a new library.
- `adapters/onelibrary/` — **read-only.** The cross-vendor USB export format - `adapters/onelibrary/` — **editable when opened as THE library; read-only
(AlphaTheta + Algoriddim + Native Instruments), read by CDJ-class hardware. when browsed from the sidebar's Devices** (`read_only=True`, cause `browsing`).
Built as the source half of a future "import a stick into Traktor" feature. 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 Full research, incl. the schema, is in
[.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md); [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md);
the four things that make it unlike the Rekordbox adapter: the four things that make it unlike the Rekordbox adapter:
@@ -313,6 +434,18 @@ Two independent apps that talk over HTTP:
`track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the `track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the
collapse rule is **shared by import** rather than copied — two definitions of collapse rule is **shared by import** rather than copied — two definitions of
"when does a tempo change start a marker" would drift silently. "when does a tempo change start a marker" would drift silently.
- **A stem file ADDED to a Traktor collection** (folder add, import, the
Traktor exporter — all `TraktorStore.add_entry`) gets `<STEMS>` rendered
from its OWN box by `stem_file.traktor_stems_json` (keys sorted, compact,
whole floats as integers, else 16 significant digits) — measured to give
Traktor's value for every local stem file and to re-render all 3,678 in the
big collection unchanged, though every one of those is NI's default
layout. Without it the entry read as plain audio (Type column, playlist
`TYPE="TRACK"`) while the deck, which reads the file, played stems.
Rekordbox and OneLibrary have no such element, so their projections take
`media_kind` from the FILE (`stem_file.is_stem_file`, only `.m4a`/`.mp4`
opened, ~0.7 ms each, cached per path in `RekordboxStore.is_stem`) — the
same mismatch otherwise: Type said audio while the deck played stems.
- `importer.py` also serves the folder add: `reference=True` adds each file - `importer.py` also serves the folder add: `reference=True` adds each file
where it is (nothing to copy or roll back), and every planned file the where it is (nothing to copy or roll back), and every planned file the
destination already points at (matched on `audio_path`, never the display destination already points at (matched on `audio_path`, never the display
@@ -322,6 +455,62 @@ Two independent apps that talk over HTTP:
the view's, so browsing elsewhere cannot point it at endpoints that do not the view's, so browsing elsewhere cannot point it at endpoints that do not
know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place
that choice is made. that choice is made.
- `stems/` — Convert to Stems around the file itself. `engine_manager.py`:
the engine version THIS build needs (`engine.json`) and the pinned weights
(`weights.json`, a copy of `engine/weights.json` a test keeps equal).
Installs under app-data (Windows: a SHORT `%LOCALAPPDATA%\Konduktor\engine`
for the 260-char limit); an install counts only after every part's hash,
the archive's, AND the unpacked engine starting and naming the expected
version (`probe`) — `installed.json` is written last. One engine at a time;
CUDA offered only for driver r580+ and capability 7.5+ (`nvidia-smi`).
Side-loading (offline) verifies against the release manifest, cached once
seen. `download.py`: resumable (`Range`, restarts if ignored), SHA-verified,
certifi TLS (a frozen macOS Python has no CA store). `engine_process.py`:
one `serve` per batch — progress, cancel-by-message, crash reported with
the engine's stderr tail, raw work files deleted as read, a Windows Job
Object and `keep_awake` (caffeinate / SetThreadExecutionState). Routes:
`GET /api/stems/engine`, `POST .../install` (a `stem-engine-install` job in
bytes, engine + weights), `POST .../sideload`, `DELETE`.
**`convert.py` — the batch** (`POST /api/tracks/stems/preview` and
`/convert`, a `stem-conversion` job in `BATCH_JOBS`, exclusive with the
engine install and import). The collection is UNTOUCHED while tracks
convert (hours, on a big batch): each becomes a verified
`<target>.konduktor-partial`, so edits made meanwhile carry over and Cancel
only deletes new files. One short END STEP under `STATE.mutation` then
publishes each (a rename that refuses to overwrite: link+unlink on POSIX),
parks each original in Replace mode (`.<name>.<ext>.konduktor-parked`,
same folder, hidden on Windows, retried while Windows holds it open) and
swaps every entry at once. Skips (reported, not failed): already a stem file
BY CONTENT, missing file, target exists (never overwritten), two sources
onto one (case-folded) target, a target the collection names; disk space is
preflighted per volume (both copies coexist until Save) and for the work
folder. Replace implies repoint; destination mode mirrors the tree (full
path, volume first, when the tracks share no folder) and may repoint or add
(+ existing / new playlist). **`pending.py` — the ledger** of conversions
awaiting Save (per library id, atomic): `AppState._save` COMMITS (deletes
parked originals, retargets export sets — inside `_save`, so import and
remap saves count too), `discard()` and opening another library RESTORE,
and `_open` RECOVERS a crash before the missing-files check (parked
originals would look missing): each item decided by whether the SAVED
library names the stem file. Every step works from what is on disk, never
the recorded state alone; only a stem file the batch PUBLISHED is ever
deleted; an uncommitted verified stem file is kept under its partial name
and REUSED by the next batch converting the same (unchanged) source.
While conversions are pending or running, remap-paths, path mapping,
relocation, import, folder add, history restore and reload answer 409
(`_require_no_pending_stems`): each would save or drop the swap.
`/api/state` reports `pending_stems`, `stem_job`, `stem_recovery`.
**`stream_cache.py` — stem PLAYBACK.** A browser decodes only an MP4's
FIRST audio stream (the mix), so each stem is served as a file of its own:
the three audio routes (collection / `source` / `folder`) take
`?stem=0..3`, and `/api/…/tracks/stems` report `[{name, color}]` read from
the FILE (`stem_file.stem_layout`: the box, and enough streams — never the
library's `<STEMS>`, which plain MP3s carry). `stem_file.extract_stream`
COPIES packets into an `ipod` MP4 — measured bit-identical to decoding the
stream in place, edit list and priming (1024 / 2112) intact, on commercial
stems too, so stems stay sample-locked to the mix and the cues. Cached in
app-data keyed by path + size + mtime, LRU under 2 GB, written partial →
rename; ~0.1 s per stem uncached.
- `app_state.py` — the one loaded library, and the **version-history commit**. - `app_state.py` — the one loaded library, and the **version-history commit**.
**`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the **`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the
quit prompt's Discard) drops every unsaved edit through the adapter's own quit prompt's Discard) drops every unsaved edit through the adapter's own
@@ -335,6 +524,105 @@ Two independent apps that talk over HTTP:
open / save / discard (and, next, a stem batch's swap step). 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, 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. 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`, `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`).
**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 - `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` 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 stores it), which is fine for things a user shrugs at losing and NOT fine for
@@ -381,7 +669,13 @@ Two independent apps that talk over HTTP:
"Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss. "Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss.
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
dir). Last-opened collection (global AND per-platform), library column 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`. - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`.
- `main.py` — thin FastAPI routes (all under `/api`), talking only to the - `main.py` — thin FastAPI routes (all under `/api`), talking only to the
adapter. Starts **unloaded**; the library is chosen at runtime via adapter. Starts **unloaded**; the library is chosen at runtime via
@@ -484,12 +778,20 @@ Two independent apps that talk over HTTP:
clicking a folder is the `folder` source kind — its audio in the ordinary clicking a folder is the `folder` source kind — its audio in the ordinary
table, read-only via `readonly_cause: 'not_in_library'`, with files the table, read-only via `readonly_cause: 'not_in_library'`, with files the
collection already holds checked off in the # column (`TrackTable`'s collection already holds checked off in the # column (`TrackTable`'s
`marked`). Capped at 40% of the sidebar and self-scrolling so a deep tree `marked`). 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 gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in
place is **asked every time with nothing preselected** — the answer depends 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 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 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 `CollectionPicker` (**two steps: which PLATFORM, then which
library** — Automatic / Open last / Find manually, the last revealing a file library** — Automatic / Open last / Find manually, the last revealing a file
browser. The platform comes first because every later answer depends on it: browser. The platform comes first because every later answer depends on it:
@@ -537,6 +839,40 @@ Two independent apps that talk over HTTP:
flushSync-driven measurement — which is why playlists were once a separate, flushSync-driven measurement — which is why playlists were once a separate,
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.) pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.)
`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
the collection = point at the stem file / add as new tracks + playlist
(folder mode only); a live preview from `POST /api/tracks/stems/preview`
— N to convert, skipped ▸ with reasons, a time estimate from measured
real-time factors, space; the engine download INLINE, offering the GPU
engine when `nvidia` is set, which keeps running if the dialog closes
(App shows it in the status bar). Every option persists as `stemConvert`),
`StemReportDialog` (the Details behind a finished run's toast — every
skipped/failed track with its reason), `StemsSettings` (Settings → Stems:
engine status / download / install from a folder / remove, compute device
`stemDevice`, the remembered defaults, originals awaiting Save). App
follows a finished run's `{old: new}` ids with the deck and the selection,
picks a running conversion back up from `/api/state.stem_job` after a
reload, and reports `stem_recovery` once. The menu item is shown DISABLED
with a reason (`MenuItem.title` — rendered `aria-disabled`, not
`disabled`, since browsers show no tooltip on a disabled button) where the
platform cannot play stem files as stems. SaveBar adds "Saving deletes N
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 `AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
slot, a per-slot Replace tick for occupied slots — never remembered, since slot, a per-slot Replace tick for occupied slots — never remembered, since
overwriting is a decision about THIS track — and the template itself overwriting is a decision about THIS track — and the template itself
@@ -564,6 +900,24 @@ Two independent apps that talk over HTTP:
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open`
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to outside Tauri; "Skip this version" persists `skippedUpdateVersion` to
userprefs via `/api/prefs`; all failures are silent). userprefs via `/api/prefs`; all failures are silent).
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
which also saves a full-length buffer. `PlaybackEngine.load` takes several
buffers: one source + gain each, all started at ONE scheduled context
time (so they stay sample-locked through seeks and loops), mute/solo as
ramped gains, never a restart. `ScratchEngine.loadStems` keeps ONE summed
copy of the audible stems (not four), re-summed in slices on a mute change.
`analyzeStems` returns the overview's three-band columns (of the sum) plus
one amplitude lane per stem, each normalised to its own 99.5th percentile
but never below 5% of the loudest (a silent stem stays silent).
`MainWaveform` draws the lanes in the file's own colours with a mute
button at each lane's left edge (click = mute, Alt/Option-click = solo);
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
mutes (every other stem muted), so each stem stays freely mutable after
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
the cost: ~140 MB per stem for 6 minutes, i.e. the same four buffers as
the file holds streams, and no more.
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it, - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it,
in three rows. **Header**: cover, title/artist · album · genre, a Read-only in three rows. **Header**: cover, title/artist · album · genre, a Read-only
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` — badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
@@ -598,8 +952,9 @@ Two independent apps that talk over HTTP:
loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so
seeking first wraps the playhead back into the old loop. seeking first wraps the playhead back into the old loop.
- **Hotcue edits live on the pad's right-click menu** (type as one-click - **Hotcue edits live on the pad's right-click menu** (type as one-click
choices, Rename…, Delete); there is no standalone type dropdown or delete choices, a colour swatch grid + Default where `cues.color` is `palette` —
button. Rename re-sets the slot with its own start/type/length plus the `ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone
type dropdown or delete button. Rename re-sets the slot with its own start/type/length plus the
new name, since `set_cue` replaces a slot. A non-editable cue gets the new name, since `set_cue` replaces a slot. A non-editable cue gets the
same menu disabled, not no menu. same menu disabled, not no menu.
Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops), Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops),
@@ -622,11 +977,12 @@ Two independent apps that talk over HTTP:
listening, and shows a "Read-only" badge). listening, and shows a "Read-only" badge).
- Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and - Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and
the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown
(`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button (`cues.types`), the cue colour swatches (`cues.color === 'palette'` +
(`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`, `cues.palette`; a `free` platform gets no picker yet), the rating scale
(`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`,
`can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag, `can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag,
since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter
exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`, and
memory-cue *editing* (one-platform features stay preserved-but-uneditable). memory-cue *editing* (one-platform features stay preserved-but-uneditable).
- `lib/trackColumns.tsx` — single source of truth for the library table's - `lib/trackColumns.tsx` — single source of truth for the library table's
columns (defs, default widths/visibility/order, the Columns-menu list, the columns (defs, default widths/visibility/order, the Columns-menu list, the
@@ -640,7 +996,11 @@ Two independent apps that talk over HTTP:
via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against
defaults so newly-added columns still appear). The prep deck's main-waveform defaults so newly-added columns still appear). The prep deck's main-waveform
zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the 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 ## Commands
@@ -652,6 +1012,13 @@ cd backend && source .venv/bin/activate
uvicorn konduktor.main:app --reload --port 8000 uvicorn konduktor.main:app --reload --port 8000
# point at another file: KONDUKTOR_NML=/path/to/collection.nml uvicorn ... # 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 # Frontend
cd frontend cd frontend
npm run dev # dev server (proxies /api -> :8000) npm run dev # dev server (proxies /api -> :8000)
@@ -679,7 +1046,12 @@ serialization path.** It enforces:
— onto a staying track's path, or two differently-keyed entries for one file — 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 — 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 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.
The guard that catches serialization regressions like the lxml reformatting bug. The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
@@ -708,6 +1080,34 @@ serialization path.** It enforces:
save round-trip; anchor-before-0 moves a whole beat with its companion, a save round-trip; anchor-before-0 moves a whole beat with its companion, a
hotcue clamps and is reported; "add" appends, keeps the original, joins a hotcue clamps and is reported; "add" appends, keeps the original, joins a
playlist, carries pending tag fields; clashes refused with nothing changed. playlist, carries pending tag fields; clashes refused with nothing changed.
- `test_engine_manager.py` — the engine manager and process against a LOCAL
Range-aware server and a FAKE engine script (no network, no torch): resume,
restart when Range is ignored, checksum refusal, cancel keeps the `.part`;
install from split parts with byte progress and a probe; a wrong-version
engine or corrupt part leaves nothing installed; side-load and weights
verified; the CUDA offer's driver/capability floors; the process relays
progress, cancels without dying, reports a crash with its reason, keeps the
Mac awake; the routes (install job in bytes, 409 while one runs, remove).
- `test_stems_batch.py` — the Convert to Stems batch through the routes with
the FAKE engine (`stem_test_support.py`, shared with
`test_engine_manager.py`), on temp collections pointed at generated MP3s:
skips with reasons (an existing target is never overwritten); Replace parks,
swaps at the end, leaves the saved file untouched, keeps prep in decoded time
and 409s the blocked routes; Save deletes parked originals and retargets an
export set; Discard and switching library restore; Cancel leaves no file;
one bad track fails alone; destination+add mirrors into a new playlist;
crash recovery restores (or finishes a committed save) and a re-run REUSES
the kept stem files without calling the engine.
- `test_stem_playback.py` — stem playback's backend half on a generated stem
file (fake stems = distinct scalings of the mix): the layout is read from
the FILE (an MP3 whose entry carries `<STEMS>` has none); each served stem
is its own MP4, bit-identical to that stream in place and the RIGHT stem;
out-of-range / non-stem requests 404; the cache reuses, follows an edited
file, evicts LRU but never what it just wrote; the folder origin serves too
and lists the file as a stem track; a stem file ADDED from a folder gets
`<STEMS>` and a `TYPE="STEM"` playlist key, the MP3 beside it neither. On a
Rekordbox copy, an added stem file projects as a stem track (also after a
reopen) and the deck is offered its stems.
- `test_traktor_adapter.py` — the **generic layer**: one parse per open, the - `test_traktor_adapter.py` — the **generic layer**: one parse per open, the
projection refreshing after every command family, cue-type translation, projection refreshing after every command family, cue-type translation,
capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity` capabilities, and `set_analysed_grid` vs `replace_grid`. `test_save_fidelity`
@@ -722,7 +1122,29 @@ serialization path.** It enforces:
against SQLite). Asserts a no-op save changes zero rows; a one-field edit against SQLite). Asserts a no-op save changes zero rows; a one-field edit
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
counter up by one and the edited row stamped with it; edits are invisible on counter up by one and the edited row stamped with it; edits are invisible on
disk until save; and playlist create/fill/rename/delete round-trip. disk until save; and playlist create/fill/rename/delete round-trip. 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`
— DELETED, never `rb_local_deleted`; the playlist row untouched, later
entries renumbered) plus, after the commit, its ANLZ files and their emptied
folder. Artwork is left (unmeasured: `_m`/`_s` sizes are not in
`contentFile`), and a track in a table that was empty when measured (Sampler,
History, Tag List, My Tag, …) is refused with nothing changed. And **adding
tracks** (J) on generated kick-track MP3s: a raising `checkpoint` cancels
before the library is touched; nothing reaches disk before save; afterwards
only INSERTs (plus the counter) into the tables Rekordbox writes for a new
track, the row filled from the file and stamped with the library's device,
one `contentFile` per analysis file + `artwork.jpg` whose Hash is the MD5;
a plain file gets Konduktor's grid ON the kick, a source's grid, hot cue
(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. - `test_onelibrary_adapter.py` — the third adapter against the same contract.
Unlike the Rekordbox tests it needs **nothing installed and nothing plugged Unlike the Rekordbox tests it needs **nothing installed and nothing plugged
in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed
@@ -731,6 +1153,45 @@ serialization path.** It enforces:
Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2` Konduktor wrote. Pins the drive-relative path resolution, the `PCOB`/`PCO2`
merge, and — cross-checked against the same cues in `master.db` — the dense 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. 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; 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 - `test_import.py` — the import feature end to end: a drive's tracks into a temp
copy of the real collection. Asserts the prep survives (hot cues keep their copy of the real collection. Asserts the prep survives (hot cues keep their
PAD, memory cues fill spare ones, the flexible grid crosses intact, no PAD, memory cues fill spare ones, the flexible grid crosses intact, no
@@ -741,8 +1202,17 @@ serialization path.** It enforces:
tempo and first beat are known rather than borrowed from another analyser: tempo and first beat are known rather than borrowed from another analyser:
exact integer and non-integer BPMs, the 125 BPM the old detector could not exact integer and non-integer BPMs, the 125 BPM the old detector could not
return, octave choice, and the loud off-beat hat and syncopated bassline that 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). `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` - `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; 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 no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
@@ -750,7 +1220,7 @@ serialization path.** It enforces:
collection — the previous implementation's route returned 500 on every call collection — the previous implementation's route returned 500 on every call
for a week while its helper's tests passed. for a week while its helper's tests passed.
- `test_grid_batch.py` — **batch analysis** from the context menu, both - `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/grid/auto-batch`) and Auto Hotcues…
(`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the (`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the
batch-only decisions: locked grids are skipped always, existing grids unless batch-only decisions: locked grids are skipped always, existing grids unless
@@ -762,6 +1232,20 @@ serialization path.** It enforces:
returns its result; opening another library cancels the run. Each shares its returns its result; opening another library cancels the run. Each shares its
helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track
button. 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 - `test_bulk_remove.py` — the context menu's **Remove ▸** routes
(`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`): (`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`):
locked grids are kept, clearing hotcues empties the whole bank (loops and the locked grids are kept, clearing hotcues empties the whole bank (loops and the
@@ -769,10 +1253,9 @@ serialization path.** It enforces:
projection AND its playlists while its audio file is untouched, removal is projection AND its playlists while its audio file is untouched, removal is
gated on `tracks.removable`, and all three are refused while a batch gated on `tracks.removable`, and all three are refused while a batch
analysis runs. `remove_tracks` is the protocol's only DESTROYING verb for analysis runs. `remove_tracks` is the protocol's only DESTROYING verb for
tracks; Traktor implements it, Rekordbox and OneLibrary refuse (a Rekordbox tracks; Traktor and Rekordbox implement it, OneLibrary (read-only) refuses.
track spans rows in several tables plus ANLZ files, and which Rekordbox The journal records it as `track/remove`, NOT an edit — otherwise history
expects deleted together is unmeasured). The journal records it as would read "edited 40 tracks".
`track/remove`, NOT an edit — otherwise history would read "edited 40 tracks".
- `test_folders.py` — the Files trees and adding loose files, through the - `test_folders.py` — the Files trees and adding loose files, through the
routes, on generated FLACs and a temp copy of the collection: a folder lists routes, on generated FLACs and a temp copy of the collection: a folder lists
only the visible audio DIRECTLY in it; the audio route refuses anything a only the visible audio DIRECTLY in it; the audio route refuses anything a
@@ -789,6 +1272,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 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 answer, and prefs are redirected to a temp file so a test can never rewrite
the user's last-opened library. 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. - `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 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 edited AFTER curation; contents dedupe across playlists and loose tracks; a
@@ -841,11 +1329,35 @@ serialization path.** It enforces:
reopen), and a running batch has stopped by the time discard returns; on 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 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. 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.
- `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 - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
imports another platform's library (checked on real imports via AST, so merely 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 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 **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 Also validate the backend interactively at `http://localhost:8000/docs` and the
frontend at `http://localhost:5173`. frontend at `http://localhost:5173`.
@@ -878,7 +1390,15 @@ frontend at `http://localhost:5173`.
e.g. `Macintosh HD/:Music/:one.mp3`. This is how playlist entries e.g. `Macintosh HD/:Music/:one.mp3`. This is how playlist entries
(`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this. (`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this.
- **Rating** = `RANKING / 51`, giving 0–5 stars (`_rating_stars`). - **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. - **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor.
Traktor stores each as a `CUE_V2 TYPE="4"` with its own `<GRID BPM>` child Traktor stores each as a `CUE_V2 TYPE="4"` with its own `<GRID BPM>` child
(flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by (flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
@@ -1063,6 +1583,27 @@ that number and nothing else — everything derives from it:
`AUDIO_ID` and `LOUDNESS` are left empty — they are Traktor's own analysis `AUDIO_ID` and `LOUDNESS` are left empty — they are Traktor's own analysis
outputs and cannot be computed; **verified that Traktor loads and plays such outputs and cannot be computed; **verified that Traktor loads and plays such
entries** and re-analyses them. entries** and re-analyses them.
**Rekordbox implements it too** (2026-10-01; gated on `tracks.addable`,
which the folder menu, the folder header and the device Import button read
from the COLLECTION's capabilities). Unlike Traktor it must ANALYSE: a
Rekordbox grid and waveform live in the ANLZ files, without which Rekordbox
shows neither grid nor cues. So `add_tracks` decodes each file once
(`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), 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
as themselves, a hot cue with no free pad becomes a memory cue. Its ANLZ
files and artwork (`NewTrack.art`, else the file's embedded cover) are
held until save and written BEFORE the grids and commit, then
`contentFile` rows hash what was written (`_m`/`_s` unlisted, as
Rekordbox does); a failed save removes them. Key, mixer gain and phrases
are Rekordbox's own analysis and are not written. The row and file
builders live in `adapters/rekordbox/new_content.py`, shared with the
Rekordbox Library exporter.
- **`jobs.py` + `importer.py`** — the app's first long-running operation. - **`jobs.py` + `importer.py`** — the app's first long-running operation.
Thread per job, polling, cooperative cancel; deliberately not asyncio or SSE. Thread per job, polling, cooperative cancel; deliberately not asyncio or SSE.
**Ordering is the safety property**: audio copies first and the library is **Ordering is the safety property**: audio copies first and the library is
@@ -1079,15 +1620,17 @@ that number and nothing else — everything derives from it:
library. Lossiness follows the settled rule: memory cues become hot cues in library. Lossiness follows the settled rule: memory cues become hot cues in
spare pads (earliest first), cue colour is dropped (Traktor derives it from spare pads (earliest first), cue colour is dropped (Traktor derives it from
type). type).
- 🟡 OneLibrary adapter — **read-only, done**. A OneLibrary USB drive opens, - ✅ OneLibrary adapter — **reading and editing done**, at parity with the
projects, browses and searches: tracks, playlists, hot cues, memory cues, loops Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)).
and flexible beatgrids. Built as the readable SOURCE half of a future A OneLibrary USB drive opens, projects, browses and searches: tracks,
**"import a OneLibrary stick into a Traktor library"** feature, which is the playlists, hot cues, memory cues, loops and flexible beatgrids. Done: track
motivating use case. Everything unknown about the format is on the write side metadata (+ file tags), playlists, hot cues and the beatgrid (in the ANLZ
(the `cue` table's MPEG seek columns, the waveform tags a CDJ draws from, the files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild
update counters), so read-only is a deliberate boundary rather than an on save, adding/removing tracks (the library places the audio), Save via a
unfinished one. All research — including the schema, which has no public spec — working copy, and "Open for editing…" on a Devices row — all verified in
is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). 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 - 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
are settled; see are settled; see
[the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md), [the export discussion doc](.claude/discussions/discuss-export-implementation-2026-09-22.md),
@@ -1219,8 +1762,8 @@ that number and nothing else — everything derives from it:
rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue rekordbox draw its own defaults (green/orange). **rekordbox draws a hot cue
from its palette CODE** (`PCP2` byte 44, before the RGB; `djmdCue.ColorTableIndex` 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 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 table MEASURED from a rekordbox 7 export (the teal-green, 0x13 #00FF30, measured
unmeasured). Type colours map by intent (cue -> light blue 0x05, loop -> green 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 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 companion is code 0 + RGB white (what rekordbox draws for it: unverified). The
**Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7 **Artwork** (`adapters/rekordbox/artwork.py`, Pillow), measured on a rekordbox 7
@@ -1281,7 +1824,12 @@ that number and nothing else — everything derives from it:
**Key notation crosses via the wheel**, never by copying the string: **Key notation crosses via the wheel**, never by copying the string:
`projection.render_key()` is the inverse of `parse_key`, shared by both Pioneer `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 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 so unlike Traktor and OneLibrary a Rekordbox export is not portable by copying
the folder. Still unwritten and documented as unknown: OneLibrary's waveform the folder. Still unwritten and documented as unknown: OneLibrary's waveform
tags and the `cue` table's MPEG seek columns. tags and the `cue` table's MPEG seek columns.
@@ -1347,6 +1895,13 @@ that number and nothing else — everything derives from it:
yet**, since nothing can be written. Note the OneLibrary work already demonstrated yet**, since nothing can be written. Note the OneLibrary work already demonstrated
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
is the DDL to do it with. is the DDL to do it with.
- ✅ **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 - ⬜ Serato adapter
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
+43
View File
@@ -200,6 +200,49 @@ play around.
--- ---
## A remote library (Konduktor server on a NAS)
Keep your whole library — the collection file and the music — on a server, and
open it from any computer with Konduktor. Prep tracks, edit playlists, and
export sticks for your gigs without the music ever living on your performance
laptop.
The server is a small container (`server/`). It holds the library and saves it.
Playback, analysis and stem separation run on the computer you open it from,
on copies it downloads, so the server needs no GPU and does very little work.
**On the server (e.g. TrueNAS SCALE):**
1. Copy `server/compose.yaml` and `server/.env.example` (renamed to `.env`)
onto the NAS. Point the volumes at your datasets, and fill in `.env`: the
platform (`traktor` or `rekordbox`), the library file, the music folder, a
username and password, and — for a collection made on a Mac — the path
mapping (`/Users/you/Music => /music`).
2. Install it: on TrueNAS, **Apps → Discover Apps → ⋮ → Install via YAML** and
paste the compose file; anywhere else, `docker compose up -d`. A bad setting
stops the container with one clear line in its log.
**In the app:** choose **Remote** on the platform screen → **Add a remote
library** → enter the server's address (and a fallback, such as its Tailscale
address, for when you're away from home), the username and the password.
Konduktor checks the server before it saves the remote, and keeps the
password in your keychain.
Good to know:
- **One computer at a time.** If another computer has the library open,
Konduktor says who has it and offers to take over. Edits that computer
hadn't saved stay with the library, and you're asked to save or discard
them.
- **Plain HTTP.** Reach the server over your home network or a VPN
(Tailscale / WireGuard). Don't expose its port to the internet.
- **Unsaved edits live on the server** until you save. Restarting the
container drops them.
- Downloaded tracks are cached on your computer (Settings → **Remote audio**
sets the size), so a track you've prepped and then export is fetched once.
---
## Good to know ## Good to know
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils) - Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
+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 # the local Rekordbox library
python bench_grid_detect.py path/to/collection.nml path/to/master.db python bench_grid_detect.py path/to/collection.nml path/to/master.db
python bench_grid_detect.py --legacy # score the old librosa beat_track python bench_grid_detect.py --legacy # score the old librosa beat_track
python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM
python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor
The reference is each track's own grid, and only single-marker grids are used: The reference is each track's own grid, and only single-marker grids are used:
a multi-marker grid is either a real tempo change (which a constant-tempo a multi-marker grid is either a real tempo change (which a constant-tempo
@@ -102,6 +104,9 @@ def main() -> int:
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
ap.add_argument("libraries", nargs="*", type=Path) ap.add_argument("libraries", nargs="*", type=Path)
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector") ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
ap.add_argument("--hold", choices=("bpm", "anchor"),
help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's "
"'Grid' tick — phase is all that is scored) or its anchor ('BPM')")
args = ap.parse_args() args = ap.parse_args()
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"] libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
@@ -119,7 +124,8 @@ def main() -> int:
for name, audio, r0, rb in refs: for name, audio, r0, rb in refs:
t0 = time.perf_counter() t0 = time.perf_counter()
try: try:
res = detect(str(audio)) hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
res = detect(str(audio), **hold)
except Exception as ex: # a failure is a data point, not a crash except Exception as ex: # a failure is a data point, not a crash
print(f" FAIL {name[:48]:48} {ex}") print(f" FAIL {name[:48]:48} {ex}")
rows.append(None) rows.append(None)
+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)
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 Not loaded by the tests; kept as documentation, and as the starting point if
Konduktor ever needs to create a drive from nothing. Konduktor ever needs to create a drive from nothing.
## rekordbox-edited/
Analysis files from a SECOND stick (Goober), after rekordbox 7 itself edited it
(2026-10-01): a hot cue added on pad E of `demo-track-2`, and a memory cue added on
the start of `nemean`'s memory loop. Trimmed the same way as above, by dropping
whole tags: only `PPTH`, `PCOB` and `PCO2` are kept, byte for byte.
They exist for one property: rekordbox writes **compact** cue entries when it
edits (48 bytes for that hot cue, 44 with no colour for the memory cue; an export
writes 88). pyrekordbox's parser raises on the 44-byte form, which once made the
reader drop the whole `.EXT`, losing pads D-H and every colour. See
`adapters/rekordbox/anlz_file.py`.
+15 -1
View File
@@ -10,7 +10,7 @@
# - python-multipart is imported as `multipart` by starlette → hidden import # - python-multipart is imported as `multipart` by starlette → hidden import
# - dulwich (version-history backups) imports git backends dynamically → # - dulwich (version-history backups) imports git backends dynamically →
# collect_submodules('dulwich') # collect_submodules('dulwich')
from PyInstaller.utils.hooks import collect_submodules, collect_all from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
hiddenimports = [] hiddenimports = []
datas = [] datas = []
@@ -31,6 +31,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"):
# Imported by name, not statically discoverable. # Imported by name, not statically discoverable.
hiddenimports += ["multipart", "anyio"] hiddenimports += ["multipart", "anyio"]
# A remote library's password lives in the OS keychain through `keyring`, which
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
# — so both the modules AND the package metadata that names them must ship.
hiddenimports += collect_submodules("keyring")
datas += copy_metadata("keyring")
# Bundle the canonical version file so konduktor.__version__ can read it at # Bundle the canonical version file so konduktor.__version__ can read it at
# runtime from sys._MEIPASS (frontend/package.json is the single source of the # runtime from sys._MEIPASS (frontend/package.json is the single source of the
# app version — see konduktor/__init__.py). Path is relative to this spec. # app version — see konduktor/__init__.py). Path is relative to this spec.
@@ -48,6 +54,14 @@ datas += [
("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"), ("fixtures/rekordbox/device/export.pdb", "fixtures/rekordbox/device"),
("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"), ("fixtures/rekordbox/device/exportExt.pdb", "fixtures/rekordbox/device"),
] ]
# Which stem engine this build needs, and the pinned weights (read at import by
# konduktor/stems/engine_manager.py).
datas += [
("konduktor/stems/engine.json", "konduktor/stems"),
("konduktor/stems/weights.json", "konduktor/stems"),
]
# The key-detection network's weights (konduktor/core/key_detect.py).
datas += [("konduktor/core/key_model.npz", "konduktor/core")]
a = Analysis( a = Analysis(
["sidecar.py"], ["sidecar.py"],
+267 -53
View File
@@ -5,28 +5,30 @@ Mirrors `adapters.rekordbox.adapter`. It holds:
* a ``OneLibraryStore`` — the retained NATIVE model (the open drive), * a ``OneLibraryStore`` — the retained NATIVE model (the open drive),
* a ``TrackIndex`` — the generic READ projection built from it. * a ``TrackIndex`` — the generic READ projection built from it.
**Read-only.** Every command is refused and `capabilities.writable` is False with **Editable when opened as THE library**, with parity with the Rekordbox adapter
cause `platform_incomplete`, so the UI never offers an edit in the first place; as the goal (decisions: `.claude/discussions/discuss-onelibrary-editing-2026-10-01.md`).
the raises here are the backstop, not the mechanism. Opened `read_only` — as the sidebar's Devices do, beside the loaded library — it
reports `writable=False` with cause `browsing`, and every command is refused.
That scope is deliberate rather than provisional. The purpose of this adapter is What a write must look like was MEASURED by diffing a stick before and after
to make a OneLibrary drive a readable SOURCE — the half an import into another rekordbox 7 edited it, rather than guessed: the update counters a drive carries
library needs — and every genuinely unknown part of the format sits on the write do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
side: the `cue` table's eight MPEG frame/offset columns, whose values a player playlists, hot cues and the beatgrid so far; adding and removing tracks next —
needs to seek accurately in a VBR file; the waveform tags a CDJ draws from; and and every command not written yet is refused, with its capability flag False so
the update counters a drive uses to reconcile edits made on hardware. None of the UI never offers it.
those has to be guessed at to read a drive, and none of them should be guessed at
at all.
""" """
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from ...core.adapter import Unsupported from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities from ...core.capabilities import Capabilities
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex from ...core.query import TrackIndex
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME
from . import capabilities as caps from . import capabilities as caps
from . import projection from . import projection
from .store import OneLibraryStore from .store import OneLibraryStore
@@ -42,23 +44,28 @@ ATTRIBUTE_SMART = 4
class OneLibraryAdapter: class OneLibraryAdapter:
platform = "onelibrary" platform = "onelibrary"
def __init__(self, path: Path): def __init__(self, path: Path, *, read_only: bool = False):
self.path = Path(path) self.path = Path(path)
self._store = OneLibraryStore(self.path) self.read_only = read_only
self._store = OneLibraryStore(self.path, read_only=read_only)
self._index = TrackIndex() self._index = TrackIndex()
self._rebuild() self._rebuild()
# ---- projection maintenance ----------------------------------------- # ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None: def _rebuild(self) -> None:
self._index.rebuild( from ...core.stem_file import is_stem_file
[
projection.to_track(row, self._drive_path(row)) tracks = []
for row in self._store.iter_content() for row in self._store.iter_content():
] path = self._drive_path(row)
) tracks.append(projection.to_track(
row, path, stem=bool(path) and is_stem_file(path)))
self._index.rebuild(tracks)
def _drive_path(self, row) -> str | None: def _drive_path(self, row) -> str | None:
resolved = self._store.layout.resolve(getattr(row, "path", None)) # Through the store: an added track plays from its incoming copy until
# Save puts it in place.
resolved = self._store.resolve_audio(getattr(row, "path", None))
return str(resolved) if resolved is not None else None return str(resolved) if resolved is not None else None
def close(self) -> None: def close(self) -> None:
@@ -70,14 +77,27 @@ class OneLibraryAdapter:
self._store.close() self._store.close()
def reload(self) -> None: def reload(self) -> None:
self._store._load() """Re-read the drive, DISCARDING unsaved edits."""
self._store.discard()
self._rebuild() self._rebuild()
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale."""
from ...core.stem_file import is_stem_file
row = self._store.content(track_id)
path = self._drive_path(row)
self._index.replace(projection.to_track(row, path, stem=bool(path) and is_stem_file(path)))
# ---- identity -------------------------------------------------------- # ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities: def capabilities(self) -> Capabilities:
return caps.capabilities_for( return caps.capabilities_for(
device_name=self._store.device_name, device_name=self._store.device_name,
version=self._store.db_version, version=self._store.db_version,
read_only=self.read_only,
editable_fields=sorted(OneLibraryStore.EDITABLE_FIELDS),
# A drive an export set wrote carries the export's manifest at its root.
managed_by_export=(self._store.layout.root / MANIFEST_NAME).is_file(),
) )
# ---- read ------------------------------------------------------------ # ---- read ------------------------------------------------------------
@@ -144,7 +164,9 @@ class OneLibraryAdapter:
rather than an absence, and treating 0 as a real id would orphan every rather than an absence, and treating 0 as a real id would orphan every
top-level playlist. top-level playlist.
""" """
rows = self._store.playlists() rows = sorted(self._store.playlists(),
key=lambda r: (int(getattr(r, "sequenceNo", 0) or 0), int(r.playlist_id)))
writable = not self.read_only
nodes: dict[str, PlaylistNode] = {} nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {} parents: dict[str, str] = {}
@@ -164,12 +186,12 @@ class OneLibraryAdapter:
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))), count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[], children=[],
selectable=kind == "playlist", selectable=kind == "playlist",
# Read-only: every per-node flag is False, and # Opened read-only, every flag is False and
# `capabilities.writable` tells the UI why, once. # `capabilities.writable` tells the UI why, once.
can_add_tracks=False, can_add_tracks=writable and kind == "playlist",
can_reorder=False, can_reorder=writable and kind == "playlist",
can_rename=False, can_rename=writable,
can_delete=False, can_delete=writable,
can_contain_children=kind == "folder", can_contain_children=kind == "folder",
) )
parent = str(getattr(r, "playlist_id_parent", 0) or 0) parent = str(getattr(r, "playlist_id_parent", 0) or 0)
@@ -201,6 +223,9 @@ class OneLibraryAdapter:
def audio_path(self, track_id: str): def audio_path(self, track_id: str):
return self._store.audio_path(track_id) return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None: def set_path_mapping(self, mapping: PathMapping) -> None:
"""Ignored: a drive's paths are relative to wherever it is mounted. """Ignored: a drive's paths are relative to wherever it is mounted.
@@ -236,32 +261,147 @@ class OneLibraryAdapter:
# ---- save ------------------------------------------------------------- # ---- save -------------------------------------------------------------
@property @property
def dirty(self) -> bool: def dirty(self) -> bool:
return False return self._store.dirty
def save(self): def save(self):
raise Unsupported(self._readonly_reason("Saving")) self._require_writable("Saving")
outcome = self._store.save()
# Save MOVES files (an added track's audio leaves its incoming copy), so
# the projection is rebuilt from what is now on the drive.
self._rebuild()
return outcome
def snapshot(self) -> bytes: def snapshot(self) -> bytes:
raise Unsupported("OneLibrary drives are not versioned by Konduktor") raise Unsupported("OneLibrary drives are not versioned by Konduktor")
# ---- commands: all refused ------------------------------------------- # ---- commands -----------------------------------------------------------
def _readonly_reason(self, what: str) -> str: def _readonly_reason(self, what: str) -> str:
if self.read_only:
return (f"{what} is not possible while the drive is open for browsing. "
"Open it for editing to change it.")
return f"{what} is not supported yet for OneLibrary drives." return f"{what} is not supported yet for OneLibrary drives."
def _refuse(self, what: str): def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what)) raise Unsupported(self._readonly_reason(what))
def add_tracks(self, items: list) -> list[str]: def _require_writable(self, what: str) -> None:
self._refuse("Adding tracks") """Every write passes through here, so a command added later cannot
forget that a browsing drive is read-only."""
if self.read_only:
self._refuse(what)
# ---- audio placement (`tracks.places_audio`) ----------------------------
def audio_home(self) -> Path:
return self._store.audio_home()
def place_audio(self, source: Path, track) -> Path | None:
self._require_writable("Adding tracks")
return self._store.place_audio(source, track)
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks, each arriving ready to prep — as the Rekordbox adapter does.
A drive keeps the beatgrid, cues and waveforms in per-track analysis
files, and rekordbox shows neither grid nor cues without them, so every
file is decoded ONCE here and its `.DAT`/`.EXT`/`.2EX` built by the
OneLibrary exporter's own writer — the files rekordbox 7 was verified
to read. A file with no grid of its own gets Konduktor's.
Two phases, as in Rekordbox: FIRST the slow, cancellable part (decoding,
grid detection, building the analysis and artwork bytes) before the
library is touched; THEN the rows, with hot cues replayed through the
ordinary `set_cue` so they keep its conventions. Memory cues — and a hot
cue with no free pad — cross as memory cues, written with the files.
`audio_path` is where `place_audio` said to copy it (or the file itself,
already on the stick); Save moves copies into place.
"""
from ...core import audio_tags, grid_detect, key_detect, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
self._require_writable("Adding tracks")
exporter = OneLibraryExporter()
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})", step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
try:
rel = self._store.drive_relative(self._store.final_of(audio))
except ValueError:
raise InvalidCommand(f"{audio} is not on this drive") from None
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
hot, memory, taken = [], [], set()
for cue in sorted((item.cues.cues if item.cues else []), key=lambda c: c.start):
if (cue.role == "hotcue" and cue.slot is not None
and 0 <= cue.slot < caps.HOTCUE_SLOTS and cue.slot not in taken):
hot.append(cue)
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
# A file with no key of its own gets one, as it gets a grid.
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
export_track = ExportTrack(track=track, destination=audio,
cues=TrackCues(grid_markers=markers, cues=memory))
# Decoded once above; the writer must not decode it again.
export_track.waveform = lambda *, lead=0.0, m=measured: m
art = item.art or audio_tags.read_cover(audio)
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
length = track.length or (int(measured.duration) if measured else None)
prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else track.bpm, length=length)
for cue in hot:
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
cue_type="loop" if cue.length else "cue",
length_sec=cue.length or 0.0, name=cue.name)
code, _rgb = palette.code_for(cue.color)
if cue.color and code:
self._store.set_cue_color(track_id, cue.slot, code)
added.append(track_id)
self._rebuild()
return added
def remove_tracks(self, track_ids: list[str]) -> int: def remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks") """Remove tracks — and, on a stick, their audio and analysis files at Save
(decision 3: a stick's audio belongs to its library)."""
self._require_writable("Removing tracks")
n = self._store.remove_tracks(track_ids)
if n:
self._rebuild()
return n
def apply_stem_swaps(self, swaps, *, add_to_playlist=None): def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
self._refuse("Converting tracks to stems") self._refuse("Converting tracks to stems")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata") self._require_writable("Editing track metadata")
self._store.set_track_metadata(track_id, fields)
self._refresh(track_id)
return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art") self._refuse("Editing cover art")
@@ -270,52 +410,126 @@ class OneLibraryAdapter:
return self._store.cover_art(track_id) return self._store.cover_art(track_id)
def create_playlist(self, name: str, parent_id: str | None = None) -> str: def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists") self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
def create_folder(self, name: str, parent_id: str | None = None) -> str: def create_folder(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlist folders") self._require_writable("Creating playlist folders")
return self._store.create_folder(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None: def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists") self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None: def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists") self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._refuse("Editing playlists") self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
def set_cue(self, track_id: str, **kw) -> TrackCues: def _refresh_cues(self, track_id: str) -> TrackCues:
self._refuse("Editing cues") """Re-project a track AND return its fresh cues — every cue/grid command
ends here, so a route can never serve a stale projection."""
self._refresh(track_id)
return self.track_cues(track_id) or TrackCues()
def _check_cue_type(self, cue_type: str) -> None:
if cue_type not in WRITABLE_CUE_TYPES:
raise Unsupported(f"OneLibrary has no cue type {cue_type!r}")
def set_cue(
self,
track_id: str,
*,
slot: int,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
role: str = "hotcue",
name: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
if role != "hotcue":
# 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: def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._refuse("Editing cues") self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's hot cue colours")
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues: def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._refuse("Deleting cues") self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._refuse("Placing cues") self._require_writable("Placing cues")
for cue in cues:
self._check_cue_type(getattr(cue, "type", "cue"))
self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id)
# ---- commands: beatgrid -----------------------------------------------
@staticmethod
def _markers_from(markers: list) -> list:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
return [m if isinstance(m, GridMarker) else GridMarker(start=float(m[0]), bpm=float(m[1]))
for m in markers]
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._refuse("Editing the beatgrid") self._require_writable("Editing the beatgrid")
self._store.add_grid_marker(track_id, start_sec, bpm)
return self._refresh_cues(track_id)
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._refuse("Editing the beatgrid") self._require_writable("Editing the beatgrid")
self._store.move_grid_marker(track_id, index, start_sec)
return self._refresh_cues(track_id)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues: def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._refuse("Editing the beatgrid") self._require_writable("Editing the beatgrid")
self._store.set_grid_marker_bpm(track_id, index, bpm)
return self._refresh_cues(track_id)
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues: def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._refuse("Editing the beatgrid") self._require_writable("Editing the beatgrid")
self._store.delete_grid_marker(track_id, index)
return self._refresh_cues(track_id)
def replace_grid(self, track_id: str, markers: list) -> TrackCues: def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid") self._require_writable("Editing the beatgrid")
self._store.replace_grid(track_id, self._markers_from(markers))
return self._refresh_cues(track_id)
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues: def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid") """An analysis result, as rekordbox's analyser would write it: nothing is
paired with a marker (the companion cue is Traktor's), so a replace."""
return self.replace_grid(track_id, markers)
def delete_grid(self, track_id: str) -> TrackCues: def delete_grid(self, track_id: str) -> TrackCues:
self._refuse("Deleting the beatgrid") self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
raise Unsupported("OneLibrary has no beatgrid lock") raise Unsupported("OneLibrary has no beatgrid lock")
@@ -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: 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 Returns None when the file has no `PQTZ` — which is a real state, not an
error: rekordbox analyses one-shot samples too, and gives them an analysis error: rekordbox analyses one-shot samples too, and gives them an analysis
@@ -39,7 +40,7 @@ def beats_from_pqtz(anlz) -> tuple[list[float], list[float], list[int]] | None:
for tag in getattr(anlz, "tags", []): for tag in getattr(anlz, "tags", []):
if tag.type != "PQTZ": if tag.type != "PQTZ":
continue continue
entries = getattr(getattr(tag.struct, "content", None), "entries", None) entries = tag.entries
if not entries: if not entries:
return None return None
times: list[float] = [] times: list[float] = []
@@ -1,25 +1,27 @@
"""What a OneLibrary drive can persist: nothing, for now. """What a OneLibrary drive can persist.
`writable` is False with cause `platform_incomplete`. That is the distinction the Opened as THE library, a drive is writable, and the per-feature flags say which
capability system exists to draw — this is a ROADMAP GAP, not a refusal. A edits have landed: track metadata, playlists, hot cues, the grid, and adding
cloud-synced Rekordbox library is refused permanently to protect the user's other and removing tracks, so the UI never offers an edit the adapter
machines; a OneLibrary drive simply has no write path yet, and the UI must word would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
those two very differently. loaded library — `writable` is False with cause `browsing`, which the UI words
as "open it for editing", not as a missing feature.
The per-feature flags below still report what the FORMAT supports rather than With `writable=False` the per-feature flags still report what the FORMAT
being blanked to false, because that is what `writable=False` is for: the UI can supports rather than being blanked, because that is what the library-level flag
show a drive's cues and grid honestly, and say once, in one place, that the whole is for: the UI can show a drive's cues and grid honestly and say once, in one
library is read-only. Blanking them would claim OneLibrary has no hot cues. place, that the library is read-only. Blanking them would claim OneLibrary has no
hot cues.
Two answers are worth recording now, while the evidence is in front of us, since Two answers are worth recording now, while the evidence is in front of us, since
getting them wrong later would be a silent data bug rather than a missing getting them wrong later would be a silent data bug rather than a missing
feature: feature:
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three * cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
#FF8C00. This differs from the desktop Rekordbox adapter, which reports RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
"palette" because `djmdCue` stores an index into a built-in table — the same 16 swatches and both are written. (This was first read as "free RGB" off the
vendor, two genuinely different representations. RGB bytes alone; the code byte beside them is what decides.)
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer * a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
as Traktor and Rekordbox, and NOT the `separate_bank` the original as Traktor and Rekordbox, and NOT the `separate_bank` the original
multi-platform plan assumed. multi-platform plan assumed.
@@ -34,44 +36,59 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, 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, # Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`). # so the bank really is 1..8 (see `cues.py`).
HOTCUE_SLOTS = 8 HOTCUE_SLOTS = 8
def capabilities_for(device_name: str | None = None, version: str | None = None) -> Capabilities: def capabilities_for(
device_name: str | None = None,
version: str | None = None,
*,
read_only: bool = False,
editable_fields: list[str] | None = None,
managed_by_export: bool = False,
) -> Capabilities:
return Capabilities( return Capabilities(
platform="onelibrary", platform="onelibrary",
version=version, version=version,
# A roadmap gap, not a protective refusal — the UI words the two writable=not read_only,
# differently, which is the whole reason `readonly_cause` exists. readonly_cause="browsing" if read_only else None,
writable=False,
readonly_cause="platform_incomplete",
cues=CueCapabilities( cues=CueCapabilities(
editable=False, editable=True,
hotcue_slots=HOTCUE_SLOTS, hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter", slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does. They are # OneLibrary carries memory cues, as Rekordbox does: projected and
# projected and preserved; nothing here is editable anyway. # preserved, NOT editable (the two-platform rule, as in Rekordbox).
memory_cues=True, memory_cues=True,
max_memory_cues=None, max_memory_cues=None,
types=["cue", "loop"], types=WRITABLE_CUE_TYPES,
color="free", # PCO2 stores RGB per cue, not a palette index color="palette",
palette=[], palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # PCO2 carries a per-cue comment named=True, # PCO2 carries a per-cue comment
loops="cue_type", loops="cue_type",
), ),
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do # The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
# survive an export — so the format is flexible even though Konduktor # No per-track grid lock exists in the format.
# does not write it here. grid=GridCapabilities(editable=True, flexible=True, lockable=False),
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
tracks=TrackCapabilities( tracks=TrackCapabilities(
rating_max=5, # stored 0-5 directly, as in master.db rating_max=5, # stored 0-5 directly, as in master.db
editable_fields=[], # The Rekordbox adapter's set: `producer`/`mix` have no column.
media_kinds=["audio"], editable_fields=sorted(editable_fields or []),
# `artwork` gates EDITING, and a drive is read-only here. Reading media_kinds=["audio", "stem"],
# 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=False,
artwork_note=None, 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 # A drive carries no smart playlists: rekordbox resolves them to
# static lists on export, because a CDJ cannot evaluate rules. # static lists on export, because a CDJ cannot evaluate rules.
smart="none", smart="none",
reorder=False, reorder=True,
), ),
save=SaveCapabilities( save=SaveCapabilities(
app_name="OneLibrary", # Named for the DRIVE ("Save to Goober"): a person has several
library_label=device_name or "exportLibrary.db", # sticks, and "Save to OneLibrary" would not say which.
# Nothing is written, so nothing can be overwritten by another app. app_name=device_name or "OneLibrary",
library_label="exportLibrary.db",
# Another app writing the drive between open and save is CAUGHT,
# not risked: the store fingerprints the database at open and
# refuses to save over a change it did not make.
overwrite_risk="none", overwrite_risk="none",
managed_by_export=managed_by_export,
# A drive is a database plus N analysis files plus the audio itself, # A drive is a database plus N analysis files plus the audio itself,
# so there is no single blob that IS the library — the same reason # so there is no single blob that IS the library — the same reason
# Rekordbox libraries are not versioned. # Rekordbox libraries are not versioned.
+36 -23
View File
@@ -37,6 +37,7 @@ from __future__ import annotations
import logging import logging
from ...core.model import CuePoint from ...core.model import CuePoint
from ..rekordbox import palette
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -47,14 +48,13 @@ NO_LOOP = 0xFFFFFFFF
# `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue. # `hot_cue` for a cue that sits in no pad bank, i.e. a memory cue.
MEMORY_SLOT = 0 MEMORY_SLOT = 0
# PCO2/PCOB entry kinds. The value is the same in both tags; PCOB exposes it as # PCO2/PCOB entry kinds. The value is the same in both tags.
# a construct enum and PCO2 as a plain int, so both are normalised to an int.
ENTRY_CUE = 1 ENTRY_CUE = 1
ENTRY_LOOP = 2 ENTRY_LOOP = 2
def _entry_kind(value) -> int: def _entry_kind(value) -> int:
"""PCOB gives an enum, PCO2 an int — one number out of either.""" """An entry's kind as an int, defaulting to a point cue if unreadable."""
try: try:
return int(value) return int(value)
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -68,8 +68,17 @@ def _color(entry) -> str | None:
real black in principle, but rekordbox uses it as "unset" and shows such a real black in principle, but rekordbox uses it as "unset" and shows such a
cue in the default colour, so it is reported as no colour rather than as cue in the default colour, so it is reported as no colour rather than as
black. Memory cues in the reference export are exactly this case. black. Memory cues in the reference export are exactly this case.
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
code is reported as that swatch; a cue with code 0 and an RGB (older
exports, the reference fixture) is reported by its RGB.
""" """
swatch = palette.hex_for(getattr(entry, "color_code", None))
if swatch is not None:
return swatch
try: try:
# None on an entry too short to carry a colour: every PCPT, and the
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue) r, g, b = int(entry.color_red), int(entry.color_green), int(entry.color_blue)
except (AttributeError, TypeError, ValueError): except (AttributeError, TypeError, ValueError):
return None return None
@@ -78,7 +87,7 @@ def _color(entry) -> str | None:
return f"#{r:02X}{g:02X}{b:02X}" return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool) -> CuePoint | None: def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable.""" """One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try: try:
hot_cue = int(entry.hot_cue) hot_cue = int(entry.hot_cue)
@@ -111,11 +120,11 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
length=length, length=length,
slot=slot, slot=slot,
color=_color(entry) if with_color else None, color=_color(entry) if with_color else None,
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a # Hot cues are editable on a drive opened for editing (the caller says
# command. `capabilities.writable` is what the UI actually gates on; # so). MEMORY cues never are — preserved-but-uneditable, as in the
# this keeps the per-cue answer consistent with it. # Rekordbox adapter (the two-platform rule).
editable=False, editable=editable and role == "hotcue",
readonly_reason="platform_managed", readonly_reason=None if editable and role == "hotcue" else "platform_managed",
grid_marker=None, grid_marker=None,
) )
@@ -130,15 +139,14 @@ def _entries(anlz, tag_type: str) -> list:
""" """
out: list = [] out: list = []
for tag in getattr(anlz, "tags", []): for tag in getattr(anlz, "tags", []):
if tag.type != tag_type: if tag.type == tag_type:
continue out.extend(tag.entries)
content = getattr(tag.struct, "content", None)
out.extend(getattr(content, "entries", None) or [])
return out return out
def cues_from_anlz(dat, ext) -> list[CuePoint]: def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`. """The track's complete cue list, from its parsed `.DAT` and `.EXT`
(`rekordbox.anlz_file.AnlzFile`s).
Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track Either may be None — a drive can carry a `.DAT` with no `.EXT` — and a track
with no cues at all yields an empty list rather than an error. with no cues at all yields an empty list rather than an error.
@@ -153,14 +161,14 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
for f in files: for f in files:
pco2.extend(_entries(f, "PCO2")) pco2.extend(_entries(f, "PCO2"))
if pco2: if pco2:
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None] cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
else: else:
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the # Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
# .EXT the rest, so either alone is an incomplete bank. # .EXT the rest, so either alone is an incomplete bank.
pcob: list = [] pcob: list = []
for f in files: for f in files:
pcob.extend(_entries(f, "PCOB")) pcob.extend(_entries(f, "PCOB"))
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None] cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
return _dedupe(cues) return _dedupe(cues)
@@ -168,18 +176,23 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
def _dedupe(cues: list[CuePoint]) -> list[CuePoint]: def _dedupe(cues: list[CuePoint]) -> list[CuePoint]:
"""Collapse the same cue appearing in more than one tag or file. """Collapse the same cue appearing in more than one tag or file.
Identity is (role, slot, start) rather than the whole cue: the same pad can Identity is (role, slot, start, type, length) rather than the whole cue:
be described by both `PCOB` and `PCO2`, and by both files, and those copies the same pad can be described by both `PCOB` and `PCO2`, and by both files,
agree on position while differing in how much detail they carry. The first and those copies agree on all five while differing in how much detail they
one wins, which — given PCO2 is read first — is the richest. carry (colour, comment). The first one wins, which — given PCO2 is read
first — is the richest.
Type and length are part of it because two MEMORY cues may share a position:
rekordbox happily stores a memory cue on the start of a memory loop (seen on
Goober), and keying on position alone silently dropped the loop.
Ordered by position, then by slot, so the projection is stable across reads Ordered by position, then by slot, so the projection is stable across reads
regardless of the order the tags happened to store. regardless of the order the tags happened to store.
""" """
seen: set[tuple[str, int | None, int]] = set() seen: set[tuple] = set()
out: list[CuePoint] = [] out: list[CuePoint] = []
for c in cues: for c in cues:
key = (c.role, c.slot, round(c.start * 1000)) key = (c.role, c.slot, round(c.start * 1000), c.type, round(c.length * 1000))
if key in seen: if key in seen:
continue continue
seen.add(key) seen.add(key)
@@ -0,0 +1,208 @@
"""Keeping a stick's legacy Device Library (`export.pdb`) in step with its OneLibrary.
Most rekordbox sticks carry BOTH: `exportLibrary.db` (OneLibrary, newer players)
and `export.pdb` (the Device Library, older players and rekordbox's own "Device
Library" view). Cues and the grid live in the analysis files both share, so they
follow an edit by themselves; titles and playlists live in each database
separately. **rekordbox itself lets them drift**: measured on Goober
(2026-10-01), its edits updated the pdb's track metadata but not a new playlist
or a reorder. Konduktor rebuilds the pdb at Save instead (decision 2 of the
editing discussion), so a stick never shows different playlists depending on
which player reads it.
**Ids are mirrored, not assigned.** rekordbox exports both libraries from the
same ids — pdb track id = `content_id`, the artist/album/genre/label/key ids, the
playlist ids, playlist `sort` = `sequenceNo`, entries `(sequenceNo, content_id,
playlist_id)`, artwork id = `image_id` — all checked on Goober. So the OneLibrary
database IS the answer for every row the pdb shares with it.
**An edit, not a regeneration.** The stick's own `export.pdb` is edited in place
(`pdb.PdbEditor`): only the tracks, the lookup tables (artist, album, genre,
label, key), artwork and the playlist tree and entries are candidates, a table is rewritten only if one of its rows changed,
and an unchanged row keeps rekordbox's bytes. A changed TRACK row is the old row
with the edited fields overwritten, so everything the pdb holds that OneLibrary
does not — the phrase-analysis strings, the `masterDbId` halves, play counts,
dates — survives. History, colours, menus and `exportExt.pdb` are never touched.
"""
from __future__ import annotations
import re
import struct
from pathlib import Path
from ..rekordbox import pdb
#: Tables this rebuild owns. Everything else in the file is left as it is.
_OWNED = (pdb.TRACKS, pdb.ARTISTS, pdb.ALBUMS, pdb.GENRES, pdb.LABELS, pdb.KEYS,
pdb.ARTWORK, pdb.PLAYLIST_TREE, pdb.PLAYLIST_ENTRIES)
def _lookup_name(table: int, row: bytes) -> str:
if table == pdb.ARTISTS:
sub, _shift, _rid, _b, ofs = struct.unpack_from("<HHIBB", row, 0)
if sub == 0x64:
ofs = struct.unpack_from("<H", row, 10)[0]
return pdb.read_dsql(row, ofs)
if table == pdb.ALBUMS:
sub, _shift, _u, _artist, _rid, _u3, _b, ofs = struct.unpack_from("<HHIIIIBB", row, 0)
return pdb.read_dsql(row, ofs)
if table == pdb.KEYS:
return pdb.read_dsql(row, 8)
return pdb.read_dsql(row, 4)
def _pdb_art_path(path: str | None) -> str:
"""OneLibrary's `image.path` names the `b<n>` file; export.pdb's artwork row
the byte-identical `a<n>` beside it (as on Goober, and as rekordbox writes)."""
return re.sub(r"/b(\d+)(\.jpg)$", r"/a\1\2", path or "")
def _tree_value(row: bytes) -> tuple:
parent, _u, sort, rid, folder = struct.unpack_from("<5I", row, 0)
return parent, sort, rid, bool(folder), pdb.read_dsql(row, 20)
def _merge(old: list[bytes], new: dict, table: int, same) -> list[bytes] | None:
"""The table's rows: old ORDER kept, an unchanged row's old BYTES kept, new
rows appended by id. None when nothing changed (the table is not rewritten).
`new` maps row id -> (value, encode()); `same(old_row, value)` says whether
an old row already says `value`.
"""
out, changed, seen = [], False, set()
for row in old:
rid = pdb.row_id(table, row)
if rid not in new:
changed = True # removed
continue
seen.add(rid)
value, encode = new[rid]
if same(row, value):
out.append(row)
else:
out.append(encode())
changed = True
for rid in sorted((r for r in new if r not in seen), key=str):
out.append(new[rid][1]())
changed = True
return out if changed else None
def rebuild(existing: bytes, session) -> bytes | None:
"""`export.pdb` edited to match the OneLibrary database open in `session`
(the working copy, edits committed); None if it already matches."""
from sqlalchemy import text
tables: dict[int, list[bytes]] = {}
# ---- lookups ----------------------------------------------------------------
for table, sql, build in (
(pdb.ARTISTS, "SELECT artist_id, name FROM artist", pdb.artist_row),
# rekordbox's export leaves an album's artist 0 (see `pdb.album_row`).
(pdb.ALBUMS, "SELECT album_id, name FROM album", pdb.album_row),
(pdb.GENRES, "SELECT genre_id, name FROM genre", pdb.id_string_row),
(pdb.LABELS, "SELECT label_id, name FROM label", pdb.id_string_row),
(pdb.KEYS, "SELECT key_id, name FROM key", pdb.key_row),
):
want = {int(i): (name or "", (lambda i=i, n=name, b=build: b(int(i), n or "")))
for i, name in session.execute(text(sql))}
merged = _merge(pdb.table_rows(existing, table), want, table,
lambda row, value, t=table: _lookup_name(t, row) == value)
if merged is not None:
tables[table] = merged
want = {int(i): (_pdb_art_path(path), (lambda i=i, p=path: pdb.id_string_row(int(i), _pdb_art_path(p))))
for i, path in session.execute(text("SELECT image_id, path FROM image"))}
merged = _merge(pdb.table_rows(existing, pdb.ARTWORK), want, pdb.ARTWORK,
lambda row, value: pdb.read_dsql(row, 4) == value)
if merged is not None:
tables[pdb.ARTWORK] = merged
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid)
if cid in old_tracks:
fields, strings = pdb.track_fields(old_tracks[cid])
else:
fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
"year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""}
want[cid] = ((fields, strings),
(lambda f=fields, s=strings: pdb.track_row(f, s)))
merged = _merge(list(old_tracks.values()), want, pdb.TRACKS,
lambda row, value: _same_track(pdb.track_fields(row), value))
if merged is not None:
tables[pdb.TRACKS] = merged
# ---- playlists ----------------------------------------------------------------
want = {int(pid): ((int(parent or 0), int(seq or 0), int(pid), int(attr or 0) == 1, name or ""),
(lambda p=pid, par=parent, s=seq, n=name, a=attr:
pdb.playlist_tree_row(int(p), int(par or 0), int(s or 0), n or "",
folder=int(a or 0) == 1)))
for pid, parent, seq, name, attr in session.execute(text(
"SELECT playlist_id, playlist_id_parent, sequenceNo, name, attribute FROM playlist"))}
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_TREE), want, pdb.PLAYLIST_TREE,
lambda row, value: _tree_value(row) == value)
if merged is not None:
tables[pdb.PLAYLIST_TREE] = merged
want = {}
for pid, cid, seq in session.execute(text(
"SELECT playlist_id, content_id, sequenceNo FROM playlist_content "
"ORDER BY playlist_id, sequenceNo")):
key = (int(seq), int(cid), int(pid))
want[key] = (key, (lambda k=key: pdb.playlist_entry_row(*k)))
merged = _merge(pdb.table_rows(existing, pdb.PLAYLIST_ENTRIES), want, pdb.PLAYLIST_ENTRIES,
lambda row, value: True)
if merged is not None:
tables[pdb.PLAYLIST_ENTRIES] = merged
if not tables:
return None
editor = pdb.PdbEditor(existing)
for table in _OWNED:
if table in tables:
editor.refill(table, tables[table])
return editor.render()
def _same_track(old: tuple[dict, dict], new: tuple[dict, dict]) -> bool:
"""Equal in every field that means something: `index_shift` is the row's slot
in its page, re-stamped whenever a page is written."""
(of, os_), (nf, ns) = old, new
return ({k: v for k, v in of.items() if k != "index_shift"}
== {k: v for k, v in nf.items() if k != "index_shift"} and os_ == ns)
def _fresh_track(cid: int, path, file_name, file_size, file_type, bitrate, bit_depth,
sample_rate, length, analysis, date_added, key_id, image_id) -> tuple[dict, dict]:
"""A track the pdb has never listed (one added to the stick by Konduktor), in
the shape `device_export` writes one — the values a rekordbox device export
was measured to carry (see that module)."""
from ..rekordbox.device_export import ANALYSED, BITMASK
added = str(date_added or "")[:10]
fields = {
"subtype": 0x24, "bitmask": BITMASK, "sample_rate": int(sample_rate or 0),
"file_size": int(file_size or 0), "u2": cid + 0x600, "artwork_id": int(image_id or 0),
"key_id": int(key_id or 0), "bitrate": int(bitrate or 0), "id": cid,
"sample_depth": int(bit_depth or 0), "duration": min(int(length or 0), 0xFFFF),
"u5": ANALYSED, "u6": int(file_type or 0), "u7": 3,
}
strings = {
"kuvo_public": "ON", "autoload_hotcues": "ON", "date_added": added,
"analyze_path": analysis or "", "analyze_date": added,
"filename": file_name or Path(str(path or "")).name, "file_path": path or "",
}
return fields, strings
@@ -73,8 +73,8 @@ class OneLibraryDriver:
except Exception: # noqa: BLE001 except Exception: # noqa: BLE001
pass pass
def open(self, path: Path) -> OneLibraryAdapter: def open(self, path: Path, *, read_only: bool = False) -> OneLibraryAdapter:
return OneLibraryAdapter(path) return OneLibraryAdapter(path, read_only=read_only)
def detect(self) -> list[dict]: def detect(self) -> list[dict]:
return discovery.detect_libraries() return discovery.detect_libraries()
+28 -10
View File
@@ -265,21 +265,21 @@ class OneLibraryExporter:
n = counter["next"] n = counter["next"]
folder = root / "PIONEER" / "Artwork" / "00001" folder = root / "PIONEER" / "Artwork" / "00001"
folder.mkdir(parents=True, exist_ok=True) folder.mkdir(parents=True, exist_ok=True)
small, medium = jpegs
files = [] files = []
for letter in ("a", "b"): for rel, data in art_files(n, jpegs):
for suffix, data in (("", small), ("_m", medium)): path = root / rel.lstrip("/")
path = folder / f"{letter}{n}{suffix}.jpg" path.write_bytes(data)
path.write_bytes(data) files.append(path)
files.append(path)
con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)", con.execute("INSERT INTO image (image_id, path) VALUES (?, ?)",
(n, f"/PIONEER/Artwork/00001/b{n}.jpg")) (n, f"/PIONEER/Artwork/00001/b{n}.jpg"))
return n, files return n, files
# ---- the analysis files -------------------------------------------------- # ---- the analysis files --------------------------------------------------
def _write_anlz(self, item: ExportTrack, rel: str, dat: Path) -> list[Path]: def anlz_files(self, item: ExportTrack, rel: str) -> list[tuple[str, bytes]]:
"""The `.DAT`, `.EXT` and `.2EX`, as rekordbox 7 writes them. """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 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, never produces a track without them, and `PCO2` — the complete list,
@@ -318,9 +318,18 @@ class OneLibraryExporter:
tags += previews tags += previews
tags += W.cue_tags(cues, extended=False) tags += W.cue_tags(cues, extended=False)
ext = [W.path_tag(rel), *ext_waves[:1], *W.cue_tags(cues, extended=True), *ext_waves[1:]] 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: 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 return written
@staticmethod @staticmethod
@@ -424,6 +433,15 @@ _FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 1
".aif": 12, ".aiff": 12} ".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: def _file_type(path: Path) -> int:
return _FILE_TYPES.get(path.suffix.lower(), 1) return _FILE_TYPES.get(path.suffix.lower(), 1)
@@ -54,7 +54,7 @@ def _bpm(row) -> float | None:
return round(int(raw) / 100.0, 2) return round(int(raw) / 100.0, 2)
def to_track(row, drive_path: str | None = None) -> Track: def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track:
"""Project one ``Content`` row. """Project one ``Content`` row.
**The three count fields are approximations here**, and deliberately so. Cues **The three count fields are approximations here**, and deliberately so. Cues
@@ -104,7 +104,8 @@ def to_track(row, drive_path: str | None = None) -> Track:
hotcue_count=0, hotcue_count=0,
grid_marker_count=1 if (bpm and has_analysis) else 0, grid_marker_count=1 if (bpm and has_analysis) else 0,
grid_locked=False, # OneLibrary has no grid lock grid_locked=False, # OneLibrary has no grid lock
media_kind="audio", # What the FILE is, as the deck plays it — see the Rekordbox projection.
media_kind="stem" if stem else "audio",
) )
File diff suppressed because it is too large. Load diff
+140 -15
View File
@@ -21,13 +21,14 @@ from __future__ import annotations
from pathlib import Path from pathlib import Path
from ...core.adapter import Unsupported from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex from ...core.query import TrackIndex
from . import capabilities as caps from . import capabilities as caps
from . import projection from . import palette, projection, timebase
from ...core import add_analysis
from .store import RekordboxStore from .store import RekordboxStore
@@ -46,7 +47,8 @@ class RekordboxAdapter:
kinds = self._store.cue_kinds() kinds = self._store.cue_kinds()
self._index.rebuild( self._index.rebuild(
[ [
projection.to_track(row, kinds.get(str(row.ID), ())) projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID)))
for row in self._store.iter_content() for row in self._store.iter_content()
] ]
) )
@@ -68,7 +70,8 @@ class RekordboxAdapter:
""" """
kinds = self._store.cue_kinds() kinds = self._store.cue_kinds()
row = self._store.content(track_id) row = self._store.content(track_id)
self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()))) self._index.replace(projection.to_track(row, kinds.get(str(row.ID), ()),
stem=self._store.is_stem(str(row.ID))))
def close(self) -> None: def close(self) -> None:
"""Release the database connection. """Release the database connection.
@@ -200,8 +203,13 @@ class RekordboxAdapter:
def audio_path(self, track_id: str): def audio_path(self, track_id: str):
return self._store.audio_path(track_id) return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None: def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping) self._store.set_path_mapping(mapping)
# The FILE decides a track's media kind, and the mapping moves files.
self._rebuild()
def unresolved_path_groups(self) -> list: def unresolved_path_groups(self) -> list:
"""Not checked yet: the open-time missing-files check is Traktor-only """Not checked yet: the open-time missing-files check is Traktor-only
@@ -211,6 +219,10 @@ class RekordboxAdapter:
def set_session_mappings(self, mappings: list[PathMapping]) -> None: def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None return None
def set_write_stored_paths(self, enabled: bool) -> None:
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
self._store.set_write_stored_paths(enabled)
def path_prefix_suggestions(self) -> dict: def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths() paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths) primary = common_dir_prefix(paths)
@@ -241,6 +253,12 @@ class RekordboxAdapter:
self._refresh(track_id) self._refresh(track_id)
return self._index.get(track_id) return self._index.get(track_id)
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
self._require_writable("Setting the key")
self._store.set_key(track_id, wheel, mode)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ---------------------------------------------- # ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str: def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists") self._require_writable("Creating playlists")
@@ -299,6 +317,18 @@ class RekordboxAdapter:
self._store.set_cue_type(track_id, slot, cue_type) self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id) return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(
f"{color!r} is not one of Rekordbox's hot cue colours"
)
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues: def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._require_writable("Deleting cues") self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot) self._store.delete_cue(track_id, slot)
@@ -366,6 +396,12 @@ class RekordboxAdapter:
def dirty(self) -> bool: def dirty(self) -> bool:
return self._store.dirty return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._journal.summary()
def save(self): def save(self):
self._require_writable("Saving") self._require_writable("Saving")
return self._store.save() return self._store.save()
@@ -400,19 +436,108 @@ class RekordboxAdapter:
if self._cloud_synced: if self._cloud_synced:
raise Unsupported(self._readonly_reason(what)) raise Unsupported(self._readonly_reason(what))
def add_tracks(self, items: list) -> list[str]: def analysis_lead(self, audio: Path) -> float:
# Not a refusal in principle — Rekordbox could receive imported """The time-base lead `add_tracks` measures a file's waveform with —
# tracks — but adding one means a djmdContent row, its lookup-table rekordbox's clock against the decoded audio, read from the file's
# foreign keys, a USN, and an ANLZ file built from scratch, which header (`timebase.py`). OPTIONAL on the protocol: a platform that does
# is unexplored (see the export handoff). Traktor is the only not analyse what it adds has none, and whoever prepares an analysis
# import target for now. for this one (a client of a server-held library) asks for it."""
self._refuse("Adding tracks") return timebase.offset(Path(audio))
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
Rekordbox keeps the beatgrid AND the waveforms in per-track analysis
files, and shows neither grid nor cues for a track without them — so
unlike Traktor, which re-analyses on load, every file is decoded here.
A file that brings no grid gets one from Konduktor's own detector
(decided 2026-10-01: a track should arrive ready to prep).
Two phases, and the split is the point. FIRST every file is decoded and
analysed, which is slow and may be cancelled through `checkpoint` —
before the library is touched, so a cancel leaves it as it was. THEN
each row is added and its grid and cues replayed through the ordinary
store commands (`replace_grid`, `set_cue`), so an added track inherits
their conventions and tests rather than growing a second copy.
Nothing is lost on the way in: Rekordbox has memory cues and coloured
cues, so both cross as themselves. A hot cue whose pad is out of the
bank or already taken becomes a memory cue at the same position rather
than being dropped.
"""
from ...core import audio_tags
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
prepared = []
total = len(items)
for n, item in enumerate(items, start=1):
audio = Path(item.audio_path)
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or audio.name} ({n}/{total})",
step=n, of=total)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}")
held.add(str(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if item.analysis is not None:
# Measured by whoever added it — a library held by a server is
# never asked to decode audio (see `PreparedAnalysis`).
analysed = item.analysis
if not markers:
markers = list(analysed.markers)
else:
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
detect=not markers,
detect_key=item.track.key_wheel is None)
markers = markers or list(analysed.markers)
measured = analysed.measured
# A file with no key of its own gets one, as it gets a grid
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
track = add_analysis.with_key(item.track, analysed.key)
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
added: list[str] = []
for item, track, audio, measured, markers, art in prepared:
track_id = self._store.add_track(
audio, track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), (),
stem=self._store.is_stem(track_id)))
if markers:
self._store.replace_grid(track_id, markers)
if item.cues is not None:
self._place_imported_cues(track_id, item.cues)
self._refresh(track_id)
added.append(track_id)
return added
def _place_imported_cues(self, track_id: str, cues) -> None:
"""Hot cues on their own pads; memory cues — and a hot cue with no
free pad — as memory cues. Colour as the nearest palette swatch."""
taken: set[int] = set()
for cue in sorted(cues.cues or [], key=lambda c: c.start):
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
code, _rgb = palette.code_for(cue.color)
common = dict(start_sec=cue.start, cue_type=cue_type,
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), color_code=code or None)
slot = cue.slot if cue.role == "hotcue" else None
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
self._store.set_cue(track_id, slot=slot, **common)
taken.add(slot)
else:
self._store.add_memory_cue(track_id, **common)
def remove_tracks(self, track_ids: list[str]) -> int: def remove_tracks(self, track_ids: list[str]) -> int:
# Same shape as adding: a track is a djmdContent row plus its cues, # What goes with a track was measured in Rekordbox 7 — see the store.
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and self._require_writable("Removing tracks")
# which of those Rekordbox expects to be deleted together is unmeasured. n = self._store.remove_tracks(track_ids)
self._refuse("Removing tracks") if n:
self._rebuild()
return n
def apply_stem_swaps(self, swaps, *, add_to_playlist=None): def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
# Rekordbox does not play native-instruments stem files as stems. # Rekordbox does not play native-instruments stem files as stems.
@@ -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) return preview_tags([0.0] * 400, [0.0] * 400)
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None, def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> bytes: 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. """One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
Two constants in here are rekordbox's, not the documented struct's: the Two constants in here are rekordbox's, not the documented struct's: the
`1000` after the kind (the struct calls it padding) and the `1` after 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 colour id. Both appear in every entry of a real export; zeros there were a
guess, and pyrekordbox's parser would never notice one. 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) red, green, blue = rgb or (0, 0, 0)
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
return struct.pack( return struct.pack(
">4sIIIBxHIIBB6xHHI", ">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), 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 # The colour is the palette CODE, then RGB: rekordbox draws from the code
# (`palette`); a code of 0 draws its default colour whatever the RGB says. # (`palette`); a code of 0 draws its default colour whatever the RGB says.
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes( ) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
PCP2_ENTRY_LEN - 48 - len(comment) 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. """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 `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) ) + bytes(16)
def _pcob(cue_type: int, chosen: list[dict]) -> bytes: def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
blob = b"".join( """A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], or new ones from `pcpt_entry`)."""
loop_ms=c["loop_ms"])
for c in chosen
)
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong # cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
# shifts every following field and the reader sees garbage. The last field # 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 # is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
# writes it. # writes it (an export, and rekordbox's own edits, alike).
last = -1 if cue_type == 1 else len(chosen) - 1 last = -1 if cue_type == 1 else len(entries) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob) 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: def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join( return pco2_tag(cue_type, [
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"), loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0)) code=c.get("code", 0), comment=c.get("comment"))
for c in chosen 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]: def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
@@ -404,13 +438,18 @@ def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
_FILE_HEADER_LEN = 28 _FILE_HEADER_LEN = 28
def write_anlz(path: Path, tags: list[bytes]) -> Path: def anlz_bytes(tags: list[bytes]) -> bytes:
"""Assemble and write an ANLZ file from built tag bytes.""" """Assemble an ANLZ file from built tag bytes."""
path.parent.mkdir(parents=True, exist_ok=True)
body = b"".join(tags) body = b"".join(tags)
header = struct.pack( header = struct.pack(
">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body), ">4sIIIIII", b"PMAI", _FILE_HEADER_LEN, _FILE_HEADER_LEN + len(body),
FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0, FILE_HEADER_U1, FILE_HEADER_U2, FILE_HEADER_U3, 0,
) )
path.write_bytes(header + body) return header + body
def write_anlz(path: Path, tags: list[bytes]) -> Path:
"""Assemble and write an ANLZ file from built tag bytes."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(anlz_bytes(tags))
return path return path
@@ -30,6 +30,7 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, TrackCapabilities,
) )
from . import palette
from .cue_types import WRITABLE_CUE_TYPES from .cue_types import WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored # Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
@@ -68,8 +69,10 @@ def capabilities_for(
max_memory_cues=None, # unlimited max_memory_cues=None, # unlimited
# Both cue types write; Rekordbox has no fade/load types. # Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES, types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's 16 swatches (all
# measured, see `palette`), offered in rekordbox's own order.
color="palette", color="palette",
palette=[], # TODO milestone 2: the built-in cue colour table palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # djmdCue.Comment named=True, # djmdCue.Comment
loops="cue_type", loops="cue_type",
), ),
@@ -83,7 +86,12 @@ def capabilities_for(
# column (its Composer is a different field), so they are absent # column (its Composer is a different field), so they are absent
# rather than mapped onto something approximate. # rather than mapped onto something approximate.
editable_fields=sorted(editable_fields or []), editable_fields=sorted(editable_fields or []),
media_kinds=["audio"], # A stem file is held (and played by Rekordbox as its mix);
# Konduktor's deck plays its stems.
media_kinds=["audio", "stem"],
removable=True,
addable=True,
key_writable=True,
artwork=False, artwork=False,
artwork_note=None, artwork_note=None,
), ),
@@ -63,7 +63,7 @@ class RekordboxDriver:
except Exception: # noqa: BLE001 except Exception: # noqa: BLE001
pass pass
def open(self, path: Path) -> RekordboxAdapter: def open(self, path: Path, *, read_only: bool = False) -> RekordboxAdapter:
return RekordboxAdapter(path) return RekordboxAdapter(path)
def detect(self) -> list[dict]: def detect(self) -> list[dict]:
+18 -83
View File
@@ -58,8 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color from ...core.cue_colors import effective_color
from . import anlz_writer as W from . import new_content, palette
from . import artwork, palette
from . import timebase from . import timebase
from .beatgrid import beats_from_markers from .beatgrid import beats_from_markers
from .capabilities import capabilities_for from .capabilities import capabilities_for
@@ -82,15 +81,8 @@ SEED = _FIXTURES / "seed.sql"
#: Rekordbox counts cue positions in frames at 150 fps, not milliseconds. #: Rekordbox counts cue positions in frames at 150 fps, not milliseconds.
FRAMES_PER_SECOND = 150 FRAMES_PER_SECOND = 150
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving #: `djmdContent.ContentLink` — see `new_content`, where its bits are measured.
#: five tracks of a Konduktor-written library different values and loading it CONTENT_LINK = new_content.CONTENT_LINK
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
#: MP3/M4A tracks carry — adds two more bits that draw an extra badge, most
#: likely claiming phrase/vocal analysis this exporter does not write. So the
#: value that claims only what is written: 0x2C060E.
CONTENT_LINK = 2885134
#: Rekordbox's playlist side file, beside master.db. It lists every playlist #: Rekordbox's playlist side file, beside master.db. It lists every playlist
#: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the #: node with a `Timestamp` matching the row's `updated_at` (ms); a playlist the
@@ -319,27 +311,7 @@ class RekordboxExporter:
@staticmethod @staticmethod
def _lookup(db, kind: str, name: str | None): def _lookup(db, kind: str, name: str | None):
"""Find-or-create a lookup row, returning its id. return new_content.lookup(db, kind, name)
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
"""
if not name:
return None
if kind == "key":
found = db.get_key(ScaleName=name).first()
if found is not None:
return found.ID
return _insert_key(db, name)
found = {"artist": db.get_artist, "album": db.get_album,
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
if found is not None:
return found.ID
created = {"artist": db.add_artist, "album": db.add_album,
"genre": db.add_genre, "label": db.add_label}[kind](name)
db.flush()
return created.ID
# ---- analysis --------------------------------------------------------------- # ---- analysis ---------------------------------------------------------------
@@ -350,24 +322,15 @@ class RekordboxExporter:
and the file on disk have to agree — so the same derivation is used here and the file on disk have to agree — so the same derivation is used here
rather than a path of our own choosing. rather than a path of our own choosing.
""" """
track_uuid = str(content.UUID) rel = new_content.anlz_rel(str(content.UUID))
# Rekordbox derives these two levels from the track's UUID, and the
# column and the file have to agree — so the same derivation is used.
rel = f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
content.AnalysisDataPath = rel content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries content.Analysed = 105 # what a rekordbox-analysed track carries
content.AnalysisUpdated = 1 content.AnalysisUpdated = 1
db.flush() db.flush()
# The same three files as a rekordbox-analysed track. The `.DAT` needs
# PVBR and the preview waveforms before rekordbox shows a grid at all
# (measured on a OneLibrary stick; the same Pioneer file here); the
# `.EXT`/`.2EX` carry the drawn waveforms. Cue lists are present but
# EMPTY — master.db keeps cues in djmdCue.
off = timebase.offset(item.destination) off = timebase.offset(item.destination)
measured = item.waveform(lead=off) measured = item.waveform(lead=off)
path = str(item.destination) beats = None
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))]
markers = item.cues.grid_markers if item.cues else [] markers = item.cues.grid_markers if item.cues else []
if markers: if markers:
duration = ((measured.duration if measured else 0.0) duration = ((measured.duration if measured else 0.0)
@@ -377,26 +340,18 @@ class RekordboxExporter:
# Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`). # Onto rekordbox's clock (~25 ms behind on MP3/AAC — `timebase`).
# The cues need no such line: they are replayed through # The cues need no such line: they are replayed through
# `set_cue`, which applies the same offset itself. # `set_cue`, which applies the same offset itself.
tags.append(W.beatgrid_tag( beats = [(n, bpm, timebase.to_pioneer(t, off))
[(n, bpm, timebase.to_pioneer(t, off)) for n, bpm, t in zip(nums, bpms, times)])) for n, bpm, t in zip(nums, bpms, times)]
if measured:
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
tags += W.flat_preview_tags()
ext_waves, two_ex = [], []
tags += W.cue_tags([], extended=False)
# AnalysisDataPath is rooted at a `share` directory BESIDE master.db, # AnalysisDataPath is rooted at a `share` directory BESIDE master.db,
# not at the library root — the read path joins it that way, and writing # not at the library root — the read path joins it that way, and writing
# it anywhere else produces a track whose grid silently reads as empty. # it anywhere else produces a track whose grid silently reads as empty.
dat = root / "share" / rel.lstrip("/") dat = root / "share" / rel.lstrip("/")
written = [ written = []
W.write_anlz(dat, tags), for suffix, data in new_content.anlz_files(item.destination, measured, beats).items():
W.write_anlz(dat.with_suffix(".EXT"), [W.path_tag(path), *ext_waves[:1], target = dat.with_suffix(suffix)
*W.cue_tags([], extended=True), *ext_waves[1:]]), target.parent.mkdir(parents=True, exist_ok=True)
] target.write_bytes(data)
if two_ex: written.append(target)
written.append(W.write_anlz(dat.with_suffix(".2EX"), [W.path_tag(path), *two_ex]))
return written return written
# ---- artwork ------------------------------------------------------------------ # ---- artwork ------------------------------------------------------------------
@@ -412,17 +367,14 @@ class RekordboxExporter:
rooted at `share/` like `AnalysisDataPath`. All measured on a real rooted at `share/` like `AnalysisDataPath`. All measured on a real
Rekordbox 7 library. Rekordbox 7 library.
""" """
if not item.art: files = new_content.artwork_files(item.art[0] if item.art else None)
if files is None:
return [] return []
jpegs = artwork.library_jpegs(item.art[0]) rel = new_content.artwork_rel(str(content.UUID))
if jpegs is None:
return []
track_uuid = str(content.UUID)
rel = f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
folder = root / "share" / rel.lstrip("/") folder = root / "share" / rel.lstrip("/")
folder.mkdir(parents=True, exist_ok=True) folder.mkdir(parents=True, exist_ok=True)
written = [] written = []
for name, data in zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs): for name, data in files.items():
(folder / name).write_bytes(data) (folder / name).write_bytes(data)
written.append(folder / name) written.append(folder / name)
content.ImagePath = f"{rel}/artwork.jpg" content.ImagePath = f"{rel}/artwork.jpg"
@@ -462,20 +414,3 @@ class RekordboxExporter:
db.add_to_playlist(playlist, content) db.add_to_playlist(playlist, content)
db.flush() db.flush()
def _insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL for the same reason the registry row is: the
ORM's DateTime binder raises on the NULLs a real row carries."""
from pyrekordbox.masterdb import models
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
seq = (db.query(models.DjmdKey).count() or 0) + 1
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
{"id": key_id, "name": name, "seq": seq,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
return key_id
@@ -0,0 +1,138 @@
"""A NEW track's rows and files in a `master.db` library.
Shared by the two places a track is created rather than edited: the Rekordbox
Library exporter (a `master.db` from nothing) and `RekordboxStore.add_tracks`
(a track added to the user's own library). One definition, because a track
row, its lookups and its analysis files are the same thing in both, and two
copies would drift.
What a track Rekordbox itself adds looks like was MEASURED (two files dragged
into Rekordbox 7.2's collection, 2026-10-01, every row and file diffed): a
`djmdContent` row, three ANLZ files plus a `.3EX`, the embedded cover as three
JPEGs, one `contentFile` row per file (its `Hash` the file's MD5), and its own
analysis results — key, mixer gain, phrases — which nothing here can produce.
"""
from __future__ import annotations
import uuid as uuidlib
from datetime import datetime
from pathlib import Path
from sqlalchemy import text
from . import anlz_writer as W
from . import artwork
#: `djmdContent.ContentLink` — NOT optional, and a bit field. Measured by giving
#: five tracks of a Konduktor-written library different values and loading it
#: in Rekordbox 7: with it NULL the song-list preview is plain blue with a "?"
#: beside CUE; any value colours the preview; the 0x200000 bit (0x2C060E here,
#: 0x0C060E without it) clears the "?"; and 0x3D060E — what the real library's
#: MP3/M4A tracks carry, and what Rekordbox writes for a track it analyses
#: itself — adds two more bits that draw an extra badge, most likely claiming
#: phrase/vocal analysis Konduktor does not write. So the value that claims
#: only what is written: 0x2C060E.
CONTENT_LINK = 2885134
def anlz_rel(track_uuid: str) -> str:
"""`djmdContent.AnalysisDataPath` for a track. Rekordbox derives it from
the track's UUID, and the column and the file have to agree."""
return f"/PIONEER/USBANLZ/{track_uuid[:3]}/{track_uuid[3:]}/ANLZ0000.DAT"
def artwork_rel(track_uuid: str) -> str:
"""The track's artwork FOLDER — the same UUID split as its analysis."""
return f"/PIONEER/Artwork/{track_uuid[:3]}/{track_uuid[3:]}"
def anlz_files(audio: Path, measured, beats: list | None) -> dict[str, bytes]:
"""The analysis files for a track, by suffix: `.DAT`, `.EXT`, `.2EX`.
The same files as a rekordbox-analysed track. The `.DAT` needs PVBR and the
preview waveforms before rekordbox shows a grid at all (measured on a
OneLibrary stick; the same Pioneer file here); the `.EXT`/`.2EX` carry the
drawn waveforms. Cue lists are present but EMPTY — master.db keeps cues in
djmdCue. `measured` is `waveform.analyse`'s result (None: flat previews).
`beats` is `(beat-in-bar, bpm, seconds)` ON REKORDBOX'S CLOCK; None writes
no `PQTZ`, and `[]` an empty one for `write_pqtz` to fill later.
"""
path = str(audio)
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(audio))]
if beats is not None:
tags.append(W.beatgrid_tag(beats))
if measured:
tags += W.preview_tags(measured.columns.rms, measured.columns.brightness)
ext_waves, two_ex = W.waveform_tags(measured.frames.bands)
else:
tags += W.flat_preview_tags()
ext_waves, two_ex = [], []
tags += W.cue_tags([], extended=False)
out = {
".DAT": W.anlz_bytes(tags),
".EXT": W.anlz_bytes([W.path_tag(path), *ext_waves[:1],
*W.cue_tags([], extended=True), *ext_waves[1:]]),
}
if two_ex:
out[".2EX"] = W.anlz_bytes([W.path_tag(path), *two_ex])
return out
def artwork_files(art: bytes | None) -> dict[str, bytes] | None:
"""The cover as a rekordbox-managed track carries it, by file name.
`artwork.jpg` (the cover, fit to 800 px), `artwork_m.jpg` (240) and
`artwork_s.jpg` (80), the last two letterboxed square; `djmdContent.
ImagePath` names `artwork.jpg`. All measured on a real Rekordbox 7 library.
None when there is no art or it cannot be read.
"""
if not art:
return None
jpegs = artwork.library_jpegs(art)
if jpegs is None:
return None
return dict(zip(("artwork.jpg", "artwork_m.jpg", "artwork_s.jpg"), jpegs))
def lookup(db, kind: str, name: str | None):
"""Find-or-create a lookup row, returning its id.
Lookups are foreign keys; pyrekordbox's `add_*` RAISES on an existing name,
so every one is find-or-create — the same rule the in-place adapter follows.
`djmdKey` is the odd one out twice over: its name column is `ScaleName`,
not `Name`, and pyrekordbox has no `add_key`. So keys are inserted
directly, with a `Seq` that keeps them in wheel order in Rekordbox's UI.
"""
if not name:
return None
if kind == "key":
found = db.get_key(ScaleName=name).first()
if found is not None:
return found.ID
return insert_key(db, name)
found = {"artist": db.get_artist, "album": db.get_album,
"genre": db.get_genre, "label": db.get_label}[kind](Name=name).first()
if found is not None:
return found.ID
created = {"artist": db.add_artist, "album": db.add_album,
"genre": db.add_genre, "label": db.add_label}[kind](name)
db.flush()
return created.ID
def insert_key(db, name: str) -> str:
"""A `djmdKey` row. Raw SQL: the ORM's DateTime binder raises on the NULLs
a real row carries."""
from pyrekordbox.masterdb import models
now = datetime.now().isoformat(sep=" ", timespec="milliseconds")
seq = (db.query(models.DjmdKey).count() or 0) + 1
key_id = str(uuidlib.uuid4().int % 2_147_483_647)
db.session.execute(
text('INSERT INTO "djmdKey" (ID, ScaleName, Seq, UUID, created_at, '
"updated_at) VALUES (:id, :name, :seq, :uuid, :now, :now)"),
{"id": key_id, "name": name, "seq": seq,
"uuid": str(uuidlib.uuid4()), "now": now},
)
db.flush()
return key_id
@@ -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 own palette, one colour per pad, exported to a stick, and read back. Rekordbox
writes the palette's exact RGB beside each code. writes the palette's exact RGB beside each code.
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16 * The teal-green between 0x0E and 0x16 was missed by that measurement, and
(probably code 0x12); a cue that should be it maps to its nearest neighbour. 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 * 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. 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 * **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 0x05: (0x00, 0x70, 0xFF), # light blue
0x09: (0x00, 0xE0, 0xFF), # cyan 0x09: (0x00, 0xE0, 0xFF), # cyan
0x0E: (0x00, 0xFF, 0xA3), # teal 0x0E: (0x00, 0xFF, 0xA3), # teal
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
0x16: (0x1A, 0xFF, 0x00), # green 0x16: (0x1A, 0xFF, 0x00), # green
0x1A: (0x80, 0xFF, 0x00), # lime 0x1A: (0x80, 0xFF, 0x00), # lime
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime 0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
@@ -91,3 +93,27 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
return min(d, 1 - d) return min(d, 1 - d)
best = min((c for c in PALETTE if c != 0x2B), key=hue_gap) best = min((c for c in PALETTE if c != 0x2B), key=hue_gap)
return best, PALETTE[best] return best, PALETTE[best]
#: The swatches a user can pick, in rekordbox's own order — what
#: `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 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}"
def swatch_code(color: str) -> int | None:
"""The code of an EXACT palette colour, else None — for a user's pick, which
must be a swatch, unlike `code_for`'s nearest-hue mapping for exports."""
rgb = _parse(color)
return next((code for code, value in PALETTE.items() if value == rgb), None)
+163
View File
@@ -430,3 +430,166 @@ __all__ = [
"album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row", "album_row", "artist_row", "dsql", "id_string_row", "key_row", "playlist_entry_row",
"playlist_tree_row", "read", "read_dsql", "template", "track_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 from __future__ import annotations
import re from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase from . import beatgrid, palette, timebase
from .cue_types import cue_type, role_and_slot from .cue_types import cue_type, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or # Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
# Open Key notation. Parsing that is platform knowledge and belongs here. # holds whatever text a track's key TAG carried when it was imported, so a real
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I) # stick has "12A" beside "Abm". Parsing therefore accepts every notation.
# 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,
}
def parse_key(key: str | None) -> tuple[int | None, str | None]: def parse_key(key: str | None) -> tuple[int | None, str | None]:
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name.""" """(Camelot wheel position 1-12, mode) for a key name in any notation."""
if not key: return musical_key.parse(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)
# 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 # 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 # 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 # "10m" where the deck expects "Cm". Rendering from the wheel is the only
# correct crossing. Shared with the OneLibrary exporter: same vendor, same # correct crossing. Shared by the adapter and both Pioneer exporters.
# 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()))}
def render_key(wheel: int | None, mode: str | None) -> str | None: 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 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. worse than a blank one, and Pioneer software shows blanks without complaint.
""" """
if not wheel or not (1 <= wheel <= 12): return musical_key.render(wheel, mode, "musical")
return None
if mode == "minor":
name = _MINOR_NAMES.get(wheel)
return f"{name}m" if name else None
return _MAJOR_NAMES.get(wheel)
def _iso_date(value) -> str | None: def _iso_date(value) -> str | None:
@@ -97,10 +64,10 @@ def _name_of(related) -> str | None:
return None return None
def to_track(row, cue_kinds=()) -> Track: def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
"""Project one ``DjmdContent`` row. """Project one ``DjmdContent`` row.
`cue_kinds` is this track's ``(Kind, OutMsec)`` pairs from the store's single `cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
query — passed in rather than read off the row, which would be a per-track query — passed in rather than read off the row, which would be a per-track
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
same definition `to_track_cues` uses, so the table's count and dots agree same definition `to_track_cues` uses, so the table's count and dots agree
@@ -118,12 +85,11 @@ def to_track(row, cue_kinds=()) -> Track:
BPM are precisely the 22 with no grid. BPM are precisely the 22 with no grid.
""" """
chips: list[HotcueChip] = [] chips: list[HotcueChip] = []
for kind, out_msec in cue_kinds: for kind, out_msec, color_code in cue_kinds:
role, slot = role_and_slot(kind) role, slot = role_and_slot(kind)
if role == "hotcue" and slot is not None: if role == "hotcue" and slot is not None:
# Rekordbox's colour is a palette index nobody has decoded yet (see chips.append(HotcueChip(slot=slot, type=cue_type(out_msec),
# `_cue_color`), so no colour is claimed and the UI uses the type's. color=palette.hex_for(color_code)))
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec), color=None))
chips.sort(key=lambda chip: chip.slot) chips.sort(key=lambda chip: chip.slot)
key_name = _name_of(getattr(row, "Key", None)) key_name = _name_of(getattr(row, "Key", None))
wheel, mode = parse_key(key_name) wheel, mode = parse_key(key_name)
@@ -157,7 +123,10 @@ def to_track(row, cue_kinds=()) -> Track:
hotcues=chips, hotcues=chips,
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0, grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
grid_locked=False, # Rekordbox has no per-track grid lock grid_locked=False, # Rekordbox has no per-track grid lock
media_kind="audio", # What the FILE is (`store.is_stem`): Rekordbox itself plays a stem
# file's mix, but Konduktor's deck plays its stems, and the Type column
# must not disagree with the deck.
media_kind="stem" if stem else "audio",
) )
@@ -210,11 +179,6 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
def _cue_color(row) -> str | None: def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE INDEX, not an RGB value. """Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
The generic model carries ``#RRGGBB``, and the built-in palette that index return palette.hex_for(getattr(row, "ColorTableIndex", None))
refers to is not yet known, so no colour is claimed rather than a wrong one
being invented. `capabilities.cues.color` already says "palette", so the UI
knows not to offer a free colour picker.
"""
return None
+437 -74
View File
@@ -37,15 +37,52 @@ from sqlalchemy import func, select, text
from sqlalchemy.exc import OperationalError from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import joinedload from sqlalchemy.orm import joinedload
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome from ...core.adapter import (
InvalidCommand,
LibraryNotSupported,
NotFound,
SaveOutcome,
Unsupported,
)
from ...core.edit_journal import EditJournal 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 . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot from .cue_types import beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
def _file_facts(audio: Path) -> dict:
"""What Rekordbox reads off the file itself for a new track's row."""
from datetime import date
out: dict = {}
try:
st = audio.stat()
born = getattr(st, "st_birthtime", None) or st.st_mtime
out["created"] = date.fromtimestamp(born)
except OSError:
pass
try:
import mutagen
info = mutagen.File(str(audio)).info
out["length"] = int(round(info.length)) if info.length else None
if getattr(info, "bitrate", None):
out["bitrate"] = int(round(info.bitrate / 1000)) # kbps, as Rekordbox stores it
if getattr(info, "sample_rate", None):
out["sample_rate"] = int(info.sample_rate)
if getattr(info, "bits_per_sample", None):
out["bit_depth"] = int(info.bits_per_sample)
except Exception: # noqa: BLE001 — facts are a nicety; the row stands without them
log.debug("could not read %s", audio, exc_info=True)
return out
# Where a track's analysis files live, as `contentFile.Path` spells it.
_ANLZ_ROOT = "/PIONEER/USBANLZ/"
@contextmanager @contextmanager
def rekordbox_probe_suppressed(): def rekordbox_probe_suppressed():
"""Stop `pyrekordbox.commit()` refusing because a Rekordbox process exists. """Stop `pyrekordbox.commit()` refusing because a Rekordbox process exists.
@@ -74,17 +111,25 @@ def _iso_stamp(value) -> str:
return str(value) return str(value)
class RekordboxStore: class RekordboxStore(ReplaceGridCommands):
"""One open Rekordbox library.""" """One open Rekordbox library."""
def __init__(self, path: Path): def __init__(self, path: Path):
self.path = Path(path) self.path = Path(path)
self._mapping = PathMapping() 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._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
self._journal = EditJournal() self._journal = EditJournal()
# Grid edits buffered until save(): ANLZ files are written to disk, so # Grid edits buffered until save(): ANLZ files are written to disk, so
# applying them at command time would break the save contract. # applying them at command time would break the save contract.
self._pending_grids: dict[str, tuple[list, list, list]] = {} self._pending_grids: dict[str, tuple[list, list, list]] = {}
# Analysis/artwork files of removed tracks, `share`-relative, deleted
# by save() AFTER the commit — a failed commit must leave them in place.
self._pending_file_removals: set[str] = set()
# Files of ADDED tracks, `share`-relative path -> bytes, written by
# save() BEFORE the commit (and removed again if it fails).
self._pending_new_files: dict[str, bytes] = {}
self._load() self._load()
# ---- open ------------------------------------------------------------ # ---- open ------------------------------------------------------------
@@ -98,6 +143,7 @@ class RekordboxStore:
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
self._grid_cache.clear() self._grid_cache.clear()
self._stem_cache: dict[str, bool] = {}
self._content_cache: list | None = None self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None self._by_id: dict[str, object] | None = None
@@ -117,6 +163,8 @@ class RekordboxStore:
self.close() self.close()
self._journal = EditJournal() self._journal = EditJournal()
self._pending_grids.clear() self._pending_grids.clear()
self._pending_file_removals.clear()
self._pending_new_files.clear()
self._load() self._load()
def close(self) -> None: def close(self) -> None:
@@ -210,8 +258,9 @@ class RekordboxStore:
raise NotFound(f"No track {track_id!r}") raise NotFound(f"No track {track_id!r}")
return row return row
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None]]]: def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None, int | None]]]:
"""``{track_id: [(Kind, OutMsec), ...]}`` for every live cue, in one query. """``{track_id: [(Kind, OutMsec, ColorTableIndex), ...]}`` for every live
cue, in one query.
Just enough per cue for the library table's count and hotcue dots, Just enough per cue for the library table's count and hotcue dots,
without a per-track round trip. What a ``Kind`` means is decided in the without a per-track round trip. What a ``Kind`` means is decided in the
@@ -220,12 +269,13 @@ class RekordboxStore:
""" """
t = self._tables t = self._tables
rows = self._db.session.execute( rows = self._db.session.execute(
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec) select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec,
t.DjmdCue.ColorTableIndex)
.where(t.DjmdCue.rb_local_deleted == 0) .where(t.DjmdCue.rb_local_deleted == 0)
).all() ).all()
out: dict[str, list[tuple[int | None, int | None]]] = {} out: dict[str, list[tuple[int | None, int | None, int | None]]] = {}
for content_id, kind, out_msec in rows: for content_id, kind, out_msec, color_code in rows:
out.setdefault(str(content_id), []).append((kind, out_msec)) out.setdefault(str(content_id), []).append((kind, out_msec, color_code))
return out return out
def cues(self, track_id: str) -> list: def cues(self, track_id: str) -> list:
@@ -327,6 +377,28 @@ class RekordboxStore:
def set_path_mapping(self, mapping: PathMapping) -> None: def set_path_mapping(self, mapping: PathMapping) -> None:
self._mapping = mapping or PathMapping() 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
cached per path, since the projection asks for every track at open."""
from ...core.stem_file import is_stem_file
path = self.audio_path(track_id)
if path is None:
return False
key = str(path)
if key not in self._stem_cache:
self._stem_cache[key] = is_stem_file(path)
return self._stem_cache[key]
@property @property
def path_mapping(self) -> PathMapping: def path_mapping(self) -> PathMapping:
return self._mapping return self._mapping
@@ -444,6 +516,46 @@ class RekordboxStore:
self._db.flush() self._db.flush()
self._db.session.expire(row) 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 ------------------------------------------------ # ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str): def _playlist(self, node_id: str):
t = self._tables t = self._tables
@@ -517,13 +629,278 @@ class RekordboxStore:
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id)) .filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
.all() .all()
) )
# NOT `remove_from_playlist`: it commits, which wrote an unsaved edit
# to disk (beyond Discard's reach) and raised while Rekordbox ran.
# The list is rebuilt from 1 below, so no renumbering is needed.
for song in existing: for song in existing:
self._db.remove_from_playlist(playlist, song) self._db.delete(song)
self._db.flush()
for n, track_id in enumerate(track_ids, start=1): for n, track_id in enumerate(track_ids, start=1):
self._db.add_to_playlist(playlist, str(track_id), track_no=n) self._db.add_to_playlist(playlist, str(track_id), track_no=n)
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids)) self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
return len(track_ids) return len(track_ids)
# ---- writes: adding tracks ---------------------------------------------
#
# MEASURED, by dragging two files into Rekordbox 7.2's collection and
# diffing (2026-10-01): see `new_content`. Rekordbox fills the row from the
# FILE (size, sample rate, bit rate, and `DateCreated` from the file's
# creation date), stamps it with this library's device, and lists every
# file it writes for the track in `contentFile` with the file's MD5.
def add_track(self, audio: Path, track, *, measured, with_grid: bool,
art: bytes | None) -> str:
"""Add one track's row, return its id. Its analysis files and artwork
are held until save(); its grid and cues are the caller's to replay
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
in the `.DAT` for `replace_grid` to fill."""
from . import new_content
audio = Path(audio)
if not audio.is_file():
raise InvalidCommand(f"No audio file at {audio}")
t = self._tables
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),
Title=track.title or audio.stem,
Length=facts.get("length") or track.length,
BitRate=facts.get("bitrate") or (int(track.bitrate / 1000) if track.bitrate else None),
SampleRate=facts.get("sample_rate"),
BitDepth=facts.get("bit_depth", 16),
Rating=track.rating or 0,
Commnt=track.comment or "",
ReleaseDate=track.release_date or "",
)
year = str(track.release_date or "")[:4]
if year.isdigit():
content.ReleaseYear = int(year)
if facts.get("created"):
content.DateCreated = facts["created"]
content.ArtistID = new_content.lookup(self._db, "artist", track.artist)
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)
# 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)
content.AnalysisDataPath = rel
content.Analysed = 105 # what a rekordbox-analysed track carries
content.AnalysisUpdated = 1
files = new_content.anlz_files(audio, measured, [] if with_grid else None)
for suffix, data in files.items():
self._pending_new_files[str(Path(rel).with_suffix(suffix))] = data
art_files = new_content.artwork_files(art)
if art_files:
folder = new_content.artwork_rel(track_uuid)
for name, data in art_files.items():
self._pending_new_files[f"{folder}/{name}"] = data
content.ImagePath = f"{folder}/artwork.jpg"
self._db.flush()
track_id = str(content.ID)
if self._content_cache is not None and self._by_id is not None:
self._content_cache.append(content)
self._by_id[track_id] = content
self._grid_cache.pop(track_id, None)
self._journal.record("track", "add", track_id)
return track_id
def _write_new_files(self) -> list[Path]:
"""Write added tracks' files; return what was written."""
share = self.path.parent / "share"
written: list[Path] = []
try:
for rel, data in self._pending_new_files.items():
path = share / rel.lstrip("/")
path.parent.mkdir(parents=True, exist_ok=True)
written.append(path) # before the write: a partial file is cleaned too
path.write_bytes(data)
except BaseException:
for path in written:
path.unlink(missing_ok=True)
raise
return written
def _add_content_files(self, written: list[Path]) -> None:
"""One `contentFile` row per file an added track carries, as Rekordbox
writes them: `Hash` is the file's MD5, and its `_m`/`_s` artwork sizes
are not listed."""
import hashlib
from urllib.parse import quote
t = self._tables
share = self.path.parent / "share"
by_folder = {}
for row in self.iter_content():
for rel in (row.AnalysisDataPath, row.ImagePath):
if rel:
by_folder[str(Path(rel).parent)] = row
for path in written:
if path.name in ("artwork_m.jpg", "artwork_s.jpg"):
continue
rel = "/" + path.relative_to(share).as_posix()
row = by_folder.get(str(Path(rel).parent))
if row is None:
continue
self._db.add(t.ContentFile(
ID=f"{row.UUID}_{quote(rel, safe='')}",
ContentID=str(row.ID),
Path=rel,
Hash=hashlib.md5(path.read_bytes()).hexdigest(),
Size=path.stat().st_size,
rb_local_path=str(path),
UUID=str(uuid.uuid4()),
created_at=datetime.now(),
updated_at=datetime.now(),
))
self._db.flush()
# ---- writes: removing tracks -------------------------------------------
#
# MEASURED, by removing a track in Rekordbox 7.2 and diffing every row and
# every file under `share/` (Demo Track 2, 2026-10-01): Rekordbox DELETES
# the rows — it does not set `rb_local_deleted` — from these tables, leaves
# the playlist row itself alone, and deletes the files `contentFile` lists
# (there, the four ANLZ files) together with their emptied folders. That
# track had no artwork, and an Artwork folder holds `_m`/`_s` sizes that
# `contentFile` does not list, so artwork is left in place: an orphaned
# image is harmless, a guessed deletion is not.
_REMOVED_WITH_TRACK = ("DjmdCue", "ContentCue", "ContentFile", "DjmdMixerParam",
"DjmdSongPlaylist")
# Also keyed by ContentID, but empty in the measured library, so what
# Rekordbox does with them is unknown. A track that appears in one is
# refused rather than guessed at.
_UNMEASURED_LINKS = {
"djmdSongHistory": "a History list",
"djmdSongSampler": "the Sampler",
"djmdSongTagList": "the Tag List",
"djmdSongMyTag": "My Tag",
"djmdSongHotCueBanklist": "a Hot Cue Bank List",
"djmdSongRelatedTracks": "Related Tracks",
"djmdSongRequestList": "a request list",
"djmdActiveCensor": "an Active Censor",
"contentActiveCensor": "an Active Censor",
"djmdCloudExportSongPlaylist": "a cloud export",
}
def _unmeasured_links(self, ids: list[str]) -> list[tuple[str, str]]:
"""``(track_id, where)`` for each track named by an unmeasured table."""
params = {f"i{n}": tid for n, tid in enumerate(ids)}
marks = ", ".join(f":{k}" for k in params)
found: list[tuple[str, str]] = []
for table, where in self._UNMEASURED_LINKS.items():
try:
rows = self._db.session.execute(
text(f'SELECT DISTINCT ContentID FROM "{table}" '
f"WHERE ContentID IN ({marks})"), params
).all()
except Exception: # noqa: BLE001 — table absent in this schema version
continue
found += [(str(r[0]), where) for r in rows]
return found
def remove_tracks(self, track_ids: list[str]) -> int:
"""Remove tracks from the library and every playlist; return how many.
Validated as a whole first, so a refused batch changes nothing. The
audio files are never touched; the analysis files go at save().
"""
t = self._tables
self.iter_content()
assert self._by_id is not None
ids = [str(tid) for tid in dict.fromkeys(track_ids) if str(tid) in self._by_id]
if not ids:
return 0
blocked = self._unmeasured_links(ids)
if blocked:
tid, where = blocked[0]
title = self._by_id[tid].Title or tid
more = f" (and {len(blocked) - 1} more)" if len(blocked) > 1 else ""
raise Unsupported(
f"“{title}” is in {where} in Rekordbox{more}, and Konduktor does not "
"yet know how Rekordbox removes a track from there. Remove it in "
"Rekordbox instead — nothing was changed."
)
playlists: set[str] = set()
for tid in ids:
for name in self._REMOVED_WITH_TRACK:
table = getattr(t, name)
for row in self._db.session.query(table).filter(table.ContentID == tid):
if name == "ContentFile" and str(row.Path or "").startswith(_ANLZ_ROOT):
self._pending_file_removals.add(str(row.Path))
elif name == "DjmdSongPlaylist":
playlists.add(str(row.PlaylistID))
self._db.delete(row)
self._db.delete(self._by_id[tid])
self._pending_grids.pop(tid, None)
self._grid_cache.pop(tid, None)
self._journal.record("track", "remove", tid)
self._db.flush()
for playlist_id in playlists:
self._renumber(playlist_id)
self._content_cache = None
self._by_id = None
return len(ids)
def _renumber(self, playlist_id: str) -> None:
"""Close the gaps removed entries left in a playlist's `TrackNo`s, as
`pyrekordbox.remove_from_playlist` does — one 'move' for the registry,
not an update per row."""
t = self._tables
moved = []
now = datetime.now()
rows = (
self._db.session.query(t.DjmdSongPlaylist)
.filter(t.DjmdSongPlaylist.PlaylistID == playlist_id)
.order_by(t.DjmdSongPlaylist.TrackNo)
)
with self._db.registry.disabled():
for n, row in enumerate(rows, start=1):
if row.TrackNo != n:
row.TrackNo = n
row.updated_at = now
moved.append(row)
if moved:
self._db.registry.on_move(moved)
def _delete_removed_files(self) -> None:
"""Delete removed tracks' analysis/artwork files, then their emptied
folders. Called after the commit; a file another track still lists is
kept, and a failure only leaves an orphan behind, so it is logged."""
t = self._tables
share = (self.path.parent / "share").resolve()
still_listed = {str(p) for (p,) in self._db.session.query(t.ContentFile.Path)}
for rel in sorted(self._pending_file_removals - still_listed):
parts = Path(rel.lstrip("/\\")).parts
path = (share / Path(*parts)).resolve()
# Folders below e.g. `PIONEER/USBANLZ` are the track's own; that
# level and above are Rekordbox's and stay even when emptied.
keep = (share / Path(*parts[:2])).resolve()
if len(parts) < 3 or keep not in path.parents:
continue
try:
path.unlink(missing_ok=True)
folder = path.parent
while folder != keep and not any(folder.iterdir()):
folder.rmdir()
folder = folder.parent
except OSError as ex:
log.warning("Could not delete %s: %s", path, ex)
self._pending_file_removals.clear()
# ---- save -------------------------------------------------------------- # ---- save --------------------------------------------------------------
@property @property
def dirty(self) -> bool: def dirty(self) -> bool:
@@ -546,9 +923,20 @@ class RekordboxStore:
""" """
summary = self._journal.summary() summary = self._journal.summary()
# Files first: if an analysis file cannot be written, nothing should have # Files first: if an analysis file cannot be written, nothing should have
# been committed to the database either. # been committed to the database either. An added track's files go
self._flush_grids() # before the grids, which write into them, and their `contentFile`
self._commit() # rows after, which hash what was finally written.
written = self._write_new_files()
try:
self._flush_grids()
self._add_content_files(written)
self._commit()
except BaseException:
for path in written:
path.unlink(missing_ok=True)
raise
self._pending_new_files.clear()
self._delete_removed_files()
self._journal.clear() self._journal.clear()
# Reads go through the same session, so nothing needs re-projecting from # Reads go through the same session, so nothing needs re-projecting from
# scratch — but the grid cache is keyed by track and survives a save. # scratch — but the grid cache is keyed by track and survives a save.
@@ -669,13 +1057,17 @@ class RekordboxStore:
) -> None: ) -> None:
"""Create or replace the cue in `slot`. A loop is a cue with a length. """Create or replace the cue in `slot`. A loop is a cue with a length.
`color_code` is a rekordbox palette code (`palette.PALETTE`); None or 0 `color_code` is a rekordbox palette code (`palette.PALETTE`). None KEEPS
writes the uncoloured convention, which is what every edit through the the colour of the cue already in the slot — the colour belongs to the
adapter does — only the exporter passes a colour. pad, so a rename, a type change or an Auto Hotcues Replace leaves it as
the user set it — and a new cue is uncoloured. Only `set_cue_color`
clears one.
""" """
if int(slot) < 0: if int(slot) < 0:
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}") raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
existing = self._cue_row(track_id, slot) existing = self._cue_row(track_id, slot)
if color_code is None and existing is not None:
color_code = existing.ColorTableIndex or None
self._write_cue( self._write_cue(
track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec, track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code, cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
@@ -748,26 +1140,44 @@ class RekordboxStore:
cue.BeatLoopSize = beat_loop_size(beats) if beats else None cue.BeatLoopSize = beat_loop_size(beats) if beats else None
cue.ActiveLoop = 0 cue.ActiveLoop = 0
cue.CueMicrosec = 0 cue.CueMicrosec = 0
cue.Color = 255
cue.ColorTableIndex = 0
else: else:
cue.BeatLoopSize = None cue.BeatLoopSize = None
cue.ActiveLoop = None cue.ActiveLoop = None
cue.CueMicrosec = None cue.CueMicrosec = None
cue.Color = -1 self._apply_color(cue, color_code, is_loop)
cue.ColorTableIndex = None
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. How rekordbox stores a
# COLOURED LOOP is not in the reference library; the same column is
# assumed and is what the smoke test checks.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
cue.Comment = name or None cue.Comment = name or None
self._db.flush() self._db.flush()
self._sync_content_cue(track_id) self._sync_content_cue(track_id)
@staticmethod
def _apply_color(cue, color_code: int | None, is_loop: bool) -> None:
"""A row's two colour columns — the one definition of both conventions."""
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. Coloured loops store the
# same; verified in Rekordbox 7 through the master.db export.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
elif is_loop:
# What Rekordbox writes on the loops and auto-cues it creates.
cue.Color = 255
cue.ColorTableIndex = 0
else:
cue.Color = -1
cue.ColorTableIndex = None
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
colour columns, so the position does not take a time-base round trip."""
cue = self._cue_row(track_id, slot)
if cue is None:
raise NotFound(f"No cue in slot {slot}")
self._apply_color(cue, color_code, (cue.OutMsec or 0) > 0)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None: def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
cue = self._cue_row(track_id, slot) cue = self._cue_row(track_id, slot)
if cue is None: if cue is None:
@@ -930,53 +1340,6 @@ class RekordboxStore:
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0 row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
self._journal.record("grid", "replace" if ordered else "delete", track_id) 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: def _flush_grids(self) -> None:
"""Write buffered grids into their ANLZ files. Called by save(). """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,446 @@
"""`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,
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 .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]] = {}
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 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"))
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)."""
self._uploads.pop(str(path), None)
self.client.delete_upload(str(path))
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)
for n, item in enumerate(items, start=1):
key = str(item.audio_path)
source, lead = self._uploads.get(key, (None, None))
analysis = item.analysis
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 item in items:
self._uploads.pop(str(item.audio_path), 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
# ---- 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
+302
View File
@@ -0,0 +1,302 @@
"""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 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
@@ -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")
+29 -2
View File
@@ -15,7 +15,7 @@ from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from types import SimpleNamespace 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.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues from ...core.model import PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping from ...core.pathmap import PathMapping
@@ -146,6 +146,12 @@ class TraktorAdapter:
self._refresh(track_id) self._refresh(track_id)
return self._index.get(track_id) return self._index.get(track_id)
def set_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: def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
with _translate(): with _translate():
self._store.set_track_art(track_id, data, mime) self._store.set_track_art(track_id, data, mime)
@@ -173,7 +179,7 @@ class TraktorAdapter:
return result return result
# ---- adding tracks ---------------------------------------------------- # ---- adding tracks ----------------------------------------------------
def add_tracks(self, items: list) -> list[str]: def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep. """Add tracks that came from somewhere else, with their prep.
Two steps, and the split is the point. The store creates a bare ENTRY — Two steps, and the split is the point. The store creates a bare ENTRY —
@@ -195,6 +201,7 @@ class TraktorAdapter:
type, so a free RGB value has nowhere to go. type, so a free RGB value has nowhere to go.
Returns the new track ids, in the order the items were given. Returns the new track ids, in the order the items were given.
`checkpoint` is unused: nothing here is slow (Traktor analyses on load).
""" """
added: list[str] = [] added: list[str] = []
for item in items: for item in items:
@@ -298,6 +305,10 @@ class TraktorAdapter:
self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type)) self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type))
return self._refresh(track_id) return self._refresh(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
# Traktor colours a cue by its type (capabilities.cues.color = "none").
raise Unsupported("Traktor colours cues by their type")
def delete_cue(self, track_id: str, slot: int) -> TrackCues: def delete_cue(self, track_id: str, slot: int) -> TrackCues:
with _translate(): with _translate():
self._store.delete_hotcue(track_id, slot) self._store.delete_hotcue(track_id, slot)
@@ -372,12 +383,22 @@ class TraktorAdapter:
def audio_path(self, track_id: str): def audio_path(self, track_id: str):
return self._store.audio_path(track_id) return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None: def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping) self._store.set_path_mapping(mapping)
def set_session_mappings(self, mappings: list[PathMapping]) -> None: def set_session_mappings(self, mappings: list[PathMapping]) -> None:
self._store.set_session_mappings(mappings) 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]: def unresolved_path_groups(self) -> list[PathGroup]:
return self._store.unresolved_path_groups() return self._store.unresolved_path_groups()
@@ -400,6 +421,12 @@ class TraktorAdapter:
def dirty(self) -> bool: def dirty(self) -> bool:
return self._store.dirty return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._edit_summary()
def save(self): def save(self):
outcome = self._store.save() outcome = self._store.save()
self._rebuild() # save() re-parses, so every object identity changed self._rebuild() # save() re-parses, so every object identity changed
@@ -49,7 +49,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
# Traktor has no memory cues — every cue occupies a bank slot. # Traktor has no memory cues — every cue occupies a bank slot.
memory_cues=False, memory_cues=False,
types=CUE_TYPES, types=CUE_TYPES,
color="free", # Traktor colours a cue by its TYPE; the only COLOR it stores is a
# grid marker's white companion, so there is nothing to pick.
color="none",
named=True, named=True,
# A saved loop is a cue TYPE in Traktor, not a separate bank. # A saved loop is a cue TYPE in Traktor, not a separate bank.
loops="cue_type", loops="cue_type",
@@ -60,7 +62,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable_fields=sorted(editable_fields), editable_fields=sorted(editable_fields),
media_kinds=["audio", "stem"], media_kinds=["audio", "stem"],
removable=True, removable=True,
addable=True,
stem_convertible=True, stem_convertible=True,
key_writable=True,
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA, # `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both. # but only on Windows, and a file added on one OS must play on both.
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"], audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
+1 -1
View File
@@ -25,7 +25,7 @@ class TraktorDriver:
return False return False
return b"<NML" in head and b"VERSION=" in head 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) return TraktorAdapter(path)
def detect(self) -> list[dict]: def detect(self) -> list[dict]:
@@ -7,15 +7,14 @@ from __future__ import annotations
import re import re
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase from . import beatgrid, timebase
from .cue_types import NATIVE_TO_CUE_TYPE from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"), # Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
# depending on a user preference — so the library can contain either. Parsing # depending on a user preference, and INFO@KEY also holds whatever a file's key
# notation is platform knowledge and belongs here, not in the UI. # tag said ("Gm", "Amin") — so every notation is parsed (`core/musical_key`).
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$") _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 # "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
# timestamp's date part is the date). # 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]: 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). def musical_key_value(wheel: int, mode: str) -> int:
""" """`<MUSICAL_KEY VALUE>`: the tonic's pitch class (C = 0), plus 12 for minor
if not key: — 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 return None, None
k = key.strip() mode = "minor" if value >= 12 else "major"
if m := _CAMELOT.match(k): return musical_key.wheel_of(value % 12, mode), mode
n = int(m.group(1))
if 1 <= n <= 12:
return n, "minor" if m.group(2).lower() == "a" else "major" def entry_key(e) -> tuple[str | None, int | None, str | None]:
if m := _OPEN_KEY.match(k): """(display string, wheel, mode) for an ENTRY.
n = int(m.group(1))
if 1 <= n <= 12: INFO@KEY is the text Traktor shows and writes to the file's tag; the
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major" analysed key itself is `<MUSICAL_KEY>`. 1,354 of the real collection's
return None, None 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: def iso_date(value: str | None) -> str | None:
@@ -122,7 +140,7 @@ def to_track(e) -> Track:
), ),
key=lambda chip: chip.slot, key=lambda chip: chip.slot,
) )
wheel, mode = parse_key(info.key if info else None) key_text, wheel, mode = entry_key(e)
return Track( return Track(
id=primary_key(loc) if loc else (e.title or ""), id=primary_key(loc) if loc else (e.title or ""),
artist=e.artist, artist=e.artist,
@@ -137,7 +155,7 @@ def to_track(e) -> Track:
# Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING). # Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING).
comment2=info.rating if info else None, comment2=info.rating if info else None,
bpm=beatgrid.effective_bpm(e), bpm=beatgrid.effective_bpm(e),
key=info.key if info else None, key=key_text,
key_wheel=wheel, key_wheel=wheel,
key_mode=mode, key_mode=mode,
rating=_rating_stars(info.ranking if info else None), rating=_rating_stars(info.ranking if info else None),
+99 -17
View File
@@ -22,7 +22,6 @@ import copy
import math import math
import threading import threading
import uuid as uuidlib import uuid as uuidlib
from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from traktor_nml_utils import ( from traktor_nml_utils import (
@@ -36,6 +35,7 @@ from traktor_nml_utils.models.collection import (
Entrytype, Entrytype,
GridType, GridType,
Infotype, Infotype,
MusicalKeytype,
Locationtype, Locationtype,
Nodetype, Nodetype,
Playlisttype, Playlisttype,
@@ -46,16 +46,17 @@ from traktor_nml_utils.models.collection import (
) )
from xsdata.formats.dataclass.serializers import XmlSerializer 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.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix 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.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode from ...schemas import PlaylistNode
from . import beatgrid, timebase from . import beatgrid, timebase
from .locations import os_path_to_location, resolve_path 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 # Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
# this email is what makes the stars show up in Traktor itself. # this email is what makes the stars show up in Traktor itself.
@@ -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: class TraktorStore:
def __init__(self, nml_path: Path): def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path) self.nml_path = Path(nml_path)
@@ -87,6 +79,9 @@ class TraktorStore:
self.dirty = False self.dirty = False
# Active OS-path prefix remapping (empty = identity). Survives _load(). # Active OS-path prefix remapping (empty = identity). Survives _load().
self._path_mapping = PathMapping() 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. # Mappings the user confirmed in the open-time missing-files check.
# Session-only: never saved, re-derived on every open. # Session-only: never saved, re-derived on every open.
self._session_mappings: list[PathMapping] = [] self._session_mappings: list[PathMapping] = []
@@ -109,6 +104,7 @@ class TraktorStore:
self._journal = EditJournal() self._journal = EditJournal()
# track_id -> (image_bytes, mime) of staged replacement cover art # track_id -> (image_bytes, mime) of staged replacement cover art
self._track_art: dict[str, tuple[bytes, str]] = {} self._track_art: dict[str, tuple[bytes, str]] = {}
self._notation: str | None = None
self.dirty = False self.dirty = False
def _note( def _note(
@@ -409,6 +405,69 @@ class TraktorStore:
self._journal.record("track", "set", track_id, k) self._journal.record("track", "set", track_id, k)
self.dirty = True 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 -------------------------------------------------- # ---- adding tracks --------------------------------------------------
def add_entry(self, track, audio_path: Path) -> str: def add_entry(self, track, audio_path: Path) -> str:
"""Append a brand-new ENTRY for `audio_path` and return its track id. """Append a brand-new ENTRY for `audio_path` and return its track id.
@@ -429,9 +488,16 @@ class TraktorStore:
and ``loudness``. Both are outputs of Traktor's own analysis and cannot and ``loudness``. Both are outputs of Traktor's own analysis and cannot
be computed here; Traktor re-analyses a track that has none. Writing a be computed here; Traktor re-analyses a track that has none. Writing a
plausible-looking fingerprint would be inventing data. plausible-looking fingerprint would be inventing data.
A stem FILE gets ``<STEMS>``, rendered from its own ``stem`` box as
Traktor renders it: that element is what makes the entry a stem track
(its playlist keys ``TYPE="STEM"``, the Type column), and without it a
stem file added here read as plain audio.
""" """
# Read before the lock: it opens the file.
stems = nml_stems_for(audio_path)
with self._lock: 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}" key = f"{volume}{dir_}{file}"
if key in self._entry_by_key: if key in self._entry_by_key:
raise PlaylistError( raise PlaylistError(
@@ -446,7 +512,7 @@ class TraktorStore:
remixer=getattr(track, "remixer", None) or None, remixer=getattr(track, "remixer", None) or None,
producer=getattr(track, "producer", None) or None, producer=getattr(track, "producer", None) or None,
mix=getattr(track, "mix", 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, bitrate=getattr(track, "bitrate", None) or None,
playcount=getattr(track, "playcount", None) or None, playcount=getattr(track, "playcount", None) or None,
# The generic model carries ISO dates; Traktor writes "YYYY/M/D". # The generic model carries ISO dates; Traktor writes "YYYY/M/D".
@@ -472,7 +538,14 @@ class TraktorStore:
# projected BPM so a track with no grid still shows a tempo; # projected BPM so a track with no grid still shows a tempo;
# `replace_grid` overwrites it from the markers when they land. # `replace_grid` overwrites it from the markers when they land.
tempo=Tempotype(bpm=float(bpm)) if bpm else None, 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=[], cue_v2=[],
stems=Stemstype(stems=stems) if stems else None,
) )
self._nml.collection.entry.append(entry) self._nml.collection.entry.append(entry)
self._entry_by_key[key] = entry self._entry_by_key[key] = entry
@@ -990,6 +1063,15 @@ class TraktorStore:
with self._lock: with self._lock:
self._path_mapping = mapping 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: def set_session_mappings(self, mappings: list[PathMapping]) -> None:
"""Set the mappings confirmed for this session (applied at resolve time).""" """Set the mappings confirmed for this session (applied at resolve time)."""
with self._lock: with self._lock:
@@ -1285,7 +1367,7 @@ class TraktorStore:
if swap.mode not in ("repoint", "add"): if swap.mode not in ("repoint", "add"):
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}") raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
seen_ids.add(swap.track_id) 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) new_key = "".join(x or "" for x in loc)
if new_key in self._entry_by_key or new_key in new_keys: if new_key in self._entry_by_key or new_key in new_keys:
raise PlaylistError( raise PlaylistError(
+111 -24
View File
@@ -28,11 +28,12 @@ import os
import threading import threading
from pathlib import Path 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 import registry
from .core.adapter import LibraryAdapter from .core.adapter import LibraryAdapter
from .core.pathmap import PathMapping from .core.pathmap import PathMapping
from .relocation import RelocationCheck from .relocation import RelocationCheck
from .services import LibraryServices, LocalServices
class AppState: class AppState:
@@ -57,6 +58,22 @@ class AppState:
# the middle of another would commit a half-applied state; reentrant so # the middle of another would commit a half-applied state; reentrant so
# one of them may call another. # one of them may call another.
self.mutation = threading.RLock() self.mutation = threading.RLock()
# Converted-to-stem tracks awaiting Save or Discard (see stems/pending.py),
# 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 @property
def loaded(self) -> bool: def loaded(self) -> bool:
@@ -75,7 +92,7 @@ class AppState:
rests on, and an adapter is the thing that knows whether it is true — rests on, and an adapter is the thing that knows whether it is true —
so it is asserted here rather than assumed everywhere else. 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 adapter.capabilities().writable:
if hasattr(adapter, "close"): if hasattr(adapter, "close"):
try: try:
@@ -83,7 +100,7 @@ class AppState:
except Exception: # noqa: BLE001 except Exception: # noqa: BLE001
pass pass
raise ValueError( 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" "(such as a OneLibrary drive) can be opened as a source"
) )
self.close_source() self.close_source()
@@ -116,21 +133,13 @@ class AppState:
# write-ahead log beside a file another process replaces is how a SQLite # 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 # library gets corrupted. Only close once the new one has parsed, so a
# failed open leaves the current library intact. # failed open leaves the current library intact.
previous = self.adapter self._release_previous()
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
# Apply this library's saved OS-path remapping (per-machine, keyed by the # Apply this library's saved OS-path remapping (per-machine, keyed by the
# library's local path) so runtime translation is live on open. # library's local path) so runtime translation is live on open.
saved = prefs.get_path_mapping(str(path)) saved = prefs.get_path_mapping(str(path))
if saved: if saved:
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
self.path, self.adapter = path, adapter self.path, self.adapter = path, adapter
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(adapter)
caps = adapter.capabilities() caps = adapter.capabilities()
# No sidecar beside a removable library: writing to a user's USB stick to # No sidecar beside a removable library: writing to a user's USB stick to
# satisfy Konduktor's own bookkeeping is not a trade worth making. Those # satisfy Konduktor's own bookkeeping is not a trade worth making. Those
@@ -144,9 +153,67 @@ class AppState:
label=Path(str(path)).name, label=Path(str(path)).name,
sidecar=not getattr(driver, "removable", False), sidecar=not getattr(driver, "removable", False),
) )
# Version history: record an "as I found it" baseline (deduped, so # A crash may have left converted tracks mid-lifecycle: settle them from
# re-opening an unchanged library is a no-op). Best-effort. # what the SAVED library says, BEFORE the missing-files check — a parked
history.ensure_baseline(path) # original is exactly what that check would report as missing.
from .stems.pending import Pending
self.pending = Pending(self.library_id)
self.recovery = None
if self.pending.items:
self.recovery = self.pending.recover(lambda item: adapter.track(item["new_id"]) is not None)
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(adapter)
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): def save(self):
"""Write the library, then record the saved bytes in version history. """Write the library, then record the saved bytes in version history.
@@ -161,15 +228,16 @@ class AppState:
def _save(self): def _save(self):
outcome = self.adapter.save() outcome = self.adapter.save()
# Not every platform is versioned. A library that is more than one file commit = self.services.commit_save(self.adapter, outcome)
# has no single blob that IS the library, and it says so through its # The swap is now on disk: what it replaced can go. After the library
# capabilities rather than this module knowing which platforms those are. # write, so a failed save deletes nothing; here rather than in the save
versioned = self.adapter.capabilities().save.history # route, because import and path remap save too.
commit = None if self.pending is not None and self.pending.swapped():
if versioned and outcome.snapshot is not None: renames = self.pending.commit()
commit = history.commit( if renames and self.library_id:
self.path, outcome.snapshot, outcome.summary, __version__ from . import exports
)
exports.retarget(self.library_id, renames)
return outcome, commit return outcome, commit
def discard(self) -> None: def discard(self) -> None:
@@ -181,8 +249,27 @@ class AppState:
""" """
assert self.adapter is not None assert self.adapter is not None
with self.mutation: 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() 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() STATE = AppState()
+116 -4
View File
@@ -28,6 +28,21 @@ from .pathmap import PathMapping
from .relocate import PathGroup 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 @dataclass
class SaveOutcome: class SaveOutcome:
"""What a save produced, in terms every platform can answer. """What a save produced, in terms every platform can answer.
@@ -50,6 +65,60 @@ class SaveOutcome:
tag_results: list = field(default_factory=list) 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 @dataclass
class NewTrack: class NewTrack:
"""A track to ADD to a library, described generically. """A track to ADD to a library, described generically.
@@ -73,6 +142,14 @@ class NewTrack:
track: Track track: Track
audio_path: Path audio_path: Path
cues: TrackCues | None = None cues: TrackCues | None = None
# The cover as the SOURCE library shows it — `(bytes, mime)` from its
# `cover_art` — since a library's art is not always embedded in the file.
# 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) @dataclass(frozen=True)
@@ -133,6 +210,11 @@ class Unsupported(AdapterError):
"""The platform cannot represent this edit at all.""" """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 @runtime_checkable
class LibraryAdapter(Protocol): class LibraryAdapter(Protocol):
"""One open library. Stateful; exactly one is loaded at a time.""" """One open library. Stateful; exactly one is loaded at a time."""
@@ -152,6 +234,7 @@ class LibraryAdapter(Protocol):
def facets(self) -> Facets: ... def facets(self) -> Facets: ...
def stats(self, playlist_count: int) -> Stats: ... def stats(self, playlist_count: int) -> Stats: ...
def playlist_tree(self) -> list[PlaylistNode]: ... def playlist_tree(self) -> list[PlaylistNode]: ...
def playlist_count(self) -> int: ...
def playlist_entries(self, node_id: str) -> list[str] | None: ... def playlist_entries(self, node_id: str) -> list[str] | None: ...
def playlist_tracks(self, node_id: str) -> list[Track] | None: ... def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
def track_cues(self, track_id: str) -> TrackCues | None: ... def track_cues(self, track_id: str) -> TrackCues | None: ...
@@ -173,12 +256,25 @@ class LibraryAdapter(Protocol):
# fidelity guarantee hold. A new entry has no parsed original, so the rule # fidelity guarantee hold. A new entry has no parsed original, so the rule
# becomes "an added entry must not perturb any existing one" — which is # becomes "an added entry must not perturb any existing one" — which is
# what `test_save_fidelity.py` checks rather than taking on trust. # what `test_save_fidelity.py` checks rather than taking on trust.
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ... #
# `checkpoint(message, step, of)` is called before each slow step (a
# platform that must ANALYSE what it adds, like Rekordbox, decodes every
# file) and may raise to cancel; it is only ever called before the library
# 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 # 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. # entry naming a track the library no longer has is a dangling reference.
# Never touches audio files. Returns how many were removed; gated on # Never touches audio files, except where `tracks.places_audio` (a stick's
# `capabilities().tracks.removable`. # 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: ... def remove_tracks(self, track_ids: list[str]) -> int: ...
# Swap converted stem files into the library (see `StemSwap`), all at once: # Swap converted stem files into the library (see `StemSwap`), all at once:
@@ -190,6 +286,10 @@ class LibraryAdapter(Protocol):
# ---- commands: track metadata / art --------------------------------- # ---- commands: track metadata / art ---------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ... 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 set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ... def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
@@ -206,6 +306,9 @@ class LibraryAdapter(Protocol):
name: str | None = None, name: str | None = None,
) -> TrackCues: ... ) -> TrackCues: ...
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ... def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ...
# `color` is "#RRGGBB" from `capabilities().cues.palette`, or None for the
# platform's uncoloured cue. Any other cue command keeps a slot's colour.
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ... def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ... def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
@@ -220,7 +323,12 @@ class LibraryAdapter(Protocol):
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ... def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
# ---- audio / paths --------------------------------------------------- # ---- 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_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: ... def set_path_mapping(self, mapping: PathMapping) -> None: ...
# The open-time missing-files check (`core/relocate.py`): the stored volumes # 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 — # in which NO track resolves, and the mappings the user confirmed for them —
@@ -260,7 +368,11 @@ class LibraryDriver(Protocol):
selects: str selects: str
def can_open(self, path: Path) -> bool: ... 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 # 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 — # 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 # 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). # The safe, editable metadata we sync to files (the adapter's editable field set).
# rating is 0–5 stars. # rating is 0–5 stars.
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer, 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 @dataclass
@@ -170,6 +173,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
TDRC, TDRC,
TIT2, TIT2,
TIT3, TIT3,
TKEY,
TPE1, TPE1,
TPE4, TPE4,
TPUB, TPUB,
@@ -185,6 +189,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
"remixer": TPE4, "remixer": TPE4,
"mix": TIT3, "mix": TIT3,
"release_date": TDRC, "release_date": TDRC,
"key": TKEY,
} }
for field, frame in simple.items(): for field, frame in simple.items():
if field in meta: if field in meta:
@@ -262,7 +267,8 @@ def _write_mp4(path: Path, meta: TagMeta) -> None:
else: else:
t[atom] = [val] t[atom] = [val]
# No standard MP4 atoms for these — use iTunes-style freeform atoms. # 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(): for field, name in freeform.items():
if field in meta: if field in meta:
key = f"----:com.apple.iTunes:{name}" key = f"----:com.apple.iTunes:{name}"
@@ -297,6 +303,7 @@ def _write_flac(path: Path, meta: TagMeta) -> None:
"comment": "comment", "comment": "comment",
"mix": "mixname", "mix": "mixname",
"release_date": "date", "release_date": "date",
"key": "initialkey",
} }
for field, vc in mapping.items(): for field, vc in mapping.items():
if field in meta: if field in meta:
+41 -2
View File
@@ -22,7 +22,15 @@ from pydantic import BaseModel
# permanent refusal protecting their other machines. # permanent refusal protecting their other machines.
# `not_in_library` is a folder of loose files being browsed: nothing there is a # `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. # 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"] CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"] CueRole = Literal["hotcue", "memory"]
@@ -61,17 +69,37 @@ class TrackCapabilities(BaseModel):
editable_fields: list[str] = [] editable_fields: list[str] = []
media_kinds: list[MediaKind] = ["audio"] media_kinds: list[MediaKind] = ["audio"]
# Tracks can be removed from the library (and so from its playlists). The # 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 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 # Tracks can be converted to native-instruments STEM files, which this
# platform plays as stems (`apply_stem_swaps`). # platform plays as stems (`apply_stem_swaps`).
stem_convertible: bool = False 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 # 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 # browsed folder offers to add — a file the library would refuse, or that
# the DJ app cannot play, is not worth listing as addable. # the DJ app cannot play, is not worth listing as addable.
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"] audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
artwork: bool = False artwork: bool = False
artwork_note: str | None = None 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): class PlaylistCapabilities(BaseModel):
@@ -80,6 +108,13 @@ class PlaylistCapabilities(BaseModel):
reorder: bool = False reorder: 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): class SaveCapabilities(BaseModel):
"""Structured facts, never finished sentences. """Structured facts, never finished sentences.
@@ -92,6 +127,9 @@ class SaveCapabilities(BaseModel):
library_label: str library_label: str
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none" overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
history: bool = True 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): class Capabilities(BaseModel):
@@ -111,4 +149,5 @@ class Capabilities(BaseModel):
grid: GridCapabilities = GridCapabilities() grid: GridCapabilities = GridCapabilities()
tracks: TrackCapabilities = TrackCapabilities() tracks: TrackCapabilities = TrackCapabilities()
playlists: PlaylistCapabilities = PlaylistCapabilities() playlists: PlaylistCapabilities = PlaylistCapabilities()
paths: PathCapabilities = PathCapabilities()
save: SaveCapabilities save: SaveCapabilities
+9 -2
View File
@@ -31,6 +31,7 @@ from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
from .model import PlaylistNode, Track, TrackCues from .model import PlaylistNode, Track, TrackCues
from .places import is_hidden from .places import is_hidden
from .stem_file import is_stem_file
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -59,7 +60,8 @@ def _bpm(tags) -> float | None:
def read_track(path: Path) -> Track: def read_track(path: Path) -> Track:
"""Project one audio file. Never raises: an unreadable tag is an untitled track.""" """Project one audio file. Never raises: an unreadable tag is an untitled track."""
track = Track(id=str(path), title=path.stem, filepath=str(path)) track = Track(id=str(path), title=path.stem, filepath=str(path),
media_kind="stem" if is_stem_file(path) else "audio")
try: try:
import mutagen import mutagen
@@ -112,7 +114,7 @@ def capabilities_for(folder: Path) -> Capabilities:
platform="folder", platform="folder",
writable=False, writable=False,
readonly_cause="not_in_library", readonly_cause="not_in_library",
tracks=TrackCapabilities(editable_fields=[], artwork=False), tracks=TrackCapabilities(editable_fields=[], artwork=False, media_kinds=["audio", "stem"]),
save=SaveCapabilities( save=SaveCapabilities(
app_name="Files", app_name="Files",
library_label=folder.name or str(folder), library_label=folder.name or str(folder),
@@ -148,6 +150,11 @@ class FolderSource:
def audio_path(self, track_id: str) -> Path | None: def audio_path(self, track_id: str) -> Path | None:
return Path(track_id) if track_id in self._by_id else 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]: def playlist_tree(self) -> list[PlaylistNode]:
return [] return []
+50 -11
View File
@@ -213,12 +213,27 @@ def detect_grid(
*, *,
y: np.ndarray | None = None, y: np.ndarray | None = None,
sr: int = _SR, sr: int = _SR,
bpm: float | None = None,
anchor: float | None = None,
) -> GridResult: ) -> GridResult:
"""Detect a track's constant tempo and first beat. """Detect a track's constant tempo and first beat.
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly. ``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). 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: if y is None:
import librosa import librosa
y, sr = librosa.load(audio_path, sr=sr, mono=True) y, sr = librosa.load(audio_path, sr=sr, mono=True)
@@ -227,10 +242,42 @@ def detect_grid(
if duration < 1.5: if duration < 1.5:
raise ValueError("Track is too short to detect a tempo") raise ValueError("Track is too short to detect a tempo")
lo, hi = bpm_range
low = _onset(_band_env(y, sr, 30.0, 150.0)) 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)) 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)) full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
o_tempo = low + mid + 0.5 * full o_tempo = low + mid + 0.5 * full
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0: 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) bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
phase = _phase(low, attack, 60.0 / bpm) phase = _phase(low, attack, 60.0 / bpm)
drift = _drift(attack, bpm, phase) drift = _drift(attack, bpm, phase)
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration) return _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),
)
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]: 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:
import librosa
y, sr = librosa.load(audio_path, sr=SR, mono=True)
return detect_key_samples(y, sr)
Binary file not shown.
+4 -1
View File
@@ -194,6 +194,9 @@ class LibraryInfo(BaseModel):
path: str path: str
display_name: str # short label for the status bar display_name: str # short label for the status bar
version: str | None = None 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): class PlatformOption(BaseModel):
@@ -208,7 +211,7 @@ class PlatformOption(BaseModel):
platform: str platform: str
name: str name: str
library_label: str library_label: str
selects: Literal["file", "directory"] = "file" selects: Literal["file", "directory", "remote"] = "file"
installed: bool = False installed: bool = False
#: How many libraries this platform has right now; `installed` is `found > 0`. #: How many libraries this platform has right now; `installed` is `found > 0`.
found: int = 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 True
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/") 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: def apply(self, os_path: Path) -> Path:
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the """Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
path unchanged when it doesn't match (non-matching tracks untouched).""" path unchanged when it doesn't match (non-matching tracks untouched)."""
@@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str:
else: else:
break break
return "/".join(common) 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
+2 -2
View File
@@ -44,8 +44,8 @@ def driver_for(path: Path) -> LibraryDriver:
raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}") raise LibraryNotSupported(f"No DJ library Konduktor recognises at {path}")
def open_library(path: Path): def open_library(path: Path, *, read_only: bool = False):
return driver_for(path).open(path) return driver_for(path).open(path, read_only=read_only)
def describe(path: Path) -> dict: def describe(path: Path) -> dict:
+124 -1
View File
@@ -36,6 +36,7 @@ Things that were measured and are easy to get wrong:
from __future__ import annotations from __future__ import annotations
import fractions import fractions
import json
import struct import struct
import sys import sys
from dataclasses import dataclass from dataclasses import dataclass
@@ -347,8 +348,130 @@ def is_stem_file(path: Path | str) -> bool:
return False return False
def stem_layout(path: Path | str) -> list[dict] | None:
"""The stems a file carries, for PLAYBACK: `[{"name", "color"}]` in stream
order (stream k+1 is stem k), or None when the file is not a playable stem
file — no `stem` box, a box that does not parse, or fewer audio streams than
it names. Read from the FILE, never from the library's `<STEMS>`: 105 plain
MP3 entries in the real collection carry that element."""
import json
path = Path(path)
try:
raw = read_stem_box(path)
if raw is None:
return None # not a stem file: nothing to count, no decoder needed
stems = json.loads(raw).get("stems") or []
streams = _audio_stream_count(path)
except (OSError, ValueError):
return None
if not stems or streams < 1 + len(stems):
return None
return [{"name": str(s.get("name") or f"Stem {i + 1}"), "color": str(s.get("color") or "#FFFFFF")}
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 av.open(str(path), metadata_errors="ignore") 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"
if isinstance(v, float):
return str(int(v)) if v.is_integer() else "%.16g" % v
if isinstance(v, (int, str)) or v is None:
return json.dumps(v, ensure_ascii=False)
if isinstance(v, list):
return "[" + ",".join(_traktor_json(x) for x in v) + "]"
if isinstance(v, dict):
return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{_traktor_json(v[k])}"
for k in sorted(v)) + "}"
raise TypeError(f"not JSON: {v!r}")
def traktor_stems_json(box: bytes) -> str:
"""A `stem` box payload as Traktor writes it into `<STEMS STEMS="…">`: keys
sorted, no spaces, a whole float as an integer, any other to 16 significant
digits. Measured: it reproduces Traktor's value for every stem file on this
machine, and re-renders each of the 3,678 `<STEMS>` in the user's big
collection unchanged — but all of those carry ONE layout (NI's defaults),
so a box with other values is the same rule extrapolated. Raises ValueError
on a box that is not JSON."""
return _traktor_json(json.loads(box))
def nml_stems_for(path: Path | str) -> str | None:
"""The `<STEMS>` value a library entry for this file should carry, or None
when it is not a playable stem file (the test `stem_layout` applies)."""
if stem_layout(path) is None:
return None
try:
return traktor_stems_json(read_stem_box(path))
except (OSError, ValueError, TypeError):
return None
def extract_stream(path: Path | str, stream: int, fp) -> None:
"""Copy audio stream `stream` (0 = the mix, 1-4 the stems) into its own MP4,
written to the file object `fp` — packets COPIED, never re-encoded.
A browser decodes only an MP4's first audio stream, so this is how the deck
gets at the stems. Measured bit-identical to decoding the stream in place,
with the edit list (and so the priming: 1024 for FFmpeg's encoder, 2112 for
Apple's) carried across — on Konduktor's files and commercial ones alike, so
every stem stays sample-locked to the mix and to the cue timeline.
"""
import av
with av.open(str(path), metadata_errors="ignore") 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]
out = av.open(fp, "w", format="ipod")
try:
ost = out.add_stream_from_template(ist)
for pkt in inp.demux(ist):
if pkt.dts is None:
continue # the demuxer's end-of-stream flush packet
pkt.stream = ost
out.mux(pkt)
finally:
out.close()
__all__ = [ __all__ = [
"DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source", "DEMUCS_ORDER", "NML_STEMS_JSON", "SR", "STEM_BOX_JSON", "STEM_NAMES", "Source",
"StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode", "StemFileError", "Written", "add_stem_box", "build", "choose_bitrate", "decode",
"default_encoder", "is_stem_file", "read_stem_box", "stem_target_name", "verify", "default_encoder", "extract_stream", "is_stem_file", "nml_stems_for", "read_stem_box", "stem_layout",
"stem_target_name", "traktor_stems_json", "verify",
] ]
+12 -1
View File
@@ -173,7 +173,18 @@ def _frames(y: np.ndarray, lead: float) -> Frames:
def analyse(path: Path, *, n_columns: int = 400, lead: float = 0.0) -> Analysis | None: def analyse(path: Path, *, n_columns: int = 400, lead: float = 0.0) -> Analysis | None:
"""Decode `path` once and measure both resolutions; None if undecodable.""" """Decode `path` once and measure both resolutions; None if undecodable."""
y = _decode(path) return analyse_samples(decode(path), n_columns=n_columns, lead=lead)
def decode(path: Path) -> np.ndarray | None:
"""Mono float32 at `SR` — the same samples `analyse` measures, for a caller
that needs them for something else too (grid detection runs at `SR`)."""
return _decode(path)
def analyse_samples(y: np.ndarray | None, *, n_columns: int = 400,
lead: float = 0.0) -> Analysis | None:
"""`analyse` on samples already decoded by `decode`."""
if y is None or len(y) < max(n_columns, N_FFT): if y is None or len(y) < max(n_columns, N_FFT):
return None return None
return Analysis(columns=_columns(y, n_columns), frames=_frames(y, lead)) return Analysis(columns=_columns(y, n_columns), frames=_frames(y, lead))
+16 -15
View File
@@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan:
resolved = exports.resolve(adapter, export_set) 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] 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 # The source is the adapter's file, never `Track.filepath`: that is a
# a DISPLAY path, which on Traktor omits the volume and ignores the active # 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 # path mapping — so every track off the boot volume (or on a remapped
# Windows drive) read as missing and the export was "empty". # Windows drive) read as missing and the export was "empty". Its FACTS,
sources = {t.id: adapter.audio_path(t.id) for t in tracks} # 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 # Mirror relative to the deepest shared folder, so the export carries the
# user's structure without carrying their home directory. # user's structure without carrying their home directory.
@@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan:
previous = _previous_copies(destination) previous = _previous_copies(destination)
claimed: set[Path] = set() claimed: set[Path] = set()
for track in tracks: for track in tracks:
source = sources[track.id] source = sources.get(track.id)
exists = False fact = facts.get(track.id)
size = mtime_ns = 0 exists = fact is not None
try: size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0)
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
planned = PlannedTrack( planned = PlannedTrack(
track_id=track.id, track_id=track.id,
title=track.title or (source.name if source else track.id), title=track.title or (source.name if source else track.id),
@@ -519,7 +517,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
done += n done += n
handle.progress(done=done) 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) os.replace(partial, target)
payload_tracks.append( payload_tracks.append(
ExportTrack( ExportTrack(
+34 -3
View File
@@ -123,8 +123,39 @@ def _store_path(library_id: str) -> Path:
return paths.app_data_dir() / "exports" / f"{library_id}.json" return paths.app_data_dir() / "exports" / f"{library_id}.json"
# A library whose sets are kept somewhere other than this computer's app-data —
# a library held by a server keeps them beside itself, so every computer that
# opens it sees the same sets. Each store reads and writes the WHOLE document
# (`{"library_id", "sets"}`); everything else here is unchanged by where it is.
_STORES: dict[str, object] = {}
def use_store(library_id: str, store) -> None:
"""Keep `library_id`'s sets in `store` (`read() -> dict`, `write(dict)`);
None returns them to this computer's app-data."""
if store is None:
_STORES.pop(library_id, None)
else:
_STORES[library_id] = store
def _read_doc(library_id: str) -> dict:
store = _STORES.get(library_id)
if store is not None:
return store.read()
return paths.read_json(_store_path(library_id), {})
def _write_doc(library_id: str, doc: dict) -> None:
store = _STORES.get(library_id)
if store is not None:
store.write(doc)
else:
paths.write_json(_store_path(library_id), doc)
def _load(library_id: str) -> dict[str, ExportSet]: def _load(library_id: str) -> dict[str, ExportSet]:
data = paths.read_json(_store_path(library_id), {}) data = _read_doc(library_id)
raw = data.get("sets") if isinstance(data, dict) else None raw = data.get("sets") if isinstance(data, dict) else None
out: dict[str, ExportSet] = {} out: dict[str, ExportSet] = {}
if isinstance(raw, dict): if isinstance(raw, dict):
@@ -158,8 +189,8 @@ def _targets(values: dict) -> list[str]:
def _save(library_id: str, sets: dict[str, ExportSet]) -> None: def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
paths.write_json( _write_doc(
_store_path(library_id), library_id,
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}}, {"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
) )
+107 -15
View File
@@ -112,18 +112,19 @@ def _key(path: Path) -> str:
def _existing_files(dest) -> dict[str, str]: def _existing_files(dest) -> dict[str, str]:
"""Every audio file the destination points at → its track id. """Every audio file the destination points at → its track id.
Resolved through the adapter's own `audio_path`, which is the only answer Resolved through the adapter's own `audio_facts`, which is the only answer
that includes the volume and the active path mapping; the projected that includes the volume and the active path mapping; the projected
`filepath` is a display string and is not good enough to match on. `filepath` is a display string and is not good enough to match on. Facts,
not `audio_path`: on a library held by a server that would download every
file it has.
""" """
out: dict[str, str] = {} out: dict[str, str] = {}
for track in dest.tracks: try:
try: facts = dest.audio_facts([t.id for t in dest.tracks])
path = dest.audio_path(track.id) except Exception: # noqa: BLE001
except Exception: # noqa: BLE001 return out
path = None for track_id, fact in facts.items():
if path is not None: out.setdefault(_key(Path(fact.key)), track_id)
out.setdefault(_key(path), track.id)
return out return out
@@ -216,7 +217,16 @@ def _all_playlists(source) -> list[tuple[str, str]]:
return out return out
def free_bytes(path: Path) -> int | None: def free_bytes(path: Path, dest=None) -> int | None:
"""Free space where the audio will land. On the DESTINATION's machine: a
library held by a server reports its own disk (`free_space`), since the
path names a folder there, not here."""
remote_free = getattr(dest, "free_space", None) if dest is not None and uploads_audio(dest) else None
if remote_free is not None:
try:
return remote_free(str(path))
except Exception: # noqa: BLE001 — unknown is not "full"
return None
try: try:
target = path if path.exists() else path.parent target = path if path.exists() else path.parent
return shutil.disk_usage(target).free return shutil.disk_usage(target).free
@@ -224,6 +234,15 @@ def free_bytes(path: Path) -> int | None:
return None return None
def uploads_audio(dest) -> bool:
"""Whether added audio is SENT to the machine holding the library (a
server) rather than copied on this one — `tracks.audio_destination`."""
try:
return dest.capabilities().tracks.audio_destination == "library" and hasattr(dest, "upload_audio")
except Exception: # noqa: BLE001
return False
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path: def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
"""A free filename in `folder`, suffixing on collision. """A free filename in `folder`, suffixing on collision.
@@ -290,9 +309,21 @@ def run(
destination and nothing to roll back. `into_playlist` appends every planned destination and nothing to roll back. `into_playlist` appends every planned
track — the new ones and those the destination already held — to one of the track — the new ones and those the destination already held — to one of the
destination's playlists before the save, so both land in one commit. destination's playlists before the save, so both land in one commit.
A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary
stick) overrides both: `dest.place_audio` names each copy's target, or says
the file can be used where it is, and `reference`/`plan.destination` are
ignored.
""" """
destination = plan.destination destination = plan.destination
if not reference: places = places_audio(dest)
# A library held by a server: each file is UPLOADED into `destination`,
# a folder on the server, instead of copied here. Nothing can be left in
# place — the server cannot see this computer's files.
uploads = not places and uploads_audio(dest)
if uploads and reference:
raise ValueError("A remote library cannot reference files on this computer")
if not reference and not places and not uploads:
assert destination is not None assert destination is not None
destination.mkdir(parents=True, exist_ok=True) destination.mkdir(parents=True, exist_ok=True)
@@ -306,6 +337,8 @@ def run(
# from it leaves the half-written file behind — which then makes the next # from it leaves the half-written file behind — which then makes the next
# attempt suffix around a file that is not really there. # attempt suffix around a file that is not really there.
created: list[Path] = [] created: list[Path] = []
# Files sent to the server, which a failure asks it to delete again.
uploaded: list[Path] = []
taken: set[str] = set() taken: set[str] = set()
moved = 0 moved = 0
@@ -318,11 +351,31 @@ def run(
for planned in importable: for planned in importable:
handle.raise_if_cancelled() handle.raise_if_cancelled()
assert planned.source_path is not None assert planned.source_path is not None
if reference: if places:
target = dest.place_audio(planned.source_path, source.track(planned.track_id))
if target is None:
copied.append((planned, planned.source_path))
continue
target.parent.mkdir(parents=True, exist_ok=True)
elif reference:
copied.append((planned, planned.source_path)) copied.append((planned, planned.source_path))
continue continue
elif uploads:
handle.progress(message=f"Uploading {planned.title}")
def sent(n: int) -> None:
handle.raise_if_cancelled() # mid-file: the server drops the partial
bump(n)
# The server never overwrites: a taken name comes back `-2`…
target = dest.upload_audio(planned.source_path, str(destination),
planned.source_path.name, progress=sent)
uploaded.append(target)
copied.append((planned, target))
continue
else:
target = _unique_target(destination, planned.source_path.name, taken)
handle.progress(message=f"Copying {planned.title}") handle.progress(message=f"Copying {planned.title}")
target = _unique_target(destination, planned.source_path.name, taken)
created.append(target) # registered BEFORE the write, so a cancel created.append(target) # registered BEFORE the write, so a cancel
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
copied.append((planned, target)) copied.append((planned, target))
@@ -340,9 +393,23 @@ def run(
cues = source.track_cues(planned.track_id) cues = source.track_cues(planned.track_id)
except Exception: # noqa: BLE001 — prep is a bonus, not a blocker except Exception: # noqa: BLE001 — prep is a bonus, not a blocker
log.debug("could not read cues for %s", planned.track_id, exc_info=True) log.debug("could not read cues for %s", planned.track_id, exc_info=True)
items.append(NewTrack(track=track, audio_path=target, cues=cues)) art = None
cover_art = getattr(source, "cover_art", None)
if cover_art is not None:
try:
art = cover_art(planned.track_id)
except Exception: # noqa: BLE001 — art is a bonus too
log.debug("could not read art for %s", planned.track_id, exc_info=True)
items.append(NewTrack(track=track, audio_path=target, cues=cues, art=art))
new_ids = dest.add_tracks(items) def checkpoint(message: str, *, step: int, of: int) -> None:
# A platform that analyses what it adds (Rekordbox) is slow here,
# and calls this before touching the library — so a cancel still
# leaves it untouched and the copies are cleaned up below.
handle.raise_if_cancelled()
handle.progress(done=step - 1, total=of, message=message)
new_ids = dest.add_tracks(items, checkpoint=checkpoint)
by_source = { by_source = {
planned.track_id: new_id planned.track_id: new_id
for (planned, _), new_id in zip(copied, new_ids) for (planned, _), new_id in zip(copied, new_ids)
@@ -382,9 +449,34 @@ def run(
target.unlink(missing_ok=True) target.unlink(missing_ok=True)
except OSError: except OSError:
log.debug("could not clean up %s", target, exc_info=True) log.debug("could not clean up %s", target, exc_info=True)
for target in uploaded:
try:
dest.delete_upload(target) # refused once the library names it
except Exception: # noqa: BLE001
log.debug("could not clean up upload %s", target, exc_info=True)
raise raise
def places_audio(dest) -> bool:
"""Whether the destination decides where added audio goes (a stick)."""
try:
return bool(dest.capabilities().tracks.places_audio) and hasattr(dest, "place_audio")
except Exception: # noqa: BLE001
return False
def placed_bytes(dest, plan: ImportPlan) -> int:
"""What an import into a self-placing library will COPY: a file already under
its `audio_home()` is used in place and costs nothing."""
home = dest.audio_home()
total = 0
for planned in plan.importable:
path = planned.source_path
if path is not None and not path.resolve().is_relative_to(home.resolve()):
total += planned.size
return total
def _save(dest): def _save(dest):
"""Save through AppState so the version-history commit is not skipped.""" """Save through AppState so the version-history commit is not skipped."""
from .app_state import STATE from .app_state import STATE
+18 -1
View File
@@ -53,6 +53,13 @@ class Job:
#: library is written — so the UI can word them. Empty = unspecified. #: library is written — so the UI can word them. Empty = unspecified.
unit: str = "" unit: str = ""
message: str = "" message: str = ""
#: How far the CURRENT unit of work has got, 0..1 — so the overall bar can
#: move within a long item: at 99 % of the first of two tracks it reads
#: ~50 %, not 0. Reset whenever `done` advances.
fraction: float = 0.0
#: What the current item is doing ("separating 41 %"), shown beside its name
#: and never truncated in its place. Reset whenever `done` advances.
status: str = ""
result: Any = None result: Any = None
error: str | None = None error: str | None = None
started_at: float = field(default_factory=time.time) started_at: float = field(default_factory=time.time)
@@ -75,6 +82,8 @@ class Job:
"done": self.done, "done": self.done,
"unit": self.unit, "unit": self.unit,
"message": self.message, "message": self.message,
"fraction": self.fraction,
"status": self.status,
"result": self.result, "result": self.result,
"error": self.error, "error": self.error,
"started_at": self.started_at, "started_at": self.started_at,
@@ -94,11 +103,19 @@ class JobHandle:
self._job = job self._job = job
def progress(self, done: int | None = None, total: int | None = None, def progress(self, done: int | None = None, total: int | None = None,
message: str | None = None, unit: str | None = None) -> None: message: str | None = None, unit: str | None = None,
fraction: float | None = None, status: str | None = None) -> None:
if unit is not None: if unit is not None:
self._job.unit = unit self._job.unit = unit
if done is not None: if done is not None:
if done != self._job.done: # a new item: its progress starts over
self._job.fraction = 0.0
self._job.status = ""
self._job.done = done self._job.done = done
if fraction is not None:
self._job.fraction = max(0.0, min(1.0, fraction))
if status is not None:
self._job.status = status
if total is not None: if total is not None:
self._job.total = total self._job.total = total
if message is not None: if message is not None:
+730 -75
View File
File diff suppressed because it is too large. Load diff
+68 -31
View File
@@ -3,10 +3,19 @@
A self-contained JSON file in the app's per-OS user-writable data dir (see A self-contained JSON file in the app's per-OS user-writable data dir (see
``paths.app_data_dir``) so it survives a frozen/packaged build and works the same ``paths.app_data_dir``) so it survives a frozen/packaged build and works the same
on every platform. Best-effort: any I/O error degrades to "no prefs". on every platform. Best-effort: any I/O error degrades to "no prefs".
**Every read-modify-write holds ``_LOCK`` and every write is atomic.** FastAPI
runs ``PATCH /api/prefs`` on a thread pool, and the UI sends several at once on
launch. Unlocked, with ``write_text`` truncating before it wrote, a reader could
catch the file empty, take it for "no prefs" and write back only its own key —
wiping everything else (measured: 249 of 300 trials of three concurrent patches).
A file that exists but will not parse is moved aside before it is replaced, so
it is never silently overwritten.
""" """
from __future__ import annotations from __future__ import annotations
import json import json
import threading
from pathlib import Path from pathlib import Path
from . import paths from . import paths
@@ -16,6 +25,9 @@ from . import paths
_PREFS_PATH = paths.app_data_dir() / "userprefs.json" _PREFS_PATH = paths.app_data_dir() / "userprefs.json"
_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json" _LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
# Reentrant: the helpers below read and write inside one critical section.
_LOCK = threading.RLock()
def _migrate_legacy() -> None: def _migrate_legacy() -> None:
"""One-time: if the new file is absent but a legacy package-relative one """One-time: if the new file is absent but a legacy package-relative one
@@ -27,29 +39,52 @@ def _migrate_legacy() -> None:
pass pass
def load_prefs() -> dict: def _read(*, for_write: bool) -> dict:
"""The stored prefs, or {} if there are none or they cannot be read.
With ``for_write``, a file that exists but is not a JSON object is renamed
to ``userprefs.json.corrupt`` first, since the caller is about to replace it.
"""
try: try:
_migrate_legacy() _migrate_legacy()
data = json.loads(_PREFS_PATH.read_text()) text = _PREFS_PATH.read_text()
return data if isinstance(data, dict) else {} except OSError:
except (OSError, ValueError):
return {} return {}
try:
data = json.loads(text)
if isinstance(data, dict):
return data
except ValueError:
pass
if for_write:
try:
_PREFS_PATH.replace(_PREFS_PATH.with_name(_PREFS_PATH.name + ".corrupt"))
except OSError:
pass
return {}
def load_prefs() -> dict:
with _LOCK:
return _read(for_write=False)
def save_prefs(prefs: dict) -> None: def save_prefs(prefs: dict) -> None:
try: with _LOCK:
_PREFS_PATH.write_text(json.dumps(prefs, indent=2)) try:
except OSError: paths.write_json(_PREFS_PATH, prefs)
pass # non-fatal — prefs are a convenience, not a requirement except OSError:
pass # non-fatal — prefs are a convenience, not a requirement
def update_prefs(patch: dict) -> dict: def update_prefs(patch: dict) -> dict:
"""Shallow-merge `patch` into the stored prefs and persist. Returns the """Shallow-merge `patch` into the stored prefs and persist. Returns the
full updated prefs dict.""" full updated prefs dict."""
prefs = load_prefs() with _LOCK:
prefs.update(patch) prefs = _read(for_write=True)
save_prefs(prefs) prefs.update(patch)
return prefs save_prefs(prefs)
return prefs
def get_path_mapping(collection_path: str) -> dict | None: def get_path_mapping(collection_path: str) -> dict | None:
@@ -69,16 +104,17 @@ def set_path_mapping(
collection_path: str, from_prefix: str | None, to_prefix: str | None collection_path: str, from_prefix: str | None, to_prefix: str | None
) -> None: ) -> None:
"""Persist (or, when either prefix is blank, clear) a collection's mapping.""" """Persist (or, when either prefix is blank, clear) a collection's mapping."""
prefs = load_prefs() with _LOCK:
mappings = prefs.get("path_mappings") prefs = _read(for_write=True)
if not isinstance(mappings, dict): mappings = prefs.get("path_mappings")
mappings = {} if not isinstance(mappings, dict):
if from_prefix and to_prefix: mappings = {}
mappings[collection_path] = {"from": from_prefix, "to": to_prefix} if from_prefix and to_prefix:
else: mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
mappings.pop(collection_path, None) else:
prefs["path_mappings"] = mappings mappings.pop(collection_path, None)
save_prefs(prefs) prefs["path_mappings"] = mappings
save_prefs(prefs)
def get_last_collection(platform: str | None = None) -> str | None: def get_last_collection(platform: str | None = None) -> str | None:
@@ -105,12 +141,13 @@ def get_last_collection(platform: str | None = None) -> str | None:
def set_last_collection(path: str, platform: str | None = None) -> None: def set_last_collection(path: str, platform: str | None = None) -> None:
"""Record a library as the last opened, globally and for its platform.""" """Record a library as the last opened, globally and for its platform."""
prefs = load_prefs() with _LOCK:
prefs["last_collection"] = path prefs = _read(for_write=True)
if platform: prefs["last_collection"] = path
by_platform = prefs.get("last_collection_by_platform") if platform:
if not isinstance(by_platform, dict): by_platform = prefs.get("last_collection_by_platform")
by_platform = {} if not isinstance(by_platform, dict):
by_platform[platform] = path by_platform = {}
prefs["last_collection_by_platform"] = by_platform by_platform[platform] = path
save_prefs(prefs) prefs["last_collection_by_platform"] = by_platform
save_prefs(prefs)
+270
View File
@@ -0,0 +1,270 @@
"""The wire contract between a Konduktor SERVER and the app that opens it.
A library held by a server (`konduktor.server`, a container on the user's NAS)
is opened on a laptop through `adapters/remote`'s `RemoteAdapter`, which speaks
THIS protocol to the server. Both sides import this module, so the method list,
which commands need the session, and the version they speak cannot drift apart.
The protocol is the `LibraryAdapter` protocol itself, not the UI's `/api`
routes: commands in, projections out. Every member of `LibraryAdapter` is
either in `RPC` or in `EXCLUDED` with the reason it does not travel —
`test_remote_protocol.py` fails the moment a new protocol member is neither, so
a command added later cannot silently be missing from remote libraries.
Arguments and results are (de)serialised with pydantic `TypeAdapter`s built
from the protocol's own type hints; the model classes are pydantic already and
the dataclasses convert. Bytes never travel as JSON — art, audio and uploads
have routes of their own.
"""
from __future__ import annotations
import base64
import inspect
import io
import typing
from dataclasses import dataclass
from functools import lru_cache
from typing import Any
from pydantic import BaseModel, TypeAdapter
from .core.adapter import LibraryAdapter
from .core.model import AutoHotcue, Track, TrackCues
#: (major, minor). A client speaks to a server of the SAME major whose minor is
#: at least its own: minors only add. Bump the minor for an added route or
#: method, the major for anything an older client would misread.
API_VERSION: tuple[int, int] = (1, 0)
#: How long a session survives without a heartbeat, and how often the holder
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
#: address; short enough that moving to another computer after closing a lid
#: rarely needs a takeover (decided 2026-10-02).
LEASE_SECONDS = 120.0
HEARTBEAT_SECONDS = 15.0
#: The header that carries the session token on every command.
SESSION_HEADER = "X-Konduktor-Session"
def compatible(client: tuple[int, int], server: tuple[int, int]) -> str | None:
"""None when `client` can talk to `server`; otherwise which side to update."""
if client[0] != server[0]:
return "app" if server[0] > client[0] else "server"
if server[1] < client[1]:
return "server"
return None
@dataclass(frozen=True)
class Method:
name: str
#: Changes the library — needs the session token, bumps the revision.
mutating: bool
#: A property on the protocol rather than a method (`tracks`, `dirty`).
prop: bool = False
#: Parameter types where the protocol's hint is too loose to validate.
overrides: tuple[tuple[str, Any], ...] = ()
_READ = (
"capabilities", "track", "query_tracks", "facets", "stats", "playlist_tree",
"playlist_count", "playlist_entries", "playlist_tracks", "track_cues", "audio_facts",
)
_MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker",
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
)
RPC: dict[str, Method] = {
**{n: Method(n, False) for n in _READ},
"tracks": Method("tracks", False, prop=True),
"dirty": Method("dirty", False, prop=True),
**{n: Method(n, True) for n in _MUTATING},
}
RPC["place_cues"] = Method("place_cues", True, overrides=(("cues", list[AutoHotcue]),))
#: Protocol members that do not travel as RPC, and why.
EXCLUDED: dict[str, str] = {
"reload": "POST /v1/discard — a discard on the server is what drops its edits",
"save": "POST /v1/save — the server saves, versions and backs up beside the library",
"snapshot": "version history lives on the server",
"audio_path": "GET /v1/audio — a server path names no file on this computer",
"cover_art": "GET /v1/art — bytes",
"set_cover_art": "PUT /v1/art — bytes",
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
"set_path_mapping": "the server's path mapping is its own configuration",
"set_session_mappings": "the missing-files check searches THIS computer's drives",
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
"path_prefix_suggestions": "paths.remappable is false for a remote library",
"remap_preview": "paths.remappable is false for a remote library",
"remap_locations": "paths.remappable is false for a remote library",
}
def protocol_members() -> set[str]:
"""Every method and property `LibraryAdapter` declares (not its attributes)."""
out = set()
for name, value in vars(LibraryAdapter).items():
if name.startswith("_"):
continue
if inspect.isfunction(value) or isinstance(value, property):
out.add(name)
return out
def _callable(name: str):
member = getattr(LibraryAdapter, name)
return member.fget if isinstance(member, property) else member
@lru_cache(maxsize=None)
def _hints(name: str) -> dict[str, Any]:
hints = typing.get_type_hints(_callable(name))
method = RPC[name]
hints.update(dict(method.overrides))
return hints
@lru_cache(maxsize=None)
def _params(name: str) -> tuple[tuple[str, Any, Any], ...]:
"""(name, type, default) for each parameter the RPC takes."""
if name == "query_tracks":
# `**kw` on the protocol: the index's own signature is the real one.
from .core.query import TrackIndex
sig = inspect.signature(TrackIndex.query_tracks)
hints = typing.get_type_hints(TrackIndex.query_tracks)
else:
sig = inspect.signature(_callable(name))
hints = _hints(name)
out = []
for p in sig.parameters.values():
if p.name == "self" or p.kind in (p.VAR_KEYWORD, p.VAR_POSITIONAL):
continue
if name == "add_tracks" and p.name == "checkpoint":
continue # a callable; the server reports progress instead
hint = hints.get(p.name, Any)
if name == "add_tracks" and p.name == "items":
hint = list[WireNewTrack]
out.append((p.name, hint, p.default))
return tuple(out)
@lru_cache(maxsize=None)
def _adapter(hint) -> TypeAdapter:
return TypeAdapter(hint)
def dump_args(name: str, args: dict) -> dict:
"""Arguments → JSON-able, by the protocol's own types."""
out = {}
for pname, hint, _default in _params(name):
if pname in args:
out[pname] = _adapter(hint).dump_python(args[pname], mode="json")
return out
def load_args(name: str, raw: dict) -> dict:
"""JSON → validated arguments. Unknown names are refused rather than
ignored: a misspelt argument silently taking its default is a wrong edit."""
params = {p: (h, d) for p, h, d in _params(name)}
unknown = set(raw) - set(params)
if unknown:
raise ValueError(f"{name}: unknown argument(s) {sorted(unknown)}")
out = {}
for pname, (hint, default) in params.items():
if pname in raw:
out[pname] = _adapter(hint).validate_python(raw[pname])
elif default is inspect.Parameter.empty:
raise ValueError(f"{name}: missing argument {pname!r}")
return out
def _result_hint(name: str):
if name == "add_tracks":
return list[str]
return _hints(name).get("return", Any)
def dump_result(name: str, value) -> Any:
return _adapter(_result_hint(name)).dump_python(value, mode="json")
def load_result(name: str, raw) -> Any:
return _adapter(_result_hint(name)).validate_python(raw)
# ---- adding tracks -------------------------------------------------------------
class WireArt(BaseModel):
data: str # base64
mime: str
class WireNewTrack(BaseModel):
"""`NewTrack` as it crosses the wire. `audio_path` is a path ON THE SERVER —
the client uploaded the file first (`POST /v1/upload`), exactly as a local
import copies it first. The analysis is the client's (the server never
decodes audio)."""
track: Track
audio_path: str
cues: TrackCues | None = None
art: WireArt | None = None
analysis: str | None = None # base64 `.npz`, see `pack_analysis`
def pack_analysis(prepared) -> str | None:
"""A `PreparedAnalysis` → base64 `.npz` (float32: what the writers use)."""
if prepared is None or prepared.measured is None:
return None
import numpy as np
m = prepared.measured
buf = io.BytesIO()
markers = np.array([[g.start, g.bpm] for g in prepared.markers], dtype=np.float64).reshape(-1, 2)
np.savez(
buf,
rms=np.asarray(m.columns.rms, dtype=np.float32),
brightness=np.asarray(m.columns.brightness, dtype=np.float32),
columns_duration=np.float64(m.columns.duration),
bands=np.asarray(m.frames.bands, dtype=np.float32),
frames_duration=np.float64(m.frames.duration),
markers=markers,
**({} if prepared.key is None else {
"key": np.array([prepared.key.pitch_class, prepared.key.wheel,
prepared.key.mode == "minor", prepared.key.confidence], dtype=np.float64)}),
)
return base64.b64encode(buf.getvalue()).decode("ascii")
def unpack_analysis(text: str | None):
"""The inverse of `pack_analysis` → `PreparedAnalysis` (or None)."""
if not text:
return None
import numpy as np
from .core import waveform
from .core.adapter import PreparedAnalysis
from .core.model import GridMarker
with np.load(io.BytesIO(base64.b64decode(text))) as z:
measured = waveform.Analysis(
columns=waveform.Columns(rms=z["rms"], brightness=z["brightness"],
duration=float(z["columns_duration"])),
frames=waveform.Frames(bands=z["bands"], duration=float(z["frames_duration"])),
)
markers = [GridMarker(start=float(s), bpm=float(b)) for s, b in z["markers"]]
key = None
if "key" in z:
from .core.key_detect import KeyResult
pitch, wheel, minor, confidence = z["key"]
key = KeyResult(pitch_class=int(pitch), mode="minor" if minor else "major",
wheel=int(wheel), confidence=float(confidence))
return PreparedAnalysis(measured=measured, markers=markers, key=key)
+99
View File
@@ -133,6 +133,40 @@ class AutoGridRequest(BaseModel):
track_id: str track_id: str
class AnalyzeRequest(BaseModel):
"""The Analyze dialog's choices. BPM and Grid are independent halves of a
beatgrid (`core/grid_plan`); `replace_grid` only guards a FULL re-analysis
(both ticked), since with one tick adjusting the grid is the point.
`replace_key` lets detection overwrite a key the track already has."""
track_ids: list[str]
bpm: bool = True
grid: bool = True
key: bool = False
replace_grid: bool = False
replace_key: bool = False
class AnalyzePreview(BaseModel):
"""What an Analyze run WOULD do, for the dialog. Counted from the
projection, so on a platform whose marker counts are lazy (Rekordbox,
OneLibrary: 1 for any track with a BPM) a flexible grid is only found when
the run reads the real grid — it is then skipped and reported."""
total: int
tracks_to_analyze: int = 0 # tracks with anything to do (grid and key overlap)
# Grid: what `plan_grid` decides per track — full / bpm / phase / skipped.
grid_full: int = 0
grid_bpm: int = 0
grid_phase: int = 0
grid_locked: int = 0
grid_existing: int = 0 # skipped: has a grid, Replace not ticked
grid_flexible: int = 0
with_grid: int = 0 # unlocked tracks that have a grid (the Replace tick's count)
# Key.
key_set: int = 0
key_existing: int = 0 # skipped: has a key, Replace not ticked
with_key: int = 0 # tracks that have a key (the Replace tick's count)
class AutoGridBatchRequest(BaseModel): class AutoGridBatchRequest(BaseModel):
track_ids: list[str] track_ids: list[str]
# False skips tracks that already have a grid. Locked grids are skipped # False skips tracks that already have a grid. Locked grids are skipped
@@ -146,9 +180,49 @@ class SetCueType(BaseModel):
type: CueType type: CueType
class SetCueColor(BaseModel):
track_id: str
slot: int
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
class StemEngineInstall(BaseModel):
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
target: str | None = None
# Also fetch the model weights (the engine is useless without them).
weights: bool = True
class StemSideLoad(BaseModel):
path: str
kind: Literal["engine", "weights"]
class StemConvert(BaseModel):
track_ids: list[str]
# "replace": the stem file supersedes the original where it lives (the
# original is parked until Save deletes it); "destination": a chosen folder,
# originals never touched.
mode: Literal["replace", "destination"]
destination: str | None = None
# "repoint": the entry now names the stem file; "add": a new entry beside it
# (destination mode only).
collection: Literal["repoint", "add"] = "repoint"
playlist_id: str | None = None # add mode: into this existing playlist…
new_playlist: str | None = None # …or a new one with this name
class EditState(BaseModel): class EditState(BaseModel):
dirty: bool # unsaved in-memory changes exist dirty: bool # unsaved in-memory changes exist
library: LibraryInfo library: LibraryInfo
# Converted tracks awaiting Save/Discard: {tracks, parked, bytes}.
pending_stems: dict | None = None
# A running stem conversion's job id, so a reloaded page finds it again.
stem_job: str | None = None
# What this open's crash recovery did about an interrupted conversion.
stem_recovery: dict | None = None
# A remote library's connection: {state, via, machine}. None when local.
remote: dict | None = None
# ---- collection selection ---- # ---- collection selection ----
@@ -162,12 +236,34 @@ class CollectionStatus(BaseModel):
# Identity of the loaded library, so the UI can name it without parsing the # Identity of the loaded library, so the UI can name it without parsing the
# path (a Serato library is a directory, not a file). # path (a Serato library is a directory, not a file).
library: LibraryInfo | None = None library: LibraryInfo | None = None
# Opening a remote library: the unsaved edits another computer left there,
# {machine, summary} — the user chooses to save or discard them.
pending_edits: dict | None = None
class OpenCollection(BaseModel): class OpenCollection(BaseModel):
path: str path: str
class RemoteIn(BaseModel):
"""A remote's settings as the picker's form sends them. `password` may be
omitted on an edit, which keeps the saved one."""
name: str
host: str
port: int | None = None
fallback_host: str | None = None
fallback_port: int | None = None
username: str
password: str | None = None
class OpenRemote(BaseModel):
remote_id: str
# Take the session from the computer holding it (the user confirmed).
takeover: bool = False
class CollectionCandidate(BaseModel): class CollectionCandidate(BaseModel):
path: str path: str
label: str # folder name, e.g. "Traktor 4.5.0" label: str # folder name, e.g. "Traktor 4.5.0"
@@ -451,6 +547,9 @@ class JobStatus(BaseModel):
# needs to tell a byte count from a track count. # needs to tell a byte count from a track count.
unit: str = "" unit: str = ""
message: str message: str
# The current item's own progress (0..1) and what it is doing — see jobs.Job.
fraction: float = 0.0
status: str = ""
result: dict | None = None result: dict | None = None
error: str | None = None error: str | None = None
started_at: float started_at: float
+2
View File
@@ -0,0 +1,2 @@
"""Konduktor's server: one library, held on the machine where its audio lives,
opened from the desktop app as a "Remote" library. See `app.py`."""
+37
View File
@@ -0,0 +1,37 @@
"""`python -m konduktor.server` — what the container runs.
Configuration is the environment (see `config.py`); a bad setting stops here
with one clear line instead of serving a library that half-works.
"""
from __future__ import annotations
import logging
import sys
import uvicorn
from .config import ConfigError, from_env
def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
try:
config = from_env()
except ConfigError as ex:
print(f"konduktor-server: {ex}", file=sys.stderr)
return 2
from .app import Server, create_app
server = Server(config)
try:
server.open()
except ConfigError as ex:
print(f"konduktor-server: {ex}", file=sys.stderr)
return 2
uvicorn.run(create_app(server), host=config.host, port=config.port,
log_level="info", proxy_headers=True)
return 0
if __name__ == "__main__":
sys.exit(main())
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff. Show more