Added grid support to Rekordbox Adapter

This commit is contained in:
patben8 committed 2026-09-19 11:01:51 +02:00
1 parent 30065a94fe
commit 5aeb9956cd
8 files changed
+465 -48

No files matched your search

+53 -23
View File
@@ -23,7 +23,7 @@ from pathlib import Path
from ...core.adapter import Unsupported
from ...core.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
@@ -303,6 +303,56 @@ class RekordboxAdapter:
self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id)
# ---- commands: beatgrid -----------------------------------------------
def _markers_from(self, markers: list) -> list:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
out = []
for m in markers:
if isinstance(m, GridMarker):
out.append(m)
else:
start, bpm = m
out.append(GridMarker(start=float(start), bpm=float(bpm)))
return out
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.add_grid_marker(track_id, start_sec, bpm)
return self._refresh_cues(track_id)
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.move_grid_marker(track_id, index, start_sec)
return self._refresh_cues(track_id)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.set_grid_marker_bpm(track_id, index, bpm)
return self._refresh_cues(track_id)
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.delete_grid_marker(track_id, index)
return self._refresh_cues(track_id)
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._require_writable("Editing the beatgrid")
self._store.replace_grid(track_id, self._markers_from(markers))
return self._refresh_cues(track_id)
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
"""Write an analysis result the way Rekordbox's own analyser would.
Rekordbox pairs nothing with a grid marker — the companion cue is a
Traktor convention — so this is just a replace.
"""
return self.replace_grid(track_id, markers)
def delete_grid(self, track_id: str) -> TrackCues:
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
@@ -348,26 +398,6 @@ class RekordboxAdapter:
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return None
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._refuse("Editing the beatgrid")
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues:
self._refuse("Editing the beatgrid")
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues:
self._refuse("Editing the beatgrid")
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues:
self._refuse("Editing the beatgrid")
def replace_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
def set_analysed_grid(self, track_id: str, markers: list) -> TrackCues:
self._refuse("Editing the beatgrid")
def delete_grid(self, track_id: str) -> TrackCues:
self._refuse("Editing the beatgrid")
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
self._refuse("Locking the beatgrid")
# Rekordbox has no per-track grid lock; capabilities.grid.lockable says so.
raise Unsupported("Rekordbox has no beatgrid lock")
@@ -78,3 +78,51 @@ def beats_from_markers(
n = n % 4 + 1
t += step
return beat_nums, bpms, times
# ---- writing the analysis file ----------------------------------------------
#
# The grid lives in the ANLZ files, and only `.DAT`'s `PQTZ` tag is written here.
# `.EXT` carries a second, "extended" grid (`PQT2`) whose per-beat byte and `u3`
# field are NOT decoded — `pyrekordbox` itself calls the field `unkown` — so
# rewriting it would mean guessing at bytes in real user data that has no version
# history. Leaving it alone is the only safe option until it is decoded.
#
# `.DAT`/`.EXT` round-trip byte-identically through parse -> build (verified
# across a whole library), which is what makes this checkable at all: a rebuild
# must differ ONLY inside the tag we touched.
def write_pqtz(path, beat_nums, bpms, times) -> bool:
"""Replace the beat grid in an ANLZ `.DAT`, in place. True if written.
`pyrekordbox`'s own `PQTZAnlzTag.set*()` refuse to change the NUMBER of
beats ("only values of existing beats can be set"), and every real grid edit
changes it — so the entry list is rebuilt directly and the tag's own
`update_len()` recomputes `len_tag`. `check_parse()` then asserts the
declared count and the list agree before anything is written.
"""
import construct
from pyrekordbox.anlz import AnlzFile
anlz = AnlzFile.parse_file(str(path))
tag = next((t for t in anlz.tags if t.type == "PQTZ"), None)
if tag is None:
return False
entries = construct.ListContainer()
for beat, bpm, t in zip(beat_nums, bpms, times):
entries.append(
construct.Container(
beat=int(beat),
tempo=int(round(bpm * 100)), # BPM is stored x100
time=int(round(t * 1000)), # seconds -> ms
)
)
tag.struct.content.entries = entries
tag.struct.content.entry_count = len(entries)
tag.update_len()
tag.check_parse()
data = anlz.build()
with open(path, "wb") as fh:
fh.write(data)
return True
@@ -73,7 +73,10 @@ def capabilities_for(
named=True, # djmdCue.Comment
loops="cue_type",
),
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
# The grid is written into the track's ANLZ .DAT (PQTZ). Verified:
# Rekordbox reads the grid and its BPM readout from there, and leaves a
# Konduktor-written file alone. It has no per-track grid lock.
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
# Narrower than Traktor's: `producer` and `mix` have no Rekordbox
@@ -60,6 +60,9 @@ class RekordboxStore:
self._mapping = PathMapping()
self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {}
self._journal = EditJournal()
# Grid edits buffered until save(): ANLZ files are written to disk, so
# applying them at command time would break the save contract.
self._pending_grids: dict[str, tuple[list, list, list]] = {}
self._load()
# ---- open ------------------------------------------------------------
@@ -445,6 +448,9 @@ class RekordboxStore:
`capabilities.save.history` says so.
"""
summary = self._journal.summary()
# Files first: if an analysis file cannot be written, nothing should have
# been committed to the database either.
self._flush_grids()
self._commit()
self._journal.clear()
# Reads go through the same session, so nothing needs re-projecting from
@@ -719,3 +725,127 @@ class RekordboxStore:
mirror.Cues = json.dumps(records, ensure_ascii=False)
mirror.rb_cue_count = len(records)
self._db.flush()
# ---- writes: the beatgrid ---------------------------------------------
#
# The grid lives in the track's ANLZ `.DAT` (`PQTZ`), not in the database.
# Verified in Rekordbox 7: it reads the grid and the deck's BPM readout from
# `PQTZ`, leaves a rewritten `.DAT` exactly as Konduktor wrote it, ignores
# the stale extended grid in `.EXT` — and does NOT reconcile
# `djmdContent.BPM`, which stayed at the old tempo while the deck showed the
# new one. So that column is Konduktor's to maintain.
#
# Edits are BUFFERED and the files are written on save(), so the grid obeys
# the same "edit in memory, Save writes to disk" contract as everything else
# — an unsaved grid change must not already be on disk.
def current_markers(self, track_id: str) -> list:
"""The track's grid as a generic marker list (pending edits included)."""
from . import beatgrid as grid_math
grid = self.anlz_grid(track_id)
if grid is None:
return []
times, bpms = grid
return grid_math.markers_from_beats(times, bpms)
def track_duration(self, track_id: str) -> float:
"""Seconds, for expanding markers back into beats."""
length = getattr(self.content(track_id), "Length", None)
if length:
return float(length)
grid = self.anlz_grid(track_id)
if grid and grid[0]:
return float(grid[0][-1]) + 1.0
return 0.0
def replace_grid(self, track_id: str, markers: list) -> None:
"""Set the grid to exactly these markers. The one primitive; every
marker-level command is expressed as a read-modify-replace on top."""
from . import beatgrid as grid_math
for m in markers:
if m.bpm <= 0:
raise InvalidCommand(f"A beatgrid marker needs a positive tempo, got {m.bpm}")
if m.start < 0:
raise InvalidCommand("A beatgrid marker cannot be before the track starts")
ordered = sorted(markers, key=lambda m: m.start)
duration = self.track_duration(track_id)
beat_nums, bpms, times = grid_math.beats_from_markers(ordered, duration)
# Buffer as the same (times, bpms) shape the reader returns, so the
# projection needs no special case for an unsaved grid.
self._pending_grids[str(track_id)] = (beat_nums, bpms, times)
self._grid_cache[str(track_id)] = (times, bpms) if times else None
# TEMPO mirrors the first marker, exactly as Traktor's <TEMPO> does —
# Rekordbox will not do it for us.
row = self.content(track_id)
row.BPM = int(round(ordered[0].bpm * 100)) if ordered else 0
self._journal.record("grid", "replace" if ordered else "delete", track_id)
def delete_grid(self, track_id: str) -> None:
self.replace_grid(track_id, [])
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> None:
from ...core.model import GridMarker
markers = self.current_markers(track_id)
if bpm is None:
# Inherit the tempo governing this point, like Traktor's add does.
governing = [m for m in markers if m.start <= start_sec]
bpm = governing[-1].bpm if governing else (markers[0].bpm if markers else None)
if not bpm:
raise InvalidCommand("The first marker on an ungridded track needs a tempo")
if any(abs(m.start - start_sec) < 0.001 for m in markers):
raise InvalidCommand("There is already a marker here")
markers.append(GridMarker(start=float(start_sec), bpm=float(bpm)))
self.replace_grid(track_id, markers)
def _marker_at(self, track_id: str, index: int) -> tuple[list, int]:
markers = self.current_markers(track_id)
if not 0 <= index < len(markers):
raise NotFound(f"No grid marker {index}")
return markers, index
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
markers, i = self._marker_at(track_id, index)
# Clamp between neighbours so the list cannot reorder under the caller.
low = markers[i - 1].start + 0.001 if i > 0 else 0.0
high = markers[i + 1].start - 0.001 if i + 1 < len(markers) else None
target = max(low, float(start_sec))
if high is not None:
target = min(target, high)
markers[i] = markers[i].model_copy(update={"start": target})
self.replace_grid(track_id, markers)
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
markers, i = self._marker_at(track_id, index)
if bpm <= 0:
raise InvalidCommand(f"A tempo must be positive, got {bpm}")
markers[i] = markers[i].model_copy(update={"bpm": float(bpm)})
self.replace_grid(track_id, markers)
def delete_grid_marker(self, track_id: str, index: int) -> None:
markers, i = self._marker_at(track_id, index)
del markers[i]
self.replace_grid(track_id, markers)
def _flush_grids(self) -> None:
"""Write buffered grids into their ANLZ files. Called by save().
Only `.DAT`'s `PQTZ` is written — `.EXT`'s extended grid carries
undecoded bytes, and Rekordbox was verified to read the grid from
`PQTZ` and to be untroubled by the other being stale.
"""
from . import beatgrid as grid_math
for track_id, (beat_nums, bpms, times) in list(self._pending_grids.items()):
rel = getattr(self.content(track_id), "AnalysisDataPath", None)
if not rel:
raise InvalidCommand(
"This track has no analysis file, so it has nowhere to store a beatgrid"
)
path = self.path.parent / "share" / str(rel).lstrip("/\\")
if not path.is_file():
raise InvalidCommand(f"Analysis file is missing: {path}")
grid_math.write_pqtz(path, beat_nums, bpms, times)
self._pending_grids.clear()