Added support for flexible beatgrids

This commit is contained in:
patben8 committed 2026-09-17 15:14:07 +02:00
1 parent 3f51444e2a
commit dd97f27ac7
20 files changed
+2176 -346

No files matched your search

+225 -33
View File
@@ -31,7 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-a
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
from konduktor.collection_service import CollectionService # noqa: E402
from konduktor.playlist_store import PlaylistStore # noqa: E402
from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402
failed = False
@@ -232,24 +232,42 @@ with tempfile.TemporaryDirectory() as d:
check("create+delete round-trips to the original bytes", work.read_bytes() == original)
# ---- Invariant E: a beatgrid edit is fully localized -------------------
print("== E. grid/bpm edit touches only that track's ENTRY ==")
print("== E. grid marker edit touches only that track's ENTRY ==")
from konduktor import beatgrid as bg # noqa: E402
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = PlaylistStore(work)
# first entry that has both a tempo and a grid marker
entry = next(
e
for e in store._nml.collection.entry
if e.tempo and store._grid_marker(e) is not None
)
loc = entry.location
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
orig_bpm = entry.tempo.bpm
store.set_grid(track_id, bpm=orig_bpm / 2, anchor_sec=1.5)
def _key(e):
loc = e.location
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else ""
# An entry with a tempo and exactly ONE marker whose companion (if any) sits
# at an EXACTLY equal START. That predicate is load-bearing: a companion a
# fraction of a ms off would be normalised to exact by the first move, so the
# byte-revert below would fail through no fault of the code.
def _clean_single(e):
ms = bg.grid_markers(e)
if not (e.tempo and len(ms) == 1):
return False
comp = bg.companions(e).get(0)
return comp is None or comp.start == ms[0].start
entry = next(e for e in store._nml.collection.entry if _clean_single(e))
loc = entry.location
track_id = _key(entry)
orig_bpm = entry.tempo.bpm
orig_anchor_ms = bg.grid_markers(entry)[0].start
comp_slot = (
bg.companions(entry)[0].hotcue if 0 in bg.companions(entry) else None
)
store.set_grid_marker_bpm(track_id, 0, orig_bpm / 2)
store.move_grid_marker(track_id, 0, 1.5)
store.save()
edited = work.read_bytes()
@@ -272,30 +290,28 @@ with tempfile.TemporaryDirectory() as d:
from traktor_nml_utils import TraktorCollection
reparsed = TraktorCollection(path=work)
e0 = next(
e
for e in reparsed.nml.collection.entry
if e.location
and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id
)
e0 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id)
markers = bg.grid_markers(e0)
m = store._grid_marker(e0)
check("tempo BPM halved + persisted", abs(e0.tempo.bpm - orig_bpm / 2) < 1e-3)
check("grid marker BPM matches tempo", m is not None and abs(m.grid.bpm - orig_bpm / 2) < 1e-3)
check("grid anchor moved to 1.5s (1500 ms)", m is not None and abs(m.start - 1500.0) < 1)
# A move must reposition the grid, never fork it into a flexible one.
check("still exactly one grid marker", len(markers) == 1, str(len(markers)))
# _grid_marker is the first marker BY START, not by document order.
check("_grid_marker == first marker by start", m is markers[0])
if comp_slot is not None:
comp = bg.companions(e0).get(0)
check("companion dragged along with its marker",
comp is not None and abs(comp.start - 1500.0) < 1, str(comp.start if comp else None))
check("companion kept its hotcue slot", comp is not None and comp.hotcue == comp_slot)
# Reverting BPM + anchor to the original values round-trips to the file.
orig_anchor_ms = store._grid_marker(
next(
e
for e in TraktorCollection(path=REAL).nml.collection.entry
if e.location
and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id
)
).start
# Reverting BPM + position round-trips to the original bytes.
store2 = PlaylistStore(work)
store2.set_grid(track_id, bpm=orig_bpm, anchor_sec=orig_anchor_ms / 1000.0)
store2.set_grid_marker_bpm(track_id, 0, orig_bpm)
store2.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0)
store2.save()
check("revert BPM + anchor round-trips to original bytes", work.read_bytes() == original)
check("revert BPM + position round-trips to original bytes", work.read_bytes() == original)
# ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
@@ -365,12 +381,13 @@ with tempfile.TemporaryDirectory() as d:
print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==")
from konduktor import auto_hotcues as ah # noqa: E402
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; anchor 0.0.
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; marker at 0.0.
BPM, ANCHOR, DUR = 128.0, 0.0, 300.0
GRID = [(ANCHOR, BPM)] # a constant grid is a one-marker list
# Raw boundaries near (but not exactly on) phrase multiples + a fragmented pair.
raw = [(0.3, 0.2), (29.4, 0.5), (30.6, 0.55), (61.0, 0.9), (150.0, 0.3), (270.2, 0.25)]
specs = ah.select_hotcues(
raw, bpm=BPM, anchor=ANCHOR, duration=DUR,
raw, markers=GRID, duration=DUR,
free_slots=[2, 3, 4, 5, 6, 7], existing_times=[], max_cues=8,
)
starts = [s["start"] for s in specs]
@@ -383,13 +400,27 @@ check("names are unique (ordinal de-dupe)", len({s["name"] for s in specs}) == l
# A hotcue already sitting on the 60s phrase must not get a duplicate.
specs2 = ah.select_hotcues(
raw, bpm=BPM, anchor=ANCHOR, duration=DUR,
raw, markers=GRID, duration=DUR,
free_slots=[0, 1, 2, 3, 4, 5, 6, 7], existing_times=[60.0], max_cues=8,
)
check("boundary colliding with an existing hotcue is dropped", 60.0 not in [s["start"] for s in specs2], str([s["start"] for s in specs2]))
# No free slots => nothing placed.
check("no free slots => empty result", ah.select_hotcues(raw, bpm=BPM, anchor=ANCHOR, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == [])
check("no free slots => empty result", ah.select_hotcues(raw, markers=GRID, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == [])
# Flexible grid: each segment snaps to ITS OWN phrase length. Segment 2 starts
# at 120s at 120 BPM => 16-bar phrase = 32.0s, so points there land on 120+k*32.
FLEX = [(0.0, 128.0), (120.0, 120.0)]
flex_specs = ah.select_hotcues(
[(29.4, 0.5), (61.0, 0.9), (152.5, 0.4), (215.0, 0.3)],
markers=FLEX, duration=DUR, free_slots=[0, 1, 2, 3, 4, 5, 6, 7],
existing_times=[], max_cues=8,
)
flex_starts = [s_["start"] for s_ in flex_specs]
check("flexible grid: pre-seam points snap to the 30s phrase",
all(abs(round(t / 30.0) * 30.0 - t) < 0.01 for t in flex_starts if t < 120.0), str(flex_starts))
check("flexible grid: post-seam points snap to that segment's 32s phrase",
all(abs(120.0 + round((t - 120.0) / 32.0) * 32.0 - t) < 0.01 for t in flex_starts if t >= 120.0), str(flex_starts))
# ---- Invariant H: path write-back is localized + round-trips -----------
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")
@@ -517,5 +548,166 @@ with tempfile.TemporaryDirectory() as d:
check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys)
# ---- Invariant I: flexible (multi-marker) beatgrids round-trip ---------
print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
def _key(e):
loc = e.location
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else ""
def entry_span(data: bytes, file_name: str):
marker = f'FILE="{file_name}"'.encode()
i = data.find(marker)
st = data.rfind(b"<ENTRY ", 0, i)
en = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
return st, en
# Synthesize the flexible grid rather than relying on the handful of real
# ones: those are the user's own data and could change at any time.
store = PlaylistStore(work)
entry = next(
e for e in store._nml.collection.entry
if e.tempo and len(bg.grid_markers(e)) == 1
and (bg.companions(e).get(0) is None or bg.companions(e)[0].start == bg.grid_markers(e)[0].start)
)
loc = entry.location
track_id = _key(entry)
_m0 = bg.grid_markers(entry)[0]
m0_start, m0_bpm = _m0.start, _m0.grid.bpm
orig_tempo = entry.tempo.bpm
store.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99)
store.save()
two = work.read_bytes()
reparsed = TraktorCollection(path=work)
e1 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id)
ms = bg.grid_markers(e1)
check("I: second marker added", len(ms) == 2, str(len(ms)))
check("I: markers ascending by START", ms[0].start < ms[1].start)
check("I: second marker kept its own BPM", abs(ms[1].grid.bpm - m0_bpm * 0.99) < 1e-3)
check("I: TEMPO still mirrors the FIRST marker", abs(e1.tempo.bpm - orig_tempo) < 1e-6,
f"{e1.tempo.bpm} vs {orig_tempo}")
check("I: CUE_V2 still ascending by START",
all((c.start or 0) <= (ms_ .start or 0) for c, ms_ in zip(e1.cue_v2, e1.cue_v2[1:])))
check("I: new GRID BPM rendered at 6 decimals",
f'<GRID BPM="{m0_bpm * 0.99:.6f}">'.encode() in two)
os_, oe = entry_span(original, loc.file)
es_, ee = entry_span(two, loc.file)
check("I: adding a marker is confined to that ENTRY",
original[:os_] + b"@@" + original[oe:] == two[:es_] + b"@@" + two[ee:])
# Removing it must return the file to its original bytes exactly.
store2 = PlaylistStore(work)
store2.delete_grid_marker(track_id, 1)
store2.save()
check("I: deleting the added marker round-trips to original bytes",
work.read_bytes() == original)
# Moves clamp between neighbours rather than reordering the list.
store3 = PlaylistStore(work)
store3.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99)
store3.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0)
e3 = store3.model_entry(track_id)
ms3 = bg.grid_markers(e3)
check("I: move clamps below the next marker", ms3[0].start < ms3[1].start)
check("I: move never changes the marker count", len(ms3) == 2)
# delete_grid takes the companions with it and keeps TEMPO.
store3.delete_grid(track_id)
e3 = store3.model_entry(track_id)
whites = [c for c in (e3.cue_v2 or []) if c.color == "#FFFFFF" and getattr(c, "grid", None) is None]
check("I: delete_grid removes every marker", len(bg.grid_markers(e3)) == 0)
check("I: delete_grid leaves no companion debris", not whites, str(len(whites)))
check("I: delete_grid keeps TEMPO", e3.tempo is not None and e3.tempo.bpm == orig_tempo)
# ---- Invariant J: companion cues are protected from hotcue edits -------
print("== J. grid companion cues cannot be clobbered by hotcue commands ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = PlaylistStore(work)
entry = next(
e for e in store._nml.collection.entry if bg.companions(e).get(0) is not None
)
track_id = f"{entry.location.volume or ''}{entry.location.dir or ''}{entry.location.file or ''}"
slot = bg.companions(entry)[0].hotcue
for label, fn in [
("set_hotcue", lambda: store.set_hotcue(track_id, slot, 5.0, 0)),
("set_hotcue_type", lambda: store.set_hotcue_type(track_id, slot, 1)),
("delete_hotcue", lambda: store.delete_hotcue(track_id, slot)),
]:
try:
fn()
check(f"J: {label} refuses a companion slot", False, "no error raised")
except PlaylistError:
check(f"J: {label} refuses a companion slot", True)
check("J: refusals leave the store clean", store.dirty is False)
store.save()
check("J: save after refusals is byte-identical", work.read_bytes() == original)
# The guard must be narrow: a free slot in the same track still works.
used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
free = next(s_ for s_ in range(8) if s_ not in used)
store.set_hotcue(track_id, free, 12.0, 0)
check("J: a non-companion slot is still editable", store.dirty is True)
# Auto Hotcues must skip companion slots even when told to overwrite.
store2 = PlaylistStore(work)
spec = type("S", (), {"slot": slot, "start": 42.0, "name": "X", "type": 0, "length": 0.0})()
store2.place_hotcues(track_id, [spec], overwrite=True)
e2 = store2.model_entry(track_id)
comp = bg.companions(e2).get(0)
check("J: place_hotcues(overwrite) skips a companion slot",
comp is not None and abs(comp.start - 42_000.0) > 1)
# Deleting the grid releases the slot it was holding.
store2.delete_grid(track_id)
e2 = store2.model_entry(track_id)
check("J: delete_grid frees the companion's hotcue slot",
not any(c.hotcue == slot for c in (e2.cue_v2 or [])))
# ---- Invariant K: real flexible grids project correctly (read-only) ----
print("== K. genuine Traktor flexible grids read correctly ==")
_real = TraktorCollection(path=REAL).nml.collection.entry
_flex = [e for e in _real if len(bg.grid_markers(e)) > 1]
if not _flex:
print(" [SKIP] no flexible-grid entries in the reference collection")
else:
import konduktor.main as _m
ok_order = ok_tempo = ok_proj = ok_comp = True
for e in _flex:
ms = bg.grid_markers(e)
ok_order &= all(ms[i].start < ms[i + 1].start for i in range(len(ms) - 1))
if e.tempo and e.tempo.bpm:
ok_tempo &= abs(e.tempo.bpm - ms[0].grid.bpm) < 1e-6
tc = _m._build_track_cues(e)
ok_proj &= len(tc.grid_markers) == len(ms) and all(
abs(g.bpm - m.grid.bpm) < 1e-9 and abs(g.start - (m.start or 0) / 1000.0) < 1e-9
for g, m in zip(tc.grid_markers, ms)
)
# A marker with no companion must project None, not raise.
comps = bg.companions(e)
ok_comp &= all(
(tc.grid_markers[i].companion is None) == (i not in comps) for i in range(len(ms))
)
print(f" ({len(_flex)} flexible entr{'y' if len(_flex) == 1 else 'ies'} checked)")
check("K: markers strictly ascending by START", ok_order)
check("K: TEMPO mirrors the first marker", ok_tempo)
check("K: every marker projects with its own BPM + position", ok_proj)
check("K: a marker without a companion projects None", ok_comp)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)