Implemented OneLibrary cue and grid edits

This commit is contained in:
patben8 committed 2026-10-01 15:48:44 +02:00
1 parent 775e94168c
commit e73fa05e1f
13 files changed
+696 -157

No files matched your search

@@ -12,20 +12,22 @@ reports `writable=False` with cause `browsing`, and every command is refused.
What a write must look like was MEASURED by diffing a stick before and after
rekordbox 7 edited it, rather than guessed: the update counters a drive carries
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata
and playlists first; cues, grid, adding and removing tracks after — and every
command not written yet is refused, with its capability flag False so the UI
never offers it.
do NOT move, and the `cue` table stays empty. Landing in steps — track metadata,
playlists, hot cues and the beatgrid so far; adding and removing tracks next —
and every command not written yet is refused, with its capability flag False so
the UI never offers it.
"""
from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.adapter import InvalidCommand, Unsupported
from ...core.capabilities import Capabilities
from ...core.model import HotcueChip, PlaylistNode, Track, TrackCues
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from . import capabilities as caps
from . import projection
from .store import OneLibraryStore
@@ -317,41 +319,107 @@ class OneLibraryAdapter:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
def set_cue(self, track_id: str, **kw) -> TrackCues:
self._refuse("Editing cues")
def _refresh_cues(self, track_id: str) -> TrackCues:
"""Re-project a track AND return its fresh cues — every cue/grid command
ends here, so a route can never serve a stale projection."""
self._refresh(track_id)
return self.track_cues(track_id) or TrackCues()
def _check_cue_type(self, cue_type: str) -> None:
if cue_type not in WRITABLE_CUE_TYPES:
raise Unsupported(f"OneLibrary 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":
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
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._refuse("Editing cues")
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 set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._refuse("Editing cues")
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's hot cue colours")
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._refuse("Deleting cues")
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._refuse("Placing cues")
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)
# ---- commands: beatgrid -----------------------------------------------
@staticmethod
def _markers_from(markers: list) -> list:
"""Accept either GridMarkers or the (start, bpm) tuples routes send."""
return [m if isinstance(m, GridMarker) else GridMarker(start=float(m[0]), bpm=float(m[1]))
for m in markers]
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues:
self._refuse("Editing the beatgrid")
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._refuse("Editing the beatgrid")
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._refuse("Editing the beatgrid")
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._refuse("Editing the beatgrid")
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._refuse("Editing the beatgrid")
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:
self._refuse("Editing the beatgrid")
"""An analysis result, as rekordbox's analyser would write it: nothing is
paired with a marker (the companion cue is Traktor's), so a replace."""
return self.replace_grid(track_id, markers)
def delete_grid(self, track_id: str) -> TrackCues:
self._refuse("Deleting the beatgrid")
self._require_writable("Deleting the beatgrid")
self._store.delete_grid(track_id)
return self._refresh_cues(track_id)
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
raise Unsupported("OneLibrary has no beatgrid lock")
@@ -1,8 +1,8 @@
"""What a OneLibrary drive can persist.
Opened as THE library, a drive is writable, and the per-feature flags say which
edits have landed: track metadata and playlists so far; cues, the grid, adding
and removing tracks are still False, so the UI never offers an edit the adapter
edits have landed: track metadata, playlists, hot cues and the grid so far;
adding and removing tracks are still False, so the UI never offers an edit the adapter
would refuse. Opened `read_only` — the sidebar's Devices, browsing beside the
loaded library — `writable` is False with cause `browsing`, which the UI words
as "open it for editing", not as a missing feature.
@@ -17,11 +17,11 @@ Two answers are worth recording now, while the evidence is in front of us, since
getting them wrong later would be a silent data bug rather than a missing
feature:
* cue colour is **free RGB**, not a palette index. The `PCO2` tag stores three
bytes per cue, and the reference drive held #4D00FF, #33FF00, #00C4FF and
#FF8C00. This differs from the desktop Rekordbox adapter, which reports
"palette" because `djmdCue` stores an index into a built-in table — the same
vendor, two genuinely different representations.
* cue colour is a **palette**, like master.db's. `PCO2` stores a palette CODE
and an RGB per cue, and rekordbox DRAWS from the code (an export writing only
RGB had every cue in rekordbox's defaults) — so a pick is one of rekordbox's
16 swatches and both are written. (This was first read as "free RGB" off the
RGB bytes alone; the code byte beside them is what decides.)
* a loop is a cue with an out-point, so ``loops="cue_type"`` — the same answer
as Traktor and Rekordbox, and NOT the `separate_bank` the original
multi-platform plan assumed.
@@ -36,6 +36,8 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`).
@@ -55,23 +57,22 @@ def capabilities_for(
writable=not read_only,
readonly_cause="browsing" if read_only else None,
cues=CueCapabilities(
editable=False,
editable=True,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does. They are
# projected and preserved; nothing here is editable anyway.
# OneLibrary carries memory cues, as Rekordbox does: projected and
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
memory_cues=True,
max_memory_cues=None,
types=["cue", "loop"],
color="free", # PCO2 stores RGB per cue, not a palette index
palette=[],
types=WRITABLE_CUE_TYPES,
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # PCO2 carries a per-cue comment
loops="cue_type",
),
# The grid is the ANLZ `PQTZ` tag, per beat, and multi-tempo grids do
# survive an export — so the format is flexible even though Konduktor
# does not write it here.
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
# The grid is the ANLZ `PQTZ` tag, per beat; multi-tempo grids survive.
# No per-track grid lock exists in the format.
grid=GridCapabilities(editable=True, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # stored 0-5 directly, as in master.db
# The Rekordbox adapter's set: `producer`/`mix` have no column.
+17 -9
View File
@@ -37,6 +37,7 @@ from __future__ import annotations
import logging
from ...core.model import CuePoint
from ..rekordbox import palette
log = logging.getLogger(__name__)
@@ -67,7 +68,14 @@ def _color(entry) -> str | None:
real black in principle, but rekordbox uses it as "unset" and shows such a
cue in the default colour, so it is reported as no colour rather than as
black. Memory cues in the reference export are exactly this case.
rekordbox DRAWS a cue from its palette CODE (`rekordbox.palette`), so a known
code is reported as that swatch; a cue with code 0 and an RGB (older
exports, the reference fixture) is reported by its RGB.
"""
swatch = palette.hex_for(getattr(entry, "color_code", None))
if swatch is not None:
return swatch
try:
# None on an entry too short to carry a colour: every PCPT, and the
# compact 44-byte PCP2 rekordbox writes for a memory cue it added.
@@ -79,7 +87,7 @@ def _color(entry) -> str | None:
return f"#{r:02X}{g:02X}{b:02X}"
def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | None:
"""One ANLZ cue entry as a generic `CuePoint`, or None if unreadable."""
try:
hot_cue = int(entry.hot_cue)
@@ -112,11 +120,11 @@ def _to_cue(entry, *, with_color: bool) -> CuePoint | None:
length=length,
slot=slot,
color=_color(entry) if with_color else None,
# A OneLibrary drive is read-only in Konduktor, so no cue accepts a
# command. `capabilities.writable` is what the UI actually gates on;
# this keeps the per-cue answer consistent with it.
editable=False,
readonly_reason="platform_managed",
# Hot cues are editable on a drive opened for editing (the caller says
# so). MEMORY cues never are — preserved-but-uneditable, as in the
# Rekordbox adapter (the two-platform rule).
editable=editable and role == "hotcue",
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
grid_marker=None,
)
@@ -136,7 +144,7 @@ def _entries(anlz, tag_type: str) -> list:
return out
def cues_from_anlz(dat, ext) -> list[CuePoint]:
def cues_from_anlz(dat, ext, *, editable: bool = False) -> list[CuePoint]:
"""The track's complete cue list, from its parsed `.DAT` and `.EXT`
(`rekordbox.anlz_file.AnlzFile`s).
@@ -153,14 +161,14 @@ def cues_from_anlz(dat, ext) -> list[CuePoint]:
for f in files:
pco2.extend(_entries(f, "PCO2"))
if pco2:
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True)) is not None]
cues = [c for e in pco2 if (c := _to_cue(e, with_color=True, editable=editable)) is not None]
else:
# Fallback: merge PCOB across BOTH files. The .DAT holds pads 1-3 and the
# .EXT the rest, so either alone is an incomplete bank.
pcob: list = []
for f in files:
pcob.extend(_entries(f, "PCOB"))
cues = [c for e in pcob if (c := _to_cue(e, with_color=False)) is not None]
cues = [c for e in pcob if (c := _to_cue(e, with_color=False, editable=editable)) is not None]
return _dedupe(cues)
+316 -14
View File
@@ -50,10 +50,13 @@ from pathlib import Path
from ...core.adapter import FileTagResult, InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.model import CuePoint
from ... import paths
from . import beatgrid, cues as cue_reader
from ..rekordbox import anlz_file, timebase
from ..rekordbox import anlz_file, palette, timebase
from ..rekordbox import anlz_writer as W
from ..rekordbox import beatgrid as rb_beatgrid
from .layout import DriveLayout
log = logging.getLogger(__name__)
@@ -94,6 +97,11 @@ def _fingerprint(db: Path) -> tuple:
return tuple(out)
def _fingerprint_file(path: Path) -> tuple:
st = path.stat()
return (st.st_size, st.st_mtime_ns)
def _work_root() -> Path:
root = paths.app_data_dir() / "onelibrary" / "work"
root.mkdir(parents=True, exist_ok=True)
@@ -107,7 +115,7 @@ def _backup_root(layout: DriveLayout) -> Path:
return paths.app_data_dir() / "onelibrary" / "backups" / name
class OneLibraryStore:
class OneLibraryStore(ReplaceGridCommands):
# Metadata a OneLibrary drive can hold, matched to the Rekordbox adapter's
# set. `producer` and `mix` have no column; `composer`/`lyricist` are
# different fields and are not mapped onto them approximately.
@@ -142,6 +150,10 @@ class OneLibraryStore:
# an order of magnitude apart: a grid read must not drag in the .EXT.
self._dat_cache: dict[str, object | None] = {}
self._ext_cache: dict[str, object | None] = {}
# Analysis files with unsaved edits: path -> (edited file, how the
# original looked on disk when first edited). The SAME objects sit in
# the caches above, so every read sees the edit; Save writes them.
self._pending_anlz: dict[Path, tuple[anlz_file.AnlzFile, tuple]] = {}
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
self._load()
@@ -171,6 +183,7 @@ class OneLibraryStore:
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
self._db, self._work = db, work
self._journal.clear()
self._pending_anlz.clear()
self._dat_cache.clear()
self._ext_cache.clear()
self._content_cache = None
@@ -349,9 +362,11 @@ class OneLibraryStore:
only mean anything once merged across two files, and handing that to the
projection would put ANLZ knowledge on both sides of the boundary.
"""
dat = self._anlz(track_id, extended=False)
ext = self._anlz(track_id, extended=True)
# A hot cue accepts commands only where there are files to write it to.
cues = cue_reader.cues_from_anlz(
self._anlz(track_id, extended=False),
self._anlz(track_id, extended=True),
dat, ext, editable=not self.read_only and dat is not None and ext is not None,
)
# Positions are stored on rekordbox's clock; the generic model is the
# decoded audio's. A loop keeps its length.
@@ -600,6 +615,267 @@ class OneLibraryStore:
self._journal.record("playlist", "entries", playlist.name, after=len(track_ids))
return len(track_ids)
# ---- writes: cues and the beatgrid (the ANLZ files) ------------------------
#
# Both live in the track's analysis files, not the database (the `cue`
# table stays empty — measured, rekordbox's own edits included). An edit
# replaces only the cue LISTS it touches, and inside them only the entries
# it touches: every other entry keeps rekordbox's bytes, compact forms
# included, as does every other tag of the file. Each step below was checked
# against what rekordbox 7 wrote when it made the same edit on Goober.
#
# Where a hot cue lives (dense, 1-based pads; 0 = memory):
# .DAT PCOB hot pads 1-3 .EXT PCOB hot pads 4+
# .DAT PCOB mem memory cues .EXT PCOB mem (empty)
# .EXT PCO2 hot EVERY pad, + colour/name
# .EXT PCO2 mem every memory cue
_DAT_ORDER = ("PPTH", "PVBR", "PQTZ", "PWAV", "PWV2", "PCOB")
_EXT_ORDER = ("PPTH", "PWV3", "PCOB", "PCO2")
HOTCUE_SLOTS = 8
def _anlz_paths(self, track_id: str) -> tuple[Path, Path]:
dat = self.layout.resolve(getattr(self.content(track_id), "analysisDataFilePath", None))
if dat is None or not dat.is_file() or not self.layout.extended_anlz(dat).is_file():
raise InvalidCommand(
"This track has no analysis files on the drive, so it has nowhere to "
"store cues or a beatgrid. Analyse it in rekordbox first."
)
return dat, self.layout.extended_anlz(dat)
def _editing(self, track_id: str) -> tuple[anlz_file.AnlzFile, anlz_file.AnlzFile]:
"""The track's `.DAT` and `.EXT` as EDITABLE copies, registered for Save.
A file is fingerprinted the first time it is edited, so Save can refuse
to overwrite a change another app made meanwhile.
"""
out = []
for path, cache in zip(self._anlz_paths(track_id), (self._dat_cache, self._ext_cache)):
pending = self._pending_anlz.get(path)
if pending is None:
try:
parsed = anlz_file.parse_file(path)
except (OSError, anlz_file.AnlzError) as ex:
raise InvalidCommand(f"Cannot read the analysis file {path.name}: {ex}") from ex
pending = (parsed, _fingerprint_file(path))
self._pending_anlz[path] = pending
cache[str(track_id)] = pending[0]
out.append(pending[0])
return out[0], out[1]
def _offset(self, track_id: str) -> float:
return timebase.offset(self.audio_path(track_id))
def _hot_entry(self, ext: anlz_file.AnlzFile, hot: int) -> bytes | None:
"""The pad's `PCO2` entry — the complete one, with colour and name."""
i = ext.find("PCO2", anlz_file.LIST_HOT)
if i is None:
return None
return next((e for e in anlz_file.raw_entries(ext.tags[i])
if anlz_file.entry_hot_cue(e) == hot), None)
@staticmethod
def _decoded(entry: bytes) -> anlz_file.CueEntry:
return anlz_file.decode_entry(entry)
def _ensure_pco2(self, dat: anlz_file.AnlzFile, ext: anlz_file.AnlzFile) -> None:
"""Give an `.EXT` without `PCO2` both lists, seeded from its `PCOB`s.
Readers (Konduktor's, and players) prefer `PCO2` the moment it has any
entry, so writing one holding only the edited pad would hide every other
pad and memory cue still listed only in `PCOB`. A drive old enough to
lack it gets the complete lists on the first edit.
"""
if ext.find("PCO2") is not None:
return
for kind in (anlz_file.LIST_HOT, anlz_file.LIST_MEMORY):
seeded = []
for f in (dat, ext):
i = f.find("PCOB", kind)
for e in (anlz_file.raw_entries(f.tags[i]) if i is not None else []):
c = anlz_file.decode_entry(e)
seeded.append(W.pcp2_entry(
hot_cue=c.hot_cue, kind=c.type, time_ms=c.time,
loop_ms=None if c.loop_time == anlz_file.NO_LOOP else c.loop_time,
rgb=None, beats=None))
ext.put("PCO2", W.pco2_tag(kind, seeded), list_kind=kind, after=self._EXT_ORDER)
def _replace_hot(self, track_id: str, hot: int, pcpt: bytes | None, pcp2: bytes | None) -> None:
"""Take pad `hot` out of every hot list and, if given, put the new entries in.
A new entry is APPENDED, as rekordbox does (it appended the hot cue it
added after pads 7 and 6); order within a list carries no meaning.
"""
dat, ext = self._editing(track_id)
self._ensure_pco2(dat, ext)
for f, order, home in ((dat, self._DAT_ORDER, hot <= 3), (ext, self._EXT_ORDER, hot > 3)):
i = f.find("PCOB", anlz_file.LIST_HOT)
kept = ([e for e in anlz_file.raw_entries(f.tags[i]) if anlz_file.entry_hot_cue(e) != hot]
if i is not None else [])
if pcpt is not None and home:
kept.append(pcpt)
if i is not None or kept:
f.put("PCOB", W.pcob_tag(anlz_file.LIST_HOT, kept),
list_kind=anlz_file.LIST_HOT, after=order)
i = ext.find("PCO2", anlz_file.LIST_HOT)
kept = ([e for e in anlz_file.raw_entries(ext.tags[i]) if anlz_file.entry_hot_cue(e) != hot]
if i is not None else [])
if pcp2 is not None:
kept.append(pcp2)
ext.put("PCO2", W.pco2_tag(anlz_file.LIST_HOT, kept),
list_kind=anlz_file.LIST_HOT, after=self._EXT_ORDER)
def _slot(self, slot: int) -> int:
slot = int(slot)
if not 0 <= slot < self.HOTCUE_SLOTS:
raise InvalidCommand(f"Hot cue slot must be 0-{self.HOTCUE_SLOTS - 1}, got {slot}")
return slot + 1 # ANLZ pads are dense and 1-based
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 hot cue on a pad. A loop is a cue with a length.
The pad KEEPS its colour (it belongs to the pad, as in the Rekordbox
adapter), and its name unless one is given — a hand move passes none.
A new cue is uncoloured, like one the Rekordbox adapter writes.
"""
from .export import _loop_beats
hot = self._slot(slot)
if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track")
dat, ext = self._editing(track_id)
old = self._hot_entry(ext, hot)
prior = self._decoded(old) if old is not None else None
code = (prior.color_code or 0) if prior else 0
rgb = ((prior.color_red, prior.color_green, prior.color_blue)
if prior and prior.color_red is not None else (0, 0, 0))
if name is None and prior is not None:
name = prior.comment or None
is_loop = cue_type == "loop" and length_sec > 0
off = self._offset(track_id)
time_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000))
loop_ms = int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000)) if is_loop else None
grid = self.anlz_grid(track_id)
beats = (_loop_beats(start_sec, length_sec, list(zip(grid[2], grid[1], grid[0])))
if is_loop and grid else None)
kind = 2 if is_loop else 1
self._replace_hot(
track_id, hot,
W.pcpt_entry(hot_cue=hot, kind=kind, time_ms=time_ms, loop_ms=loop_ms),
W.pcp2_entry(hot_cue=hot, kind=kind, time_ms=time_ms, loop_ms=loop_ms,
rgb=rgb, beats=beats, code=code, comment=name or None),
)
self._journal.record("cue", "add" if old is None else "modify", track_id, f"slot:{slot}")
def _existing(self, track_id: str, slot: int) -> tuple[int, anlz_file.CueEntry]:
hot = self._slot(slot)
_dat, ext = self._editing(track_id)
entry = self._hot_entry(ext, hot)
if entry is None:
raise NotFound(f"No cue in slot {slot}")
return hot, self._decoded(entry)
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
_hot, cue = self._existing(track_id, slot)
off = self._offset(track_id)
start = timebase.from_pioneer(cue.time / 1000.0, off)
length = 0.0
if cue_type == "loop":
if cue.loop_time != anlz_file.NO_LOOP and cue.loop_time > cue.time:
length = (cue.loop_time - cue.time) / 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)
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
"""Recolour a pad: ONLY its `PCP2` colour bytes change (as rekordbox does).
`PCP2` stores the palette code and its RGB; rekordbox draws from the code.
None is uncoloured (code 0, black), as an uncoloured rekordbox cue is.
"""
hot, cue = self._existing(track_id, slot)
code = int(color_code or 0)
rgb = palette.PALETTE.get(code, (0, 0, 0)) if code else (0, 0, 0)
_dat, ext = self._editing(track_id)
i = ext.find("PCO2", anlz_file.LIST_HOT)
entries = []
for e in anlz_file.raw_entries(ext.tags[i]):
if anlz_file.entry_hot_cue(e) == hot:
# rekordbox's compact 44-byte form has no colour bytes to change.
e = anlz_file.entry_with_colour(e, code, rgb) or W.pcp2_entry(
hot_cue=hot, kind=cue.type, time_ms=cue.time,
loop_ms=None if cue.loop_time == anlz_file.NO_LOOP else cue.loop_time,
rgb=rgb, beats=cue.loop_numerator or None, code=code,
comment=cue.comment or None)
entries.append(e)
ext.tags[i] = anlz_file.Tag("PCO2", W.pco2_tag(anlz_file.LIST_HOT, entries))
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
def delete_cue(self, track_id: str, slot: int) -> None:
hot, _cue = self._existing(track_id, slot)
self._replace_hot(track_id, hot, None, None)
self._journal.record("cue", "delete", track_id, f"slot:{slot}")
def hot_slots(self, track_id: str) -> set[int]:
"""Occupied 0-based slots (pending edits included)."""
return {c.slot for c in self.cues(track_id) if c.role == "hotcue" and c.slot is not None}
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> None:
"""Batch placement (Auto Hotcues). Fills empty slots unless overwriting."""
taken = self.hot_slots(track_id)
for cue in cues:
slot = int(getattr(cue, "slot"))
if not overwrite and slot in taken:
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))
# The grid: `PQTZ` in the .DAT, every beat. rekordbox's measured grid edit,
# reproduced: PQTZ rewritten, `.EXT`'s extended grid PQT2 BLANKED (not
# recomputed), every loop's beat length cleared to 0/0, `.2EX` untouched,
# and `content.bpmx100` following the first marker.
def current_markers(self, track_id: str) -> list:
grid = self.anlz_grid(track_id)
return beatgrid.markers_from_beats(*grid) if grid is not None else []
def _duration(self, track_id: str) -> float:
length = getattr(self.content(track_id), "length", None)
if length:
# Whole seconds rounded down; one more keeps the track's last beat.
return float(length) + 1.0
grid = self.anlz_grid(track_id)
return float(grid[0][-1]) + 1.0 if grid and grid[0] else 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 (`ReplaceGridCommands`) is a read-modify-replace."""
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)
dat, ext = self._editing(track_id)
off = self._offset(track_id)
nums, bpms, times = rb_beatgrid.beats_from_markers(ordered, self._duration(track_id))
dat.put("PQTZ", W.beatgrid_tag([(n, b, timebase.to_pioneer(t, off))
for n, b, t in zip(nums, bpms, times)]),
after=("PPTH", "PVBR"))
i = ext.find("PQT2")
if i is not None:
ext.tags[i] = anlz_file.Tag("PQT2", W.blank_pqt2(ext.tags[i].data))
for kind in (anlz_file.LIST_HOT, anlz_file.LIST_MEMORY):
i = ext.find("PCO2", kind)
if i is not None:
entries = [anlz_file.entry_without_loop_beats(e)
for e in anlz_file.raw_entries(ext.tags[i])]
ext.tags[i] = anlz_file.Tag("PCO2", W.pco2_tag(kind, entries))
self.content(track_id).bpmx100 = int(round(ordered[0].bpm * 100)) if ordered else 0
self._require_db().flush()
self._journal.record("grid", "replace" if ordered else "delete", track_id)
# ---- save ----------------------------------------------------------------
@property
def dirty(self) -> bool:
@@ -614,17 +890,22 @@ class OneLibraryStore:
In this order, each step a precondition for the next:
1. the drive is still there, and NOTHING else has written its database
since it was opened — otherwise this would silently undo it;
2. the working copy is committed and closed, which folds its WAL in, so
(or an analysis file this save rewrites) since Konduktor read it —
otherwise this would silently undo that;
2. the drive's current database and those analysis files are backed
up to app-data;
3. each edited analysis file is written beside itself and renamed over
it — BEFORE the database, as the Rekordbox store writes files before
committing, so a failure here leaves the database untouched;
4. the working copy is committed and closed, which folds its WAL in, so
the copy is one self-contained file;
3. the drive's current database is backed up to app-data;
4. the copy is written beside the drive's database under a temporary
5. the copy is written beside the drive's database under a temporary
name, the stale `-wal`/`-shm` are deleted (SQLite would REPLAY an
old WAL into the new file), and the copy is renamed over it — a
stick pulled mid-save keeps one whole library or the other;
5. edited text fields go into the audio files' own tags (best-effort,
6. edited text fields go into the audio files' own tags (best-effort,
reported per file, never failing the save);
6. the working copy is re-taken from what is now on the drive.
7. the working copy is re-taken from what is now on the drive.
`snapshot` is None: a drive is a database plus analysis files plus the
audio, so there is no single blob to version (`capabilities.save.history`).
@@ -635,7 +916,11 @@ class OneLibraryStore:
f"{self.layout.root.name} is not connected. Plug it back in and "
"save again — your changes are still here."
)
if _fingerprint(self.path) != self._opened_as:
changed_anlz = []
for path, (edited, seen) in self._pending_anlz.items():
if not path.is_file() or _fingerprint_file(path) != seen:
changed_anlz.append(path)
if _fingerprint(self.path) != self._opened_as or changed_anlz:
raise InvalidCommand(
f"Another app has changed {self.layout.root.name} since Konduktor "
"opened it, and saving would undo that. Discard your changes and "
@@ -644,6 +929,19 @@ class OneLibraryStore:
summary = self._journal.summary()
# Read BEFORE the session closes: the rows are useless after it.
tag_jobs = self._tag_jobs()
# Only files whose bytes really changed: an edit that was undone, or a
# command that failed after reading, leaves nothing to write.
anlz_writes = [(path, data) for path, (edited, _seen) in self._pending_anlz.items()
if (data := edited.to_bytes()) != path.read_bytes()]
self._backup([path for path, _ in anlz_writes])
for path, data in anlz_writes:
partial = path.with_name(f".{path.name}.konduktor-partial")
partial.write_bytes(data)
os.replace(partial, path)
# Ours now: a retry after a later failure must not mistake this
# write for another app's.
self._pending_anlz[path] = (self._pending_anlz[path][0], _fingerprint_file(path))
db.session.commit()
work, working = self._work, self._work / self.path.name
@@ -656,7 +954,6 @@ class OneLibraryStore:
except Exception: # noqa: BLE001
log.debug("OneLibrary close step failed", exc_info=True)
try:
self._backup()
partial = self.path.with_name(f".{self.path.name}.konduktor-partial")
shutil.copyfile(working, partial)
with open(partial, "rb+") as f:
@@ -682,8 +979,9 @@ class OneLibraryStore:
self._content_cache = None
self._by_id = None
def _backup(self) -> Path:
"""Copy the drive's database (and a live WAL) to app-data before replacing it."""
def _backup(self, anlz: list[Path] = ()) -> Path:
"""Copy the drive's database (and a live WAL), and the analysis files about
to be rewritten, to app-data — laid out as they are on the drive."""
root = _backup_root(self.layout)
dest = root / time.strftime("%Y%m%d-%H%M%S")
n = 1
@@ -694,6 +992,10 @@ class OneLibraryStore:
for p in (self.path, self.path.with_name(self.path.name + "-wal")):
if p.is_file():
shutil.copy2(p, dest / p.name)
for p in anlz:
target = dest / p.relative_to(self.layout.root)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(p, target)
for old in sorted(d for d in root.iterdir() if d.is_dir())[:-_BACKUPS_KEPT]:
shutil.rmtree(old, ignore_errors=True)
return dest
@@ -74,6 +74,31 @@ class AnlzFile:
struct.pack_into(">I", head, 8, len(head) + len(body))
return bytes(head) + body
def copy(self) -> "AnlzFile":
return AnlzFile(self.header, [Tag(t.type, t.data) for t in self.tags])
def find(self, kind: str, list_kind: int | None = None) -> int | None:
"""Index of the first `kind` tag (of that cue-list kind, if given)."""
for i, t in enumerate(self.tags):
if t.type == kind and (list_kind is None or t.list_kind == list_kind):
return i
return None
def put(self, kind: str, data: bytes, *, list_kind: int | None = None,
after: tuple[str, ...] = ()) -> None:
"""Replace the `kind` tag IN PLACE, keeping every other tag where it is.
A file without one gets it inserted after the last tag named in
`after` (rekordbox's order), else at the end.
"""
tag = Tag(kind, data)
i = self.find(kind, list_kind)
if i is not None:
self.tags[i] = tag
return
at = max((j for j, t in enumerate(self.tags) if t.type in after), default=len(self.tags) - 1)
self.tags.insert(at + 1, tag)
class AnlzError(ValueError):
pass
@@ -135,6 +160,52 @@ class CueEntry:
len_entry: int = 0
def raw_entries(tag: Tag) -> list[bytes]:
"""A `PCOB`/`PCO2` tag's entries as their own bytes, each at its own length —
so an entry Konduktor does not change goes back exactly as rekordbox wrote it."""
if tag.type == "PCOB":
count, first, magic = struct.unpack_from(">H", tag.data, 18)[0], 24, b"PCPT"
elif tag.type == "PCO2":
count, first, magic = struct.unpack_from(">H", tag.data, 16)[0], 20, b"PCP2"
else:
return []
return [tag.data[off:off + n] for off, n in _walk(tag.data, first, magic, count)]
def decode_entry(entry: bytes) -> CueEntry:
"""One raw `PCPT` or `PCP2` entry, decoded."""
if entry[:4] == b"PCPT":
return _pcob(struct.pack(">4sIIIHHi", b"PCOB", 24, 24 + len(entry), 0, 0, 1, -1) + entry)[0]
return _pco2(struct.pack(">4sIIIHH", b"PCO2", 20, 20 + len(entry), 0, 1, 0) + entry)[0]
def entry_hot_cue(entry: bytes) -> int:
"""A PCPT/PCP2 entry's `hot_cue`: its pad, 1-based; 0 for a memory cue."""
return struct.unpack_from(">I", entry, 12)[0]
def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> bytes | None:
"""A `PCP2` entry with ONLY its colour bytes changed — what rekordbox itself
does to recolour a cue (measured: those 4 bytes and nothing else). None if
the entry is too short to carry a colour (rekordbox's 44-byte form)."""
if len(entry) < 44:
return None
len_comment = struct.unpack_from(">I", entry, 40)[0]
at = 44 + len_comment
if at + 4 > len(entry):
return None
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
def entry_without_loop_beats(entry: bytes) -> bytes:
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
rather than recomputing it."""
if len(entry) < 40 or entry[36:40] == b"\0\0\0\0":
return entry
return entry[:36] + bytes(4) + entry[40:]
def _walk(data: bytes, first: int, magic: bytes, count: int):
"""(offset, len_entry) for each entry, trusting each entry's own length."""
off = first
@@ -215,5 +286,6 @@ _DECODERS = {"PCOB": _pcob, "PCO2": _pco2, "PQTZ": _pqtz}
__all__ = [
"AnlzError", "AnlzFile", "Beat", "CueEntry", "LIST_HOT", "LIST_MEMORY",
"NO_LOOP", "Tag", "parse", "parse_file",
"NO_LOOP", "Tag", "decode_entry", "entry_hot_cue", "entry_with_colour", "entry_without_loop_beats",
"parse", "parse_file", "raw_entries",
]
@@ -313,30 +313,38 @@ def flat_preview_tags() -> list[bytes]:
return preview_tags([0.0] * 400, [0.0] * 400)
def _pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0) -> bytes:
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
comment: str | None = None) -> bytes:
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
Two constants in here are rekordbox's, not the documented struct's: the
`1000` after the kind (the struct calls it padding) and the `1` after the
colour id. Both appear in every entry of a real export; zeros there were a
guess, and pyrekordbox's parser would never notice one.
A `comment` (the cue's name) is UTF-16BE with a terminating NUL, and
`len_comment` counts the terminator — crate-digger's layout, which both
Konduktor's reader and pyrekordbox's agree with. No reference cue carries
one, so that detail is documented rather than measured. The entry stays the
exported 88 bytes unless the name needs more.
"""
comment = b""
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
red, green, blue = rgb or (0, 0, 0)
length = max(PCP2_ENTRY_LEN, 48 + len(comment_bytes))
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, PCP2_ENTRY_LEN, hot_cue, kind, 1000,
b"PCP2", 16, length, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
0, 1, beats or 0, 1 if beats else 0, len(comment),
0, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
# The colour is the palette CODE, then RGB: rekordbox draws from the code
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
) + comment + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
PCP2_ENTRY_LEN - 48 - len(comment)
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
length - 48 - len(comment_bytes)
)
def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
`len_header` is **28**, not 12: a reader that trusts it finds the body 16
@@ -353,28 +361,54 @@ def _pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -
) + bytes(16)
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
)
def pcob_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCOB` around already-built `PCPT` entries (rekordbox's own, untouched,
or new ones from `pcpt_entry`)."""
# cue_type is Int32ub (an Enum over it), NOT Int16 — getting this wrong
# shifts every following field and the reader sees garbage. The last field
# is -1 on a hot-cue list and (count - 1) on a memory list, as rekordbox
# writes it.
last = -1 if cue_type == 1 else len(chosen) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(chosen), last) + blob)
# writes it (an export, and rekordbox's own edits, alike).
last = -1 if cue_type == 1 else len(entries) - 1
return _wrap("PCOB", struct.pack(">IHHi", cue_type, 0, len(entries), last) + b"".join(entries))
def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
"""A `PCO2` around already-built `PCP2` entries."""
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(entries), 0) + b"".join(entries))
def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
return pcob_tag(cue_type, [
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"])
for c in chosen
])
def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
blob = b"".join(
_pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0))
return pco2_tag(cue_type, [
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0), comment=c.get("comment"))
for c in chosen
)
return _wrap("PCO2", struct.pack(">IHH", cue_type, len(chosen), 0) + blob)
])
#: `PQT2` as rekordbox 7 leaves it after a grid edit: header kept, every count
#: and the beat list gone (56 bytes, the `len_header`). MEASURED on Goober
#: (2026-10-01): rekordbox does not recompute this "extended" grid when the grid
#: changes, it blanks it, and a CDJ then works from `PQTZ`.
_PQT2_HEADER = 56
def blank_pqt2(tag: bytes) -> bytes:
"""The blanked form of an existing `PQT2` tag, exactly as rekordbox writes it.
Bytes 12-24 (rekordbox's constants, `00000000 01000002 00000000` on every
file seen) are KEPT; the counts and first/last-beat fields after them are
zeroed, and the beat entries dropped.
"""
return tag[:8] + struct.pack(">I", _PQT2_HEADER) + tag[12:24] + bytes(_PQT2_HEADER - 24)
def cue_tags(cues: list[dict], *, extended: bool) -> list[bytes]:
@@ -69,8 +69,8 @@ def capabilities_for(
max_memory_cues=None, # unlimited
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's swatches (the 15 that
# were measured, see `palette`), offered in rekordbox's own order.
# A hot cue's colour is one of rekordbox's 16 swatches (all
# measured, see `palette`), offered in rekordbox's own order.
color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # djmdCue.Comment
@@ -9,8 +9,9 @@ The table was MEASURED, not recalled: 16 hot cues coloured through rekordbox 7's
own palette, one colour per pad, exported to a stick, and read back. Rekordbox
writes the palette's exact RGB beside each code.
* One palette colour went unmeasured — the teal-green between 0x0E and 0x16
(probably code 0x12); a cue that should be it maps to its nearest neighbour.
* The teal-green between 0x0E and 0x16 was missed by that measurement, and
found later: it is **0x13 = #00FF30**, which rekordbox 7 wrote itself as the
DEFAULT colour of a hot cue added on a stick (Goober, 2026-10-01).
* 0x2B (#FF0017) was observed on a real export though it is not one of the 16
swatches; it is kept so such a colour survives a round trip exactly.
* **The palette has no white or grey.** A colourless (white/grey) cue — above
@@ -32,6 +33,7 @@ PALETTE: dict[int, tuple[int, int, int]] = {
0x05: (0x00, 0x70, 0xFF), # light blue
0x09: (0x00, 0xE0, 0xFF), # cyan
0x0E: (0x00, 0xFF, 0xA3), # teal
0x13: (0x00, 0xFF, 0x30), # teal-green (rekordbox's default for a new hot cue)
0x16: (0x1A, 0xFF, 0x00), # green
0x1A: (0x80, 0xFF, 0x00), # lime
0x1E: (0xE6, 0xFF, 0x00), # yellow-lime
@@ -94,18 +96,17 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
#: The swatches a user can pick, in rekordbox's own order — what
#: `capabilities.cues.palette` offers. 15 of rekordbox's 16: the unmeasured
#: teal-green is left out rather than offered with a guessed RGB, and 0x2B is
#: not a swatch at all (see the module note).
#: `capabilities.cues.palette` offers: all 16. 0x2B is not a swatch at all (see
#: the module note).
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
def hex_for(code: int | None) -> str | None:
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
An unknown code (the unmeasured teal-green) projects as no colour rather
than a guessed one; it is still kept on the row, since editing a cue's
position, type or name never rewrites its colour.
An unknown code projects as no colour rather than a guessed one; it is
still kept on the row, since editing a cue's position, type or name never
rewrites its colour.
"""
rgb = PALETTE.get(code) if code else None
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
+2 -48
View File
@@ -45,6 +45,7 @@ from ...core.adapter import (
Unsupported,
)
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping
from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot
@@ -110,7 +111,7 @@ def _iso_stamp(value) -> str:
return str(value)
class RekordboxStore:
class RekordboxStore(ReplaceGridCommands):
"""One open Rekordbox library."""
def __init__(self, path: Path):
@@ -1285,53 +1286,6 @@ class RekordboxStore:
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().
+69
View File
@@ -0,0 +1,69 @@
"""Marker-level beatgrid commands, for a store whose one primitive is "replace".
A platform that stores the grid as a flat list of beats (Rekordbox's `PQTZ`, and
so OneLibrary's) has no native "move this marker": every marker-level command is
a read-modify-replace of the generic marker list. Promoted here when OneLibrary
became the second store needing exactly that, so "where does a moved marker
clamp" cannot mean two things. (Traktor's store has markers natively and keeps
its own, companion-cue-aware versions.)
A store using it provides `current_markers(track_id)` and
`replace_grid(track_id, markers)`.
"""
from __future__ import annotations
from .adapter import InvalidCommand, NotFound
from .model import GridMarker
class ReplaceGridCommands:
def current_markers(self, track_id: str) -> list[GridMarker]: # pragma: no cover
raise NotImplementedError
def replace_grid(self, track_id: str, markers: list[GridMarker]) -> None: # pragma: no cover
raise NotImplementedError
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:
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)