From 30065a94fe43badfd184e9587d78f4fe48ae5478 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sat, 19 Sep 2026 09:57:26 +0200 Subject: [PATCH] Improved Rekordbox adapter --- .claude/handoffs/rekordbox-adapter.md | 98 ++++++ CLAUDE.md | 43 ++- .../konduktor/adapters/rekordbox/adapter.py | 77 ++++- .../adapters/rekordbox/capabilities.py | 14 +- .../konduktor/adapters/rekordbox/cue_types.py | 15 + backend/konduktor/adapters/rekordbox/store.py | 284 +++++++++++++++++- backend/test_rekordbox_adapter.py | 85 +++++- backend/test_rekordbox_fidelity.py | 80 +++++ 8 files changed, 658 insertions(+), 38 deletions(-) diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md index cb97080..3fcf695 100644 --- a/.claude/handoffs/rekordbox-adapter.md +++ b/.claude/handoffs/rekordbox-adapter.md @@ -826,3 +826,101 @@ Also corrected in CLAUDE.md: the cue routes are `/api/tracks/cue`, not `rb_local_usn` on `djmdCue` rows — Rekordbox itself leaves them NULL. - `test_rekordbox_fidelity.py` is the harness to extend: add a cue edit and a grid edit as phases F and G, asserting the same "exactly these rows" property. + +### Milestone 3a landed: hot cue writes + +`./run_tests.sh` green at **288 assertions**. `cues.editable` is now true; +`grid.editable` is still false. + +Every native field convention was read off the real library before writing any +of it, and all of them are asserted in `test_rekordbox_fidelity.py` phase F: + +| Field | Value Konduktor writes | Evidence | +|---|---|---| +| `InFrame` / `OutFrame` | `floor(msec × 150 / 1000)` | matches every row in the library | +| `ContentUUID` | the **track's** UUID | verified == `djmdContent.UUID` | +| `contentCue.ID` | the **track's** UUID too | same | +| uncoloured cue | `Color=-1, ColorTableIndex=NULL` | how Rekordbox wrote Ben's uncoloured hot cues | +| loop | `Color=255, ColorTableIndex=0, ActiveLoop=0, CueMicrosec=0` | how Rekordbox wrote both loops | +| `BeatLoopSize` | `(beats << 16) \| 1`, beats from the track's own tempo | §8.11, verified at two tempos | + +Fidelity phases F and G assert that a cue write touches **only** `djmdCue`, +`contentCue` and `agentRegistry` — never `djmdContent` — that the mirror holds +one record per live cue row with `rb_cue_count` agreeing, and that a delete +clears both. + +**Memory cues are refused**, not because they are hard but because of the +two-platform promotion rule: Rekordbox is the only platform that has them, so +they are projected and displayed and never written. `role="memory"` raises +`Unsupported` with that explanation. + +### Milestone 3b: the beatgrid — read this before starting + +`pyrekordbox`'s ANLZ tags **cannot change the number of beats**. `PQTZAnlzTag`'s +`set()`, `set_beats()`, `set_bpms()` and `set_times()` all raise unless the new +sequence is exactly as long as the existing one ("For now only values of existing +beats can be set"). Since a tempo change alters how many beats fit in a track, +every real grid edit changes that count. + +So a grid write means manipulating `tag.content.entries` (a `construct` +ListContainer) directly, setting `content.entry_count`, and calling the tag's +`update_len()` — which exists for exactly this and recomputes +`len_tag = len_header + 8 × entries`. `check_parse()` asserts the count and the +list agree, so it is worth calling after. + +Two further things that make this the riskiest piece so far: +- the grid lives in **two files** — `PQTZ` in `.DAT` and `PQT2` in `.EXT` — which + presumably must stay consistent; and `djmdContent.BPM` (tempo ×100) is a third + copy that Rekordbox shows in the library list. +- `.DAT`/`.EXT` round-trip byte-identically today (§8.3), which is the property + that makes a grid write verifiable at all. **Re-check it after any write**: if + a rebuilt file stops being byte-identical in the regions we did not touch, the + write is corrupting something. + +`beatgrid.beats_from_markers()` is already written and unit-tested as the exact +inverse of the read projection, so the marker→beat maths is not the hard part. + +### Milestone 3a verification: point cues confirmed, LOOP WRITES DISABLED + +The staged acceptance test was run in Rekordbox 7. Two results, one good and one +that changed the plan. + +**Good: Rekordbox accepted the cue rows verbatim.** A re-read after the session +showed both rows byte-for-byte as Konduktor wrote them — same `Kind`, same +`BeatLoopSize`, same USN stamps. No repair, no renumbering. The write mechanism +and the `contentCue` mirror are sound, and a point cue written with `Kind=2` +landed on **pad B** exactly as predicted. + +**Bad: a cue row carrying `OutMsec` does not land in the slot its `Kind` names.** +Written with `Kind=4` plus an out-point, it appeared as a **memory cue** with pad +D left empty (confirmed from a screenshot of the deck — only B lit). The loop's +*length* was right (4 beats), so `BeatLoopSize` is correct; only its placement is +wrong. Rekordbox's own 4-beat loop on pad F — the 6th pad — stores `Kind=7`, so +loops evidently use a slot encoding that has not been measured. + +**So loop writing is now refused** (`WRITABLE_CUE_TYPES = ["cue"]`, and +`capabilities.cues.types` reports only `cue`). Loops are still READ and projected +with their length — losing them from the projection would be worse than being +unable to edit them. Writing one anyway would have silently created a memory cue, +which Konduktor deliberately cannot edit or delete, on a platform with no version +history. + +**To finish loops, measure the encoding**: in Rekordbox, put a 4-beat loop on pad +**D** and another on pad **E** of any track, quit, and read the `Kind` values — +two points on known pads, plus Rekordbox-authored loop rows to diff field by +field against Konduktor's. Until then this is the one gap in cue support. + +### Found while verifying: pyrekordbox refuses to commit while Rekordbox runs + +`pyrekordbox.commit()` raises `RuntimeError` outright when it detects a Rekordbox +process. That contradicts the settled decision to **warn but proceed** (§6), and +the check is **process-wide rather than per-file** — so it refuses to write a +temp copy while the user has an entirely different library open, which made the +whole test suite fail purely because Rekordbox happened to be running. + +`RekordboxStore._commit()` now suppresses that veto for the duration of the call +and logs a warning instead, so everything else `commit()` does — the USN +auto-increment and keeping `masterPlaylists6.xml`'s timestamps in step — still +runs as the library intends. `store.app_running` exposes the detection for +warning the user rather than blocking them. A test pins the behaviour by faking +a running process. diff --git a/CLAUDE.md b/CLAUDE.md index 04aa7b0..a3ed3fe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,8 +59,8 @@ Two independent apps that talk over HTTP: - `driver.py`/`discovery.py` — `can_open`, default-location detection, restore. - `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion rules, LOCATION ↔ OS path conversion, and its capability set. - - `adapters/rekordbox/` — **track metadata + playlists writable; cues and the - beatgrid still read-only** (milestone 2). + - `adapters/rekordbox/` — **track metadata, playlists and hot cues writable; + the beatgrid still read-only** (milestones 2 and 3a). `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 @@ -74,7 +74,25 @@ Two independent apps that talk over HTTP: 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. + `rb_local_usn` on `contentCue`, never on the cue rows. Every cue write ends + in `_sync_content_cue()`, which rebuilds the mirror from the rows — leaving + it stale is this platform's version of Traktor's companion-cue desync. + Field conventions are read off a real library, not guessed: + `InFrame`/`OutFrame` are the position in frames at **150 fps**, a cue's + `ContentUUID` and its mirror row's `ID` are both the **track's UUID**, an + uncoloured cue is `Color=-1, ColorTableIndex=NULL`, and a loop is + `Color=255, ColorTableIndex=0` with `BeatLoopSize = (beats << 16) | 1`. + **Memory cues stay preserved-but-uneditable** (Rekordbox is the only + platform with them — the two-platform promotion rule), and **saved loops + are read but not written**: verified in Rekordbox, a cue row carrying + `OutMsec` does NOT land in the hot cue slot its `Kind` names — it becomes a + memory cue — so writing one would silently create an object Konduktor + cannot then edit. `cue_types.WRITABLE_CUE_TYPES` is the narrower set. + - **Saving warns but does not block when Rekordbox is running.** + `pyrekordbox.commit()` refuses outright, and its check is process-wide + rather than per-file, so `RekordboxStore._commit()` suppresses that veto + and logs instead — otherwise a temp copy could not be written while the + user had a different library open. - **`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. @@ -350,15 +368,16 @@ that number and nothing else — everything derives from it: - ✅ 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 above `adapters/traktor/` knows what Traktor is. -- 🟡 Rekordbox adapter — **read + metadata/playlist writes done** (milestones 1 - and 2). A Rekordbox library opens, projects, browses and now accepts track - metadata and playlist edits, verified row-by-row by `test_rekordbox_fidelity.py` - and end to end through the API. Research is captured in - `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that - Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining - (milestone 3): the hand-written cue store (`djmdCue` + the `contentCue` JSON - mirror) and the ANLZ beatgrid store. **No version history on Rekordbox** — - accepted scope decision, see handoff §11. +- 🟡 Rekordbox adapter — **read + metadata/playlist/hot-cue writes done** + (milestones 1, 2 and 3a). A Rekordbox library opens, projects, browses and + accepts track metadata, playlist and hot cue edits, verified row-by-row by + `test_rekordbox_fidelity.py` and end to end through the API. Research is + captured in `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified + result that Rekordbox accepts Konduktor-written rows when USNs are maintained. + Remaining (3b): the ANLZ beatgrid store — riskier, because `pyrekordbox`'s ANLZ + tags refuse to change the NUMBER of beats, so a grid rewrite means manipulating + the `construct` containers directly and calling `update_len()`. **No version + history on Rekordbox** — accepted scope decision, see handoff §11. - ⬜ Serato adapter; ⬜ export/conversion - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index a02fe70..ddc75c9 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -51,6 +51,15 @@ class RekordboxAdapter: ] ) + def _refresh_cues(self, track_id: str) -> TrackCues: + """Re-project a track AND return its fresh cues. + + Every mutating cue/grid command ends here: the contract is that a command + returns the refreshed projection, so a route can never serve a stale one. + """ + self._refresh(track_id) + return self.track_cues(track_id) or TrackCues() + def _refresh(self, track_id: str) -> None: """Re-project one track after a command, so the UI cannot go stale. @@ -238,6 +247,62 @@ class RekordboxAdapter: self._require_writable("Editing playlists") return self._store.set_playlist_entries(node_id, track_ids) + # ---- commands: cues --------------------------------------------------- + def _check_cue_type(self, cue_type: str) -> None: + if cue_type == "loop": + # Reading loops is fine; writing one is not. A cue row with an + # out-point does not land in the slot its Kind names — verified in + # Rekordbox — so it would silently become an uneditable memory cue. + raise Unsupported( + "Saved loops can be read but not yet written to Rekordbox libraries" + ) + if cue_type not in caps.WRITABLE_CUE_TYPES: + raise Unsupported(f"Rekordbox has no cue type {cue_type!r}") + + def set_cue( + self, + track_id: str, + *, + slot: int, + start_sec: float, + cue_type: str, + length_sec: float = 0.0, + role: str = "hotcue", + name: str | None = None, + ) -> TrackCues: + self._require_writable("Editing cues") + if role != "hotcue": + # Rekordbox is the ONLY platform with memory cues, so under the + # two-platform promotion rule they stay preserved-but-uneditable: + # they are projected and shown, never written. + raise Unsupported( + "Memory cues are shown but cannot be edited — only hot cues are writable" + ) + self._check_cue_type(cue_type) + self._store.set_cue( + track_id, slot=slot, start_sec=start_sec, cue_type=cue_type, + length_sec=length_sec, name=name, + ) + return self._refresh_cues(track_id) + + def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: + self._require_writable("Editing cues") + self._check_cue_type(cue_type) + self._store.set_cue_type(track_id, slot, cue_type) + return self._refresh_cues(track_id) + + def delete_cue(self, track_id: str, slot: int) -> TrackCues: + self._require_writable("Deleting cues") + self._store.delete_cue(track_id, slot) + return self._refresh_cues(track_id) + + def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: + self._require_writable("Placing cues") + for cue in cues: + self._check_cue_type(getattr(cue, "type", "cue")) + self._store.place_cues(track_id, cues, overwrite=overwrite) + return self._refresh_cues(track_id) + # ---- save ------------------------------------------------------------- @property def dirty(self) -> bool: @@ -283,18 +348,6 @@ class RekordboxAdapter: 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") diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index 8163b67..d41d899 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -30,7 +30,7 @@ from ...core.capabilities import ( SaveCapabilities, TrackCapabilities, ) -from .cue_types import CUE_TYPES +from .cue_types import WRITABLE_CUE_TYPES # Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored # slot number is NOT a plain letter index (see cue_types), so the adapter keeps @@ -54,16 +54,20 @@ def capabilities_for( writable=not cloud_synced, readonly_cause="cloud_synced" if cloud_synced else None, cues=CueCapabilities( - # Milestone 3: the cue store is hand-written (djmdCue rows plus the - # contentCue JSON mirror, kept consistent) and does not exist yet. - editable=False, + # Hot cues are writable: djmdCue rows plus the contentCue JSON + # mirror, kept in step. MEMORY cues stay preserved-but-uneditable — + # Rekordbox is the only platform that has them, and the two-platform + # promotion rule says a one-platform concept does not become an + # editing feature. + editable=True, hotcue_slots=HOTCUE_SLOTS, slot_labels="letter", # Rekordbox is the only platform with memory cues, so they are # projected and PRESERVED but not editable (two-platform rule). memory_cues=True, max_memory_cues=None, # unlimited - types=CUE_TYPES, + # Loops are READ but not written — see cue_types.WRITABLE_CUE_TYPES. + types=WRITABLE_CUE_TYPES, color="palette", palette=[], # TODO milestone 2: the built-in cue colour table named=True, # djmdCue.Comment diff --git a/backend/konduktor/adapters/rekordbox/cue_types.py b/backend/konduktor/adapters/rekordbox/cue_types.py index f2fe01f..b992310 100644 --- a/backend/konduktor/adapters/rekordbox/cue_types.py +++ b/backend/konduktor/adapters/rekordbox/cue_types.py @@ -23,6 +23,21 @@ MEMORY_KIND = 0 # Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only. CUE_TYPES = ["cue", "loop"] +# What Konduktor will WRITE, which is currently narrower than what it reads. +# +# A loop is projected and displayed correctly, but writing one is disabled: a +# cue row carrying `OutMsec` does NOT land in the hot cue slot its `Kind` names. +# Verified in Rekordbox 7 — a row written with `Kind=4` plus an out-point showed +# up as a MEMORY cue with pad D left empty, while an identical row without an +# out-point landed on pad B exactly as `Kind=2` predicts. Rekordbox's own 4-beat +# loop on pad F (the 6th pad) stores `Kind=7`, so loops evidently use a different +# slot encoding that has not been measured yet. +# +# Writing one anyway would silently create a MEMORY cue — which Konduktor +# deliberately cannot edit or delete — on a platform with no version history. +# Preserving a loop we cannot place is strictly better than misplacing it. +WRITABLE_CUE_TYPES = ["cue"] + def role_and_slot(kind: int | None) -> tuple[str, int | None]: """(role, slot) for a native ``Kind``.""" diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 411fd3a..da89e90 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -26,7 +26,10 @@ Two things here are not obvious and are load-bearing: """ from __future__ import annotations +import json import logging +import uuid +from datetime import datetime from pathlib import Path from sqlalchemy import func, select, text @@ -35,10 +38,20 @@ from sqlalchemy.orm import joinedload from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome from ...core.edit_journal import EditJournal from ...core.pathmap import PathMapping +from .cue_types import beat_loop_size log = logging.getLogger(__name__) +def _iso_stamp(value) -> str: + """Rekordbox writes timestamps in the JSON mirror as ISO-8601 with a + +00:00 offset and millisecond precision (e.g. 2026-09-17T20:55:13.862+00:00). + """ + if isinstance(value, datetime): + return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}+00:00" + return str(value) + + class RekordboxStore: """One open Rekordbox library.""" @@ -432,8 +445,277 @@ class RekordboxStore: `capabilities.save.history` says so. """ summary = self._journal.summary() - self._db.commit(autoinc=True) + self._commit() self._journal.clear() # Reads go through the same session, so nothing needs re-projecting from # scratch — but the grid cache is keyed by track and survives a save. return SaveOutcome(summary=summary, snapshot=None, tag_results=[]) + + def _commit(self) -> None: + """Commit, warning rather than refusing if Rekordbox is running. + + `pyrekordbox.commit()` raises outright when it sees a Rekordbox process. + That is not Konduktor's behaviour: the settled decision is to **warn but + proceed**, matching how Traktor is handled — the user is told, not + blocked on a detection heuristic. The check is also process-wide rather + than per-file, so it would refuse to write a temp copy of a library while + Rekordbox had an entirely different one open, which makes tests depend on + whether the app happens to be running. + + The veto is suppressed by neutralising the process probe for the duration + of the call, so every other thing `commit()` does — the USN + auto-increment, the session commit, and keeping `masterPlaylists6.xml`'s + timestamps in step — still runs as the library intends. Duplicating that + body here would silently drift from it on upgrade. + """ + from pyrekordbox.db6 import database as rb_database + + if rb_database.get_rekordbox_pid(): + log.warning( + "Rekordbox appears to be running; saving anyway. It may overwrite " + "or re-sync the library while it is open." + ) + original = rb_database.get_rekordbox_pid + rb_database.get_rekordbox_pid = lambda *a, **kw: 0 + try: + self._db.commit(autoinc=True) + finally: + rb_database.get_rekordbox_pid = original + + @property + def app_running(self) -> bool: + """Whether a Rekordbox process is up — for warning the user, not blocking.""" + try: + from pyrekordbox.db6 import database as rb_database + + return bool(rb_database.get_rekordbox_pid()) + except Exception: # noqa: BLE001 — detection must never break a save + return False + + # ---- writes: cues ----------------------------------------------------- + # + # Rekordbox keeps cues in TWO places that must agree: normalized `djmdCue` + # rows, and a denormalized JSON mirror in `contentCue.Cues` alongside a + # `rb_cue_count`. Every mutation here ends in `_sync_content_cue()`. + # + # Field conventions below are read off a real library (see the handoff's + # Findings), not guessed: + # * `Kind` is the bank slot; 0 means a memory cue. + # * a loop is an ordinary cue row with `OutMsec` > 0 plus `BeatLoopSize`. + # * `InFrame`/`OutFrame` are the position in frames at 150 fps. + # * an uncoloured cue is `Color=-1, ColorTableIndex=NULL`; Rekordbox writes + # `Color=255, ColorTableIndex=0` on the loops and auto-cues it creates. + + _FPS = 150 # Rekordbox stores cue positions in frames as well as ms + + @staticmethod + def _frames(msec: int) -> int: + return int(msec * RekordboxStore._FPS / 1000) + + def _cue_row(self, track_id: str, slot: int): + """The hot cue occupying `slot` on this track, or None.""" + t = self._tables + return ( + self._db.session.query(t.DjmdCue) + .filter(t.DjmdCue.ContentID == str(track_id)) + .filter(t.DjmdCue.Kind == int(slot)) + .filter(t.DjmdCue.rb_local_deleted == 0) + .first() + ) + + def _loop_beats(self, track_id: str, start_sec: float, length_sec: float) -> int | None: + """Musical length of a loop, from the track's own tempo at that point.""" + if length_sec <= 0: + return None + bpm = None + grid = self.anlz_grid(track_id) + if grid: + times, bpms = grid + for t, b in zip(times, bpms): + if t <= start_sec: + bpm = b + else: + break + if bpm is None and bpms: + bpm = bpms[0] + if not bpm: + raw = getattr(self.content(track_id), "BPM", 0) or 0 + bpm = raw / 100.0 if raw else None + if not bpm: + return None + beats = round(length_sec / (60.0 / bpm)) + return max(1, int(beats)) + + def set_cue( + self, + track_id: str, + *, + slot: int, + start_sec: float, + cue_type: str, + length_sec: float = 0.0, + name: str | None = None, + ) -> None: + """Create or replace the cue in `slot`. A loop is a cue with a length.""" + if start_sec < 0: + raise InvalidCommand("A cue cannot be before the start of the track") + if int(slot) < 1: + raise InvalidCommand("Hot cue slots start at 1") + row = self.content(track_id) + in_ms = int(round(start_sec * 1000)) + is_loop = cue_type == "loop" and length_sec > 0 + out_ms = int(round((start_sec + length_sec) * 1000)) if is_loop else -1 + + existing = self._cue_row(track_id, slot) + op = "add" if existing is None else "modify" + cue = existing + if cue is None: + t = self._tables + cue = t.DjmdCue.create( + ID=str(self._db.generate_unused_id(t.DjmdCue)), + ContentID=str(track_id), + # Verified: a cue's ContentUUID is the TRACK's UUID, which is also + # the id of its contentCue mirror row. + ContentUUID=str(row.UUID), + UUID=str(uuid.uuid4()), + Kind=int(slot), + rb_data_status=0, + rb_local_data_status=0, + rb_local_deleted=0, + rb_local_synced=0, + ) + self._db.add(cue) + + cue.InMsec = in_ms + cue.InFrame = self._frames(in_ms) + cue.InMpegFrame = 0 + cue.InMpegAbs = 0 + cue.OutMsec = out_ms + cue.OutFrame = self._frames(out_ms) if is_loop else 0 + cue.OutMpegFrame = 0 + cue.OutMpegAbs = 0 + cue.Kind = int(slot) + if is_loop: + beats = self._loop_beats(track_id, start_sec, length_sec) + cue.BeatLoopSize = beat_loop_size(beats) if beats else None + cue.ActiveLoop = 0 + cue.CueMicrosec = 0 + cue.Color = 255 + cue.ColorTableIndex = 0 + else: + cue.BeatLoopSize = None + cue.ActiveLoop = None + cue.CueMicrosec = None + cue.Color = -1 + cue.ColorTableIndex = None + cue.Comment = name or None + + self._db.flush() + self._sync_content_cue(track_id) + self._journal.record("cue", op, track_id, f"slot:{slot}") + + def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None: + cue = self._cue_row(track_id, slot) + if cue is None: + raise NotFound(f"No cue in slot {slot}") + start = (cue.InMsec or 0) / 1000.0 + length = 0.0 + if cue_type == "loop": + if cue.OutMsec and cue.OutMsec > 0: + length = (cue.OutMsec - (cue.InMsec or 0)) / 1000.0 + else: + raise InvalidCommand( + "Turning a cue into a loop needs a length — set the loop first" + ) + self.set_cue( + track_id, slot=slot, start_sec=start, cue_type=cue_type, + length_sec=length, name=cue.Comment, + ) + + def delete_cue(self, track_id: str, slot: int) -> None: + cue = self._cue_row(track_id, slot) + if cue is None: + raise NotFound(f"No cue in slot {slot}") + self._db.delete(cue) + self._db.flush() + self._sync_content_cue(track_id) + self._journal.record("cue", "delete", track_id, f"slot:{slot}") + + def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> None: + """Batch placement (Auto Hotcues). Fills empty slots unless overwriting.""" + for cue in cues: + slot = int(getattr(cue, "slot")) + if not overwrite and self._cue_row(track_id, slot) is not None: + continue + self.set_cue( + track_id, + slot=slot, + start_sec=float(getattr(cue, "start", 0.0)), + cue_type=getattr(cue, "type", "cue"), + length_sec=float(getattr(cue, "length", 0.0) or 0.0), + name=getattr(cue, "name", None), + ) + + def _sync_content_cue(self, track_id: str) -> None: + """Rebuild the denormalized `contentCue` mirror for a track. + + Rekordbox keeps a JSON copy of every cue alongside a count, and stamps + its USN on THAT row rather than on the individual cue rows — it is the + sync unit. Leaving it stale after editing `djmdCue` would make the two + disagree, which is this platform's version of Traktor's companion-cue + trap. + + Keys whose value is NULL are omitted, which is what Rekordbox's own + serializer does in every row observed. + """ + t = self._tables + row = self.content(track_id) + cues = ( + self._db.session.query(t.DjmdCue) + .filter(t.DjmdCue.ContentID == str(track_id)) + .filter(t.DjmdCue.rb_local_deleted == 0) + .order_by(t.DjmdCue.InMsec) + .all() + ) + fields = ( + "ID", "ContentID", "ContentUUID", "InMsec", "InFrame", "InMpegFrame", + "InMpegAbs", "OutMsec", "OutFrame", "OutMpegFrame", "OutMpegAbs", + "Kind", "Color", "ColorTableIndex", "ActiveLoop", "Comment", + "BeatLoopSize", "CueMicrosec", "UUID", + ) + records = [] + for cue in cues: + rec = {} + for field in fields: + value = getattr(cue, field, None) + if value is None: + continue + rec[field] = value + for stamp in ("created_at", "updated_at"): + value = getattr(cue, stamp, None) + if value is not None: + rec[stamp] = _iso_stamp(value) + records.append(rec) + + mirror = ( + self._db.session.query(t.ContentCue) + .filter(t.ContentCue.ContentID == str(track_id)) + .first() + ) + if mirror is None: + if not records: + return + mirror = t.ContentCue.create( + # Verified: the mirror's id IS the track's UUID. + ID=str(row.UUID), + ContentID=str(track_id), + UUID=str(uuid.uuid4()), + rb_data_status=0, + rb_local_data_status=0, + rb_local_deleted=0, + rb_local_synced=0, + ) + self._db.add(mirror) + mirror.Cues = json.dumps(records, ensure_ascii=False) + mirror.rb_cue_count = len(records) + self._db.flush() diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index d17e3d5..f12b4e1 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -40,7 +40,7 @@ from konduktor.core.adapter import ( # noqa: E402 NotFound, Unsupported, ) -from konduktor.core.model import GridMarker # noqa: E402 +from konduktor.core.model import GridMarker, TrackCues # noqa: E402 failed = False @@ -218,12 +218,16 @@ with tempfile.TemporaryDirectory() as d: check("with no read-only cause", caps.readonly_cause is None, str(caps.readonly_cause)) check("per-feature flags still describe what Rekordbox CAN do", caps.cues.memory_cues and caps.grid.flexible) - check("cues are NOT editable yet (milestone 3)", caps.cues.editable is False) - check("the grid is NOT editable yet (milestone 3)", caps.grid.editable is False) + check("hot cues are editable", caps.cues.editable is True) + check("the grid is NOT editable yet (milestone 3b)", caps.grid.editable is False) 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"]) + # Loops are READ but not WRITTEN — a cue row with an out-point does not land + # in the slot its Kind names (verified in Rekordbox), so offering it would + # silently create an uneditable memory cue. + check("only writable cue types are advertised", caps.cues.types == ["cue"], + str(caps.cues.types)) # 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") @@ -244,10 +248,6 @@ with tempfile.TemporaryDirectory() as d: print("== the unimplemented stores still refuse, with a reason ==") commands = { "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), @@ -308,6 +308,75 @@ with tempfile.TemporaryDirectory() as d: check("unknown fields are ignored, never guessed at", adapter.set_track_metadata(writable_target.id, {"not_a_field": "x"}) is not None) + print("== hot cue writes ==") + cue_track = next((t for t in adapter.tracks if t.bpm), adapter.tracks[0]) + tc = adapter.set_cue(cue_track.id, slot=6, start_sec=30.0, cue_type="cue", name="Probe") + placed = [c for c in tc.cues if c.slot == 6] + check("the command returns the refreshed cues", len(placed) == 1, str(len(placed))) + if placed: + check("the cue is where it was put", abs(placed[0].start - 30.0) < 0.001) + check("it is a hot cue with a slot", placed[0].role == "hotcue" and placed[0].slot == 6) + check("its name round-trips", placed[0].name == "Probe", str(placed[0].name)) + check("writing a loop is refused until its slot encoding is known", + _raises(lambda: adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, + cue_type="loop", length_sec=1.92), Unsupported)) + # Reading one must still work: Rekordbox libraries contain loops and losing + # them from the projection would be worse than not being able to edit them. + looped = [ + c + for t in adapter.tracks[:40] + for c in (adapter.track_cues(t.id) or TrackCues()).cues + if c.type == "loop" + ] + if looped: + check("existing loops are still projected, with their length", + all(c.length > 0 for c in looped), str([c.length for c in looped])) + # Replacing an occupied slot must not leave two cues in it. + tc = adapter.set_cue(cue_track.id, slot=6, start_sec=45.0, cue_type="cue") + in_six = [c for c in tc.cues if c.slot == 6] + check("re-setting a slot replaces rather than duplicates", len(in_six) == 1, str(len(in_six))) + if in_six: + check("and moves it", abs(in_six[0].start - 45.0) < 0.001) + tc = adapter.delete_cue(cue_track.id, 6) + check("a deleted slot is empty", not [c for c in tc.cues if c.slot == 6]) + check("deleting an empty slot is NotFound", + _raises(lambda: adapter.delete_cue(cue_track.id, 6), NotFound)) + check("a Traktor-only cue type is Unsupported", + _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=1.0, + cue_type="fade_in"), Unsupported)) + # Rekordbox is the ONLY platform with memory cues, so they stay + # preserved-but-uneditable under the two-platform promotion rule. + check("memory cues are shown but not writable", + _raises(lambda: adapter.set_cue(cue_track.id, slot=1, start_sec=1.0, + cue_type="cue", role="memory"), Unsupported)) + check("slot 0 is rejected — it is the memory-cue encoding, not a bank slot", + _raises(lambda: adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, + cue_type="cue"), InvalidCommand)) + check("a negative position is rejected", + _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0, + cue_type="cue"), InvalidCommand)) + + print("== saving warns but proceeds while Rekordbox is running ==") + # pyrekordbox's own commit() refuses outright if it sees a Rekordbox process. + # Konduktor's settled behaviour is to warn, not block — matching Traktor — + # and the library's check is process-wide, so it would otherwise refuse to + # write a temp copy while the user had a different library open. + from pyrekordbox.db6 import database as _rb_database + + _real_pid = _rb_database.get_rekordbox_pid + _rb_database.get_rekordbox_pid = lambda *a, **kw: 4242 # pretend it is running + try: + adapter.set_track_metadata(sample.id, {"title": "Saved While Running"}) + adapter.save() + check("a save completes with Rekordbox running", True) + except Exception as ex: # noqa: BLE001 + check("a save completes with Rekordbox running", False, f"{type(ex).__name__}: {ex}") + finally: + _rb_database.get_rekordbox_pid = _real_pid + check("and the edit really landed", + adapter.track(sample.id).title == "Saved While Running", + str(adapter.track(sample.id).title)) + print("== a cloud-synced library is refused permanently, not pending a milestone ==") # The one failure mode version history cannot undo: a local edit the sync # server did not issue could corrupt the user's OTHER machines. Detection is diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 4cb6ac0..d7d83eb 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -237,5 +237,85 @@ with tempfile.TemporaryDirectory() as d: len(final.playlist_tree()) == len(before_tree), f"{len(final.playlist_tree())} vs {len(before_tree)}") + # ---- F: a cue write touches the cue row AND its mirror --------------- + print("== F: a hot cue write is localized, and keeps the mirror in step ==") + clean_copy(REAL, work, closing=[adapter, again, final, reopened]) + before = dump(work) + adapter = RekordboxAdapter(work) + cue_track = next((t for t in adapter.tracks if t.bpm), adapter.tracks[0]) + adapter.set_cue(cue_track.id, slot=6, start_sec=30.0, cue_type="cue", name="Probe") + adapter.save() + changes = diff(before, dump(work)) + tables_touched = {t for t, _, _, _ in changes} + # djmdCue gains a row, contentCue's mirror is rewritten, the counter moves. + # Nothing else may move — in particular not djmdContent. + check("only the cue, its mirror and the counter change", + tables_touched == {"djmdCue", "contentCue", "agentRegistry"}, + str(tables_touched)) + cue_rows = [c for c in changes if c[0] == "djmdCue"] + check("exactly one cue row is inserted", + len(cue_rows) == 1 and cue_rows[0][2] == "INSERT", describe(cue_rows)) + if cue_rows and cue_rows[0][2] == "INSERT": + row = cue_rows[0][3] + check("it is a hot cue in the slot asked for", row["Kind"] == 6, str(row["Kind"])) + check("positions are stored in ms AND frames at 150fps", + row["InMsec"] == 30000 and row["InFrame"] == 4500, + f"{row['InMsec']}/{row['InFrame']}") + check("a non-loop has no out-point", row["OutMsec"] == -1, str(row["OutMsec"])) + check("an uncoloured cue matches Rekordbox's own convention", + row["Color"] == -1 and row["ColorTableIndex"] is None, + f"{row['Color']}/{row['ColorTableIndex']}") + check("the cue points at its track's UUID", + row["ContentUUID"] == dump(work)["djmdContent"][cue_track.id]["UUID"]) + + # The mirror is the trap: leaving it stale is this platform's version of + # Traktor's companion-cue desync. + mirror = [c for c in changes if c[0] == "contentCue"] + check("the JSON mirror was rewritten", len(mirror) == 1, describe(mirror)) + after = dump(work) + mirror_row = next( + (r for r in after["contentCue"].values() if r["ContentID"] == cue_track.id), None + ) + check("a mirror row exists for the track", mirror_row is not None) + if mirror_row: + import json as _json + + records = _json.loads(mirror_row["Cues"]) + live = [ + r for r in after["djmdCue"].values() + if r["ContentID"] == cue_track.id and not r["rb_local_deleted"] + ] + check("the mirror holds one record per cue row", + len(records) == len(live), f"{len(records)} vs {len(live)}") + check("rb_cue_count agrees with both", + mirror_row["rb_cue_count"] == len(live), + f"{mirror_row['rb_cue_count']} vs {len(live)}") + check("the mirror's id is the track's UUID", + mirror_row["ID"] == after["djmdContent"][cue_track.id]["UUID"]) + check("the new cue is in the mirror", any(r["Kind"] == 6 for r in records)) + + # ---- G: deleting a cue removes it from both places ------------------- + print("== G: deleting a cue clears the row and the mirror ==") + adapter.delete_cue(cue_track.id, 6) + adapter.save() + after = dump(work) + live = [ + r for r in after["djmdCue"].values() + if r["ContentID"] == cue_track.id and r["Kind"] == 6 and not r["rb_local_deleted"] + ] + check("the cue row is gone", not live, str(len(live))) + mirror_row = next( + (r for r in after["contentCue"].values() if r["ContentID"] == cue_track.id), None + ) + if mirror_row: + import json as _json + + records = _json.loads(mirror_row["Cues"]) + check("and gone from the mirror too", not any(r["Kind"] == 6 for r in records)) + check("with rb_cue_count updated", + mirror_row["rb_cue_count"] == len(records), + f"{mirror_row['rb_cue_count']} vs {len(records)}") + adapter.close() + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0)