Fixed auto hotcue overlap and analysis locked hotcue

This commit is contained in:
patben8 committed 2026-09-24 14:05:35 +02:00
1 parent 46ce3db916
commit 6c123e2597
14 files changed
+132 -100

No files matched your search

@@ -123,8 +123,9 @@ def to_track_cues(entry) -> TrackCues:
The beatgrid is the FULL ordered marker list — a constant grid is a list of
length one. Grid markers themselves are not cues; their companion cues are,
because they occupy real hotcue slots, and each is tagged with the marker it
belongs to so the UI can show it as beatgrid-owned rather than editable.
because they occupy real hotcue slots. Each is tagged with the marker it sits
on, but is an ordinary, editable hotcue: Traktor 4 keeps a beatgrid without
one, so nothing depends on it staying put.
"""
markers = beatgrid.grid_markers(entry)
comps = beatgrid.companions(entry)
@@ -156,10 +157,8 @@ def to_track_cues(entry) -> TrackCues:
length=(c.len or 0.0) / 1000.0,
slot=slot,
color=c.color,
# A grid marker's companion belongs to the beatgrid: the store
# refuses hotcue commands on it, so say so up front.
editable=marker is None,
readonly_reason="beatgrid_companion" if marker is not None else None,
editable=True,
readonly_reason=None,
grid_marker=marker,
)
)
+1 -24
View File
@@ -468,21 +468,6 @@ class TraktorStore:
raise PlaylistError(f"Track not found: {track_id}")
return entry
@staticmethod
def _reject_if_companion(entry: Entrytype, slot: int) -> None:
"""Refuse to touch a slot held by a grid marker's companion cue.
Traktor pairs most grid markers with a white cue in a real hotcue slot.
Overwriting, retyping or deleting one desyncs it from its marker, so the
beatgrid commands own these slots — move or delete the marker instead.
"""
cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None)
if cue is not None and beatgrid.is_companion(entry, cue):
raise PlaylistError(
f"Hotcue {slot + 1} belongs to a beatgrid marker — "
"move or delete the marker instead"
)
def set_hotcue(
self,
track_id: str,
@@ -502,7 +487,6 @@ class TraktorStore:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
self._reject_if_companion(entry, slot)
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms
len_ms = max(0.0, length_sec * 1000.0)
existing = next(
@@ -547,13 +531,8 @@ class TraktorStore:
occupied = {
c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0
}
# Companion slots belong to the beatgrid — never fill them, even
# with overwrite=True (occupied alone only guards them while False).
protected = {
c.hotcue for c in beatgrid.companions(entry).values() if c.hotcue is not None
}
for spec in specs:
if spec.slot in protected or (not overwrite and spec.slot in occupied):
if not overwrite and spec.slot in occupied:
continue
self.set_hotcue(
track_id,
@@ -570,7 +549,6 @@ class TraktorStore:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
self._reject_if_companion(entry, slot)
cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None)
if cue is None:
raise PlaylistError(f"Hotcue {slot} is not set")
@@ -581,7 +559,6 @@ class TraktorStore:
def delete_hotcue(self, track_id: str, slot: int) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
self._reject_if_companion(entry, slot)
before = entry.cue_v2 or []
entry.cue_v2 = [c for c in before if c.hotcue != slot]
if len(entry.cue_v2) != len(before): # only count an actual removal
+18 -3
View File
@@ -42,6 +42,7 @@ NOT_FOUND = "not_found" # the track has no such event (e.g. no third drop
OUT_OF_RANGE = "out_of_range" # the offset moves it before the start / past the end
OCCUPIED = "occupied" # the slot holds a cue and overwrite was not asked for
PROTECTED = "protected" # the slot holds a cue the adapter will not replace
DUPLICATE = "duplicate" # a lower slot is already getting a cue on this beat
@dataclass(frozen=True)
@@ -59,6 +60,7 @@ class SlotOutcome:
status: str
start: float | None = None
name: str | None = None
duplicate_of: int | None = None # the slot that got this beat, for DUPLICATE
def cue_name(event: str, offset_beats: int) -> str:
@@ -75,11 +77,19 @@ def plan(
"""Decide every requested slot.
``existing`` maps each occupied slot to whether its cue is EDITABLE — a
non-editable one (a Traktor grid marker's companion) is never replaced, even
non-editable one (a cue the platform manages itself) is never replaced, even
when overwrite is ticked, because the adapter would refuse it anyway.
Two slots that resolve to the SAME BEAT get one cue, in the lower slot: a
second pad on the same beat is a wasted pad, and it happens by construction
(Build 2 is Breakdown 1 when two drops are close). Slots are decided in slot
order so "lower wins" holds whatever order the request lists them in, and
the comparison is on the beat INDEX — exact, where comparing seconds would
need a tolerance.
"""
out: list[SlotOutcome] = []
for r in requests:
taken: dict[int, int] = {} # beat index -> the slot placing a cue there
for r in sorted(requests, key=lambda r: r.slot):
if r.slot in existing and not existing[r.slot]:
out.append(SlotOutcome(r.slot, r.event, PROTECTED))
continue
@@ -90,9 +100,14 @@ def plan(
if beat is None:
out.append(SlotOutcome(r.slot, r.event, NOT_FOUND))
continue
t = structure.beat_time(beat + r.offset_beats)
index = beat + r.offset_beats
t = structure.beat_time(index)
if t < 0 or t >= structure.duration:
out.append(SlotOutcome(r.slot, r.event, OUT_OF_RANGE))
continue
if index in taken:
out.append(SlotOutcome(r.slot, r.event, DUPLICATE, duplicate_of=taken[index]))
continue
taken[index] = r.slot
out.append(SlotOutcome(r.slot, r.event, PLACED, round(t, 4), cue_name(r.event, r.offset_beats)))
return out
+1 -1
View File
@@ -131,7 +131,7 @@ class CuePoint(BaseModel):
# False when the adapter refuses commands on this cue — the UI gates on THIS
# rather than on any platform-specific reason.
editable: bool = True
readonly_reason: Literal["beatgrid_companion", "platform_managed"] | None = None
readonly_reason: Literal["platform_managed"] | None = None
# Index of the grid marker this cue mirrors, where the platform pairs them.
# A display hint only; None on platforms that do not.
grid_marker: int | None = None
+4 -3
View File
@@ -823,9 +823,10 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
Each requested slot is bound to an event (``drop_1``, ``outro``, …) plus an
offset in beats. Every slot reports an outcome — placed, not found, out of
range, occupied (a cue is there and overwrite was not asked for) or
protected (a cue the adapter will not replace) — so the UI can say which
events this track does not have. Requires a beatgrid.
range, occupied (a cue is there and overwrite was not asked for), protected
(a cue the adapter will not replace) or duplicate (a lower slot already got
that beat) — so the UI can say which events this track does not have.
Requires a beatgrid.
"""
a = require_adapter()
cues = a.track_cues(body.track_id)
+2 -1
View File
@@ -88,7 +88,7 @@ AutoCueEvent = Literal[
"build_3", "drop_3", "breakdown_3",
"outro", "last_beat",
]
AutoCueStatus = Literal["placed", "not_found", "out_of_range", "occupied", "protected"]
AutoCueStatus = Literal["placed", "not_found", "out_of_range", "occupied", "protected", "duplicate"]
class AutoCueSlot(BaseModel):
@@ -111,6 +111,7 @@ class AutoCueOutcome(BaseModel):
status: AutoCueStatus
start: float | None = None # seconds, when placed
name: str | None = None
duplicate_of: int | None = None # for "duplicate": the slot that got this beat
+26
View File
@@ -154,6 +154,25 @@ check("an occupied slot is left alone by default", out[4].status == ah.OCCUPIED)
check("…and replaced when overwrite is asked for", out[5].status == ah.PLACED)
check("a protected cue is never replaced, even with overwrite", out[6].status == ah.PROTECTED)
print("== plan: two slots on the same beat get ONE cue, in the lower slot ==")
dup = fake_structure({"drop_1": 128, "breakdown_1": 112, "build_2": 112})
out = {o.slot: o for o in ah.plan(dup, [
R(3, "breakdown_1"),
R(4, "build_2"), # the same beat as slot 3, by a different event
R(5, "drop_1", -16), # …and again, by an offset (128 - 16 = 112)
R(6, "drop_1", -15), # one beat later: a different beat, placed
], existing={})}
check("the lower slot keeps the beat", out[3].status == ah.PLACED)
check("a higher slot on the same beat is skipped", out[4].status == ah.DUPLICATE and out[4].duplicate_of == 3, str(out[4]))
check("…whichever event or offset got it there", out[5].status == ah.DUPLICATE and out[5].duplicate_of == 3, str(out[5]))
check("one beat apart is not a duplicate", out[6].status == ah.PLACED)
rev = {o.slot: o.status for o in ah.plan(dup, [R(4, "build_2"), R(3, "breakdown_1")], existing={})}
check("lower slot wins whatever order the request lists them in",
rev == {3: ah.PLACED, 4: ah.DUPLICATE}, str(rev))
kept = {o.slot: o.status for o in ah.plan(dup, [R(3, "breakdown_1"), R(4, "build_2")], existing={3: True})}
check("a slot that is NOT placed (occupied) does not claim its beat",
kept == {3: ah.OCCUPIED, 4: ah.PLACED}, str(kept))
flex = structure.Structure(beats=np.r_[np.arange(0, 10, 0.5), np.arange(10, 30, 1.0)], bar0=0, n_bars=10, duration=30)
flex.events = {"drop_1": 24} # beat 24 is at 14 s (20 beats at 0.5 s, then 4 at 1.0 s)
o = ah.plan(flex, [R(0, "drop_1", -8)], {})[0]
@@ -198,6 +217,13 @@ with tempfile.TemporaryDirectory() as d:
r2 = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f1, "event": "drop_1"}]})
check("running again leaves the now-occupied slot alone",
r2.status_code == 200 and r2.json()["outcomes"][0]["status"] == "occupied", r2.text[:200])
f3, f4 = free_slots(a.track_cues(tid))[:2]
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [
{"slot": f3, "event": "first_beat"}, {"slot": f4, "event": "drop_1", "offset_beats": -64},
]})
oc = {o["slot"]: o for o in r.json()["outcomes"]} if r.status_code == 200 else {}
check("the route reports a same-beat slot as a duplicate of the lower one",
oc.get(f4, {}).get("status") == "duplicate" and oc[f4]["duplicate_of"] == f3, r.text[:300])
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f0, "event": "drop_1"}, {"slot": f0, "event": "outro"}]})
check("a slot requested twice is refused", r.status_code == 400)
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f0, "event": "the_best_bit"}]})
+46 -36
View File
@@ -594,55 +594,65 @@ with tempfile.TemporaryDirectory() as d:
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 ==")
# ---- Invariant J: companion cues are ordinary, editable hotcues ---------
# Traktor 4 keeps a beatgrid without its white beat-1 cue, so the cue is not
# the grid's to protect: every hotcue command works on it, and none of them may
# touch the grid marker it happened to sit on.
print("== J. grid companion cues are editable, and editing one leaves the grid alone ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = TraktorStore(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
def fresh():
st = TraktorStore(work)
e = next(e for e in st._nml.collection.entry if bg.companions(e).get(0) is not None)
tid = f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}"
return st, tid, bg.companions(e)[0].hotcue, [(m.start, m.grid.bpm) for m in bg.grid_markers(e)]
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)),
("set_hotcue moves it", lambda st, tid, slot: st.set_hotcue(tid, slot, 5.0, 0)),
("set_hotcue_type retypes it", lambda st, tid, slot: st.set_hotcue_type(tid, slot, 1)),
("delete_hotcue deletes it", lambda st, tid, slot: st.delete_hotcue(tid, slot)),
]:
store, track_id, slot, grid_before = fresh()
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)
fn(store, track_id, slot)
ok = True
except PlaylistError as ex:
ok = False
check(f"J: {label}", False, str(ex))
if ok:
e = store.model_entry(track_id)
check(f"J: {label}", store.dirty is True)
check(f"J: …and the grid is unchanged ({label.split()[0]})",
[(m.start, m.grid.bpm) for m in bg.grid_markers(e)] == grid_before)
check(f"J: …and it is no longer the marker's companion ({label.split()[0]})",
0 not in bg.companions(e))
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)
store, track_id, slot, _ = fresh()
from konduktor.adapters.traktor.projection import to_track_cues
proj = to_track_cues(store.model_entry(track_id))
comp_cue = next(c for c in proj.cues if c.slot == slot)
check("J: the projection offers it as editable",
comp_cue.editable is True and comp_cue.readonly_reason is None)
# 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 = TraktorStore(work)
# Auto Hotcues treats it like any other occupied slot.
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)
store.place_hotcues(track_id, [spec])
e = store.model_entry(track_id)
check("J: place_hotcues leaves it alone without overwrite",
bg.companions(e).get(0) is not None)
store.place_hotcues(track_id, [spec], overwrite=True)
e = store.model_entry(track_id)
check("J: place_hotcues(overwrite) replaces it",
any(c.hotcue == slot and abs(c.start - 42_000.0) < 1 for c in (e.cue_v2 or [])))
# Deleting the grid releases the slot it was holding.
store2.delete_grid(track_id)
e2 = store2.model_entry(track_id)
# Deleting the grid still removes a companion that is still on its marker.
store, track_id, slot, _ = fresh()
store.delete_grid(track_id)
e = store.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 [])))
not any(c.hotcue == slot for c in (e.cue_v2 or [])))
# ---- Invariant K: real flexible grids project correctly (read-only) ----