Implemented Rekordbox core base

This commit is contained in:
patben8 committed 2026-09-18 09:12:59 +02:00
1 parent 6e24f5ef1d
commit 4592e13228
18 files changed
+2170 -6

No files matched your search

+700
View File
@@ -0,0 +1,700 @@
# Handoff: the Rekordbox adapter
**For**: an agent picking up Konduktor with no prior context.
**Task**: add Rekordbox as the second platform — step 4 of the multi-platform plan.
**Status of the plan**: steps 1–3 are done and committed (`08c9b81`, `c9e85bb`, `6e24f5e`).
All *design* decisions for this work were settled in
[`.claude/discussions/discuss-multi-platform-library-2026-09-17.md`](../discussions/discuss-multi-platform-library-2026-09-17.md).
Read its **"If Moving to Planning/Implementation"** section before designing
anything. This handoff is the *current-state* companion to it: what exists now,
what to do next, and what will bite you. Where the two disagree, the discussion
doc wins on intent and this one wins on facts about the code.
---
## 1. Where the project is
Konduktor is a library-management and track-prep tool for DJ software. Until
recently it was Traktor-only. It now has a **generic model + per-platform adapter**
architecture with Traktor as the only adapter, and the generic shape reaches all
the way to the UI — nothing above `adapters/traktor/` knows Traktor exists.
**The architecture is projection + command replay.** The generic model is a *read
projection*. Edits are strictly-generic commands that an adapter replays onto its
**retained native model**, which stays the write target. The generic model is
**never** serialized back over a library. That is what preserves byte-exact saves,
and it is the only model that works for a format you cannot regenerate — which is
exactly Rekordbox's situation.
```
backend/konduktor/
core/ generic. MUST NOT import a native library type.
model.py Track, CuePoint, GridMarker, TrackCues, PlaylistNode…
adapter.py LibraryAdapter / LibraryDriver protocols + error tree
capabilities.py Capabilities — what a loaded library can persist
query.py TrackIndex: query/filter/sort/facets/stats
edit_journal.py EditJournal: every edit at field resolution
registry.py adapter selection by can_open() probe
audio_tags.py pathmap.py auto_hotcues.py
adapters/traktor/ the reference implementation — read this first
store.py retained native model (TraktorStore)
adapter.py TraktorAdapter: owns store + TrackIndex
projection.py native -> generic
driver.py capabilities.py beatgrid.py locations.py cue_types.py
app_state.py the one loaded library + version-history commits
main.py thin routes; talks only to the adapter
```
Frontend (`frontend/src/`) is already generic: `api.ts` carries string cue types,
`lib/capabilities.tsx` exposes `useCaps()`, `lib/platformCopy.ts` composes
per-platform wording from adapter-supplied *facts*. No component branches on the
platform name.
**Tests**: `cd backend && ./run_tests.sh` → 146 assertions across
`test_layering.py`, `test_save_fidelity.py`, `test_traktor_adapter.py`,
`test_phase3.py`, `test_history.py`. Frontend: `npm run build && npm run test`
(25 vitest assertions on `lib/beatgrid.ts`).
---
## 2. Start here: research before code
The discussion doc lists one genuinely open question, and it gates the whole
write path:
> **Rekordbox `rb_local_usn` / update-sequence + cloud-sync columns**: writing rows
> without maintaining these may corrupt Rekordbox's own sync state.
Settle this **first**, empirically, against a real `master.db` — do not design the
write path around an assumption. Specifically find out:
- What `rb_local_usn` is per row, what the per-table/global sequence is, and what
Rekordbox does on next launch when it sees a row it did not write.
- Whether `pyrekordbox` maintains these for you on write, or whether that is the
caller's job. (Assume nothing; read its source.)
- What `USN`/`rb_data_status`/`rb_local_deleted` and the other `rb_*` columns mean.
- What happens on a cloud-synced library specifically, since that is the failure
mode that could lose data on *other* machines — which is worse than a local
corruption the version history can undo.
Write the findings up as a **Findings** section in this file (the discussion doc
is Concluded; don't edit it). If the answer turns out to be "Konduktor cannot
safely write a cloud-synced library", that is a legitimate result and should be
surfaced to Ben as a scope decision, not worked around silently.
**Standing lesson from the discussion, which has already been proved right twice**:
establish format capabilities empirically against real files rather than assuming
them. Both previous assumptions that got checked (Traktor cue colours, flexible
grid marker naming) turned out to be wrong.
---
## 3. What to build
### 3.1 The adapter
Create `backend/konduktor/adapters/rekordbox/` mirroring the Traktor package, and
register it in `adapters/__init__.py` (one line; the registry does the rest).
Implement the two protocols in `core/adapter.py`. `LibraryDriver` is small:
`can_open` / `open` / `detect` / `describe` / `restore`. `LibraryAdapter` is the
real surface — 38 methods, all already defined in generic terms:
```
capabilities reload
tracks track query_tracks facets stats
playlist_tree playlist_entries playlist_tracks track_cues
create_playlist rename_playlist delete_playlist set_playlist_entries
set_track_metadata set_cover_art cover_art
set_cue set_cue_type 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
audio_path set_path_mapping path_prefix_suggestions remap_preview remap_locations
dirty save snapshot
```
Two rules the Traktor adapter follows and yours must too:
1. **Every mutating command returns its refreshed projection.** This makes the
refresh an adapter-internal invariant rather than something a route has to
remember. A forgotten refresh is a silently stale UI that no test would catch.
2. **`core/` stays clean.** `test_layering.py` fails the build if anything in
`core/` imports a native type. If you find yourself wanting to widen a `core/`
model for a Rekordbox-only reason, that is the two-platform promotion rule
telling you not to — see §4.
`can_open` must not be extension-based: Rekordbox's library is `master.db` and
Serato's is a *directory*. Probe cheaply (Traktor's reads 4 KB and looks for the
NML header; yours will need to recognise a SQLCipher file without decrypting it
twice).
### 3.2 Capabilities
`core/capabilities.py` already has the fields. Rekordbox's answers, from the
discussion doc's platform notes — **verify each against a real library**:
| Field | Expected for Rekordbox | Note |
|---|---|---|
| `cues.hotcue_slots` | 8 | |
| `cues.slot_labels` | `'letter'` | **First real customer.** The field exists but no UI has exercised it — expect to find bugs. |
| `cues.memory_cues` | `true` | See §4: still *not editable*. |
| `cues.types` | `['cue','loop']` | No fade_in/fade_out/load — those are Traktor-only. |
| `cues.color` | `'free'` or `'palette'` | Determine empirically; if palette, populate it. |
| `grid.flexible` | likely `true` | Verify. |
| `grid.lockable` | ? | Rekordbox's analysis lock is a *different concept* from Traktor's LOCK — check before mapping it. |
| `save.overwrite_risk` | `'while_running'` | Rekordbox holds the DB open and cloud-syncs. The copy already exists in `lib/platformCopy.ts`. |
| `save.library_label` | `'master.db'` | |
### 3.3 Verification — non-negotiable
The project's core safety property is: **an edit changes only what it was supposed
to change.** For Traktor that is a byte diff. A byte diff is meaningless against
SQLite, so build the agreed analogue:
- **`test_rekordbox_fidelity.py`** — full table dump before/after, row-level diff.
A no-op save must produce zero row changes. A single metadata edit must change
exactly one row (plus whatever the USN research says *must* also change).
- **`test_rekordbox_adapter.py`** — the generic-layer test, modelled on
`test_traktor_adapter.py`: one parse per open, the projection refreshing after
each command family, cue-type translation, capabilities, `Unsupported` where the
platform cannot represent an edit.
- Add both to `run_tests.sh`.
- **Back up `master.db` *and* its `-wal`/`-shm`** before any write. A `.db` copied
without its WAL is not a consistent snapshot.
**Never test against Ben's real library.** Every existing test copies to a temp
dir first. Do the same.
---
## 4. Landmines (earned, not speculative)
**`history.py` assumes a single tracked file.** It commits one blob named after the
library file into a git repo keyed by a hash of the library's OS path. Neither
assumption survives `master.db` + WAL/SHM. There is a read-side fallback chain for
the blob name, but the *multi-artefact* case is genuinely unimplemented. Decide
early whether Rekordbox history commits a snapshot set or is disabled for this
platform — and if disabled, `capabilities.save.history` must say so, because the
UI reads it.
**Four spots in the adapter protocol are over-fitted to Traktor.** These were
recorded during the refactor precisely so you would not rediscover them. Expect to
revise the protocol; v1 was never frozen:
- `GridMarker.companion` — a Traktor convention (a white cue paired with a grid
marker, occupying a real hotcue slot). Should be `null` on Rekordbox.
- **Hotcue `slot` as a plain `int`** — memory cues have no slot. `CuePoint.slot` is
already nullable, but every *command* is slot-addressed. This is the most likely
thing to need changing, and the frontend design considered (and deferred) opaque
cue IDs as the fix. Revisit that decision with real evidence.
- **Grid marker `index` as identity** — fine for a list-shaped grid, untested
against rows with their own primary keys.
- `set_analysed_grid` — invented for one caller (Auto Grid), to let Traktor write
the companion cue without leaking the concept upward. Check it still earns its
keep with two platforms.
**Memory cues stay preserved-but-uneditable even after this lands.** The
two-platform promotion rule promotes a concept once **two or more** platforms have
it. Rekordbox is the *only* platform with memory cues (Traktor has none, Serato has
a saved-loop bank instead). So: project them, show them read-only, do **not** build
a memory-cue editing UI. This will feel wrong — build it anyway, the rule exists to
stop one-platform concepts becoming fake abstractions.
**Per-cue colour, by contrast, *is* now promotable.** Traktor and Rekordbox both
have it, which is two platforms. `cueColor()` in `frontend/src/lib/cues.ts` already
prefers a stored colour over the type palette, and `capabilities.cues.color` is
already plumbed — but there is **no colour-editing control yet**. Adding one is
legitimately in scope for this step.
**`slot_labels: 'letter'` has never run.** Rekordbox labels hotcues A–H. The field
is threaded through `HotcueBar`, `drawCues` and the keyboard map, but nothing has
ever set it to `'letter'`. Assume it is subtly broken.
---
## 5. Working agreements
- **`./run_tests.sh` must be green at the end of every step.** The Traktor refactor
was done in 18 steps with the suite green at each one; that discipline is why a
1,500-line change to the save path landed without a fidelity regression.
- **`schemas.py` and `api.ts` land in the same commit, always.** They are one
contract in two languages.
- **The collection is real, irreplaceable data.** Point `KONDUKTOR_NML` (or the
Rekordbox equivalent) at a **copy** when testing writes. See CLAUDE.md gotcha 2.
- Read `CLAUDE.md` in full before starting — its Architecture and "Write path"
sections describe the current state accurately and its "Critical gotchas" are
all still live.
## 6. Do not relitigate
Settled in the discussion doc; reopening these wastes a session:
- Projection + command replay as the save model (and why generic-model-as-source-of-truth
and diff-based writeback were both rejected).
- Strictly-generic command vocabulary, **no adapter escape hatches**.
- Rich core model + mandatory capability system.
- Rekordbox before Serato (`pyrekordbox` is the more mature library, despite the
riskier write target).
- **Warn but proceed** if Rekordbox is running — do not hard-refuse.
- Export is step 6, after Serato. Export Sets, fresh-target-only, copied audio.
- **CDJ/USB export (`export.pdb` + ANLZ) is rejected as impractical.** It has been
re-proposed once already. Do not raise it again.
- Deferred, do not reopen without Ben raising them: the export loss report, Tauri
packaging, two-way sync.
**Bulk metadata editing** was deferred *to* this point specifically so it would
only have to be written once, against the adapter architecture. It is now
unblocked, and is a much smaller piece of work than the Rekordbox adapter. If Ben
wants something shippable sooner, that is the alternative — confirm with him rather
than assuming.
---
## 7. One outstanding verification from step 3
**The React UI has never been rendered in a browser.** The generic wire format was
verified end-to-end through the Vite proxy (every endpoint, full write round trip,
byte-fidelity diff), but no browser driver was available on the dev machine —
no `chromium-cli`, no Playwright, and `npx` refused to install one.
Before building on top of the frontend, open `http://localhost:5173` (`./dev.sh`)
and click through the prep deck, the library table and the playlist tree. If you
can get a browser driver working, capturing the launch recipe via
`/run-skill-generator` would be worth it — the app needs `KONDUKTOR_NML` and
`KONDUKTOR_DATA_DIR` pointed at a temp copy to be driven safely, which is exactly
the kind of thing a project skill should hold.
---
## 8. Findings — Rekordbox research spike (2026-09-17)
Answers to §2, established empirically against a real Rekordbox 7 library
(`~/Library/Pioneer/rekordbox/master.db`, 52 tracks, 23 cues, 1 playlist) with
`pyrekordbox` 0.4.4. **Every experiment ran against a copy in a scratch dir; the
real library was only ever read.** Rekordbox was not running.
Each finding is marked **VERIFIED** (observed directly), **INFERRED** (strongly
implied but not directly exercised) or **UNTESTED**.
### 8.1 The USN question is answered — and it is not a blocker
**VERIFIED — the sequence model.** There is one global counter and one per-row
stamp:
- `agentRegistry` row `registry_id='localUpdateCount'`, column `int_1` — the
global local USN. Observed at **1489**, with the highest `rb_local_usn` found
anywhere in the library at 1487. The global counter is the high-water mark.
- Every syncable table carries `rb_local_usn`. One edit = increment the global
counter by one, stamp the changed row with the new value.
**VERIFIED — `pyrekordbox` maintains this for you.** It is not the caller's job.
`RekordboxAgentRegistry` hooks SQLAlchemy's update/create/delete events into an
update buffer, and `db.commit()` (default `autoinc=True`) calls
`autoincrement_local_update_count(set_row_usn=True)`, which walks the buffer,
increments the counter once per change and stamps each affected row
(`db6/registry.py:311-347`). Konduktor should **use `commit()` and not touch USNs
by hand.**
**VERIFIED — a single metadata edit is exactly as localized as the Traktor
invariant demands.** Full 47-table row-level dump before/after a one-field Title
edit produced exactly two changed rows:
```
agentRegistry localUpdateCount UPDATE int_1: 1489->1490
djmdContent 231764591 UPDATE Title: 'NOISE'->'...', rb_local_usn: 210->1490
```
A no-op open+close, and an open + `commit()` with no edits, both produce **zero
row changes**. Invariants A and C from `test_save_fidelity.py` therefore have
direct, achievable Rekordbox analogues.
**VERIFIED — the cloud columns are inert on a local library.** `usn` (the
*server* sequence number, distinct from `rb_local_usn`) is **NULL on every row of
every table**, and `rb_data_status`, `rb_local_data_status`, `rb_local_deleted`
and `rb_local_synced` are **0 on every row**. This library has a signed-in
account (`agentRegistry.agentCredentials` is populated) but Cloud Library Sync is
not enabled for the collection.
**UNTESTED — the cloud-synced case.** Because nothing in this library is synced,
the spike could not observe what the server does with a locally-bumped USN it did
not issue. The risk in the handoff stands unrefuted for that configuration. Two
mitigations are available and cheap, and both should be built:
1. Detect sync state on open — `usn` non-NULL anywhere, or a populated
`djmdCloudProperty`/`cloudAgentRegistry` — and surface it.
2. Gate writes on a cloud-synced library behind an explicit confirmation, or
report `save.overwrite_risk` accordingly. **Recommend raising this with Ben as
a scope decision before the write path is built**, per the handoff.
**VERIFIED — detecting a running Rekordbox is already solved**:
`pyrekordbox.utils.get_rekordbox_pid()`. That is all "warn but proceed" needs.
### 8.2 The real surprise: the write surface is three artefacts, not one
This is the finding that should change the plan. Konduktor's prep features do not
all live in `master.db`.
**VERIFIED — the beatgrid is NOT in the database.** There is no beatgrid, beat,
grid or tempo table anywhere in the 47-table schema. `djmdContent.BPM` is a
scalar display value stored ×100 (`12500` = 125.00 BPM) and is **`0` for 22 of
the 52 tracks** despite all 52 being analysed. The grid lives in the ANLZ
analysis files that `djmdContent.AnalysisDataPath` points at.
**VERIFIED — and it is a per-beat list, not a marker list.** The `PQTZ` tag in
`ANLZ0000.DAT` stores **every beat explicitly** — beat-number-in-bar, BPM and
time per beat (one track: 496 entries). This is a materially different shape from
Traktor's marker list. The adapter must *derive* `GridMarker`s from runs of
constant BPM on read, and *expand* markers back into a full beat list on write.
This directly revises the handoff's §4 landmine "grid marker `index` as identity
— untested against rows with their own primary keys": Rekordbox has no marker
rows at all. Index-as-identity is actually fine here, because the adapter mints
the marker list itself. The real work is the projection both ways.
**VERIFIED — cues live only in the database, in two places at once.**
`djmdCue` holds normalized cue rows, and `contentCue` holds a **JSON mirror** of
the same cues per track (`contentCue.Cues` is a JSON array of the full cue
objects, with `rb_cue_count` alongside). Both are maintained by Rekordbox and
must be kept consistent by any writer — this is Rekordbox's structural analogue
of Traktor's companion-cue convention, and the same class of trap.
**VERIFIED — the ANLZ cue lists are empty and can be ignored.** Across the whole
library, every `PCOB` (hotcue and memory) and `PCO2` tag in every `.DAT` and
`.EXT` has a cue count of **0**, while the database holds 23 cues. Rekordbox 7
populates the ANLZ cue tags only on device/USB export — which is out of scope.
**Konduktor should write cues to the DB only.**
**VERIFIED — Rekordbox does not stamp `rb_local_usn` on `djmdCue`.** All 23
`djmdCue` rows have a NULL `rb_local_usn`, while `contentCue` rows are stamped
(956–1482). The sync unit for cues is `contentCue`, not the individual rows.
Note that `pyrekordbox`'s `set_row_usn=True` stamps *every* buffered instance
that has the attribute, so committing a new `DjmdCue` through it **would stamp a
row Rekordbox itself leaves NULL**. Whether that matters is UNTESTED, but it is a
deviation from observed native behaviour and worth matching deliberately.
### 8.3 ANLZ write fidelity — a clean, defensible boundary
Parse → `build()` → byte-compare, over every analysis file in the library:
| File | Byte-identical | Differs | Holds |
|---|---|---|---|
| `.DAT` | **52 / 52** | 0 | `PQTZ` beatgrid, waveform, cue tags |
| `.EXT` | **52 / 52** | 0 | `PQT2`, colour waveform, `PSSI`, cue tags |
| `.2EX` | 32 / 52 | **20** | RB7 colour-waveform tags only |
`.DAT` and `.EXT` — the only files Konduktor needs to write — round-trip
**byte-exactly**, so the gotcha-3 guarantee generalizes. `.2EX` loses ~4 KB on
rebuild because `pyrekordbox` 0.4.4 drops tags it does not know (`PVDI`), and
`.3EX` it cannot parse at all (`File type '.3EX' not supported!`). Neither holds
anything Konduktor edits.
**Rule for the adapter: only ever rebuild `.DAT` and `.EXT`; never touch `.2EX`
or `.3EX`.** A `test_rekordbox_fidelity.py` assertion should pin this.
### 8.4 `pyrekordbox` has no cue or beatgrid write API
Its write surface is playlists, folders, smart playlists, albums, artists,
genres, labels, `add_content`, and attribute assignment on ORM objects. There is
no `add_cue`/`set_cue`/`delete_cue` — only `get_cue` / `get_content_cue`.
So Konduktor must implement itself, against the ORM:
- creating/updating/deleting `DjmdCue` rows (including Rekordbox's own ID/UUID
minting convention),
- regenerating the `contentCue.Cues` JSON mirror and `rb_cue_count`,
- the whole beatgrid path via the `anlz` module (`set_beats`/`set_bpms`/
`set_times` exist on `PQTZAnlzTag`, plus `AnlzFile.build()`/`save()`).
**This is the single biggest correction to the effort estimate in this handoff.**
§3.1 frames the adapter as implementing 38 already-defined methods against a
mature library. That is true for metadata and playlists; it is not true for cues
and grids, which are the prep deck — Konduktor's most valuable feature — and
which need a hand-written native store per artefact type.
### 8.5 Two hazards found by hitting them
**A stale WAL beside a restored `.db` silently corrupts it.** `pyrekordbox` leaves
`master.db-wal`/`-shm` behind on `close()` — the write is in the WAL, not the
main file. The handoff's "back up the WAL too" is right, and there is a sharper
corollary for restore: **deleting any existing `-wal`/`-shm` before putting a
snapshot back is mandatory**, or SQLite replays the old WAL onto the new file.
Version-history restore for Rekordbox must be a *set* operation, never a
single-file copy. This cost real time in the spike: an early experiment reported
a clean diff that was an artefact of a stale WAL.
**A clean Rekordbox quit leaves no WAL.** `master.db-wal`/`-shm` exist only while
Rekordbox (or another writer) holds the DB open; on a clean quit it checkpoints
and removes them. So §3.3's "back up `master.db` *and* its `-wal`/`-shm`" is
conditional: copy them **if present**, and treat their presence on open as a
signal that something else has the library open. Konduktor's own writer must
checkpoint (`PRAGMA wal_checkpoint(TRUNCATE)`) before anything copies or
snapshots the file, or the snapshot is stale.
**`AnlzFile.keys()` / `len()` infinitely recurse** in 0.4.4 (`__len__` →
`keys()` → `__len__`). Use `file.tags`, `get_tag()` and `getall_tags()`; never
treat an `AnlzFile` as a Mapping.
### 8.6 Dependency posture
`pyrekordbox` 0.4.4 and `sqlcipher3` both install cleanly on Python 3.14 from
prebuilt wheels — no Rust or OpenSSL source build — so they satisfy the
constraint in CLAUDE.md's Conventions. The SQLCipher key is embedded obfuscated
in `pyrekordbox` (`db6/database.py`, `deobfuscate(BLOB)`); no key download or
extraction step is needed.
### 8.7 Capability table, revised against the real library
Replaces the "expected" column in §3.2. Still to be confirmed per item where
marked.
| Field | Value | Evidence |
|---|---|---|
| `cues.hotcue_slots` | 8 | INFERRED (RB convention; not exercised — this library has no full bank) |
| `cues.slot_labels` | `'letter'` | INFERRED |
| `cues.memory_cues` | `true` | VERIFIED (`djmdCue.Kind` distinguishes them) |
| `cues.types` | `['cue','loop']` | VERIFIED (a loop row carries `OutMsec` + `BeatLoopSize`) |
| `cues.color` | `'palette'` (probable) | UNRESOLVED: `djmdCue` has `Color` + `ColorTableIndex`, but the `djmdColor` table (8 rows: Pink/Red/Orange/Yellow/Green/Aqua/Blue/Purple) is the **track**-colour palette, not necessarily the cue one. Settle by colouring a cue in Rekordbox and diffing. |
| `cues.named` | `true` | VERIFIED (`djmdCue.Comment`, e.g. `"1.1Bars"`) |
| `grid.flexible` | `true` | VERIFIED (per-beat BPM in `PQTZ` can vary) |
| `grid.lockable` | ? | UNRESOLVED — no obvious lock column found; check `djmdContent` flags |
| `save.overwrite_risk` | `'while_running'` | as planned |
| `save.library_label` | `'master.db'` | |
| `save.history` | **`false` initially** | The artefact set is `master.db` + N ANLZ files + `masterPlaylists6.xml`; `history.py` is single-blob. See §4. |
**UNRESOLVED — the `djmdCue.Kind` encoding.** Observed: `Kind=1` ×20 (one per
analysed track, near t=0, comment `"1.1Bars"` — Rekordbox's auto-placed cue),
plus `Kind=2`, `Kind=3` and `Kind=5` (the loop) on the one hand-prepped track.
The ANLZ tags could not disambiguate because they are empty. Resolve by setting a
known hot cue A–H and a known memory cue in Rekordbox and re-reading the table —
a five-minute experiment that needs the app.
### 8.8 Recommended next steps
1. ~~Ask Ben the scope question: cloud-synced libraries.~~ **DECIDED 2026-09-17:
detect and refuse.** If the library is cloud-synced, Konduktor opens it
read-only and does not write. Detection: `usn` non-NULL on any row, or a
populated `djmdCloudProperty` / `cloudAgentRegistry`. This needs a capability
answer the UI can gate on — the existing `save` capabilities have no
"readable but not writable" state, so either add one or report every
`editable_fields`/grid/cue capability as empty. Prefer an explicit flag: a
silently uneditable library looks like a bug.
2. **The one experiment this spike could not run**: make a Konduktor-shaped write
to a *copy* of `master.db`, put it in place, launch Rekordbox, and observe
whether it accepts the rows, rewrites them, or complains. This needs Ben's
go-ahead because it means pointing the real app at a modified library. It also
resolves the `Kind` encoding above in the same session.
3. **Re-scope step 4 before building.** The adapter is metadata + playlists
(straightforward, `pyrekordbox` does the work) *plus* a hand-written cue store
(two tables kept consistent) *plus* an ANLZ beatgrid store (per-beat ⇄ marker
projection). Consider landing them as three separately-green milestones rather
than one adapter.
### 8.9 Rekordbox mutates the library just by starting up
**VERIFIED.** Launching Rekordbox 7 and doing nothing advanced the global USN by
five (1489 → 1494) and changed, with no user edit at all:
- `agentRegistry.agentCredentials` — the auth token, `str_1`/`str_2`/`text_1` and
its date, **rotated on launch**;
- `agentRegistry.notificationNextFetch` / `notificationFetchedUID` /
`LangPath` / `SyncSettingsRootPath` / `unrecoverableAuth` — timers and timestamps;
- three `djmdSampler` rows restamped (`rb_local_usn` 104→1490, 105→1492, 106→1494).
Two consequences:
1. **The "no-op changes nothing" invariant is only assertable across Konduktor's
own open/save cycle against a static file** — which is how §8.1 verified it.
`test_rekordbox_fidelity.py` must work on a temp copy and must not try to
assert quiescence across a Rekordbox app session. Worth stating in the test's
docstring, because the natural reading of "a no-op save changes nothing" will
otherwise look false the moment anyone launches the app.
2. **A whole-file restore of `master.db` rolls back more than library data.** It
would revert the auth token, notification state and sampler rows to whatever
they were at snapshot time. Traktor's `collection.nml` has no equivalent —
restoring it is harmless. This is an independent argument for
`capabilities.save.history = false` on Rekordbox at first, and for any later
history support being a *selective* restore rather than a file swap.
### 8.10 Acceptance test: Rekordbox accepts Konduktor's writes — VERIFIED
The §8.8 experiment has now been run, on the real library (full backup taken
first). A `master.db` carrying exactly one Konduktor-shaped edit — `djmdContent`
Title + `rb_local_usn` 843→1490, and `agentRegistry.localUpdateCount` 1489→1490,
committed through `pyrekordbox` — was installed and Rekordbox 7 was launched
against it.
**Result: accepted, cleanly.**
- Rekordbox **displayed the edited title** (`Demo Track 1 [KONDUKTOR WROTE
THIS]`). No warning, no error, no database-repair prompt, no re-analysis.
- It **left the edited row untouched**: `rb_local_usn` was still exactly 1490
afterwards. Rekordbox did not restamp, revert or re-derive it.
- Crucially, it **continued the sequence from Konduktor's value instead of
resetting it**: startup housekeeping took `localUpdateCount` 1490 → 1495,
handing 1491/1493/1495 to the `djmdSampler` rows it always touches (§8.9).
- The only other differences were that same launch housekeeping — auth-token
rotation, notification timers, sampler restamps. Nothing related to the edit.
So the USN protocol `pyrekordbox` implements is the one Rekordbox actually
expects, and a third-party write that maintains it is indistinguishable to
Rekordbox from its own. **This removes the last blocker on the local write path.**
Scope of the claim: one library, one field, one table, local-only (not cloud
synced), Rekordbox 7 on macOS. It does not license writing *any* row — the cue
and beatgrid paths (§8.2, §8.4) are still unexercised and carry their own risks.
But the premise the whole step was gated on — "writing rows without maintaining
the sync columns may corrupt Rekordbox's sync state" — is answered: maintain them
via `commit()` and Rekordbox is content.
**Still unresolved: the `djmdCue.Kind` encoding** (§8.7). The cue half of the
experiment was not performed; `Demo Track 2` still has zero cues. It needs
someone to set a hot cue in slot A, a hot cue in slot C (skipping B, to separate
slot-letter from sequence), a memory cue, and a distinctive colour on one of
them, in Rekordbox — then diff `djmdCue`.
### 8.11 The cue encoding, resolved
Settled by setting known cues in Rekordbox on a previously cue-free track
(`Demo Track 2`, 120.00 BPM) and reading back `djmdCue`. **VERIFIED** unless noted.
**`Kind` is the cue's bank slot, and `0` means "memory cue".**
| Observed | `Kind` | `OutMsec` | `ColorTableIndex` |
|---|---|---|---|
| hot cue **A** @ 25 ms | `1` | `-1` | 22 |
| hot cue **C** @ 62.5 s | `3` | `-1` | 62 |
| memory cue @ 78.0 s | `0` | `-1` | — |
| memory cue @ 25 ms | `0` | `-1` | — |
| hot cue **F**, 4-beat loop @ 120.0 s | `7` | `122026` | 0 |
So `Kind = 0` → memory cue (unslotted, unlimited), `Kind = N ≥ 1` → hot cue in
slot N. A→1 and C→3 confirm a 1-based letter index directly.
**CAVEAT — the slot→letter mapping is NOT a plain letter index.** The 4-beat loop
sits on pad **F**, the 6th of the eight pads (confirmed from a screenshot of the
deck: A/C/F lit, F sixth), yet it stored `Kind = 7`. So the observed mapping is
A→1, C→3, **F→7**, which no linear rule fits. The other track in the library
(`Motorola`) has `Kind` 2, 3 and 5, but which pads those were set on was never
observed, so it cannot arbitrate.
Both loops in the library sit at a `Kind` one above the next-lowest used slot,
which hints the anomaly may be loop-related — but that is one sample and a guess.
**Do not infer the mapping; measure it.** Set a cue on *all eight* pads A–H of a
fresh track and read the eight `Kind` values in one go. Two minutes, and it
yields the complete table with no inference. Until then the adapter should treat
`Kind` as an **opaque slot id** — store it, round-trip it, address cues by it —
and only the presentation layer needs the letter, which is precisely what
`cues.slot_labels = 'letter'` is for. Nothing else in this section depends on
the answer.
**A loop is an ordinary cue row with an out-point.** There is no separate loop
bank: `OutMsec` becomes the loop end and `BeatLoopSize` carries the musical
length. So `capabilities.cues.loops = 'cue_type'` (as Traktor), **not**
`'separate_bank'`. A loop can occupy a hot cue slot (`Kind=7` above) or be a
memory cue.
**`BeatLoopSize = (beats << 16) | 1`** — VERIFIED against two loops at different
tempos, each agreeing with the measured millisecond span:
| Track | BPM | `OutMsec - InMsec` | `BeatLoopSize` | hex | beats |
|---|---|---|---|---|---|
| Motorola | 125.00 | 480 ms | 65537 | `0x10001` | 1 |
| Demo Track 2 | 120.00 | 2000 ms | 262145 | `0x40001` | 4 |
The adapter must write both `OutMsec` and a consistent `BeatLoopSize`; deriving
one without the other will produce a loop Rekordbox renders inconsistently.
**Cue colour is a PALETTE index, and not `djmdColor`.** This closes the §8.7
question. The user-set colours came back as `ColorTableIndex` 22 and 62, with
`Color = -1`; Rekordbox's own auto-placed cues use `Color = 255,
ColorTableIndex = 0`. Index 62 is far beyond `djmdColor`'s 8 rows, so the cue
palette is a larger built-in table — `djmdColor` is the *track* colour palette
and is unrelated. Set `capabilities.cues.color = 'palette'` and populate
`palette` from the built-in table once its values are known (reading them out of
the Rekordbox app resources, or by sampling each swatch as above). `Color = -1`
appears to mean "no explicit colour".
**Field-level notes for the writer.** `InFrame` is set alongside `InMsec`
(frames at 150 fps: 62526 ms → 9378) and `OutFrame` alongside `OutMsec`; both are
populated by Rekordbox and should be written consistently. `ID` is a random
32-bit integer as a string, `UUID` a fresh uuid4, and `ContentUUID` copies the
track's `contentCue.UUID`. `ActiveLoop`, `CueMicrosec` and `Comment` are `0`/`""`
on user cues; `Comment` carries Rekordbox's own label on auto cues (`"1.1Bars"`).
**The `contentCue` mirror is maintained in lockstep** (§8.2): after the edits it
read `rb_cue_count = 5` with a 1964-byte JSON array holding all five records,
including their `created_at`/`updated_at`. Its `rb_local_usn` was stamped (1527)
while **every `djmdCue` row's stayed NULL** — confirming §8.2's finding that
`contentCue` is the sync unit and the individual cue rows are not.
---
## 9. Milestone 1 landed: the read-only Rekordbox adapter
`backend/konduktor/adapters/rekordbox/` now opens, projects and serves a real
Rekordbox library through the generic layer. `./run_tests.sh` is green at **217
assertions** (was 146). Nothing about the Traktor path changed.
**What works**: `can_open` probe (decrypts one page, looks for `djmdContent`;
rejects a plain SQLite `.db`), default-location discovery via `pyrekordbox`'s own
config, the full read projection (tracks, cues, beatgrid, playlist tree, query /
facets / stats), `audio_path` with path remapping, and capabilities. Verified end
to end through the HTTP API: `/api/capabilities`, `/api/tracks`,
`/api/tracks/cues`, `/api/playlists`, `/api/stats` all serve Rekordbox data, and
`PATCH /api/tracks` returns a clean 422.
**What it deliberately does not do**: every one of the 21 mutating commands
raises `Unsupported`. The capability system is the mechanism (nothing is
advertised as editable); the raise is the backstop.
### Decisions made while building it, which the write path inherits
- **`Kind` stays an opaque slot id** all the way through. §8.11's anomaly (pad 6
→ `Kind` 7) therefore blocks nothing; only a UI label needs the mapping.
- **`grid_marker_count` is an approximation, corrected on read.** Reading every
ANLZ at open costs ~12 s on a full-size library, so the projection reports 1
for any track with a BPM and `track_cues()` writes the true count back. BPM —
not the presence of an analysis file — is the signal: Rekordbox analyses
one-shot samples too and gives them an ANLZ with no grid. On the reference
library the two sets agree exactly (22 tracks, both).
- **Internal Rekordbox playlists are hidden** (`SPECIAL_PLAYLIST_IDS`: "CUE
Analysis Playlist", "Cloud Library Sync"). They are not the user's.
- **Cue colour is projected as `None`, not guessed.** `ColorTableIndex` is an
index into a built-in palette whose values are not yet known, and inventing an
RGB value would be worse than admitting the gap. `capabilities.cues.color` is
already `"palette"` so the UI knows not to offer a free picker.
- **`snapshot()` and `restore()` raise.** A Rekordbox library is
`master.db` + N ANLZ files + `masterPlaylists6.xml`, and restoring the database
alone would also roll back Rekordbox's auth token and sampler state (§8.9).
`capabilities.save.history` is `False` to match.
### Two fixes that were not strictly in scope
- **`main.py` no longer imports Traktor's `describe`.** The picker's "last
opened" shortcut ran every path through `adapters.traktor.discovery.describe`
regardless of platform — a layering leak `test_layering.py` could not see,
because it only guards `core/`. There is now a generic `registry.describe()`
that delegates to whichever driver recognises the path and falls back to a
plain `exists: false` record for a library that has since moved.
- **`test_layering.py` now guards every adapter**, not just `core/`: no adapter
may import another platform's library. It checks real imports via AST rather
than text, because the first (text-matching) version failed on docstrings that
merely *mention* the other platform.
### Next, in order
1. **Milestone 2 — metadata + playlist writes.** This is the part `pyrekordbox`
actually implements and §8.1/§8.10 verified: commit through it, USNs are
maintained, Rekordbox accepts the result. Needs `test_rekordbox_fidelity.py`
(the row-level dump/diff harness — a working prototype exists in the session
scratch dir and is described in §8.1), plus the cloud-sync refusal wired to a
real capability rather than only to `Unsupported`.
2. **The capability system needs a "readable but not writable" state.** Right now
read-only is expressed by reporting every individual capability as false,
which is indistinguishable from "this platform has no such feature" and will
read as a bug to a user. Add an explicit flag before milestone 2, not after.
3. **Milestone 3 — the cue store and the ANLZ grid store.** Both hand-written;
see §8.2 and §8.4. `beatgrid.beats_from_markers()` is already written and
unit-tested as the inverse of the read projection, so the grid write has a
starting point.
+36 -2
View File
@@ -59,6 +59,27 @@ Two independent apps that talk over HTTP:
- `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore.
- `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion
rules, LOCATION ↔ OS path conversion, and its capability set. rules, LOCATION ↔ OS path conversion, and its capability set.
- `adapters/rekordbox/` — **READ-ONLY** (milestone 1 of the Rekordbox work).
`master.db` is SQLCipher-encrypted SQLite, read via `pyrekordbox`. Every
mutating command raises `Unsupported` and `capabilities()` advertises nothing
as editable, so the UI never offers an edit. Three things differ from Traktor
and are the reason this adapter is not a copy of it:
- **The beatgrid is NOT in the database.** There is no grid table at all; it
lives in per-track ANLZ analysis files as a `PQTZ` tag listing EVERY BEAT.
`beatgrid.py` collapses those into the generic marker list on read and
expands them back on write. `store.anlz_grid()` parses them **lazily** —
~1.4 ms each, i.e. ~12 s for a library of 8,500 if done at open — so
`Track.grid_marker_count` carries a documented approximation (1 when the
track has a BPM) that `track_cues()` corrects.
- **Cues live in two places** that must agree: `djmdCue` rows and a JSON
mirror in `contentCue.Cues` (+ `rb_cue_count`). Rekordbox stamps
`rb_local_usn` on `contentCue`, never on the cue rows.
- **`djmdCue.Kind` is an OPAQUE slot id**: 0 = memory cue, N = hot cue slot N.
Pads A and C store 1 and 3, but the 6th pad stored 7 — so the slot→letter
mapping is NOT a plain index and is deliberately left to the UI.
Writes are refused outright on a **cloud-synced** library (detected by a
server-issued `usn` on any row): a bad sync state would propagate to the
user's other machines, which version history cannot undo.
- `app_state.py` — the one loaded library, and the **version-history commit**. - `app_state.py` — the one loaded library, and the **version-history commit**.
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.
@@ -178,7 +199,14 @@ serialization path.** It enforces:
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`
covers the store and its bytes; without this the adapter layer would be untested. covers the store and its bytes; without this the adapter layer would be untested.
- `test_layering.py` — `core/` imports nothing platform-specific. - `test_rekordbox_adapter.py` — the second adapter against the same contract:
cue/grid/key translation as pure units (they need no library), then the
projection, playlist tree, capabilities and the refusal of all 21 commands
against a **temp copy** of the local Rekordbox library. Skips cleanly when no
Rekordbox is installed, so it is safe on any machine.
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
imports another platform's library (checked on real imports via AST, so merely
naming a platform in a comment is fine).
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`.
@@ -284,7 +312,13 @@ that number and nothing else — everything derives from it:
- ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of - ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of
the multi-platform plan. Backend, wire format and UI are all generic; nothing the multi-platform plan. Backend, wire format and UI are all generic; nothing
above `adapters/traktor/` knows what Traktor is. above `adapters/traktor/` knows what Traktor is.
- ⬜ Rekordbox adapter; ⬜ Serato adapter; ⬜ export/conversion - 🟡 Rekordbox adapter — **read-only milestone done**: a Rekordbox library opens,
projects and browses through the generic layer (tracks, playlists, cues,
beatgrid), with every command refused. Research for the write path is captured
in `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that
Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining:
metadata/playlist writes, then the hand-written cue store and ANLZ grid store.
- ⬜ Serato adapter; ⬜ export/conversion
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
## Write path (playlists + track metadata + prep) ## Write path (playlists + track metadata + prep)
+4 -1
View File
@@ -1,6 +1,9 @@
"""Per-platform adapters. Each owns a native library model and translates the """Per-platform adapters. Each owns a native library model and translates the
generic commands onto it; nothing outside an adapter package sees a native type. generic commands onto it; nothing outside an adapter package sees a native type.
Importing this package registers every adapter. Importing this package registers every adapter. Order matters only for the
registry's ``can_open()`` probe, and the probes are mutually exclusive: Traktor
requires an NML header, Rekordbox an encrypted database with its own schema.
""" """
from . import rekordbox # noqa: F401 — registers the Rekordbox driver
from . import traktor # noqa: F401 — registers the Traktor driver from . import traktor # noqa: F401 — registers the Traktor driver
@@ -0,0 +1,14 @@
"""The Rekordbox adapter: ``master.db`` (SQLCipher) via ``pyrekordbox``.
Importing this package registers the platform, so ``core.registry`` can find it
without knowing it exists.
Read-only in this milestone: the library is projected, browsed and searched, but
every command is refused. See `capabilities.py` for what that reports and the
handoff's Findings section for the research the write path will be built on.
"""
from ...core import registry
from .driver import RekordboxDriver
REKORDBOX = RekordboxDriver()
registry.register(REKORDBOX)
@@ -0,0 +1,274 @@
"""The Rekordbox adapter: owns the native database and the generic projection.
Mirrors `adapters.traktor.adapter`. It holds:
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
* a ``TrackIndex`` — the generic READ projection built from it.
**Read-only milestone.** Every mutating command raises `Unsupported`, and
`capabilities()` reports nothing as editable, so a correct UI never offers one
in the first place; the raise is the backstop, not the mechanism.
Writes are refused for a second, permanent reason on a cloud-synced library:
propagating a bad sync state to the user's other machines is not something
version history can undo. That check lives here so it cannot be bypassed by a
future command path forgetting it.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import projection
from .store import RekordboxStore
class RekordboxAdapter:
platform = "rekordbox"
def __init__(self, path: Path):
self.path = Path(path)
self._store = RekordboxStore(self.path)
self._index = TrackIndex()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
counts = self._store.cue_counts()
self._index.rebuild(
[
projection.to_track(row, counts.get(str(row.ID), (0, 0)))
for row in self._store.iter_content()
]
)
def reload(self) -> None:
self._store._load()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(self.path, cloud_synced=self._cloud_synced)
@property
def cloud_synced(self) -> bool:
return self._cloud_synced
# ---- read ------------------------------------------------------------
@property
def tracks(self) -> list[Track]:
return self._index.tracks
@property
def by_key(self) -> dict[str, Track]:
return self._index.by_key
def track(self, track_id: str) -> Track | None:
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)
def playlist_count(self) -> int:
return self._store.count_playlists()
def track_cues(self, track_id: str) -> TrackCues | None:
if self._index.get(track_id) is None:
return None
cues = projection.to_track_cues(
self._store.cues(track_id), self._store.anlz_grid(track_id)
)
# The track projection carries an APPROXIMATE grid_marker_count until the
# grid is actually read (see projection.to_track). This is that moment —
# correct it, so the library table stops showing the guess.
track = self._index.get(track_id)
if track is not None:
track.grid_marker_count = len(cues.grid_markers)
return cues
# ---- playlists -------------------------------------------------------
def playlist_tree(self) -> list[PlaylistNode]:
"""Rekordbox stores the tree as a flat table with ``ParentID`` links."""
from pyrekordbox.db6 import tables
rows = self._store.playlists()
folder = int(tables.PlaylistType.FOLDER)
smart = int(tables.PlaylistType.SMART_PLAYLIST)
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
for r in rows:
attribute = int(r.Attribute or 0)
kind = "folder" if attribute == folder else ("smart" if attribute == smart else "playlist")
node_id = str(r.ID)
nodes[node_id] = PlaylistNode(
id=node_id,
name=r.Name or "",
kind=kind,
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
# A smart playlist has no static entry list; a folder has no tracks.
selectable=kind == "playlist",
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
can_contain_children=kind == "folder",
)
parent = str(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
roots: list[PlaylistNode] = []
for node_id, node in nodes.items():
parent_id = parents.get(node_id, "root")
parent = nodes.get(parent_id)
if parent is None:
roots.append(node)
else:
parent.children.append(node)
return roots
def playlist_entries(self, node_id: str) -> list[str] | None:
ids = self._store.playlist_song_ids(node_id)
return ids if ids or self._is_playlist(node_id) else None
def playlist_tracks(self, node_id: str) -> list[Track] | None:
keys = self.playlist_entries(node_id)
if keys is None:
return None
return [t for k in keys if (t := self._index.get(k)) is not None]
def _is_playlist(self, node_id: str) -> bool:
return any(str(r.ID) == str(node_id) for r in self._store.playlists())
# ---- audio / paths ----------------------------------------------------
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
return {"primary": primary, "groups": [{"prefix": primary, "count": len(paths)}] if primary else []}
def remap_preview(self, mapping: PathMapping) -> dict:
paths = [Path(p) for p in self._store.all_audio_paths()]
matched = [p for p in paths if mapping.matches(p)]
samples = []
for p in matched[:5]:
target = mapping.apply(p)
samples.append({"from": str(p), "to": str(target), "exists": target.exists()})
existing = sum(1 for p in matched if mapping.apply(p).exists())
return {
"total": len(paths),
"matched": len(matched),
"existing": existing,
"samples": samples,
}
def remap_locations(self, mapping: PathMapping) -> int:
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return False
def save(self):
raise Unsupported(self._readonly_reason("Saving"))
def snapshot(self) -> bytes:
"""The library's bytes, for version history.
`master.db` alone is NOT a complete snapshot of a Rekordbox library (the
beatgrids live in separate ANLZ files, and restoring the database
wholesale would also roll back Rekordbox's own auth and sampler state),
which is why `capabilities.save.history` is False. Nothing should be
calling this.
"""
raise Unsupported("Rekordbox libraries are not versioned by Konduktor")
# ---- commands: all refused in this milestone -------------------------
def _readonly_reason(self, what: str) -> str:
if self._cloud_synced:
return (
f"{what} is not possible: this Rekordbox library is synced with "
"Rekordbox Cloud, and Konduktor will not write to a cloud-synced "
"library."
)
return f"{what} is not supported yet for Rekordbox libraries."
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists")
def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists")
def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists")
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._refuse("Editing playlists")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return None
def set_cue(self, track_id: str, **kw) -> TrackCues:
self._refuse("Editing cues")
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._refuse("Editing cues")
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._refuse("Deleting cues")
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._refuse("Placing cues")
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._refuse("Editing the beatgrid")
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._refuse("Editing the beatgrid")
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._refuse("Editing the beatgrid")
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._refuse("Editing the beatgrid")
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
def delete_grid(self, track_id: str) -> TrackCues:
self._refuse("Editing the beatgrid")
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
self._refuse("Locking the beatgrid")
@@ -0,0 +1,80 @@
"""Rekordbox's beatgrid <-> the generic marker list.
**Rekordbox does not store markers.** There is no beatgrid table in
``master.db`` at all; the grid lives in the track's ANLZ analysis file as a
``PQTZ`` tag holding EVERY BEAT explicitly — beat-number-in-bar, BPM and time,
one entry per beat (a 4-minute track is ~500 entries).
Konduktor's generic model is a marker list, so this module is the projection
between the two:
* read — collapse runs of equal BPM into one marker each, so a constant-tempo
track becomes a list of length one and a variable-tempo track becomes one
marker per tempo change. This is exactly the shape ``core.model.GridMarker``
describes.
* write — expand a marker list back into a full beat list (milestone 2; the
read direction is what a read-only adapter needs).
BPMs are compared with a tolerance because Rekordbox stores them as hundredths
and floating-point division reintroduces noise; two beats within `BPM_EPSILON`
are the same tempo and must not produce a spurious marker.
"""
from __future__ import annotations
from ...core.model import GridMarker
BPM_EPSILON = 0.005 # half of the 0.01 BPM Rekordbox can actually represent
def markers_from_beats(
times: list[float], bpms: list[float], beats: list[int] | None = None
) -> list[GridMarker]:
"""Collapse a per-beat grid into the generic marker list.
`times` are seconds, `bpms` the tempo in force at each beat. A marker is
emitted for the first beat and wherever the tempo changes.
"""
if not times or not bpms:
return []
out: list[GridMarker] = []
last_bpm: float | None = None
for i, (t, bpm) in enumerate(zip(times, bpms)):
if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON:
out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None))
last_bpm = float(bpm)
return out
def beats_from_markers(
markers: list[GridMarker], duration_sec: float
) -> tuple[list[int], list[float], list[float]]:
"""Expand a marker list into the per-beat arrays Rekordbox stores.
Each marker governs until the next one; the last runs to `duration_sec`.
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
each marker, which is how Rekordbox numbers bars.
Not used by the read-only adapter, but it is the inverse of
`markers_from_beats` and belongs beside it.
"""
beat_nums: list[int] = []
bpms: list[float] = []
times: list[float] = []
if not markers:
return beat_nums, bpms, times
ordered = sorted(markers, key=lambda m: m.start)
for i, m in enumerate(ordered):
if m.bpm <= 0:
continue
end = ordered[i + 1].start if i + 1 < len(ordered) else duration_sec
step = 60.0 / m.bpm
t = m.start
n = 1
# Guard against a zero/negative span producing an endless loop.
while t < end - 1e-9 and step > 0:
beat_nums.append(n)
bpms.append(m.bpm)
times.append(t)
n = n % 4 + 1
t += step
return beat_nums, bpms, times
@@ -0,0 +1,76 @@
"""What a Rekordbox library can persist.
**Milestone 1 reports everything as read-only.** The spike verified that
Rekordbox accepts writes that maintain its USN columns (see the handoff's
Findings), but the write path is not built yet, and the capability system exists
precisely so the UI never offers an edit that will not persist. Every flag here
is therefore false/empty until milestone 2 turns them on one at a time.
Two facts are already known and encoded, because getting them wrong later would
be a silent data bug rather than a missing feature:
* a saved loop is a cue with an out-point, NOT a separate bank, so
``loops="cue_type"`` — the same answer as Traktor, and NOT the
``separate_bank`` the original plan assumed;
* cue colour is a PALETTE index (``djmdCue.ColorTableIndex``), not free RGB,
and the palette is a built-in table — `djmdColor` is the *track* colour
palette and is unrelated.
"""
from __future__ import annotations
from ...core.capabilities import (
Capabilities,
CueCapabilities,
GridCapabilities,
PlaylistCapabilities,
SaveCapabilities,
TrackCapabilities,
)
from .cue_types import CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps
# slots numeric and lets the UI label them.
HOTCUE_SLOTS = 8
def capabilities_for(
path, version: str | None = None, *, cloud_synced: bool = False
) -> Capabilities:
return Capabilities(
platform="rekordbox",
version=version,
cues=CueCapabilities(
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# Rekordbox is the only platform with memory cues, so they are
# projected and PRESERVED but not editable (two-platform rule).
memory_cues=True,
max_memory_cues=None, # unlimited
types=CUE_TYPES,
color="palette",
palette=[], # TODO milestone 2: the built-in cue colour table
named=True, # djmdCue.Comment
loops="cue_type",
),
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
editable_fields=[], # read-only in this milestone
media_kinds=["audio"],
artwork=False,
artwork_note=None,
),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=False),
save=SaveCapabilities(
app_name="Rekordbox",
library_label="master.db",
# Rekordbox holds master.db open while running and cloud-syncs it,
# so a concurrent write is riskier than Traktor's overwrite-on-exit.
overwrite_risk="while_running",
# The artefact set is master.db + N ANLZ files + masterPlaylists6.xml,
# and history.py tracks a single blob. Also, restoring master.db
# wholesale would roll back Rekordbox's auth token and sampler state.
history=False,
),
)
@@ -0,0 +1,65 @@
"""Rekordbox's ``djmdCue.Kind`` encoding <-> the generic cue vocabulary.
The only place these integers are given meaning. Verified against a real
library (see the handoff's Findings section):
* ``Kind == 0`` -> a MEMORY cue: no bank slot, and Rekordbox allows any
number of them.
* ``Kind >= 1`` -> a HOT CUE occupying bank slot ``Kind``.
**``Kind`` is treated as an opaque slot id.** Setting cues on pads A and C
stored 1 and 3, but the pad in the 6th position stored 7, so the slot -> letter
mapping is NOT a plain index and has not been pinned down. Nothing here depends
on it: the adapter addresses cues by slot number and the UI labels them, which
is what ``capabilities.cues.slot_labels`` is for.
Loop-ness is NOT carried by ``Kind``. A loop is an ordinary cue row that also
has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
"""
from __future__ import annotations
MEMORY_KIND = 0
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
CUE_TYPES = ["cue", "loop"]
def role_and_slot(kind: int | None) -> tuple[str, int | None]:
"""(role, slot) for a native ``Kind``."""
if kind is None or kind == MEMORY_KIND:
return "memory", None
return "hotcue", int(kind)
def kind_for(role: str, slot: int | None) -> int:
"""The native ``Kind`` for a generic (role, slot). Inverse of `role_and_slot`."""
if role == "memory":
return MEMORY_KIND
if slot is None:
raise ValueError("a hot cue needs a slot")
return int(slot)
def cue_type(out_msec: int | None) -> str:
"""A cue with a real out-point is a loop; everything else is a plain cue.
Rekordbox writes ``OutMsec = -1`` for a non-loop.
"""
return "loop" if out_msec is not None and out_msec > 0 else "cue"
def beat_loop_size(beats: int) -> int:
"""Encode a loop's musical length.
``BeatLoopSize = (beats << 16) | 1`` — verified against two real loops at
different tempos (1 beat @125 BPM = 0x10001, 4 beats @120 BPM = 0x40001),
each agreeing with the measured millisecond span.
"""
return (int(beats) << 16) | 1
def beats_in_loop(beat_loop_size: int | None) -> int | None:
"""Decode `beat_loop_size`. None when unset."""
if not beat_loop_size:
return None
return beat_loop_size >> 16
@@ -0,0 +1,78 @@
"""Locate Rekordbox libraries in their default install locations.
Rekordbox keeps one library per install, at a fixed per-OS path:
macOS ~/Library/Pioneer/rekordbox/master.db
Windows %APPDATA%/Pioneer/rekordbox/master.db
``pyrekordbox`` already resolves this (including the v6/v7 split and any
non-default location recorded in Rekordbox's own settings), so that is the
primary source and the hard-coded paths are the fallback.
"""
from __future__ import annotations
from pathlib import Path
_RELATIVE = Path("Pioneer") / "rekordbox" / "master.db"
def _configured_paths() -> list[Path]:
"""Library paths pyrekordbox finds from Rekordbox's own configuration."""
out: list[Path] = []
try:
from pyrekordbox.config import get_config
except Exception: # noqa: BLE001 — never let discovery break startup
return out
for version in ("rekordbox7", "rekordbox6"):
try:
conf = get_config(version)
except Exception: # noqa: BLE001
continue
if not conf:
continue
p = conf.get("db_path")
if p:
out.append(Path(p))
return out
def _default_paths() -> list[Path]:
home = Path.home()
return [
home / "Library" / _RELATIVE, # macOS
home / "AppData" / "Roaming" / _RELATIVE, # Windows
]
def describe(path: Path) -> dict:
"""A candidate record for a master.db path, shaped like the picker wants."""
path = Path(path)
exists = path.is_file()
# The version Rekordbox itself is, not a schema version stamped in the file:
# master.db carries no version field, so the folder is the best label there is.
return {
"path": str(path),
"label": "Rekordbox",
"version": None,
"modified": (path.stat().st_mtime if exists else None),
"exists": exists,
}
def detect_libraries() -> list[dict]:
"""Every Rekordbox master.db found in a default location, newest first."""
seen: set[str] = set()
found: list[dict] = []
for p in _configured_paths() + _default_paths():
try:
if not p.is_file():
continue
except OSError:
continue
key = str(p.resolve())
if key in seen:
continue
seen.add(key)
found.append(describe(p))
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
return found
@@ -0,0 +1,85 @@
"""Opening Rekordbox libraries: recognition, discovery and restore."""
from __future__ import annotations
import logging
from pathlib import Path
from . import discovery
from .adapter import RekordboxAdapter
log = logging.getLogger(__name__)
_SQLITE_MAGIC = b"SQLite format 3\x00"
class RekordboxDriver:
platform = "rekordbox"
display_name = "Rekordbox"
suffixes = (".db",)
library_label = "master.db"
def can_open(self, path: Path) -> bool:
"""Recognise an encrypted Rekordbox database.
Extension is not enough — plenty of things are called ``.db`` — and a
SQLCipher file has no readable header at all (its first page is
encrypted, so it does NOT start with the SQLite magic). So the probe
decrypts just far enough to look for a table only Rekordbox has. That is
one page read, and it is the only way to answer honestly.
"""
try:
if not path.is_file() or path.suffix.lower() != ".db":
return False
with path.open("rb") as fh:
if fh.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC:
return False # a plain, unencrypted SQLite file
except OSError:
return False
return self._has_rekordbox_schema(path)
@staticmethod
def _has_rekordbox_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.db6.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
con = None
try:
con = sqlcipher.connect(str(path))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
row = con.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='djmdContent'"
).fetchone()
return row is not None
except Exception: # noqa: BLE001 — wrong key or not a database
return False
finally:
if con is not None:
try:
con.close()
except Exception: # noqa: BLE001
pass
def open(self, path: Path) -> RekordboxAdapter:
return RekordboxAdapter(path)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
def describe(self, path: Path) -> dict:
return discovery.describe(path)
def restore(self, path: Path, data: bytes) -> None:
"""Not supported: a Rekordbox library is more than one file.
`master.db` carries neither the beatgrids (ANLZ files) nor the playlist
XML, and putting an old database back would also revert Rekordbox's auth
token and sampler state. `capabilities.save.history` is False for the
same reason, so nothing should reach this.
"""
raise NotImplementedError(
"Konduktor does not version Rekordbox libraries: a restore would need "
"the analysis files and would roll back Rekordbox's own app state."
)
@@ -0,0 +1,177 @@
"""Rekordbox native rows -> the generic projection.
The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
"""
from __future__ import annotations
import re
from ...core.model import CuePoint, GridMarker, Track, TrackCues
from . import beatgrid
from .cue_types import cue_type, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
# Open Key notation. Parsing that is platform knowledge and belongs here.
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
# Camelot wheel position for each pitch class, per mode.
_CAMELOT_MINOR = {
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
"F": 4, "C": 5, "G": 6, "D": 7,
}
_CAMELOT_MAJOR = {
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
"F": 7,
}
def parse_key(key: str | None) -> tuple[int | None, str | None]:
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
if not key:
return None, None
m = _KEY_RE.match(key.strip())
if not m:
return None, None
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
pitch = letter + (accidental.replace("B", "b") if accidental else "")
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
n = table.get(pitch)
return (n, "minor" if minor else "major") if n else (None, None)
def _iso_date(value) -> str | None:
"""Rekordbox already stores ISO-ish 'YYYY-MM-DD'; blanks become None."""
if not value:
return None
s = str(value).strip()
return s or None
def _bpm(row) -> float | None:
"""``djmdContent.BPM`` is the tempo x100, and 0 means 'not known'.
It is a display value only — the real grid is in the ANLZ file — and it is
genuinely 0 for analysed tracks in real libraries.
"""
raw = getattr(row, "BPM", None)
if not raw:
return None
return round(raw / 100.0, 2)
def _name_of(related) -> str | None:
"""A joined lookup row's display name, or None when unset."""
if related is None:
return None
for attr in ("Name", "ScaleName"):
value = getattr(related, attr, None)
if value:
return str(value)
return None
def to_track(row, cue_counts: tuple[int, int] = (0, 0)) -> Track:
"""Project one ``DjmdContent`` row.
`cue_counts` is ``(total, hotcues)`` from the store's single aggregate
query — passed in rather than read off the row, which would be a per-track
round trip.
**`grid_marker_count` is an approximation here**: the real count needs the
track's ANLZ file, which is far too slow to read for every track at open
(~12 s on a library of 8,500). A track with a BPM is reported as 1 (constant
tempo, true for all but a fraction of a percent of real tracks) and the value
is corrected the moment the track's grid is actually read.
BPM — not the presence of an analysis file — is the signal, because Rekordbox
analyses one-shot samples too and gives them an ANLZ with no beatgrid at all.
On the reference library the two sets agree exactly: all 22 tracks with no
BPM are precisely the 22 with no grid.
"""
total_cues, hotcues = cue_counts
key_name = _name_of(getattr(row, "Key", None))
wheel, mode = parse_key(key_name)
return Track(
id=str(row.ID),
artist=_name_of(getattr(row, "Artist", None)),
title=getattr(row, "Title", None),
album=_name_of(getattr(row, "Album", None)),
genre=_name_of(getattr(row, "Genre", None)),
label=_name_of(getattr(row, "Label", None)),
remixer=_name_of(getattr(row, "Remixer", None)),
producer=None, # Rekordbox has Composer, which is not the same field
mix=None,
comment=getattr(row, "Commnt", None),
bpm=_bpm(row),
key=key_name,
key_wheel=wheel,
key_mode=mode,
# Rekordbox stores 0-5 stars directly — no /51 conversion, unlike Traktor.
rating=max(0, min(5, int(getattr(row, "Rating", 0) or 0))),
playcount=getattr(row, "DJPlayCount", None),
length=getattr(row, "Length", None),
bitrate=getattr(row, "BitRate", None),
import_date=_iso_date(getattr(row, "StockDate", None)),
last_played=None, # not modelled as a date in master.db
release_date=_iso_date(getattr(row, "ReleaseDate", None)),
filepath=str(getattr(row, "FolderPath", "") or "") or None,
cue_count=total_cues,
hotcue_count=hotcues,
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
grid_locked=False, # Rekordbox has no per-track grid lock
media_kind="audio",
)
def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) -> TrackCues:
"""Project a track's cues and beatgrid.
`grid` is the per-beat ``(times, bpms)`` from the ANLZ file, collapsed here
into the generic marker list. Rekordbox pairs nothing with a grid marker, so
`companion` is always None — that is a Traktor convention.
Every cue is projected as `editable=False` in this milestone, because the
adapter refuses every command; the UI gates on that flag alone.
"""
markers: list[GridMarker] = []
if grid is not None:
times, bpms = grid
markers = beatgrid.markers_from_beats(times, bpms)
cues: list[CuePoint] = []
for c in cue_rows:
role, slot = role_and_slot(getattr(c, "Kind", None))
out_msec = getattr(c, "OutMsec", None)
in_msec = getattr(c, "InMsec", 0) or 0
length = 0.0
if out_msec is not None and out_msec > 0:
length = max(0.0, (out_msec - in_msec) / 1000.0)
cues.append(
CuePoint(
name=(getattr(c, "Comment", None) or None),
type=cue_type(out_msec),
role=role,
start=in_msec / 1000.0,
length=length,
slot=slot,
color=_cue_color(c),
editable=False,
readonly_reason="platform_managed",
grid_marker=None,
)
)
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
The generic model carries ``#RRGGBB``, and the built-in palette that index
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
@@ -0,0 +1,255 @@
"""The retained native model for Rekordbox: the open ``master.db`` session.
This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted
SQLCipher session, the ANLZ analysis files, and the caches the projection reads.
**Read-only in this milestone.** The write path is deliberately absent rather
than stubbed: a store that cannot write cannot half-write.
Two things here are not obvious and are load-bearing:
* **ANLZ is read LAZILY.** The beatgrid lives in a per-track analysis file, not
in the database, and parsing them all costs ~1.4 ms each — about 12 seconds
for a library the size of the project's Traktor collection. So grids are
parsed on demand and cached, and `Track.grid_marker_count` carries a
documented approximation until a track's grid is actually read.
* **Cue counts come from ONE aggregate query**, not from walking each track's
relationship, which would be a per-track round trip at open.
"""
from __future__ import annotations
import logging
from pathlib import Path
from sqlalchemy import func, select, text
from sqlalchemy.orm import joinedload
from ...core.adapter import LibraryNotSupported, NotFound
from ...core.pathmap import PathMapping
log = logging.getLogger(__name__)
class RekordboxStore:
"""One open Rekordbox library."""
def __init__(self, path: Path):
self.path = Path(path)
self._mapping = PathMapping()
self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {}
self._load()
# ---- open ------------------------------------------------------------
def _load(self) -> None:
from pyrekordbox import Rekordbox6Database
from pyrekordbox.db6 import tables
self._tables = tables
try:
self._db = Rekordbox6Database(path=str(self.path), unlock=True)
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
self._grid_cache.clear()
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
def close(self) -> None:
try:
self._db.close()
except Exception: # noqa: BLE001 — closing must never raise
pass
# ---- identity --------------------------------------------------------
@property
def cloud_synced(self) -> bool:
"""True when this library participates in Rekordbox's Cloud Library Sync.
Konduktor REFUSES to write a cloud-synced library: a local edit that the
server did not issue could propagate a corrupt sync state to the user's
other machines, which version history cannot undo. Detection is the
presence of a server-issued sequence number (`usn`) on any row, or a
populated cloud registry.
"""
t = self._tables
with self._db.session.no_autoflush:
for table in (t.DjmdContent, t.DjmdPlaylist, t.DjmdCue):
n = self._db.session.execute(
select(func.count()).select_from(table).where(table.usn.isnot(None))
).scalar()
if n:
return True
# pyrekordbox does not model every cloud table, so the rest is a
# raw probe: any row carrying a server-issued usn means synced.
for table_name in ("cloudAgentRegistry", "djmdCloudProperty"):
try:
n = self._db.session.execute(
text(f'SELECT COUNT(*) FROM "{table_name}" WHERE usn IS NOT NULL')
).scalar()
except Exception: # noqa: BLE001 — table may be absent
continue
if n:
return True
return False
@property
def local_usn(self) -> int | None:
"""Rekordbox's global local update counter (for diagnostics/tests)."""
try:
return self._db.get_local_usn()
except Exception: # noqa: BLE001
return None
# ---- content ---------------------------------------------------------
def iter_content(self) -> list:
"""Every track, with the lookup tables eagerly joined.
Without `joinedload` each track's artist/album/genre/key would be a
separate query — thousands of round trips on a real library.
"""
if self._content_cache is None:
t = self._tables
q = (
self._db.session.query(t.DjmdContent)
.options(
joinedload(t.DjmdContent.Artist),
joinedload(t.DjmdContent.Album),
joinedload(t.DjmdContent.Genre),
joinedload(t.DjmdContent.Key),
joinedload(t.DjmdContent.Label),
joinedload(t.DjmdContent.Remixer),
)
.filter(t.DjmdContent.rb_local_deleted == 0)
)
self._content_cache = list(q)
self._by_id = {str(c.ID): c for c in self._content_cache}
return self._content_cache
def content(self, track_id: str):
self.iter_content()
assert self._by_id is not None
row = self._by_id.get(str(track_id))
if row is None:
raise NotFound(f"No track {track_id!r}")
return row
def cue_counts(self) -> dict[str, tuple[int, int]]:
"""``{track_id: (total_cues, hotcue_count)}`` in one aggregate query."""
t = self._tables
rows = self._db.session.execute(
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, func.count())
.where(t.DjmdCue.rb_local_deleted == 0)
.group_by(t.DjmdCue.ContentID, t.DjmdCue.Kind)
).all()
out: dict[str, tuple[int, int]] = {}
for content_id, kind, n in rows:
total, hot = out.get(str(content_id), (0, 0))
out[str(content_id)] = (total + n, hot + (n if (kind or 0) != 0 else 0))
return out
def cues(self, track_id: str) -> list:
"""A track's cue rows, ordered by position."""
t = self._tables
return list(
self._db.session.query(t.DjmdCue)
.filter(t.DjmdCue.ContentID == str(track_id))
.filter(t.DjmdCue.rb_local_deleted == 0)
.order_by(t.DjmdCue.InMsec)
)
# ---- playlists -------------------------------------------------------
def playlists(self) -> list:
"""User playlists, excluding Rekordbox's own internal ones.
Rekordbox keeps working lists ("CUE Analysis Playlist", "Cloud Library
Sync") in the same table at reserved ids. They are not the user's and
showing them in the sidebar would be noise.
"""
from pyrekordbox.db6.database import SPECIAL_PLAYLIST_IDS
t = self._tables
return [
p
for p in self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdPlaylist.Seq)
if str(p.ID) not in SPECIAL_PLAYLIST_IDS
]
def playlist_song_ids(self, playlist_id: str) -> list[str]:
t = self._tables
rows = (
self._db.session.query(t.DjmdSongPlaylist.ContentID)
.filter(t.DjmdSongPlaylist.PlaylistID == str(playlist_id))
.filter(t.DjmdSongPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdSongPlaylist.TrackNo)
)
return [str(r[0]) for r in rows]
def count_playlists(self) -> int:
"""Playlists the user has, for the status bar — folders excluded."""
folder = int(self._tables.PlaylistType.FOLDER)
return sum(1 for p in self.playlists() if int(p.Attribute or 0) != folder)
# ---- analysis files (the beatgrid) -----------------------------------
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None:
"""``(times_sec, bpms)`` per beat for a track, or None if unanalysed.
Parsed on demand and cached — see the module docstring for why this is
not done eagerly.
"""
key = str(track_id)
if key in self._grid_cache:
return self._grid_cache[key]
result = self._read_anlz_grid(key)
self._grid_cache[key] = result
return result
def _read_anlz_grid(self, track_id: str):
row = self.content(track_id)
rel = getattr(row, "AnalysisDataPath", None)
if not rel:
return None
# AnalysisDataPath is rooted at the library's `share` directory and is
# stored with a leading slash.
path = self.path.parent / "share" / str(rel).lstrip("/\\")
if not path.is_file():
return None
try:
from pyrekordbox.anlz import AnlzFile
anlz = AnlzFile.parse_file(str(path))
except Exception as ex: # noqa: BLE001 — a bad ANLZ must not break a read
log.debug("ANLZ parse failed for %s: %s", track_id, ex)
return None
for tag in anlz.tags:
# Never treat AnlzFile as a Mapping: keys()/len() recurse forever in
# pyrekordbox 0.4.4.
if tag.type == "PQTZ":
try:
return [float(t) for t in tag.times], [float(b) for b in tag.bpms]
except Exception: # noqa: BLE001
return None
return None
def has_analysis(self, track_id: str) -> bool:
return bool(getattr(self.content(track_id), "AnalysisDataPath", None))
# ---- paths -----------------------------------------------------------
def set_path_mapping(self, mapping: PathMapping) -> None:
self._mapping = mapping or PathMapping()
@property
def path_mapping(self) -> PathMapping:
return self._mapping
def audio_path(self, track_id: str) -> Path | None:
"""The track's audio file on THIS machine, after any path remap."""
folder = getattr(self.content(track_id), "FolderPath", None)
if not folder:
return None
return self._mapping.apply(Path(str(folder)))
def all_audio_paths(self) -> list[str]:
return [
str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None)
]
+24
View File
@@ -40,6 +40,30 @@ def open_library(path: Path):
return driver_for(path).open(path) return driver_for(path).open(path)
def describe(path: Path) -> dict:
"""Describe a library path using whichever adapter recognises it.
Used for the picker's "last opened" shortcut, which must still render when
the file has since been moved or deleted — so an unrecognised path gets a
plain description with ``exists`` false rather than an error.
"""
try:
return driver_for(path).describe(path)
except (LibraryNotSupported, OSError):
pass
try:
exists = path.is_file()
except OSError:
exists = False
return {
"path": str(path),
"label": path.name,
"version": None,
"modified": None,
"exists": exists,
}
def detect_all() -> list: def detect_all() -> list:
"""Every library found in the platforms' default install locations.""" """Every library found in the platforms' default install locations."""
out: list = [] out: list = []
+1 -2
View File
@@ -14,7 +14,6 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse from fastapi.responses import FileResponse, JSONResponse
from . import __version__, history, prefs from . import __version__, history, prefs
from .adapters.traktor.discovery import describe
from .app_state import STATE from .app_state import STATE
from .core import auto_hotcues as ah from .core import auto_hotcues as ah
from .core import registry from .core import registry
@@ -144,7 +143,7 @@ def collection_options() -> CollectionOptions:
recent = None recent = None
last = prefs.get_last_collection() last = prefs.get_last_collection()
if last: if last:
recent = CollectionCandidate(**describe(Path(last))) recent = CollectionCandidate(**registry.describe(Path(last)))
return CollectionOptions(auto=auto, recent=recent) return CollectionOptions(auto=auto, recent=recent)
+3
View File
@@ -17,3 +17,6 @@ scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0), # Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files. # NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
pyrekordbox>=0.4.4
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate source .venv/bin/activate
fail=0 fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_phase3.py test_history.py; do for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
echo "▶ $t" echo "▶ $t"
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
+35
View File
@@ -46,5 +46,40 @@ print("== adapters own their native model ==")
store = (CORE.parent / "adapters" / "traktor" / "store.py").read_text() store = (CORE.parent / "adapters" / "traktor" / "store.py").read_text()
check("the Traktor store is where traktor_nml_utils lives", "traktor_nml_utils" in store) check("the Traktor store is where traktor_nml_utils lives", "traktor_nml_utils" in store)
# No adapter may import another platform's library. That is the rule that keeps
# the packages independently removable, and it is checked on real imports (AST)
# rather than on text, so merely NAMING another platform in a comment is fine.
NATIVE = {"traktor": "traktor_nml_utils", "rekordbox": "pyrekordbox"}
def imported_modules(path):
names = set()
for node in ast.walk(ast.parse(path.read_text())):
if isinstance(node, ast.Import):
names.update(a.name for a in node.names)
elif isinstance(node, ast.ImportFrom) and not node.level:
names.add(node.module or "")
return names
for platform, module in NATIVE.items():
pkg = CORE.parent / "adapters" / platform
if not pkg.is_dir():
continue
foreign = {m for p_, m in NATIVE.items() if p_ != platform}
strays = []
for src in sorted(pkg.rglob("*.py")):
for name in imported_modules(src):
if any(name == f or name.startswith(f + ".") for f in foreign):
strays.append(f"{src.name}: {name}")
check(f"the {platform} adapter imports no other platform's library",
not strays, "; ".join(strays))
own = [
src.name
for src in sorted(pkg.rglob("*.py"))
if any(n == module or n.startswith(module + ".") for n in imported_modules(src))
]
check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+262
View File
@@ -0,0 +1,262 @@
"""Tests for the Rekordbox adapter (read-only milestone).
The counterpart to `test_traktor_adapter.py`: it exercises the GENERIC layer for
the second platform — the projection, the cue/grid translation, the playlist
tree, capabilities, and the refusal of every command — so that "a second adapter
satisfies the same contract" is a claim the suite actually checks rather than a
design intention.
Runs against a TEMP COPY of the local Rekordbox library, and skips cleanly when
there is no Rekordbox installed (CI, or any machine but the developer's).
"""
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rb-appdata-")
from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
from konduktor.adapters.rekordbox.beatgrid import ( # noqa: E402
beats_from_markers,
markers_from_beats,
)
from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402
beat_loop_size,
beats_in_loop,
kind_for,
role_and_slot,
)
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402
from konduktor.core import registry # noqa: E402
from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402
from konduktor.core.model import GridMarker # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
# ---- pure units: no library required -----------------------------------
print("== cue encoding ==")
check("Kind 0 is a memory cue with no slot", role_and_slot(0) == ("memory", None))
check("Kind N is hot cue slot N", role_and_slot(5) == ("hotcue", 5))
check("round-trips back to Kind", kind_for(*role_and_slot(5)) == 5 and kind_for("memory", None) == 0)
# Verified against two real loops: 1 beat @125 BPM and 4 beats @120 BPM.
check("BeatLoopSize encodes (beats << 16) | 1", beat_loop_size(4) == 262145 and beat_loop_size(1) == 65537)
check("and decodes back", beats_in_loop(262145) == 4 and beats_in_loop(None) is None)
print("== key parsing (Rekordbox names keys musically, not in Camelot) ==")
check("Fm -> 4A", parse_key("Fm") == (4, "minor"))
check("Am -> 8A", parse_key("Am") == (8, "minor"))
check("C -> 8B", parse_key("C") == (8, "major"))
check("Ebm -> 2A", parse_key("Ebm") == (2, "minor"))
check("unparseable key is None, not a guess", parse_key("nonsense") == (None, None))
check("absent key is None", parse_key(None) == (None, None))
print("== beatgrid: per-beat <-> marker list ==")
# Rekordbox stores EVERY beat; the generic model is a marker list.
times = [0.0, 0.5, 1.0, 1.5, 2.0, 2.4, 2.8]
bpms = [120.0, 120.0, 120.0, 120.0, 120.0, 150.0, 150.0]
markers = markers_from_beats(times, bpms)
check("a tempo change makes a second marker", len(markers) == 2, str(len(markers)))
check("markers carry their tempo and start", markers[0].bpm == 120.0 and markers[1].start == 2.4)
const = markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.0, 120.0])
check("a constant-tempo grid is ONE marker", len(const) == 1)
check("an empty grid projects to no markers", markers_from_beats([], []) == [])
# Float noise must not manufacture markers.
noisy = markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.000001, 119.999999])
check("float noise does not split a marker", len(noisy) == 1, str(len(noisy)))
# The inverse.
beat_nums, out_bpms, out_times = beats_from_markers([GridMarker(start=0.0, bpm=120.0)], 2.0)
check("expanding one marker gives a beat every 0.5s at 120 BPM", out_times == [0.0, 0.5, 1.0, 1.5], str(out_times))
check("beats are numbered 1-4 in bars", beat_nums == [1, 2, 3, 4], str(beat_nums))
check("expanding no markers gives no beats", beats_from_markers([], 10.0) == ([], [], []))
# ---- the rest needs a real library --------------------------------------
found = discovery.detect_libraries()
if not found:
print("\n== library tests SKIPPED: no Rekordbox library found on this machine ==")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
REAL = Path(found[0]["path"])
print(f"\n(using a temp copy of {REAL})")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "master.db"
shutil.copy2(REAL, work)
# The beatgrid lives in the ANLZ files under share/, not in the database.
share = REAL.parent / "share"
if share.is_dir():
shutil.copytree(share, Path(d) / "share")
print("== the driver recognises the library by probing, not by extension ==")
driver = RekordboxDriver()
check("can_open accepts a real master.db", driver.can_open(work))
plain = Path(d) / "plain.db"
import sqlite3
sqlite3.connect(plain).execute("CREATE TABLE t (a)")
check("can_open rejects an unencrypted .db", not driver.can_open(plain))
check("can_open rejects a non-database", not driver.can_open(Path(d) / "missing.db"))
check("the registry picks Rekordbox for it", registry.driver_for(work).platform == "rekordbox")
adapter = RekordboxAdapter(work)
print("== the projection ==")
check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter))
check("tracks are projected", len(adapter.tracks) > 0, str(len(adapter.tracks)))
check("the primary-key index agrees with the list", len(adapter.by_key) == len(adapter.tracks))
check("platform is reported generically", adapter.platform == "rekordbox")
sample = adapter.tracks[0]
check("a track id is a plain string", isinstance(sample.id, str) and sample.id != "")
check("track() resolves by id", adapter.track(sample.id) is sample)
check("an unknown id resolves to None", adapter.track("no-such-track") is None)
rated = [t for t in adapter.tracks if t.rating]
check("ratings are already 0-5 (no /51 conversion)", all(0 <= t.rating <= 5 for t in adapter.tracks))
if rated:
check("at least one rating survives the projection", max(t.rating for t in rated) >= 1)
print("== cues project into the generic vocabulary ==")
with_cues = [t for t in adapter.tracks if t.cue_count]
check("some track has cues", bool(with_cues), "none found")
if with_cues:
tc = adapter.track_cues(with_cues[0].id)
check("track_cues returns a projection", tc is not None)
check("every cue type is in the generic vocabulary",
all(c.type in ("cue", "loop") for c in tc.cues),
str({c.type for c in tc.cues}))
check("every role is generic", all(c.role in ("hotcue", "memory") for c in tc.cues))
check("a memory cue has no slot",
all(c.slot is None for c in tc.cues if c.role == "memory"))
check("a hot cue has a slot", all(c.slot is not None for c in tc.cues if c.role == "hotcue"))
check("no cue claims to be editable in the read-only milestone",
all(not c.editable for c in tc.cues))
check("grid markers carry no companion (a Traktor convention)",
all(m.companion is None for m in tc.grid_markers))
loops = [c for c in tc.cues if c.type == "loop"]
if loops:
check("a loop has a positive length", all(c.length > 0 for c in loops))
print("== the beatgrid is read lazily and corrects the projection ==")
# Rekordbox analyses one-shot samples too, and gives them an ANLZ file with
# no beatgrid — so "has an analysis file" does NOT mean "has a grid".
gridded = [t for t in adapter.tracks if t.bpm]
if gridded:
t = gridded[0]
tc = adapter.track_cues(t.id)
check("a track with a tempo projects at least one grid marker", len(tc.grid_markers) >= 1)
check("markers are ordered by start",
all(a.start <= b.start for a, b in zip(tc.grid_markers, tc.grid_markers[1:])))
check("every marker has a positive tempo", all(m.bpm > 0 for m in tc.grid_markers))
# The approximation must be CORRECTED by a read, for every track — including
# the sample one-shots, whose true count is zero.
mismatched = []
for t in adapter.tracks[:40]:
markers = adapter.track_cues(t.id).grid_markers
if t.grid_marker_count != len(markers):
mismatched.append(f"{t.title}: {t.grid_marker_count} vs {len(markers)}")
check("reading a grid corrects grid_marker_count on every track",
not mismatched, "; ".join(mismatched[:3]))
check("track_cues on an unknown track is None", adapter.track_cues("no-such-track") is None)
print("== playlists ==")
tree = adapter.playlist_tree()
check("the tree is a list of generic nodes", isinstance(tree, list))
ids = []
def walk(nodes):
for n in nodes:
ids.append(n.id)
check_kind = n.kind in ("folder", "playlist", "smart")
if not check_kind:
check(f"node {n.name!r} has a generic kind", False, n.kind)
walk(n.children)
walk(tree)
check("no internal Rekordbox playlist is exposed",
all(i not in ("100000", "200000") for i in ids), str(ids))
check("nothing claims to be editable", not any(
n.can_rename or n.can_delete or n.can_add_tracks or n.can_reorder
for n in tree
))
print("== capabilities gate the UI ==")
caps = adapter.capabilities()
check("platform is rekordbox", caps.platform == "rekordbox")
check("8 hot cue slots, labelled by letter",
caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter")
check("memory cues are supported", caps.cues.memory_cues)
check("no Traktor-only cue types are claimed", caps.cues.types == ["cue", "loop"])
# A loop is a cue with an out-point, NOT a separate bank — verified on a real
# library, and the opposite of what the original plan assumed.
check("a loop is a cue type, not a separate bank", caps.cues.loops == "cue_type")
check("cue colour is a palette, not free RGB", caps.cues.color == "palette")
check("the grid is flexible but not editable yet",
caps.grid.flexible and not caps.grid.editable)
check("no field is advertised as editable", caps.tracks.editable_fields == [])
check("version history is off (multi-artefact library)", caps.save.history is False)
check("the save warning says Rekordbox holds the library open",
caps.save.overwrite_risk == "while_running")
check("library label is master.db", caps.save.library_label == "master.db")
print("== every command is refused, with a reason ==")
commands = {
"set_track_metadata": lambda: adapter.set_track_metadata(sample.id, {"title": "x"}),
"create_playlist": lambda: adapter.create_playlist("x"),
"rename_playlist": lambda: adapter.rename_playlist("1", "x"),
"delete_playlist": lambda: adapter.delete_playlist("1"),
"set_playlist_entries": lambda: adapter.set_playlist_entries("1", []),
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
"set_cue": lambda: adapter.set_cue(sample.id, slot=1, start_sec=0.0, cue_type="cue"),
"set_cue_type": lambda: adapter.set_cue_type(sample.id, 1, "cue"),
"delete_cue": lambda: adapter.delete_cue(sample.id, 1),
"place_cues": lambda: adapter.place_cues(sample.id, []),
"add_grid_marker": lambda: adapter.add_grid_marker(sample.id, 0.0),
"move_grid_marker": lambda: adapter.move_grid_marker(sample.id, 0, 1.0),
"set_grid_marker_bpm": lambda: adapter.set_grid_marker_bpm(sample.id, 0, 120.0),
"delete_grid_marker": lambda: adapter.delete_grid_marker(sample.id, 0),
"replace_grid": lambda: adapter.replace_grid(sample.id, []),
"set_analysed_grid": lambda: adapter.set_analysed_grid(sample.id, []),
"delete_grid": lambda: adapter.delete_grid(sample.id),
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None),
"save": lambda: adapter.save(),
"snapshot": lambda: adapter.snapshot(),
}
refused = []
for name, fn in commands.items():
try:
fn()
refused.append(name)
except Unsupported:
pass
except Exception as ex: # noqa: BLE001 — anything else is the wrong error
refused.append(f"{name} ({type(ex).__name__})")
check("every mutating command raises Unsupported", not refused, ", ".join(refused))
check("the adapter is never dirty while read-only", adapter.dirty is False)
print("== reads that must still work ==")
page = adapter.query_tracks(limit=5)
check("query_tracks paginates", len(page.items) <= 5 and page.total == len(adapter.tracks))
facets = adapter.facets()
check("facets come from the generic index", facets.total_tracks == len(adapter.tracks))
stats = adapter.stats(playlist_count=adapter.playlist_count())
check("stats come from the generic index", stats.total_tracks == len(adapter.tracks))
check("audio_path resolves to an OS path",
adapter.audio_path(sample.id) is None or isinstance(adapter.audio_path(sample.id), Path))
check("cover_art is absent rather than an error", adapter.cover_art(sample.id) is None)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)