diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md index 3fcf695..ec0d164 100644 --- a/.claude/handoffs/rekordbox-adapter.md +++ b/.claude/handoffs/rekordbox-adapter.md @@ -924,3 +924,84 @@ 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. + +### Milestone 3b progress: the grid can be written, but only half of it + +**The mechanical problem is solved.** `beatgrid.write_pqtz()` rebuilds a `.DAT`'s +`PQTZ` entry list from scratch — including changing the number of beats, which +`pyrekordbox`'s own setters refuse — by replacing `content.entries`, setting +`entry_count`, and calling the tag's `update_len()`. Verified on a real file: +resizing 374 → 367 beats produced exactly the expected byte-size delta, re-parsed +correctly, and left **every other tag byte-identical**. + +**The blocker is `.EXT`.** The grid exists twice: `PQTZ` in `.DAT` and the +"extended" `PQT2` in `.EXT`. `PQT2` carries a 2-byte-per-beat array whose second +byte `pyrekordbox` literally names `unkown`, plus an undecoded `u3` field. +Inspection did not crack it: the value drifts ~2.75 per beat with a jump at each +bar boundary and must wrap within 8 bits, so it is neither a time nor a simple +index. Writing guesses into it would corrupt real user data on a platform with no +version history, so **`PQT2` is left untouched**. + +That leaves one empirical question, and it decides the whole feature: + +> **Does Rekordbox read the grid from `PQTZ` (`.DAT`) or from `PQT2` (`.EXT`)?** + +A test is staged: Demo Track 1's `PQTZ` rewritten to **half-time (64 BPM, 184 +beats)**, `.EXT` and `master.db` untouched, installed as a single-file copy. +Half-time is chosen because it is unmistakable — beat markers at half density and +a 64 BPM readout — rather than a subtle shift someone has to judge. + +- **If Rekordbox shows the half-time grid**: `PQTZ` is authoritative, and grid + editing is feasible. `PQT2` may still need attention for CDJ export, which is + out of scope anyway. +- **If it shows the original 128 BPM grid**: `PQT2` wins, and grid editing stays + out of reach until someone decodes it. That is a legitimate result — Rekordbox + support would ship as library management + cues, with grid editing remaining a + Traktor feature. + +Note `djmdContent.BPM` is deliberately left at 128 in this test, so the library +list and the deck disagreeing is itself a signal about which copy is read where. + +### Milestone 3b landed: the beatgrid writes + +**`PQTZ` is authoritative — verified in Rekordbox 7.** The staged half-time test +showed the deck at 64 BPM with the grid correctly half-timed. Afterwards the +`.DAT` was byte-identical to what Konduktor wrote, `.EXT` and `.2EX` were +untouched, and Rekordbox did **not** reconcile `djmdContent.BPM`, which sat at +128 while the deck showed 64. + +Three things follow, all now implemented: + +1. **Only `.DAT`'s `PQTZ` is written.** The stale extended grid in `.EXT` does + not trouble Rekordbox's own display; it would matter only for CDJ export, + which is out of scope. +2. **`djmdContent.BPM` is Konduktor's to maintain**, mirroring the first marker — + the same relationship Traktor's `` has to its first grid marker. + Without it the library list and the deck disagree. +3. **Grid edits are buffered until `save()`.** ANLZ edits are file writes, so + applying them at command time would put an unsaved edit on disk and break the + save contract every other platform obeys. `save()` writes the files first and + commits the database second, so a failed file write leaves nothing committed. + +The full marker vocabulary works — add / move (clamped between neighbours) / +retempo / delete / replace / delete-grid — including genuinely **flexible +multi-tempo grids**, end to end through the HTTP API. + +Fidelity phase H is the safety net: an unsaved grid edit does not touch the file; +`.EXT`/`.2EX` stay byte-identical; **every tag in the rewritten `.DAT` except +`PQTZ` is byte-identical**; and in the database only `BPM` + the row USN + the +counter move. Suite: **316 assertions**. + +### Remaining Rekordbox gaps + +- **Saved loops** — read but not written (§ above). Needs the slot encoding + measured: a 4-beat loop on pads D and E, then read the `Kind` values. +- ~~A Konduktor-written FLEXIBLE grid has not been seen in Rekordbox.~~ + **VERIFIED 2026-09-19**: Demo Track 1 written as 128 BPM dropping to 90 at + 1:00 displayed exactly that in Rekordbox 7 — the deck's BPM readout followed + the tempo change at the marker. Multi-marker grids are confirmed end to end, + which is the last thing milestone 3 was waiting on. +- **Cover art** — never investigated; `tracks.artwork` is false. +- **`PQT2` is undecoded**, so the extended grid drifts out of step with `PQTZ` + after any Konduktor grid edit. Harmless for Rekordbox itself; would need + solving before any CDJ/USB export (currently rejected as out of scope). diff --git a/CLAUDE.md b/CLAUDE.md index a3ed3fe..1f5acf7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,10 +65,25 @@ Two independent apps that talk over HTTP: 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 + - **The beatgrid is NOT in the database, and is written to ONE tag of ONE + file.** 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** — + expands them back on write. `write_pqtz()` rebuilds the entry list + directly — `pyrekordbox`'s own setters refuse to change the NUMBER of + beats, which every real edit does — then calls the tag's `update_len()`. + **Only `.DAT`'s `PQTZ` is written.** `.EXT` holds a second "extended" grid + (`PQT2`) whose per-beat byte `pyrekordbox` itself calls `unkown`, so + writing it would mean guessing at bytes in data with no version history. + Verified in Rekordbox 7: it reads the grid AND the deck's BPM from `PQTZ`, + leaves a Konduktor-written `.DAT` untouched, and is unbothered by the stale + `.EXT` (which would matter only for CDJ export — out of scope). It does + **not** reconcile `djmdContent.BPM`, so the adapter maintains that column + itself, mirroring the first marker exactly as Traktor's `` does. + Grid edits are **buffered until `save()`** so ANLZ file writes obey the same + "edit in memory, Save writes to disk" contract as everything else; `save()` + writes the files BEFORE committing the database, so a failed file write + leaves nothing committed. `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. @@ -368,16 +383,18 @@ 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/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. +- 🟡 Rekordbox adapter — **read + metadata/playlist/hot-cue/beatgrid writes + done** (milestones 1–3). A Rekordbox library opens, projects, browses and + accepts track metadata, playlist, hot cue and beatgrid edits — including + flexible multi-tempo grids, confirmed rendering correctly in Rekordbox 7 — + verified row-by-row by + `test_rekordbox_fidelity.py`, end to end through the API, and in Rekordbox 7 + itself. 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 gaps: **saved loops** (a cue row with an + out-point does not land in the slot its `Kind` names — encoding unmeasured) and + **cover art**. **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 ddc75c9..4abec9c 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -23,7 +23,7 @@ from pathlib import Path from ...core.adapter import Unsupported from ...core.capabilities import Capabilities -from ...core.model import PlaylistNode, Track, TrackCues +from ...core.model import GridMarker, PlaylistNode, Track, TrackCues from ...core.pathmap import PathMapping, common_dir_prefix from ...core.query import TrackIndex from . import capabilities as caps @@ -303,6 +303,56 @@ class RekordboxAdapter: self._store.place_cues(track_id, cues, overwrite=overwrite) return self._refresh_cues(track_id) + # ---- commands: beatgrid ----------------------------------------------- + def _markers_from(self, markers: list) -> list: + """Accept either GridMarkers or the (start, bpm) tuples routes send.""" + out = [] + for m in markers: + if isinstance(m, GridMarker): + out.append(m) + else: + start, bpm = m + out.append(GridMarker(start=float(start), bpm=float(bpm))) + return out + + def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: + self._require_writable("Editing the beatgrid") + self._store.add_grid_marker(track_id, start_sec, bpm) + return self._refresh_cues(track_id) + + def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: + self._require_writable("Editing the beatgrid") + self._store.move_grid_marker(track_id, index, start_sec) + return self._refresh_cues(track_id) + + def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues: + self._require_writable("Editing the beatgrid") + self._store.set_grid_marker_bpm(track_id, index, bpm) + return self._refresh_cues(track_id) + + def delete_grid_marker(self, track_id: str, index: int) -> TrackCues: + self._require_writable("Editing the beatgrid") + self._store.delete_grid_marker(track_id, index) + return self._refresh_cues(track_id) + + def replace_grid(self, track_id: str, markers: list) -> TrackCues: + self._require_writable("Editing the beatgrid") + self._store.replace_grid(track_id, self._markers_from(markers)) + return self._refresh_cues(track_id) + + def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues: + """Write an analysis result the way Rekordbox's own analyser would. + + Rekordbox pairs nothing with a grid marker — the companion cue is a + Traktor convention — so this is just a replace. + """ + return self.replace_grid(track_id, markers) + + def delete_grid(self, track_id: str) -> TrackCues: + self._require_writable("Deleting the beatgrid") + self._store.delete_grid(track_id) + return self._refresh_cues(track_id) + # ---- save ------------------------------------------------------------- @property def dirty(self) -> bool: @@ -348,26 +398,6 @@ class RekordboxAdapter: def cover_art(self, track_id: str) -> tuple[bytes, str] | None: return None - 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") + # Rekordbox has no per-track grid lock; capabilities.grid.lockable says so. + raise Unsupported("Rekordbox has no beatgrid lock") diff --git a/backend/konduktor/adapters/rekordbox/beatgrid.py b/backend/konduktor/adapters/rekordbox/beatgrid.py index 005b86e..e9c9081 100644 --- a/backend/konduktor/adapters/rekordbox/beatgrid.py +++ b/backend/konduktor/adapters/rekordbox/beatgrid.py @@ -78,3 +78,51 @@ def beats_from_markers( n = n % 4 + 1 t += step return beat_nums, bpms, times + + +# ---- writing the analysis file ---------------------------------------------- +# +# The grid lives in the ANLZ files, and only `.DAT`'s `PQTZ` tag is written here. +# `.EXT` carries a second, "extended" grid (`PQT2`) whose per-beat byte and `u3` +# field are NOT decoded — `pyrekordbox` itself calls the field `unkown` — so +# rewriting it would mean guessing at bytes in real user data that has no version +# history. Leaving it alone is the only safe option until it is decoded. +# +# `.DAT`/`.EXT` round-trip byte-identically through parse -> build (verified +# across a whole library), which is what makes this checkable at all: a rebuild +# must differ ONLY inside the tag we touched. + + +def write_pqtz(path, beat_nums, bpms, times) -> bool: + """Replace the beat grid in an ANLZ `.DAT`, in place. True if written. + + `pyrekordbox`'s own `PQTZAnlzTag.set*()` refuse to change the NUMBER of + beats ("only values of existing beats can be set"), and every real grid edit + changes it — so the entry list is rebuilt directly and the tag's own + `update_len()` recomputes `len_tag`. `check_parse()` then asserts the + declared count and the list agree before anything is written. + """ + import construct + from pyrekordbox.anlz import AnlzFile + + anlz = AnlzFile.parse_file(str(path)) + tag = next((t for t in anlz.tags if t.type == "PQTZ"), None) + if tag is None: + return False + entries = construct.ListContainer() + for beat, bpm, t in zip(beat_nums, bpms, times): + entries.append( + construct.Container( + beat=int(beat), + tempo=int(round(bpm * 100)), # BPM is stored x100 + time=int(round(t * 1000)), # seconds -> ms + ) + ) + tag.struct.content.entries = entries + tag.struct.content.entry_count = len(entries) + tag.update_len() + tag.check_parse() + data = anlz.build() + with open(path, "wb") as fh: + fh.write(data) + return True diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index d41d899..decd073 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -73,7 +73,10 @@ def capabilities_for( named=True, # djmdCue.Comment loops="cue_type", ), - grid=GridCapabilities(editable=False, flexible=True, lockable=False), + # The grid is written into the track's ANLZ .DAT (PQTZ). Verified: + # Rekordbox reads the grid and its BPM readout from there, and leaves a + # Konduktor-written file alone. It has no per-track grid lock. + grid=GridCapabilities(editable=True, flexible=True, lockable=False), tracks=TrackCapabilities( rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51 # Narrower than Traktor's: `producer` and `mix` have no Rekordbox diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index da89e90..84b6b2b 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -60,6 +60,9 @@ class RekordboxStore: self._mapping = PathMapping() self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {} self._journal = EditJournal() + # Grid edits buffered until save(): ANLZ files are written to disk, so + # applying them at command time would break the save contract. + self._pending_grids: dict[str, tuple[list, list, list]] = {} self._load() # ---- open ------------------------------------------------------------ @@ -445,6 +448,9 @@ class RekordboxStore: `capabilities.save.history` says so. """ summary = self._journal.summary() + # Files first: if an analysis file cannot be written, nothing should have + # been committed to the database either. + self._flush_grids() self._commit() self._journal.clear() # Reads go through the same session, so nothing needs re-projecting from @@ -719,3 +725,127 @@ class RekordboxStore: mirror.Cues = json.dumps(records, ensure_ascii=False) mirror.rb_cue_count = len(records) self._db.flush() + + # ---- writes: the beatgrid --------------------------------------------- + # + # The grid lives in the track's ANLZ `.DAT` (`PQTZ`), not in the database. + # Verified in Rekordbox 7: it reads the grid and the deck's BPM readout from + # `PQTZ`, leaves a rewritten `.DAT` exactly as Konduktor wrote it, ignores + # the stale extended grid in `.EXT` — and does NOT reconcile + # `djmdContent.BPM`, which stayed at the old tempo while the deck showed the + # new one. So that column is Konduktor's to maintain. + # + # Edits are BUFFERED and the files are written on save(), so the grid obeys + # the same "edit in memory, Save writes to disk" contract as everything else + # — an unsaved grid change must not already be on disk. + + def current_markers(self, track_id: str) -> list: + """The track's grid as a generic marker list (pending edits included).""" + from . import beatgrid as grid_math + + grid = self.anlz_grid(track_id) + if grid is None: + return [] + times, bpms = grid + return grid_math.markers_from_beats(times, bpms) + + def track_duration(self, track_id: str) -> float: + """Seconds, for expanding markers back into beats.""" + length = getattr(self.content(track_id), "Length", None) + if length: + return float(length) + grid = self.anlz_grid(track_id) + if grid and grid[0]: + return float(grid[0][-1]) + 1.0 + return 0.0 + + def replace_grid(self, track_id: str, markers: list) -> None: + """Set the grid to exactly these markers. The one primitive; every + marker-level command is expressed as a read-modify-replace on top.""" + from . import beatgrid as grid_math + + for m in markers: + if m.bpm <= 0: + raise InvalidCommand(f"A beatgrid marker needs a positive tempo, got {m.bpm}") + if m.start < 0: + raise InvalidCommand("A beatgrid marker cannot be before the track starts") + ordered = sorted(markers, key=lambda m: m.start) + duration = self.track_duration(track_id) + beat_nums, bpms, times = grid_math.beats_from_markers(ordered, duration) + # Buffer as the same (times, bpms) shape the reader returns, so the + # projection needs no special case for an unsaved grid. + self._pending_grids[str(track_id)] = (beat_nums, bpms, times) + self._grid_cache[str(track_id)] = (times, bpms) if times else None + # TEMPO mirrors the first marker, exactly as Traktor's does — + # Rekordbox will not do it for us. + row = self.content(track_id) + row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0 + self._journal.record("grid", "replace" if ordered else "delete", track_id) + + def delete_grid(self, track_id: str) -> None: + self.replace_grid(track_id, []) + + def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None: + from ...core.model import GridMarker + + markers = self.current_markers(track_id) + if bpm is None: + # Inherit the tempo governing this point, like Traktor's add does. + governing = [m for m in markers if m.start <= start_sec] + bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None) + if not bpm: + raise InvalidCommand("The first marker on an ungridded track needs a tempo") + if any(abs(m.start - start_sec) < 0.001 for m in markers): + raise InvalidCommand("There is already a marker here") + markers.append(GridMarker(start=float(start_sec), bpm=float(bpm))) + self.replace_grid(track_id, markers) + + def _marker_at(self, track_id: str, index: int) -> tuple[list, int]: + markers = self.current_markers(track_id) + if not 0 <= index < len(markers): + raise NotFound(f"No grid marker {index}") + return markers, index + + def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None: + markers, i = self._marker_at(track_id, index) + # Clamp between neighbours so the list cannot reorder under the caller. + low = markers[i - 1].start + 0.001 if i > 0 else 0.0 + high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None + target = max(low, float(start_sec)) + if high is not None: + target = min(target, high) + markers[i] = markers[i].model_copy(update={"start": target}) + self.replace_grid(track_id, markers) + + def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None: + markers, i = self._marker_at(track_id, index) + if bpm <= 0: + raise InvalidCommand(f"A tempo must be positive, got {bpm}") + markers[i] = markers[i].model_copy(update={"bpm": float(bpm)}) + self.replace_grid(track_id, markers) + + def delete_grid_marker(self, track_id: str, index: int) -> None: + markers, i = self._marker_at(track_id, index) + del markers[i] + self.replace_grid(track_id, markers) + + def _flush_grids(self) -> None: + """Write buffered grids into their ANLZ files. Called by save(). + + Only `.DAT`'s `PQTZ` is written — `.EXT`'s extended grid carries + undecoded bytes, and Rekordbox was verified to read the grid from + `PQTZ` and to be untroubled by the other being stale. + """ + from . import beatgrid as grid_math + + for track_id, (beat_nums, bpms, times) in list(self._pending_grids.items()): + rel = getattr(self.content(track_id), "AnalysisDataPath", None) + if not rel: + raise InvalidCommand( + "This track has no analysis file, so it has nowhere to store a beatgrid" + ) + path = self.path.parent / "share" / str(rel).lstrip("/\\") + if not path.is_file(): + raise InvalidCommand(f"Analysis file is missing: {path}") + grid_math.write_pqtz(path, beat_nums, bpms, times) + self._pending_grids.clear() diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index f12b4e1..512b1b2 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -219,7 +219,8 @@ with tempfile.TemporaryDirectory() as d: check("per-feature flags still describe what Rekordbox CAN do", caps.cues.memory_cues and caps.grid.flexible) 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("the grid is editable", caps.grid.editable is True) + check("but has no lock — Rekordbox has no such concept", caps.grid.lockable 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) @@ -232,8 +233,6 @@ with tempfile.TemporaryDirectory() as d: # 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("the editable field set is advertised", bool(caps.tracks.editable_fields)) # Rekordbox has no column for these; Traktor does. Mapping them onto its # Composer field would silently write the wrong thing. @@ -245,16 +244,10 @@ with tempfile.TemporaryDirectory() as d: caps.save.overwrite_risk == "while_running") check("library label is master.db", caps.save.library_label == "master.db") - print("== the unimplemented stores still refuse, with a reason ==") + print("== what Rekordbox genuinely cannot do still refuses, with a reason ==") commands = { "set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"), - "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), + # Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK. "set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True), "remap_locations": lambda: adapter.remap_locations(None), # save() works now; snapshot() must not, because a Rekordbox library is @@ -270,7 +263,7 @@ with tempfile.TemporaryDirectory() as d: pass except Exception as ex: # noqa: BLE001 — anything else is the wrong error refused.append(f"{name} ({type(ex).__name__})") - check("every cue/grid command still raises Unsupported", not refused, ", ".join(refused)) + check("each raises Unsupported rather than failing oddly", not refused, ", ".join(refused)) check("refusing a command leaves the adapter clean", adapter.dirty is False) print("== metadata writes, including the foreign-key fields ==") @@ -356,6 +349,57 @@ with tempfile.TemporaryDirectory() as d: _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0, cue_type="cue"), InvalidCommand)) + print("== beatgrid edits ==") + grid_track = next((t for t in adapter.tracks if t.bpm), None) + if grid_track: + check("a gridded track starts with at least one marker", + len(adapter.track_cues(grid_track.id).grid_markers) >= 1) + # Put the grid into a KNOWN state first. Reading whatever the library + # happens to hold made this section depend on the user's own edits — it + # broke the moment the reference library gained a marker at 60s. + tc = adapter.replace_grid(grid_track.id, [(0.05, 120.0)]) + check("the grid can be reset to a single known marker", + len(tc.grid_markers) == 1 and tc.grid_markers[0].bpm == 120.0, + str([(m.start, m.bpm) for m in tc.grid_markers])) + tc = adapter.set_grid_marker_bpm(grid_track.id, 0, 130.0) + check("retempo changes the marker", tc.grid_markers[0].bpm == 130.0, + str(tc.grid_markers[0].bpm)) + # Rekordbox does NOT reconcile the BPM column with the grid — verified in + # the real app, where the deck showed the new tempo and the list the old. + check("the BPM column follows the first marker", + adapter.track(grid_track.id).bpm == 130.0, + str(adapter.track(grid_track.id).bpm)) + tc = adapter.add_grid_marker(grid_track.id, 60.0, 140.0) + check("a second marker makes the grid flexible", len(tc.grid_markers) == 2, + str(len(tc.grid_markers))) + check("markers stay ordered by position", + tc.grid_markers[0].start < tc.grid_markers[1].start) + check("Rekordbox markers never carry a companion cue", + all(m.companion is None for m in tc.grid_markers)) + # A move is clamped between neighbours so the list cannot reorder. + tc = adapter.move_grid_marker(grid_track.id, 1, 0.0) + check("moving a marker past its neighbour is clamped", + tc.grid_markers[1].start > tc.grid_markers[0].start, + f"{tc.grid_markers[0].start} / {tc.grid_markers[1].start}") + tc = adapter.delete_grid_marker(grid_track.id, 1) + check("a marker can be deleted", len(tc.grid_markers) == 1, str(len(tc.grid_markers))) + check("grid_marker_count follows the real grid", + adapter.track(grid_track.id).grid_marker_count == 1) + tc = adapter.delete_grid(grid_track.id) + check("the whole grid can be deleted", tc.grid_markers == []) + check("and the BPM column is cleared with it", + adapter.track(grid_track.id).bpm is None, + str(adapter.track(grid_track.id).bpm)) + tc = adapter.replace_grid(grid_track.id, [(0.05, 128.0)]) + check("replace_grid accepts (start, bpm) tuples from the route layer", + len(tc.grid_markers) == 1 and tc.grid_markers[0].bpm == 128.0) + check("a non-positive tempo is rejected", + _raises(lambda: adapter.set_grid_marker_bpm(grid_track.id, 0, 0), InvalidCommand)) + check("an unknown marker index is NotFound", + _raises(lambda: adapter.set_grid_marker_bpm(grid_track.id, 9, 120.0), NotFound)) + check("Rekordbox has no grid lock", + _raises(lambda: adapter.set_grid_lock(grid_track.id, True), Unsupported)) + 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 — diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index d7d83eb..40539ff 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -317,5 +317,69 @@ with tempfile.TemporaryDirectory() as d: f"{mirror_row['rb_cue_count']} vs {len(records)}") adapter.close() + # ---- H: a grid write touches ONE tag of ONE file --------------------- + print("== H: a beatgrid write is localized to the .DAT's PQTZ tag ==") + from pyrekordbox.anlz import AnlzFile + + adapter = RekordboxAdapter(work) # phase G closed the previous one + grid_track = next((t for t in adapter.tracks if t.bpm), None) + if grid_track is None: + check("a gridded track exists to test with", False, "none found") + else: + rel = str(dump(work)["djmdContent"][grid_track.id]["AnalysisDataPath"]).lstrip("/") + dat = Path(d) / "share" / rel + ext = dat.with_suffix(".EXT") + two_ex = dat.with_suffix(".2EX") + before_dat = dat.read_bytes() + before_ext = ext.read_bytes() if ext.is_file() else None + before_2ex = two_ex.read_bytes() if two_ex.is_file() else None + before_db = dump(work) + + adapter.set_grid_marker_bpm(grid_track.id, 0, 130.0) + # The save contract: an unsaved grid edit must not be on disk yet. + check("an unsaved grid edit has not touched the analysis file", + dat.read_bytes() == before_dat) + adapter.save() + + check("the analysis file changed", dat.read_bytes() != before_dat) + # The extended grid carries undecoded bytes and is deliberately not + # written. Rekordbox was verified to read PQTZ and ignore this being stale. + if before_ext is not None: + check(".EXT is left untouched", ext.read_bytes() == before_ext) + if before_2ex is not None: + check(".2EX is left untouched", two_ex.read_bytes() == before_2ex) + + # The real localization test: every OTHER tag in the rewritten .DAT must + # be byte-identical. This is the ANLZ analogue of "only edited objects + # diff", and it is what would catch a rebuild corrupting the file. + old_tags = {t.type: t.build() for t in AnlzFile.parse(before_dat).tags if t.type != "PQTZ"} + new_tags = {t.type: t.build() for t in AnlzFile.parse_file(str(dat)).tags if t.type != "PQTZ"} + check("the same tags are present afterwards", + set(old_tags) == set(new_tags), f"{sorted(old_tags)} vs {sorted(new_tags)}") + differing = [k for k in old_tags if k in new_tags and old_tags[k] != new_tags[k]] + check("every tag except PQTZ is byte-identical", not differing, ", ".join(differing)) + + reread = AnlzFile.parse_file(str(dat)) + pqtz = next(t for t in reread.tags if t.type == "PQTZ") + check("the new tempo is really in the file", + abs(float(pqtz.bpms[0]) - 130.0) < 0.001, str(pqtz.bpms[0])) + check("the grid still covers the track", + len(pqtz.beats) > 1 and float(pqtz.times[-1]) > 0) + + # The BPM column is Konduktor's to maintain: Rekordbox does not + # reconcile it with the grid (verified in the real app). + changes = diff(before_db, dump(work)) + tables_touched = {t for t, _, _, _ in changes} + check("in the database, only the track's BPM and the counter move", + tables_touched == {"djmdContent", "agentRegistry"}, str(tables_touched)) + content = [c for c in changes if c[0] == "djmdContent"] + if content and content[0][2] == "UPDATE": + fields = content[0][3] + check("only BPM and the row USN changed", + set(fields) == {"BPM", "rb_local_usn"}, str(sorted(fields))) + check("BPM is stored x100", fields.get("BPM", (0, 0))[1] == 13000, + str(fields.get("BPM"))) + adapter.close() + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0)