Autohotcues are now ignored on beats with existing hot cues

This commit is contained in:
patben8 committed 2026-09-25 10:38:24 +02:00
1 parent 5909c704f4
commit b71436fad6
7 files changed
+144 -41

No files matched your search

+6 -3
View File
@@ -54,9 +54,12 @@ Two independent apps that talk over HTTP:
`structure.analyse` finds the events, `auto_hotcues.plan` resolves the
template and reports an outcome per slot (`placed` / `not_found` /
`out_of_range` / `occupied` / `protected` / `duplicate`) — "this track has
no third drop" is an answer, not a silent gap. Two slots resolving to the
same BEAT INDEX get one cue, in the lower slot (decided in slot order, so
request order cannot change who wins). How it finds them:
no third drop" is an answer, not a silent gap. **One cue per beat**: a slot
landing on a beat that already has a cue — one KEPT in the bank (the grid
cue, a hand-placed cue, within a quarter beat) or a new one in a lower
slot — is a `duplicate` of that slot. A replaced cue frees its beat only
if its replacement is placed, which is circular, so `plan` iterates to a
fixpoint. How it finds them:
- **Everything is per bar ON THE TRACK'S GRID**, bar 1 = the first marker
(Traktor's convention). Bar-1 detection from audio was tried: it never
beat that rule, because DJ tracks start on a downbeat.
+70 -14
View File
@@ -17,6 +17,8 @@ from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from .structure import EVENTS, Structure
LABELS: dict[str, str] = {
@@ -42,7 +44,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
DUPLICATE = "duplicate" # another cue (kept, or new in a lower slot) is on this beat
@dataclass(frozen=True)
@@ -53,6 +55,14 @@ class SlotRequest:
overwrite: bool = False
@dataclass(frozen=True)
class ExistingCue:
"""A hotcue already in the bank, before this run."""
editable: bool
start: float # seconds
@dataclass(frozen=True)
class SlotOutcome:
slot: int
@@ -69,31 +79,77 @@ def cue_name(event: str, offset_beats: int) -> str:
return f"{label} {offset_beats:+d}" if offset_beats else label
def _beat_of(structure: Structure, t: float) -> int | None:
"""The grid beat a cue at ``t`` sits on, or None if it is between beats.
A quarter-beat tolerance: a hand-placed cue is rarely sample-exact on the
grid, and one a DJ put on the half-beat on purpose is a different beat.
"""
b = structure.beats
i = int(np.clip(np.searchsorted(b, t), 1, len(b) - 1))
i = i if abs(b[i] - t) < abs(b[i - 1] - t) else i - 1
step = b[min(i + 1, len(b) - 1)] - b[max(i - 1, 0)]
step = step / 2 if step > 0 else 0.5
return i if abs(b[i] - t) <= step / 4 else None
def plan(
structure: Structure,
requests: list[SlotRequest],
existing: dict[int, bool],
existing: dict[int, ExistingCue],
) -> list[SlotOutcome]:
"""Decide every requested slot.
``existing`` maps each occupied slot to whether its cue is EDITABLE — a
non-editable one (a cue the platform manages itself) is never replaced, even
when overwrite is ticked, because the adapter would refuse it anyway.
``existing`` is the bank before this run. A non-editable cue (a Traktor grid
marker's companion) 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.
**One cue per beat.** A slot whose position is on a beat that already has a
cue — one this run is placing in a LOWER slot, or one that was in the bank
before and stays there (the grid cue, a hand-placed cue) — is skipped as a
duplicate of that slot: a second pad on the same beat is a wasted pad. New
cues are decided in slot order, so "lower wins" holds whatever order the
request lists them in.
A cue being REPLACED frees its beat only if its replacement is actually
placed; a replacement that is itself skipped leaves the old cue — and its
claim on the beat — where they were. That is circular (whether slot 3's old
cue survives decides slot 5, and slot 5 may be what slot 3 collides with),
so the plan is recomputed until the set of surviving cues stops changing;
each pass can only add survivors, so it ends within one pass per slot.
"""
requested = {r.slot: r for r in requests}
# Old cues whose replacement was not placed, found by the previous pass.
surviving_overwritten: set[int] = set()
while True:
claims: dict[int, int] = {} # beat index -> slot of the cue on it
for slot, cue in sorted(existing.items()):
replaced = slot in requested and requested[slot].overwrite and cue.editable
if replaced and slot not in surviving_overwritten:
continue
beat = _beat_of(structure, cue.start)
if beat is not None:
claims.setdefault(beat, slot)
out = _decide(structure, requests, existing, claims)
now = {
o.slot for o in out
if o.slot in existing and requested[o.slot].overwrite
and existing[o.slot].editable and o.status != PLACED
}
if now <= surviving_overwritten:
return out
surviving_overwritten |= now
def _decide(structure, requests, existing, claims) -> list[SlotOutcome]:
out: list[SlotOutcome] = []
taken: dict[int, int] = {} # beat index -> the slot placing a cue there
taken = dict(claims)
for r in sorted(requests, key=lambda r: r.slot):
if r.slot in existing and not existing[r.slot]:
cue = existing.get(r.slot)
if cue is not None and not cue.editable:
out.append(SlotOutcome(r.slot, r.event, PROTECTED))
continue
if r.slot in existing and not r.overwrite:
if cue is not None and not r.overwrite:
out.append(SlotOutcome(r.slot, r.event, OCCUPIED))
continue
beat = structure.events.get(r.event)
+7 -3
View File
@@ -824,8 +824,8 @@ 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), 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.
(a cue the adapter will not replace) or duplicate (that beat already has a
cue — a kept one, or a new one in a lower slot) — so the UI can say which events this track does not have.
Requires a beatgrid.
"""
a = require_adapter()
@@ -851,7 +851,11 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
except Exception as ex: # analysis is best-effort; never 500 the UI
raise HTTPException(400, f"Analysis failed: {ex}")
existing = {c.slot: c.editable for c in cues.cues if c.role == "hotcue" and c.slot is not None}
existing = {
c.slot: ah.ExistingCue(c.editable, c.start)
for c in cues.cues
if c.role == "hotcue" and c.slot is not None
}
outcomes = ah.plan(
found,
[ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in body.slots],
+1 -1
View File
@@ -111,7 +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
duplicate_of: int | None = None # for "duplicate": the slot whose cue (kept or new) has this beat
+55 -16
View File
@@ -135,6 +135,7 @@ def fake_structure(events, n_beats=400, bpm=120.0):
print("== plan: offsets and outcomes ==")
fs = fake_structure({"drop_1": 128, "outro": 384, "first_beat": 0})
R = ah.SlotRequest
E = ah.ExistingCue
out = {o.slot: o for o in ah.plan(fs, [
R(0, "first_beat"),
R(1, "drop_1", -16),
@@ -143,7 +144,7 @@ out = {o.slot: o for o in ah.plan(fs, [
R(4, "drop_1"),
R(5, "drop_1", 0, overwrite=True),
R(6, "drop_1", 0, overwrite=True),
], existing={4: True, 5: True, 6: False})}
], existing={4: E(True, 190.0), 5: E(True, 190.5), 6: E(False, 191.0)})}
check("placed on the event's beat", out[0].status == ah.PLACED and out[0].start == 0.0)
check("an offset counts BEATS: drop -16 is 8 s earlier at 120 BPM",
out[1].status == ah.PLACED and abs(out[1].start - (128 - 16) * 0.5) < 1e-9, str(out[1]))
@@ -169,9 +170,32 @@ 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))
print("== plan: cues already in the bank claim their beats too ==")
# beat k is at k * 0.5 s in fake_structure; breakdown_1 / build_2 are beat 112 = 56 s.
o = {x.slot: x for x in ah.plan(dup, [R(3, "breakdown_1")], existing={0: E(False, 56.0)})}
check("a new cue on the GRID cue's beat is skipped as its duplicate",
o[3].status == ah.DUPLICATE and o[3].duplicate_of == 0, str(o[3]))
o = {x.slot: x for x in ah.plan(dup, [R(3, "breakdown_1")], existing={6: E(True, 56.03)})}
check("…and on a hand-placed cue a few ms off the grid (higher slot, still kept)",
o[3].status == ah.DUPLICATE and o[3].duplicate_of == 6, str(o[3]))
o = {x.slot: x for x in ah.plan(dup, [R(3, "breakdown_1")], existing={6: E(True, 56.25)})}
check("a cue on the half-beat is a different beat", o[3].status == ah.PLACED, str(o[3]))
o = {x.slot: x.status for x in ah.plan(dup, [R(3, "breakdown_1"), R(4, "build_2")], existing={3: E(True, 10.0)})}
check("a kept cue elsewhere claims only ITS beat", o == {3: ah.OCCUPIED, 4: ah.PLACED}, str(o))
print("== plan: a replaced cue frees its beat only if its replacement is placed ==")
o = {x.slot: x.status for x in ah.plan(dup, [
R(2, "drop_1", overwrite=True), R(5, "breakdown_1"),
], existing={2: E(True, 56.0)})}
check("replaced → its old beat is free for another slot", o == {2: ah.PLACED, 5: ah.PLACED}, str(o))
o = {x.slot: x for x in ah.plan(dup, [
R(1, "drop_1"), R(2, "drop_1", overwrite=True), R(5, "breakdown_1"),
], existing={2: E(True, 56.0)})}
check("a replacement that is itself a duplicate is skipped…",
o[2].status == ah.DUPLICATE and o[2].duplicate_of == 1, str(o[2]))
check("…so the old cue stays, and still claims its beat",
o[5].status == ah.DUPLICATE and o[5].duplicate_of == 2, str(o[5]))
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)
@@ -193,37 +217,52 @@ with tempfile.TemporaryDirectory() as d:
# The real collection's audio is not on every machine, so the route gets a
# stand-in structure and an existing file: this pins the WIRING — request
# validation, the plan, the adapter write and the response model.
main.structure.analyse = lambda path, markers: fake_structure({"drop_1": 64, "first_beat": 0}, bpm=markers[0][1])
# Its events are put on beats chosen per track (below), clear of the cues
# already there — otherwise the one-cue-per-beat rule, not the wiring, would
# decide the outcome.
ROUTE_EVENTS: dict = {}
main.structure.analyse = lambda path, markers: fake_structure(ROUTE_EVENTS, bpm=markers[0][1])
with TestClient(main.app, raise_server_exceptions=False) as c:
a = main.require_adapter()
a.audio_path = lambda track_id: Path(__file__)
def free_slots(cu):
return [s for s in range(8) if not any(q.slot == s for q in cu.cues)]
tid = next(t.id for t in a.tracks
if (cu := a.track_cues(t.id)) and len(cu.grid_markers) == 1 and len(free_slots(cu)) >= 3)
f0, f1, f2 = free_slots(a.track_cues(tid))[:3]
if (cu := a.track_cues(t.id)) and len(cu.grid_markers) == 1 and len(free_slots(cu)) >= 4
and any(q.grid_marker is not None and q.slot is not None for q in cu.cues))
cu = a.track_cues(tid)
step = 60.0 / cu.grid_markers[0].bpm
taken_t = [q.start for q in cu.cues if q.slot is not None]
clear = [k for k in range(8, 390) if all(abs(k * step - t) > step for t in taken_t)]
drop = next(k for k in clear if k - 16 in clear and k >= 80)
outro = next(k for k in clear if k > drop + 40)
grid_cue = next(q for q in cu.cues if q.grid_marker is not None and q.slot is not None)
ROUTE_EVENTS.update(drop_1=drop, outro=outro, first_beat=round(grid_cue.start / step))
f0, f1, f2, f3 = free_slots(cu)[:4]
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [
{"slot": f0, "event": "first_beat"},
{"slot": f1, "event": "drop_1", "offset_beats": -16},
{"slot": f2, "event": "drop_3"},
{"slot": f3, "event": "outro"},
]})
check("the route answers 200", r.status_code == 200, r.text[:200])
if r.status_code == 200:
j = r.json()
st_ = {o["slot"]: o["status"] for o in j["outcomes"]}
check("outcomes per slot", st_ == {f0: "placed", f1: "placed", f2: "not_found"}, str(st_))
oc = {o["slot"]: o for o in j["outcomes"]}
st_ = {k: o["status"] for k, o in oc.items()}
check("outcomes per slot", st_ == {f0: "duplicate", f1: "placed", f2: "not_found", f3: "placed"}, str(st_))
check("a new cue on the track's real GRID cue is skipped as its duplicate",
oc[f0]["duplicate_of"] == grid_cue.slot, str(oc[f0]))
names = {q["slot"]: q["name"] for q in j["cues"]["cues"] if q["slot"] is not None}
check("the cues are in the returned projection", names.get(f1) == "Drop 1 -16", str(names))
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])
f4 = free_slots(a.track_cues(tid))[0]
r3 = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f4, "event": "outro"}]})
o3 = r3.json()["outcomes"][0] if r3.status_code == 200 else {}
check("…and a later run will not stack a cue on one it placed earlier",
o3.get("status") == "duplicate" and o3.get("duplicate_of") == f3, r3.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"}]})
+3 -2
View File
@@ -166,8 +166,9 @@ export interface AutoCueSlot {
/** What happened to one requested slot. `not_found`: the track has no such
* event (e.g. no third drop); `out_of_range`: the offset moves it outside the
* track; `occupied`: a cue is there and overwrite was off; `protected`: a cue
* the adapter will not replace (a grid marker's); `duplicate`: a lower slot
* already got a cue on the same beat (`duplicate_of`). */
* the adapter will not replace (a grid marker's); `duplicate`: that beat
* already has a cue — one kept in the bank (the grid cue, a hand-placed cue)
* or a new one in a lower slot — whose slot is `duplicate_of`. */
export type AutoCueStatus =
| 'placed' | 'not_found' | 'out_of_range' | 'occupied' | 'protected' | 'duplicate'
+2 -2
View File
@@ -232,8 +232,8 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
<p className="mt-3 text-[11px] leading-relaxed text-faint">
Events are found on the beatgrid, counting bar 1 from its first marker — if drops land a
bar or two off, move the grid marker onto the first downbeat. Occupied slots are kept
unless you tick Replace. If two slots land on the same beat, only the lower one gets
the cue. Your slot setup is remembered for the next track.
unless you tick Replace. A slot is skipped if its beat already has a cue — one you keep,
or a new one in a lower slot. Your slot setup is remembered for the next track.
</p>
</div>