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()