Improved Rekordbox adapter

This commit is contained in:
patben8 committed 2026-09-19 09:57:26 +02:00
1 parent 43e712afbd
commit 30065a94fe
8 files changed
+658 -38

No files matched your search

+65 -12
View File
@@ -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")
@@ -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
@@ -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``."""
+283 -1
View File
@@ -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()
+77 -8
View File
@@ -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
+80
View File
@@ -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)