Implemented Rekordbox core base

This commit is contained in:
patben8 committed 2026-09-18 09:12:59 +02:00
1 parent 6e24f5ef1d
commit 4592e13228
18 files changed
+2170 -6

No files matched your search

+4 -1
View File
@@ -1,6 +1,9 @@
"""Per-platform adapters. Each owns a native library model and translates the
generic commands onto it; nothing outside an adapter package sees a native type.
Importing this package registers every adapter.
Importing this package registers every adapter. Order matters only for the
registry's ``can_open()`` probe, and the probes are mutually exclusive: Traktor
requires an NML header, Rekordbox an encrypted database with its own schema.
"""
from . import rekordbox # noqa: F401 — registers the Rekordbox driver
from . import traktor # noqa: F401 — registers the Traktor driver
@@ -0,0 +1,14 @@
"""The Rekordbox adapter: ``master.db`` (SQLCipher) via ``pyrekordbox``.
Importing this package registers the platform, so ``core.registry`` can find it
without knowing it exists.
Read-only in this milestone: the library is projected, browsed and searched, but
every command is refused. See `capabilities.py` for what that reports and the
handoff's Findings section for the research the write path will be built on.
"""
from ...core import registry
from .driver import RekordboxDriver
REKORDBOX = RekordboxDriver()
registry.register(REKORDBOX)
@@ -0,0 +1,274 @@
"""The Rekordbox adapter: owns the native database and the generic projection.
Mirrors `adapters.traktor.adapter`. It holds:
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
* a ``TrackIndex`` — the generic READ projection built from it.
**Read-only milestone.** Every mutating command raises `Unsupported`, and
`capabilities()` reports nothing as editable, so a correct UI never offers one
in the first place; the raise is the backstop, not the mechanism.
Writes are refused for a second, permanent reason on a cloud-synced library:
propagating a bad sync state to the user's other machines is not something
version history can undo. That check lives here so it cannot be bypassed by a
future command path forgetting it.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import projection
from .store import RekordboxStore
class RekordboxAdapter:
platform = "rekordbox"
def __init__(self, path: Path):
self.path = Path(path)
self._store = RekordboxStore(self.path)
self._index = TrackIndex()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- projection maintenance -----------------------------------------
def _rebuild(self) -> None:
counts = self._store.cue_counts()
self._index.rebuild(
[
projection.to_track(row, counts.get(str(row.ID), (0, 0)))
for row in self._store.iter_content()
]
)
def reload(self) -> None:
self._store._load()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(self.path, cloud_synced=self._cloud_synced)
@property
def cloud_synced(self) -> bool:
return self._cloud_synced
# ---- read ------------------------------------------------------------
@property
def tracks(self) -> list[Track]:
return self._index.tracks
@property
def by_key(self) -> dict[str, Track]:
return self._index.by_key
def track(self, track_id: str) -> Track | None:
return self._index.get(track_id)
def query_tracks(self, **kw):
return self._index.query_tracks(**kw)
def facets(self):
return self._index.facets()
def stats(self, playlist_count: int):
return self._index.stats(playlist_count)
def playlist_count(self) -> int:
return self._store.count_playlists()
def track_cues(self, track_id: str) -> TrackCues | None:
if self._index.get(track_id) is None:
return None
cues = projection.to_track_cues(
self._store.cues(track_id), self._store.anlz_grid(track_id)
)
# The track projection carries an APPROXIMATE grid_marker_count until the
# grid is actually read (see projection.to_track). This is that moment —
# correct it, so the library table stops showing the guess.
track = self._index.get(track_id)
if track is not None:
track.grid_marker_count = len(cues.grid_markers)
return cues
# ---- playlists -------------------------------------------------------
def playlist_tree(self) -> list[PlaylistNode]:
"""Rekordbox stores the tree as a flat table with ``ParentID`` links."""
from pyrekordbox.db6 import tables
rows = self._store.playlists()
folder = int(tables.PlaylistType.FOLDER)
smart = int(tables.PlaylistType.SMART_PLAYLIST)
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
for r in rows:
attribute = int(r.Attribute or 0)
kind = "folder" if attribute == folder else ("smart" if attribute == smart else "playlist")
node_id = str(r.ID)
nodes[node_id] = PlaylistNode(
id=node_id,
name=r.Name or "",
kind=kind,
count=(0 if kind == "folder" else len(self._store.playlist_song_ids(node_id))),
children=[],
# A smart playlist has no static entry list; a folder has no tracks.
selectable=kind == "playlist",
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
can_contain_children=kind == "folder",
)
parent = str(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
roots: list[PlaylistNode] = []
for node_id, node in nodes.items():
parent_id = parents.get(node_id, "root")
parent = nodes.get(parent_id)
if parent is None:
roots.append(node)
else:
parent.children.append(node)
return roots
def playlist_entries(self, node_id: str) -> list[str] | None:
ids = self._store.playlist_song_ids(node_id)
return ids if ids or self._is_playlist(node_id) else None
def playlist_tracks(self, node_id: str) -> list[Track] | None:
keys = self.playlist_entries(node_id)
if keys is None:
return None
return [t for k in keys if (t := self._index.get(k)) is not None]
def _is_playlist(self, node_id: str) -> bool:
return any(str(r.ID) == str(node_id) for r in self._store.playlists())
# ---- audio / paths ----------------------------------------------------
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
return {"primary": primary, "groups": [{"prefix": primary, "count": len(paths)}] if primary else []}
def remap_preview(self, mapping: PathMapping) -> dict:
paths = [Path(p) for p in self._store.all_audio_paths()]
matched = [p for p in paths if mapping.matches(p)]
samples = []
for p in matched[:5]:
target = mapping.apply(p)
samples.append({"from": str(p), "to": str(target), "exists": target.exists()})
existing = sum(1 for p in matched if mapping.apply(p).exists())
return {
"total": len(paths),
"matched": len(matched),
"existing": existing,
"samples": samples,
}
def remap_locations(self, mapping: PathMapping) -> int:
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return False
def save(self):
raise Unsupported(self._readonly_reason("Saving"))
def snapshot(self) -> bytes:
"""The library's bytes, for version history.
`master.db` alone is NOT a complete snapshot of a Rekordbox library (the
beatgrids live in separate ANLZ files, and restoring the database
wholesale would also roll back Rekordbox's own auth and sampler state),
which is why `capabilities.save.history` is False. Nothing should be
calling this.
"""
raise Unsupported("Rekordbox libraries are not versioned by Konduktor")
# ---- commands: all refused in this milestone -------------------------
def _readonly_reason(self, what: str) -> str:
if self._cloud_synced:
return (
f"{what} is not possible: this Rekordbox library is synced with "
"Rekordbox Cloud, and Konduktor will not write to a cloud-synced "
"library."
)
return f"{what} is not supported yet for Rekordbox libraries."
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists")
def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists")
def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists")
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._refuse("Editing playlists")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
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")
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")
@@ -0,0 +1,80 @@
"""Rekordbox's beatgrid <-> the generic marker list.
**Rekordbox does not store markers.** There is no beatgrid table in
``master.db`` at all; the grid lives in the track's ANLZ analysis file as a
``PQTZ`` tag holding EVERY BEAT explicitly — beat-number-in-bar, BPM and time,
one entry per beat (a 4-minute track is ~500 entries).
Konduktor's generic model is a marker list, so this module is the projection
between the two:
* read — collapse runs of equal BPM into one marker each, so a constant-tempo
track becomes a list of length one and a variable-tempo track becomes one
marker per tempo change. This is exactly the shape ``core.model.GridMarker``
describes.
* write — expand a marker list back into a full beat list (milestone 2; the
read direction is what a read-only adapter needs).
BPMs are compared with a tolerance because Rekordbox stores them as hundredths
and floating-point division reintroduces noise; two beats within `BPM_EPSILON`
are the same tempo and must not produce a spurious marker.
"""
from __future__ import annotations
from ...core.model import GridMarker
BPM_EPSILON = 0.005 # half of the 0.01 BPM Rekordbox can actually represent
def markers_from_beats(
times: list[float], bpms: list[float], beats: list[int] | None = None
) -> list[GridMarker]:
"""Collapse a per-beat grid into the generic marker list.
`times` are seconds, `bpms` the tempo in force at each beat. A marker is
emitted for the first beat and wherever the tempo changes.
"""
if not times or not bpms:
return []
out: list[GridMarker] = []
last_bpm: float | None = None
for i, (t, bpm) in enumerate(zip(times, bpms)):
if last_bpm is None or abs(bpm - last_bpm) > BPM_EPSILON:
out.append(GridMarker(start=float(t), bpm=float(bpm), name=None, companion=None))
last_bpm = float(bpm)
return out
def beats_from_markers(
markers: list[GridMarker], duration_sec: float
) -> tuple[list[int], list[float], list[float]]:
"""Expand a marker list into the per-beat arrays Rekordbox stores.
Each marker governs until the next one; the last runs to `duration_sec`.
Returns ``(beat_in_bar, bpms, times)`` with beat numbers cycling 1-4 from
each marker, which is how Rekordbox numbers bars.
Not used by the read-only adapter, but it is the inverse of
`markers_from_beats` and belongs beside it.
"""
beat_nums: list[int] = []
bpms: list[float] = []
times: list[float] = []
if not markers:
return beat_nums, bpms, times
ordered = sorted(markers, key=lambda m: m.start)
for i, m in enumerate(ordered):
if m.bpm <= 0:
continue
end = ordered[i + 1].start if i + 1 < len(ordered) else duration_sec
step = 60.0 / m.bpm
t = m.start
n = 1
# Guard against a zero/negative span producing an endless loop.
while t < end - 1e-9 and step > 0:
beat_nums.append(n)
bpms.append(m.bpm)
times.append(t)
n = n % 4 + 1
t += step
return beat_nums, bpms, times
@@ -0,0 +1,76 @@
"""What a Rekordbox library can persist.
**Milestone 1 reports everything as read-only.** The spike verified that
Rekordbox accepts writes that maintain its USN columns (see the handoff's
Findings), but the write path is not built yet, and the capability system exists
precisely so the UI never offers an edit that will not persist. Every flag here
is therefore false/empty until milestone 2 turns them on one at a time.
Two facts are already known and encoded, because getting them wrong later would
be a silent data bug rather than a missing feature:
* a saved loop is a cue with an out-point, NOT a separate bank, so
``loops="cue_type"`` — the same answer as Traktor, and NOT the
``separate_bank`` the original plan assumed;
* cue colour is a PALETTE index (``djmdCue.ColorTableIndex``), not free RGB,
and the palette is a built-in table — `djmdColor` is the *track* colour
palette and is unrelated.
"""
from __future__ import annotations
from ...core.capabilities import (
Capabilities,
CueCapabilities,
GridCapabilities,
PlaylistCapabilities,
SaveCapabilities,
TrackCapabilities,
)
from .cue_types import 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
# slots numeric and lets the UI label them.
HOTCUE_SLOTS = 8
def capabilities_for(
path, version: str | None = None, *, cloud_synced: bool = False
) -> Capabilities:
return Capabilities(
platform="rekordbox",
version=version,
cues=CueCapabilities(
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,
color="palette",
palette=[], # TODO milestone 2: the built-in cue colour table
named=True, # djmdCue.Comment
loops="cue_type",
),
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
editable_fields=[], # read-only in this milestone
media_kinds=["audio"],
artwork=False,
artwork_note=None,
),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=False),
save=SaveCapabilities(
app_name="Rekordbox",
library_label="master.db",
# Rekordbox holds master.db open while running and cloud-syncs it,
# so a concurrent write is riskier than Traktor's overwrite-on-exit.
overwrite_risk="while_running",
# The artefact set is master.db + N ANLZ files + masterPlaylists6.xml,
# and history.py tracks a single blob. Also, restoring master.db
# wholesale would roll back Rekordbox's auth token and sampler state.
history=False,
),
)
@@ -0,0 +1,65 @@
"""Rekordbox's ``djmdCue.Kind`` encoding <-> the generic cue vocabulary.
The only place these integers are given meaning. Verified against a real
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`` 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
mapping is NOT a plain index and has not been pinned down. Nothing here depends
on it: the adapter addresses cues by slot number and the UI labels them, which
is what ``capabilities.cues.slot_labels`` is for.
Loop-ness is NOT carried by ``Kind``. A loop is an ordinary cue row that also
has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
"""
from __future__ import annotations
MEMORY_KIND = 0
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
CUE_TYPES = ["cue", "loop"]
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:
return "memory", None
return "hotcue", int(kind)
def kind_for(role: str, slot: int | None) -> int:
"""The native ``Kind`` for a generic (role, slot). Inverse of `role_and_slot`."""
if role == "memory":
return MEMORY_KIND
if slot is None:
raise ValueError("a hot cue needs a slot")
return int(slot)
def cue_type(out_msec: int | None) -> str:
"""A cue with a real out-point is a loop; everything else is a plain cue.
Rekordbox writes ``OutMsec = -1`` for a non-loop.
"""
return "loop" if out_msec is not None and out_msec > 0 else "cue"
def beat_loop_size(beats: int) -> int:
"""Encode a loop's musical length.
``BeatLoopSize = (beats << 16) | 1`` — verified against two real loops at
different tempos (1 beat @125 BPM = 0x10001, 4 beats @120 BPM = 0x40001),
each agreeing with the measured millisecond span.
"""
return (int(beats) << 16) | 1
def beats_in_loop(beat_loop_size: int | None) -> int | None:
"""Decode `beat_loop_size`. None when unset."""
if not beat_loop_size:
return None
return beat_loop_size >> 16
@@ -0,0 +1,78 @@
"""Locate Rekordbox libraries in their default install locations.
Rekordbox keeps one library per install, at a fixed per-OS path:
macOS ~/Library/Pioneer/rekordbox/master.db
Windows %APPDATA%/Pioneer/rekordbox/master.db
``pyrekordbox`` already resolves this (including the v6/v7 split and any
non-default location recorded in Rekordbox's own settings), so that is the
primary source and the hard-coded paths are the fallback.
"""
from __future__ import annotations
from pathlib import Path
_RELATIVE = Path("Pioneer") / "rekordbox" / "master.db"
def _configured_paths() -> list[Path]:
"""Library paths pyrekordbox finds from Rekordbox's own configuration."""
out: list[Path] = []
try:
from pyrekordbox.config import get_config
except Exception: # noqa: BLE001 — never let discovery break startup
return out
for version in ("rekordbox7", "rekordbox6"):
try:
conf = get_config(version)
except Exception: # noqa: BLE001
continue
if not conf:
continue
p = conf.get("db_path")
if p:
out.append(Path(p))
return out
def _default_paths() -> list[Path]:
home = Path.home()
return [
home / "Library" / _RELATIVE, # macOS
home / "AppData" / "Roaming" / _RELATIVE, # Windows
]
def describe(path: Path) -> dict:
"""A candidate record for a master.db path, shaped like the picker wants."""
path = Path(path)
exists = path.is_file()
# The version Rekordbox itself is, not a schema version stamped in the file:
# master.db carries no version field, so the folder is the best label there is.
return {
"path": str(path),
"label": "Rekordbox",
"version": None,
"modified": (path.stat().st_mtime if exists else None),
"exists": exists,
}
def detect_libraries() -> list[dict]:
"""Every Rekordbox master.db found in a default location, newest first."""
seen: set[str] = set()
found: list[dict] = []
for p in _configured_paths() + _default_paths():
try:
if not p.is_file():
continue
except OSError:
continue
key = str(p.resolve())
if key in seen:
continue
seen.add(key)
found.append(describe(p))
found.sort(key=lambda c: c["modified"] or 0.0, reverse=True)
return found
@@ -0,0 +1,85 @@
"""Opening Rekordbox libraries: recognition, discovery and restore."""
from __future__ import annotations
import logging
from pathlib import Path
from . import discovery
from .adapter import RekordboxAdapter
log = logging.getLogger(__name__)
_SQLITE_MAGIC = b"SQLite format 3\x00"
class RekordboxDriver:
platform = "rekordbox"
display_name = "Rekordbox"
suffixes = (".db",)
library_label = "master.db"
def can_open(self, path: Path) -> bool:
"""Recognise an encrypted Rekordbox database.
Extension is not enough — plenty of things are called ``.db`` — and a
SQLCipher file has no readable header at all (its first page is
encrypted, so it does NOT start with the SQLite magic). So the probe
decrypts just far enough to look for a table only Rekordbox has. That is
one page read, and it is the only way to answer honestly.
"""
try:
if not path.is_file() or path.suffix.lower() != ".db":
return False
with path.open("rb") as fh:
if fh.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC:
return False # a plain, unencrypted SQLite file
except OSError:
return False
return self._has_rekordbox_schema(path)
@staticmethod
def _has_rekordbox_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.db6.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
con = None
try:
con = sqlcipher.connect(str(path))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
row = con.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='djmdContent'"
).fetchone()
return row is not None
except Exception: # noqa: BLE001 — wrong key or not a database
return False
finally:
if con is not None:
try:
con.close()
except Exception: # noqa: BLE001
pass
def open(self, path: Path) -> RekordboxAdapter:
return RekordboxAdapter(path)
def detect(self) -> list[dict]:
return discovery.detect_libraries()
def describe(self, path: Path) -> dict:
return discovery.describe(path)
def restore(self, path: Path, data: bytes) -> None:
"""Not supported: a Rekordbox library is more than one file.
`master.db` carries neither the beatgrids (ANLZ files) nor the playlist
XML, and putting an old database back would also revert Rekordbox's auth
token and sampler state. `capabilities.save.history` is False for the
same reason, so nothing should reach this.
"""
raise NotImplementedError(
"Konduktor does not version Rekordbox libraries: a restore would need "
"the analysis files and would roll back Rekordbox's own app state."
)
@@ -0,0 +1,177 @@
"""Rekordbox native rows -> the generic projection.
The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
"""
from __future__ import annotations
import re
from ...core.model import CuePoint, GridMarker, Track, TrackCues
from . import beatgrid
from .cue_types import cue_type, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
# Open Key notation. Parsing that is platform knowledge and belongs here.
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
# Camelot wheel position for each pitch class, per mode.
_CAMELOT_MINOR = {
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
"F": 4, "C": 5, "G": 6, "D": 7,
}
_CAMELOT_MAJOR = {
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
"F": 7,
}
def parse_key(key: str | None) -> tuple[int | None, str | None]:
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
if not key:
return None, None
m = _KEY_RE.match(key.strip())
if not m:
return None, None
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
pitch = letter + (accidental.replace("B", "b") if accidental else "")
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
n = table.get(pitch)
return (n, "minor" if minor else "major") if n else (None, None)
def _iso_date(value) -> str | None:
"""Rekordbox already stores ISO-ish 'YYYY-MM-DD'; blanks become None."""
if not value:
return None
s = str(value).strip()
return s or None
def _bpm(row) -> float | None:
"""``djmdContent.BPM`` is the tempo x100, and 0 means 'not known'.
It is a display value only — the real grid is in the ANLZ file — and it is
genuinely 0 for analysed tracks in real libraries.
"""
raw = getattr(row, "BPM", None)
if not raw:
return None
return round(raw / 100.0, 2)
def _name_of(related) -> str | None:
"""A joined lookup row's display name, or None when unset."""
if related is None:
return None
for attr in ("Name", "ScaleName"):
value = getattr(related, attr, None)
if value:
return str(value)
return None
def to_track(row, cue_counts: tuple[int, int] = (0, 0)) -> Track:
"""Project one ``DjmdContent`` row.
`cue_counts` is ``(total, hotcues)`` from the store's single aggregate
query — passed in rather than read off the row, which would be a per-track
round trip.
**`grid_marker_count` is an approximation here**: the real count needs the
track's ANLZ file, which is far too slow to read for every track at open
(~12 s on a library of 8,500). A track with a BPM is reported as 1 (constant
tempo, true for all but a fraction of a percent of real tracks) and the value
is corrected the moment the track's grid is actually read.
BPM — not the presence of an analysis file — is the signal, because Rekordbox
analyses one-shot samples too and gives them an ANLZ with no beatgrid at all.
On the reference library the two sets agree exactly: all 22 tracks with no
BPM are precisely the 22 with no grid.
"""
total_cues, hotcues = cue_counts
key_name = _name_of(getattr(row, "Key", None))
wheel, mode = parse_key(key_name)
return Track(
id=str(row.ID),
artist=_name_of(getattr(row, "Artist", None)),
title=getattr(row, "Title", None),
album=_name_of(getattr(row, "Album", None)),
genre=_name_of(getattr(row, "Genre", None)),
label=_name_of(getattr(row, "Label", None)),
remixer=_name_of(getattr(row, "Remixer", None)),
producer=None, # Rekordbox has Composer, which is not the same field
mix=None,
comment=getattr(row, "Commnt", None),
bpm=_bpm(row),
key=key_name,
key_wheel=wheel,
key_mode=mode,
# Rekordbox stores 0-5 stars directly — no /51 conversion, unlike Traktor.
rating=max(0, min(5, int(getattr(row, "Rating", 0) or 0))),
playcount=getattr(row, "DJPlayCount", None),
length=getattr(row, "Length", None),
bitrate=getattr(row, "BitRate", None),
import_date=_iso_date(getattr(row, "StockDate", None)),
last_played=None, # not modelled as a date in master.db
release_date=_iso_date(getattr(row, "ReleaseDate", None)),
filepath=str(getattr(row, "FolderPath", "") or "") or None,
cue_count=total_cues,
hotcue_count=hotcues,
grid_marker_count=1 if (_bpm(row) and getattr(row, "AnalysisDataPath", None)) else 0,
grid_locked=False, # Rekordbox has no per-track grid lock
media_kind="audio",
)
def to_track_cues(cue_rows: list, grid: tuple[list[float], list[float]] | None) -> TrackCues:
"""Project a track's cues and beatgrid.
`grid` is the per-beat ``(times, bpms)`` from the ANLZ file, collapsed here
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.
"""
markers: list[GridMarker] = []
if grid is not None:
times, bpms = grid
markers = beatgrid.markers_from_beats(times, bpms)
cues: list[CuePoint] = []
for c in cue_rows:
role, slot = role_and_slot(getattr(c, "Kind", None))
out_msec = getattr(c, "OutMsec", None)
in_msec = getattr(c, "InMsec", 0) or 0
length = 0.0
if out_msec is not None and out_msec > 0:
length = max(0.0, (out_msec - in_msec) / 1000.0)
cues.append(
CuePoint(
name=(getattr(c, "Comment", None) or None),
type=cue_type(out_msec),
role=role,
start=in_msec / 1000.0,
length=length,
slot=slot,
color=_cue_color(c),
editable=False,
readonly_reason="platform_managed",
grid_marker=None,
)
)
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
The generic model carries ``#RRGGBB``, and the built-in palette that index
refers to is not yet known, so no colour is claimed rather than a wrong one
being invented. `capabilities.cues.color` already says "palette", so the UI
knows not to offer a free colour picker.
"""
return None
@@ -0,0 +1,255 @@
"""The retained native model for Rekordbox: the open ``master.db`` session.
This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted
SQLCipher session, the ANLZ analysis files, and the caches the projection reads.
**Read-only in this milestone.** The write path is deliberately absent rather
than stubbed: a store that cannot write cannot half-write.
Two things here are not obvious and are load-bearing:
* **ANLZ is read LAZILY.** The beatgrid lives in a per-track analysis file, not
in the database, and parsing them all costs ~1.4 ms each — about 12 seconds
for a library the size of the project's Traktor collection. So grids are
parsed on demand and cached, and `Track.grid_marker_count` carries a
documented approximation until a track's grid is actually read.
* **Cue counts come from ONE aggregate query**, not from walking each track's
relationship, which would be a per-track round trip at open.
"""
from __future__ import annotations
import logging
from pathlib import Path
from sqlalchemy import func, select, text
from sqlalchemy.orm import joinedload
from ...core.adapter import LibraryNotSupported, NotFound
from ...core.pathmap import PathMapping
log = logging.getLogger(__name__)
class RekordboxStore:
"""One open Rekordbox library."""
def __init__(self, path: Path):
self.path = Path(path)
self._mapping = PathMapping()
self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {}
self._load()
# ---- open ------------------------------------------------------------
def _load(self) -> None:
from pyrekordbox import Rekordbox6Database
from pyrekordbox.db6 import tables
self._tables = tables
try:
self._db = Rekordbox6Database(path=str(self.path), unlock=True)
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
raise LibraryNotSupported(f"Could not open Rekordbox library: {ex}") from ex
self._grid_cache.clear()
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
def close(self) -> None:
try:
self._db.close()
except Exception: # noqa: BLE001 — closing must never raise
pass
# ---- identity --------------------------------------------------------
@property
def cloud_synced(self) -> bool:
"""True when this library participates in Rekordbox's Cloud Library Sync.
Konduktor REFUSES to write a cloud-synced library: a local edit that the
server did not issue could propagate a corrupt sync state to the user's
other machines, which version history cannot undo. Detection is the
presence of a server-issued sequence number (`usn`) on any row, or a
populated cloud registry.
"""
t = self._tables
with self._db.session.no_autoflush:
for table in (t.DjmdContent, t.DjmdPlaylist, t.DjmdCue):
n = self._db.session.execute(
select(func.count()).select_from(table).where(table.usn.isnot(None))
).scalar()
if n:
return True
# pyrekordbox does not model every cloud table, so the rest is a
# raw probe: any row carrying a server-issued usn means synced.
for table_name in ("cloudAgentRegistry", "djmdCloudProperty"):
try:
n = self._db.session.execute(
text(f'SELECT COUNT(*) FROM "{table_name}" WHERE usn IS NOT NULL')
).scalar()
except Exception: # noqa: BLE001 — table may be absent
continue
if n:
return True
return False
@property
def local_usn(self) -> int | None:
"""Rekordbox's global local update counter (for diagnostics/tests)."""
try:
return self._db.get_local_usn()
except Exception: # noqa: BLE001
return None
# ---- content ---------------------------------------------------------
def iter_content(self) -> list:
"""Every track, with the lookup tables eagerly joined.
Without `joinedload` each track's artist/album/genre/key would be a
separate query — thousands of round trips on a real library.
"""
if self._content_cache is None:
t = self._tables
q = (
self._db.session.query(t.DjmdContent)
.options(
joinedload(t.DjmdContent.Artist),
joinedload(t.DjmdContent.Album),
joinedload(t.DjmdContent.Genre),
joinedload(t.DjmdContent.Key),
joinedload(t.DjmdContent.Label),
joinedload(t.DjmdContent.Remixer),
)
.filter(t.DjmdContent.rb_local_deleted == 0)
)
self._content_cache = list(q)
self._by_id = {str(c.ID): c for c in self._content_cache}
return self._content_cache
def content(self, track_id: str):
self.iter_content()
assert self._by_id is not None
row = self._by_id.get(str(track_id))
if row is None:
raise NotFound(f"No track {track_id!r}")
return row
def cue_counts(self) -> dict[str, tuple[int, int]]:
"""``{track_id: (total_cues, hotcue_count)}`` in one aggregate query."""
t = self._tables
rows = self._db.session.execute(
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, func.count())
.where(t.DjmdCue.rb_local_deleted == 0)
.group_by(t.DjmdCue.ContentID, t.DjmdCue.Kind)
).all()
out: dict[str, tuple[int, int]] = {}
for content_id, kind, n in rows:
total, hot = out.get(str(content_id), (0, 0))
out[str(content_id)] = (total + n, hot + (n if (kind or 0) != 0 else 0))
return out
def cues(self, track_id: str) -> list:
"""A track's cue rows, ordered by position."""
t = self._tables
return list(
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)
)
# ---- playlists -------------------------------------------------------
def playlists(self) -> list:
"""User playlists, excluding Rekordbox's own internal ones.
Rekordbox keeps working lists ("CUE Analysis Playlist", "Cloud Library
Sync") in the same table at reserved ids. They are not the user's and
showing them in the sidebar would be noise.
"""
from pyrekordbox.db6.database import SPECIAL_PLAYLIST_IDS
t = self._tables
return [
p
for p in self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdPlaylist.Seq)
if str(p.ID) not in SPECIAL_PLAYLIST_IDS
]
def playlist_song_ids(self, playlist_id: str) -> list[str]:
t = self._tables
rows = (
self._db.session.query(t.DjmdSongPlaylist.ContentID)
.filter(t.DjmdSongPlaylist.PlaylistID == str(playlist_id))
.filter(t.DjmdSongPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdSongPlaylist.TrackNo)
)
return [str(r[0]) for r in rows]
def count_playlists(self) -> int:
"""Playlists the user has, for the status bar — folders excluded."""
folder = int(self._tables.PlaylistType.FOLDER)
return sum(1 for p in self.playlists() if int(p.Attribute or 0) != folder)
# ---- analysis files (the beatgrid) -----------------------------------
def anlz_grid(self, track_id: str) -> tuple[list[float], list[float]] | None:
"""``(times_sec, bpms)`` per beat for a track, or None if unanalysed.
Parsed on demand and cached — see the module docstring for why this is
not done eagerly.
"""
key = str(track_id)
if key in self._grid_cache:
return self._grid_cache[key]
result = self._read_anlz_grid(key)
self._grid_cache[key] = result
return result
def _read_anlz_grid(self, track_id: str):
row = self.content(track_id)
rel = getattr(row, "AnalysisDataPath", None)
if not rel:
return None
# AnalysisDataPath is rooted at the library's `share` directory and is
# stored with a leading slash.
path = self.path.parent / "share" / str(rel).lstrip("/\\")
if not path.is_file():
return None
try:
from pyrekordbox.anlz import AnlzFile
anlz = AnlzFile.parse_file(str(path))
except Exception as ex: # noqa: BLE001 — a bad ANLZ must not break a read
log.debug("ANLZ parse failed for %s: %s", track_id, ex)
return None
for tag in anlz.tags:
# Never treat AnlzFile as a Mapping: keys()/len() recurse forever in
# pyrekordbox 0.4.4.
if tag.type == "PQTZ":
try:
return [float(t) for t in tag.times], [float(b) for b in tag.bpms]
except Exception: # noqa: BLE001
return None
return None
def has_analysis(self, track_id: str) -> bool:
return bool(getattr(self.content(track_id), "AnalysisDataPath", None))
# ---- paths -----------------------------------------------------------
def set_path_mapping(self, mapping: PathMapping) -> None:
self._mapping = mapping or PathMapping()
@property
def path_mapping(self) -> PathMapping:
return self._mapping
def audio_path(self, track_id: str) -> Path | None:
"""The track's audio file on THIS machine, after any path remap."""
folder = getattr(self.content(track_id), "FolderPath", None)
if not folder:
return None
return self._mapping.apply(Path(str(folder)))
def all_audio_paths(self) -> list[str]:
return [
str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None)
]
+24
View File
@@ -40,6 +40,30 @@ def open_library(path: Path):
return driver_for(path).open(path)
def describe(path: Path) -> dict:
"""Describe a library path using whichever adapter recognises it.
Used for the picker's "last opened" shortcut, which must still render when
the file has since been moved or deleted — so an unrecognised path gets a
plain description with ``exists`` false rather than an error.
"""
try:
return driver_for(path).describe(path)
except (LibraryNotSupported, OSError):
pass
try:
exists = path.is_file()
except OSError:
exists = False
return {
"path": str(path),
"label": path.name,
"version": None,
"modified": None,
"exists": exists,
}
def detect_all() -> list:
"""Every library found in the platforms' default install locations."""
out: list = []
+1 -2
View File
@@ -14,7 +14,6 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from . import __version__, history, prefs
from .adapters.traktor.discovery import describe
from .app_state import STATE
from .core import auto_hotcues as ah
from .core import registry
@@ -144,7 +143,7 @@ def collection_options() -> CollectionOptions:
recent = None
last = prefs.get_last_collection()
if last:
recent = CollectionCandidate(**describe(Path(last)))
recent = CollectionCandidate(**registry.describe(Path(last)))
return CollectionOptions(auto=auto, recent=recent)
+3
View File
@@ -17,3 +17,6 @@ scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
pyrekordbox>=0.4.4
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_phase3.py test_history.py; do
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+35
View File
@@ -46,5 +46,40 @@ print("== adapters own their native model ==")
store = (CORE.parent / "adapters" / "traktor" / "store.py").read_text()
check("the Traktor store is where traktor_nml_utils lives", "traktor_nml_utils" in store)
# No adapter may import another platform's library. That is the rule that keeps
# the packages independently removable, and it is checked on real imports (AST)
# rather than on text, so merely NAMING another platform in a comment is fine.
NATIVE = {"traktor": "traktor_nml_utils", "rekordbox": "pyrekordbox"}
def imported_modules(path):
names = set()
for node in ast.walk(ast.parse(path.read_text())):
if isinstance(node, ast.Import):
names.update(a.name for a in node.names)
elif isinstance(node, ast.ImportFrom) and not node.level:
names.add(node.module or "")
return names
for platform, module in NATIVE.items():
pkg = CORE.parent / "adapters" / platform
if not pkg.is_dir():
continue
foreign = {m for p_, m in NATIVE.items() if p_ != platform}
strays = []
for src in sorted(pkg.rglob("*.py")):
for name in imported_modules(src):
if any(name == f or name.startswith(f + ".") for f in foreign):
strays.append(f"{src.name}: {name}")
check(f"the {platform} adapter imports no other platform's library",
not strays, "; ".join(strays))
own = [
src.name
for src in sorted(pkg.rglob("*.py"))
if any(n == module or n.startswith(module + ".") for n in imported_modules(src))
]
check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+262
View File
@@ -0,0 +1,262 @@
"""Tests for the Rekordbox adapter (read-only milestone).
The counterpart to `test_traktor_adapter.py`: it exercises the GENERIC layer for
the second platform — the projection, the cue/grid translation, the playlist
tree, capabilities, and the refusal of every command — so that "a second adapter
satisfies the same contract" is a claim the suite actually checks rather than a
design intention.
Runs against a TEMP COPY of the local Rekordbox library, and skips cleanly when
there is no Rekordbox installed (CI, or any machine but the developer's).
"""
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rb-appdata-")
from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
from konduktor.adapters.rekordbox.beatgrid import ( # noqa: E402
beats_from_markers,
markers_from_beats,
)
from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402
beat_loop_size,
beats_in_loop,
kind_for,
role_and_slot,
)
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402
from konduktor.core import registry # noqa: E402
from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402
from konduktor.core.model import GridMarker # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
# ---- 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)
# 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)
print("== key parsing (Rekordbox names keys musically, not in Camelot) ==")
check("Fm -> 4A", parse_key("Fm") == (4, "minor"))
check("Am -> 8A", parse_key("Am") == (8, "minor"))
check("C -> 8B", parse_key("C") == (8, "major"))
check("Ebm -> 2A", parse_key("Ebm") == (2, "minor"))
check("unparseable key is None, not a guess", parse_key("nonsense") == (None, None))
check("absent key is None", parse_key(None) == (None, None))
print("== beatgrid: per-beat <-> marker list ==")
# Rekordbox stores EVERY beat; the generic model is a marker list.
times = [0.0, 0.5, 1.0, 1.5, 2.0, 2.4, 2.8]
bpms = [120.0, 120.0, 120.0, 120.0, 120.0, 150.0, 150.0]
markers = markers_from_beats(times, bpms)
check("a tempo change makes a second marker", len(markers) == 2, str(len(markers)))
check("markers carry their tempo and start", markers[0].bpm == 120.0 and markers[1].start == 2.4)
const = markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.0, 120.0])
check("a constant-tempo grid is ONE marker", len(const) == 1)
check("an empty grid projects to no markers", markers_from_beats([], []) == [])
# Float noise must not manufacture markers.
noisy = markers_from_beats([0.0, 0.5, 1.0], [120.0, 120.000001, 119.999999])
check("float noise does not split a marker", len(noisy) == 1, str(len(noisy)))
# The inverse.
beat_nums, out_bpms, out_times = beats_from_markers([GridMarker(start=0.0, bpm=120.0)], 2.0)
check("expanding one marker gives a beat every 0.5s at 120 BPM", out_times == [0.0, 0.5, 1.0, 1.5], str(out_times))
check("beats are numbered 1-4 in bars", beat_nums == [1, 2, 3, 4], str(beat_nums))
check("expanding no markers gives no beats", beats_from_markers([], 10.0) == ([], [], []))
# ---- the rest needs a real library --------------------------------------
found = discovery.detect_libraries()
if not found:
print("\n== library tests SKIPPED: no Rekordbox library found on this machine ==")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
REAL = Path(found[0]["path"])
print(f"\n(using a temp copy of {REAL})")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "master.db"
shutil.copy2(REAL, work)
# The beatgrid lives in the ANLZ files under share/, not in the database.
share = REAL.parent / "share"
if share.is_dir():
shutil.copytree(share, Path(d) / "share")
print("== the driver recognises the library by probing, not by extension ==")
driver = RekordboxDriver()
check("can_open accepts a real master.db", driver.can_open(work))
plain = Path(d) / "plain.db"
import sqlite3
sqlite3.connect(plain).execute("CREATE TABLE t (a)")
check("can_open rejects an unencrypted .db", not driver.can_open(plain))
check("can_open rejects a non-database", not driver.can_open(Path(d) / "missing.db"))
check("the registry picks Rekordbox for it", registry.driver_for(work).platform == "rekordbox")
adapter = RekordboxAdapter(work)
print("== the projection ==")
check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter))
check("tracks are projected", len(adapter.tracks) > 0, str(len(adapter.tracks)))
check("the primary-key index agrees with the list", len(adapter.by_key) == len(adapter.tracks))
check("platform is reported generically", adapter.platform == "rekordbox")
sample = adapter.tracks[0]
check("a track id is a plain string", isinstance(sample.id, str) and sample.id != "")
check("track() resolves by id", adapter.track(sample.id) is sample)
check("an unknown id resolves to None", adapter.track("no-such-track") is None)
rated = [t for t in adapter.tracks if t.rating]
check("ratings are already 0-5 (no /51 conversion)", all(0 <= t.rating <= 5 for t in adapter.tracks))
if rated:
check("at least one rating survives the projection", max(t.rating for t in rated) >= 1)
print("== cues project into the generic vocabulary ==")
with_cues = [t for t in adapter.tracks if t.cue_count]
check("some track has cues", bool(with_cues), "none found")
if with_cues:
tc = adapter.track_cues(with_cues[0].id)
check("track_cues returns a projection", tc is not None)
check("every cue type is in the generic vocabulary",
all(c.type in ("cue", "loop") for c in tc.cues),
str({c.type for c in tc.cues}))
check("every role is generic", all(c.role in ("hotcue", "memory") for c in tc.cues))
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))
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"]
if loops:
check("a loop has a positive length", all(c.length > 0 for c in loops))
print("== the beatgrid is read lazily and corrects the projection ==")
# Rekordbox analyses one-shot samples too, and gives them an ANLZ file with
# no beatgrid — so "has an analysis file" does NOT mean "has a grid".
gridded = [t for t in adapter.tracks if t.bpm]
if gridded:
t = gridded[0]
tc = adapter.track_cues(t.id)
check("a track with a tempo projects at least one grid marker", len(tc.grid_markers) >= 1)
check("markers are ordered by start",
all(a.start <= b.start for a, b in zip(tc.grid_markers, tc.grid_markers[1:])))
check("every marker has a positive tempo", all(m.bpm > 0 for m in tc.grid_markers))
# The approximation must be CORRECTED by a read, for every track — including
# the sample one-shots, whose true count is zero.
mismatched = []
for t in adapter.tracks[:40]:
markers = adapter.track_cues(t.id).grid_markers
if t.grid_marker_count != len(markers):
mismatched.append(f"{t.title}: {t.grid_marker_count} vs {len(markers)}")
check("reading a grid corrects grid_marker_count on every track",
not mismatched, "; ".join(mismatched[:3]))
check("track_cues on an unknown track is None", adapter.track_cues("no-such-track") is None)
print("== playlists ==")
tree = adapter.playlist_tree()
check("the tree is a list of generic nodes", isinstance(tree, list))
ids = []
def walk(nodes):
for n in nodes:
ids.append(n.id)
check_kind = n.kind in ("folder", "playlist", "smart")
if not check_kind:
check(f"node {n.name!r} has a generic kind", False, n.kind)
walk(n.children)
walk(tree)
check("no internal Rekordbox playlist is exposed",
all(i not in ("100000", "200000") for i in ids), str(ids))
check("nothing claims to be editable", not any(
n.can_rename or n.can_delete or n.can_add_tracks or n.can_reorder
for n in tree
))
print("== capabilities gate the UI ==")
caps = adapter.capabilities()
check("platform is rekordbox", caps.platform == "rekordbox")
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"])
# 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")
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("no field is advertised as editable", caps.tracks.editable_fields == [])
check("version history is off (multi-artefact library)", caps.save.history is False)
check("the save warning says Rekordbox holds the library open",
caps.save.overwrite_risk == "while_running")
check("library label is master.db", caps.save.library_label == "master.db")
print("== every command is refused, with a reason ==")
commands = {
"set_track_metadata": lambda: adapter.set_track_metadata(sample.id, {"title": "x"}),
"create_playlist": lambda: adapter.create_playlist("x"),
"rename_playlist": lambda: adapter.rename_playlist("1", "x"),
"delete_playlist": lambda: adapter.delete_playlist("1"),
"set_playlist_entries": lambda: adapter.set_playlist_entries("1", []),
"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),
"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),
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None),
"save": lambda: adapter.save(),
"snapshot": lambda: adapter.snapshot(),
}
refused = []
for name, fn in commands.items():
try:
fn()
refused.append(name)
except Unsupported:
pass
except Exception as ex: # noqa: BLE001 — anything else is the wrong error
refused.append(f"{name} ({type(ex).__name__})")
check("every mutating command raises Unsupported", not refused, ", ".join(refused))
check("the adapter is never dirty while read-only", adapter.dirty is False)
print("== reads that must still work ==")
page = adapter.query_tracks(limit=5)
check("query_tracks paginates", len(page.items) <= 5 and page.total == len(adapter.tracks))
facets = adapter.facets()
check("facets come from the generic index", facets.total_tracks == len(adapter.tracks))
stats = adapter.stats(playlist_count=adapter.playlist_count())
check("stats come from the generic index", stats.total_tracks == len(adapter.tracks))
check("audio_path resolves to an OS path",
adapter.audio_path(sample.id) is None or isinstance(adapter.audio_path(sample.id), Path))
check("cover_art is absent rather than an error", adapter.cover_art(sample.id) is None)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)