Fixed Rekordbox hotcue issues

This commit is contained in:
patben8 committed 2026-09-19 12:40:05 +02:00
1 parent 5aeb9956cd
commit 00dd3fe766
9 files changed
+327 -89

No files matched your search

@@ -249,13 +249,6 @@ class RekordboxAdapter:
# ---- 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}")
@@ -66,7 +66,7 @@ def capabilities_for(
# projected and PRESERVED but not editable (two-platform rule).
memory_cues=True,
max_memory_cues=None, # unlimited
# Loops are READ but not written — see cue_types.WRITABLE_CUE_TYPES.
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
color="palette",
palette=[], # TODO milestone 2: the built-in cue colour table
@@ -5,7 +5,24 @@ library (see the handoff's Findings section):
* ``Kind == 0`` -> a MEMORY cue: no bank slot, and Rekordbox allows any
number of them.
* ``Kind >= 1`` -> a HOT CUE occupying bank slot ``Kind``.
* ``Kind >= 1`` -> a HOT CUE.
**``Kind`` is 1-based AND it skips 4.** Konduktor's generic model numbers bank
slots from zero — slot 0 is the pad the UI labels "A", which is also how Traktor
stores its ``HOTCUE`` attribute. Rekordbox's first pad is ``Kind=1``, and the
value ``4`` is reserved: the bank runs 1, 2, 3, 5, 6, 7, 8, 9.
Measured, not guessed. A loop was written at every ``Kind`` from 1 to 8, ten
seconds apart, and read off a real deck:
Kind 1 2 3 4 5 6 7 8 9
pad A B C - D E F G H
``Kind=4`` appears on no pad at all; Rekordbox shows such a cue as a memory cue.
That one gap explains two earlier puzzles: a Rekordbox-authored loop on pad F
stored ``Kind=7``, and a Konduktor cue written as ``Kind=4`` vanished from the
bank. Getting this wrong silently moves cues to the wrong pad — or loses them
from the bank entirely.
**``Kind`` is treated as an opaque slot id.** Setting cues on pads A and C
stored 1 and 3, but the pad in the 6th position stored 7, so the slot -> letter
@@ -23,36 +40,42 @@ 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"]
# What Konduktor will write. Loops were disabled for a while because a loop
# written at `Kind=4` disappeared from the bank — which turned out to be the
# reserved-Kind gap above, not anything to do with loops. Both types write.
WRITABLE_CUE_TYPES = ["cue", "loop"]
# The Kind value that is not a bank slot. Everything at or above it is shifted
# by one relative to the pad index.
RESERVED_KIND = 4
def role_and_slot(kind: int | None) -> tuple[str, int | None]:
"""(role, slot) for a native ``Kind``."""
if kind is None or kind == MEMORY_KIND:
"""(role, 0-based slot) for a native ``Kind``.
A cue at `RESERVED_KIND` occupies no pad, so it is projected as a memory cue
— which is how Rekordbox itself displays one.
"""
if kind is None or kind == MEMORY_KIND or int(kind) == RESERVED_KIND:
return "memory", None
return "hotcue", int(kind)
kind = int(kind)
return "hotcue", kind - 1 if kind < RESERVED_KIND else kind - 2
def kind_for(role: str, slot: int | None) -> int:
"""The native ``Kind`` for a generic (role, slot). Inverse of `role_and_slot`."""
"""The native ``Kind`` for a generic (role, 0-based slot).
Inverse of `role_and_slot`; skips `RESERVED_KIND`.
"""
if role == "memory":
return MEMORY_KIND
if slot is None:
raise ValueError("a hot cue needs a slot")
return int(slot)
slot = int(slot)
if slot < 0:
raise ValueError(f"a hot cue slot cannot be negative, got {slot}")
return slot + 1 if slot < RESERVED_KIND - 1 else slot + 2
def cue_type(out_msec: int | None) -> str:
@@ -133,8 +133,13 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None)
into the generic marker list. Rekordbox pairs nothing with a grid marker, so
`companion` is always None — that is a Traktor convention.
Every cue is projected as `editable=False` in this milestone, because the
adapter refuses every command; the UI gates on that flag alone.
`editable` says whether the adapter will accept a command on THIS cue, which
is the only thing the UI gates on. Every hot cue is editable, loops included.
**Memory cues are not**: Rekordbox is the only platform that has them, so
under the two-platform promotion rule they are shown and never written. A cue
sitting on the reserved `Kind` occupies no pad and is projected the same way,
because that is how Rekordbox itself displays one.
"""
markers: list[GridMarker] = []
if grid is not None:
@@ -146,20 +151,22 @@ def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None)
role, slot = role_and_slot(getattr(c, "Kind", None))
out_msec = getattr(c, "OutMsec", None)
in_msec = getattr(c, "InMsec", 0) or 0
kind = cue_type(out_msec)
length = 0.0
if out_msec is not None and out_msec > 0:
length = max(0.0, (out_msec - in_msec) / 1000.0)
editable = role == "hotcue"
cues.append(
CuePoint(
name=(getattr(c, "Comment", None) or None),
type=cue_type(out_msec),
type=kind,
role=role,
start=in_msec / 1000.0,
length=length,
slot=slot,
color=_cue_color(c),
editable=False,
readonly_reason="platform_managed",
editable=editable,
readonly_reason=None if editable else "platform_managed",
grid_marker=None,
)
)
+19 -7
View File
@@ -33,12 +33,13 @@ from datetime import datetime
from pathlib import Path
from sqlalchemy import func, select, text
from sqlalchemy.exc import OperationalError
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
from .cue_types import beat_loop_size, kind_for
log = logging.getLogger(__name__)
@@ -485,6 +486,16 @@ class RekordboxStore:
rb_database.get_rekordbox_pid = lambda *a, **kw: 0
try:
self._db.commit(autoinc=True)
except OperationalError as ex:
# Suppressing pyrekordbox's veto does not remove SQLite's own lock:
# a running Rekordbox really does hold the database, and the raw
# error is an unhelpful 500. Say what happened and what to do.
if "locked" not in str(ex).lower():
raise
raise InvalidCommand(
"Rekordbox has the library open, so it cannot be written right "
"now. Close Rekordbox and save again — your changes are still here."
) from ex
finally:
rb_database.get_rekordbox_pid = original
@@ -519,12 +530,12 @@ class RekordboxStore:
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."""
"""The hot cue occupying the 0-based generic `slot`, 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.Kind == kind_for("hotcue", slot))
.filter(t.DjmdCue.rb_local_deleted == 0)
.first()
)
@@ -565,13 +576,14 @@ class RekordboxStore:
"""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")
if int(slot) < 0:
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
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
kind = kind_for("hotcue", slot)
existing = self._cue_row(track_id, slot)
op = "add" if existing is None else "modify"
cue = existing
@@ -584,7 +596,7 @@ class RekordboxStore:
# the id of its contentCue mirror row.
ContentUUID=str(row.UUID),
UUID=str(uuid.uuid4()),
Kind=int(slot),
Kind=kind,
rb_data_status=0,
rb_local_data_status=0,
rb_local_deleted=0,
@@ -600,7 +612,7 @@ class RekordboxStore:
cue.OutFrame = self._frames(out_ms) if is_loop else 0
cue.OutMpegFrame = 0
cue.OutMpegAbs = 0
cue.Kind = int(slot)
cue.Kind = kind
if is_loop:
beats = self._loop_beats(track_id, start_sec, length_sec)
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
+55 -24
View File
@@ -66,8 +66,24 @@ def check(label, cond, detail=""):
# ---- pure units: no library required -----------------------------------
print("== cue encoding ==")
check("Kind 0 is a memory cue with no slot", role_and_slot(0) == ("memory", None))
check("Kind N is hot cue slot N", role_and_slot(5) == ("hotcue", 5))
check("round-trips back to Kind", kind_for(*role_and_slot(5)) == 5 and kind_for("memory", None) == 0)
# The generic slot is 0-BASED (slot 0 is the pad the UI labels "A", matching how
# Traktor stores HOTCUE); Rekordbox's Kind is 1-based. Conflating them shifts
# every cue by one pad, which is exactly what shipped before it was caught.
check("Kind 1 is hot cue slot 0 — the pad labelled A", role_and_slot(1) == ("hotcue", 0))
check("slot 0 maps to Kind 1, not Kind 0", kind_for("hotcue", 0) == 1)
# MEASURED, not assumed: a loop was written at every Kind 1-8 and read off a real
# deck. Kind 4 is reserved and lands on no pad, so the bank is 1,2,3,5,6,7,8,9.
# Getting this wrong moves cues to the wrong pad or loses them from the bank.
EXPECTED_KINDS = [1, 2, 3, 5, 6, 7, 8, 9] # pads A..H
check("the bank skips the reserved Kind",
[kind_for("hotcue", i) for i in range(8)] == EXPECTED_KINDS,
str([kind_for("hotcue", i) for i in range(8)]))
check("and every one maps back to its own slot",
[role_and_slot(k)[1] for k in EXPECTED_KINDS] == list(range(8)))
check("the reserved Kind is no pad at all — Rekordbox shows it as a memory cue",
role_and_slot(4) == ("memory", None))
check("pad D is Kind 5, not Kind 4", kind_for("hotcue", 3) == 5)
check("pad H is Kind 9", kind_for("hotcue", 7) == 9)
# Verified against two real loops: 1 beat @125 BPM and 4 beats @120 BPM.
check("BeatLoopSize encodes (beats << 16) | 1", beat_loop_size(4) == 262145 and beat_loop_size(1) == 65537)
check("and decodes back", beats_in_loop(262145) == 4 and beats_in_loop(None) is None)
@@ -157,8 +173,19 @@ with tempfile.TemporaryDirectory() as d:
check("a memory cue has no slot",
all(c.slot is None for c in tc.cues if c.role == "memory"))
check("a hot cue has a slot", all(c.slot is not None for c in tc.cues if c.role == "hotcue"))
check("no cue claims to be editable in the read-only milestone",
all(not c.editable for c in tc.cues))
# `editable` must track what the adapter will ACTUALLY accept — it is
# the only thing the UI gates on, and a stale `False` here showed every
# writable hot cue with a padlock.
check("ordinary hot cues are editable",
all(c.editable for c in tc.cues if c.role == "hotcue" and c.type != "loop"))
check("memory cues are preserved but not editable",
all(not c.editable for c in tc.cues if c.role == "memory"))
check("loops are editable like any other hot cue",
all(c.editable for c in tc.cues if c.type == "loop" and c.role == "hotcue"))
check("an uneditable cue always says why",
all(c.readonly_reason for c in tc.cues if not c.editable))
check("an editable cue gives no reason",
all(c.readonly_reason is None for c in tc.cues if c.editable))
check("grid markers carry no companion (a Traktor convention)",
all(m.companion is None for m in tc.grid_markers))
loops = [c for c in tc.cues if c.type == "loop"]
@@ -224,10 +251,8 @@ with tempfile.TemporaryDirectory() as d:
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)
# 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"],
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
check("both Rekordbox cue types are writable", caps.cues.types == ["cue", "loop"],
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.
@@ -310,20 +335,20 @@ with tempfile.TemporaryDirectory() as d:
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]))
# A loop is a cue with an out-point, not a separate bank object.
tc = adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92)
loop = [c for c in tc.cues if c.slot == 7]
check("a loop can be written to the last pad", len(loop) == 1 and loop[0].type == "loop",
str([(c.slot, c.type) for c in tc.cues]))
if loop:
check("the loop keeps its length", abs(loop[0].length - 1.92) < 0.002, str(loop[0].length))
check("and is editable like any other hot cue", loop[0].editable)
# Every pad must be reachable — the reserved-Kind gap used to swallow pad D
# and shift everything above it.
for slot in range(8):
adapter.set_cue(cue_track.id, slot=slot, start_sec=5.0 + slot, cue_type="cue")
placed = {c.slot for c in adapter.track_cues(cue_track.id).cues if c.slot is not None}
check("all eight pads are individually addressable", placed == set(range(8)), str(sorted(placed)))
# 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]
@@ -342,8 +367,14 @@ with tempfile.TemporaryDirectory() as d:
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,
# Slot 0 is the FIRST pad, not an error: it is Kind=1 natively.
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue")
first = [c for c in tc.cues if c.slot == 0]
check("slot 0 is the first pad (A), not an error", len(first) == 1, str(len(first)))
tc = adapter.set_cue(cue_track.id, slot=7, start_sec=2.0, cue_type="cue")
check("slot 7 is the last pad (H)", any(c.slot == 7 for c in tc.cues))
check("a negative slot is rejected",
_raises(lambda: adapter.set_cue(cue_track.id, slot=-1, 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,
+18 -7
View File
@@ -240,10 +240,20 @@ with tempfile.TemporaryDirectory() as d:
# ---- 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")
# Empty the bank FIRST so "one row inserted" is a fact about this edit, not
# about whatever the reference library happened to hold. Reading the existing
# cues instead made this assertion flip to UPDATE the moment the real library
# gained a cue in the same slot.
for existing in list(adapter.track_cues(cue_track.id).cues):
if existing.slot is not None:
adapter.delete_cue(cue_track.id, existing.slot)
adapter.save()
before = dump(work)
# Generic slot 5 is the pad labelled F, stored natively as Kind=7 — the bank
# skips the reserved Kind 4, so pads from D up are shifted by two.
adapter.set_cue(cue_track.id, slot=5, start_sec=30.0, cue_type="cue", name="Probe")
adapter.save()
changes = diff(before, dump(work))
tables_touched = {t for t, _, _, _ in changes}
@@ -257,7 +267,8 @@ with tempfile.TemporaryDirectory() as d:
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("the 0-based slot is stored as its measured Kind",
row["Kind"] == 7, 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']}")
@@ -292,16 +303,16 @@ with tempfile.TemporaryDirectory() as d:
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))
check("the new cue is in the mirror", any(r["Kind"] == 7 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.delete_cue(cue_track.id, 5)
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"]
if r["ContentID"] == cue_track.id and r["Kind"] == 7 and not r["rb_local_deleted"]
]
check("the cue row is gone", not live, str(len(live)))
mirror_row = next(
@@ -311,7 +322,7 @@ with tempfile.TemporaryDirectory() as d:
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("and gone from the mirror too", not any(r["Kind"] == 7 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)}")