diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py new file mode 100644 index 0000000..b8afadd --- /dev/null +++ b/backend/konduktor/auto_hotcues.py @@ -0,0 +1,183 @@ +"""Auto Hotcues — structural boundary detection for DJ cue placement. + +Detection uses the McFee & Ellis (2014) Laplacian structural segmentation as +implemented on top of librosa: beat-synchronous CQT features → a +sequence-augmented recurrence Laplacian → spectral clustering of beats into +section *types* → boundaries at type changes. This is repetition/homogeneity +aware (unlike a raw energy-novelty curve), so boundaries land on real musical +transitions. Validated on real house tracks: clean, phrase-scale boundaries in +~1.5s each; pure-Python (~150MB), no torch/native build; runs on Python 3.14. + +The module is split so the DSP (`detect_boundaries`, needs the audio) is +separate from the placement logic (`select_hotcues`, pure arithmetic on the +beatgrid) — the latter is unit-testable without audio. +""" + +from __future__ import annotations + +import numpy as np + +# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can +# grow if a future Traktor allows more than 8 triggerable hotcues. +MAX_HOTCUES = 8 + +_SR = 22050 +_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding + + +def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]: + """Detect structural boundaries in a track. + + Returns ``(boundaries, duration)`` where ``boundaries`` is a list of + ``(time_sec, energy)`` pairs — one per detected section start — and + ``energy`` is that section's mean RMS normalised to 0..1 across the track + (used downstream for positional naming). Sorted by time. + """ + import librosa + from scipy.ndimage import median_filter + from scipy.sparse.csgraph import laplacian as csgraph_laplacian + from scipy.linalg import eigh + import sklearn.cluster + + y, sr = librosa.load(audio_path, sr=sr, mono=True) + duration = len(y) / sr + if duration < 1.0: + return [], duration + + # Beat-synchronous CQT — the harmonic/timbre backbone of the method. + cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max) + _, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False) + if len(beats) < 4: + return [], duration + csync = librosa.util.sync(cqt, beats, aggregate=np.median) + beat_times = librosa.frames_to_time(beats, sr=sr) + + # Sequence-augmented recurrence Laplacian (McFee & Ellis 2014): + # a repetition graph (which beats sound alike) blended with a local path + # graph (consecutive-beat timbral continuity). + rec = librosa.segment.recurrence_matrix(csync, width=3, mode="affinity", sym=True) + rec = median_filter(rec, size=(1, 7)) + mfcc = librosa.feature.mfcc(y=y, sr=sr) + msync = librosa.util.sync(mfcc, beats) + path_dist = np.sum(np.diff(msync, axis=1) ** 2, axis=0) + path_sim = np.exp(-path_dist / (np.median(path_dist) + 1e-9)) + path = np.diag(path_sim, 1) + np.diag(path_sim, -1) + deg_path, deg_rec = path.sum(1), rec.sum(1) + denom = np.sum((deg_path + deg_rec) ** 2) + 1e-9 + mu = deg_path.dot(deg_path + deg_rec) / denom + graph = mu * rec + (1 - mu) * path + + # Symmetric-normalised Laplacian → eigenvectors → k-means over beats. + lap = csgraph_laplacian(graph, normed=True) + _, evecs = eigh(lap) + evecs = median_filter(evecs, size=(9, 1)) + k = min(_N_EIGENVECTORS, evecs.shape[1]) + x = librosa.util.normalize(evecs[:, :k], norm=2, axis=1) + ids = sklearn.cluster.KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(x) + + # Boundaries = beats where the section-type label changes (plus the start). + bound_beats = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i - 1]] + + # Per-section mean RMS (energy) for positional naming, normalised 0..1. + rms = librosa.feature.rms(y=y)[0] + rms_t = librosa.times_like(rms, sr=sr) + rms_max = float(rms.max()) or 1.0 + out: list[tuple[float, float]] = [] + for j, bi in enumerate(bound_beats): + t = float(beat_times[min(bi, len(beat_times) - 1)]) + t_next = ( + float(beat_times[min(bound_beats[j + 1], len(beat_times) - 1)]) + if j + 1 < len(bound_beats) + else duration + ) + seg = rms[(rms_t >= t) & (rms_t < max(t_next, t + 1e-3))] + energy = float(seg.mean() / rms_max) if len(seg) else 0.0 + out.append((t, energy)) + return out, duration + + +def select_hotcues( + boundaries: list[tuple[float, float]], + *, + bpm: float, + anchor: float, + duration: float, + free_slots: list[int], + existing_times: list[float], + max_cues: int = MAX_HOTCUES, + phrase_bars: int = 16, +) -> list[dict]: + """Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid. + + Snaps each boundary to the nearest ``phrase_bars``-bar grid point (which + also merges near-duplicates), drops any coinciding with an existing hotcue, + caps to the free slots (down-sampling evenly if there are too many), and + assigns positional names. Returns dicts with slot/start/name/type/length. + """ + if not boundaries or not free_slots or bpm <= 0: + return [] + + beat = 60.0 / bpm + phrase = phrase_bars * 4 * beat # seconds per phrase + + # Snap to phrase grid; dedupe (keep the strongest energy seen at each point). + snapped: dict[float, float] = {} + for t, energy in boundaries: + p = anchor + round((t - anchor) / phrase) * phrase + p = max(0.0, min(p, duration - beat)) + snapped[p] = max(snapped.get(p, 0.0), energy) + + # Drop points that collide with an existing (hand-placed) hotcue. + def near_existing(t: float) -> bool: + return any(abs(t - e) < beat for e in existing_times) + + points = sorted((t, e) for t, e in snapped.items() if not near_existing(t)) + if not points: + return [] + + # If more candidates than free slots, down-sample evenly across the track + # (keeps intro..outro coverage rather than just the first N). + n = min(len(free_slots), max_cues) + if len(points) > n: + idx = np.linspace(0, len(points) - 1, n).round().astype(int) + points = [points[i] for i in sorted(set(idx))] + + names = _name_positionally([t for t, _ in points], [e for _, e in points], duration) + slots = sorted(free_slots)[: len(points)] + return [ + {"slot": slot, "start": round(t, 3), "name": name, "type": 0, "length": 0.0} + for slot, (t, _), name in zip(slots, points, names) + ] + + +def _name_positionally(times: list[float], energies: list[float], duration: float) -> list[str]: + """Positional-hint names from track position + energy trend (not true + structural classification — the names are hints; value is the position).""" + if not times: + return [] + med = float(np.median(energies)) + raw: list[str] = [] + n = len(times) + for i, (t, e) in enumerate(zip(times, energies)): + frac = t / duration if duration else 0.0 + prev = energies[i - 1] if i > 0 else e + if i == 0 or frac < 0.08: + name = "Intro" + elif i == n - 1 or frac > 0.85: + name = "Outro" + elif e - prev > 0.12 and e >= med: + name = "Drop" + elif prev - e > 0.12: + name = "Break" + elif e > prev: + name = "Build" + else: + name = "Mid" + raw.append(name) + # De-duplicate repeated labels with ordinals (Drop, Drop 2, ...). + counts: dict[str, int] = {} + out: list[str] = [] + for name in raw: + counts[name] = counts.get(name, 0) + 1 + out.append(name if counts[name] == 1 else f"{name} {counts[name]}") + return out diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 3b9fc72..0c9f7ec 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -13,11 +13,14 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse +from . import auto_hotcues as ah from . import prefs from .collection_service import CollectionService from .discovery import describe, detect_collections from .playlist_store import PlaylistError, PlaylistStore from .schemas import ( + AutoHotcue, + AutoHotcuesRequest, CollectionCandidate, CollectionOptions, CollectionStatus, @@ -426,13 +429,57 @@ def create_hotcue(body: SetHotcue) -> TrackCues: """Create (or reposition + retype) the hotcue in a slot at a position.""" try: require_store().set_hotcue( - body.track_id, body.slot, body.start, body.type, body.length + body.track_id, body.slot, body.start, body.type, body.length, name=body.name ) except PlaylistError as ex: raise HTTPException(400, str(ex)) return _sync_cue_edit(body.track_id) +@app.post("/api/tracks/auto-hotcues", response_model=TrackCues) +def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: + """Analyze the track's audio and place structural hotcues into empty slots. + + Detects section boundaries (librosa Laplacian segmentation), snaps them to + the track's beatgrid phrases, names them positionally, and places up to + MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid.""" + store = require_store() + entry = store.model_entry(body.track_id) + if entry is None: + raise HTTPException(404, "Track not found") + cues = _build_track_cues(entry) + if not cues.bpm or cues.bpm <= 0 or cues.grid_anchor is None: + raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") + path = store.audio_path(body.track_id) + if path is None or not path.exists(): + raise HTTPException(400, "Audio file not found (is the drive mounted?)") + + try: + boundaries, duration = ah.detect_boundaries(str(path)) + except Exception as ex: # analysis is best-effort; never 500 the UI + raise HTTPException(400, f"Analysis failed: {ex}") + + occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0} + free = [s for s in range(ah.MAX_HOTCUES) if s not in occupied] + existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0] + specs = ah.select_hotcues( + boundaries, + bpm=cues.bpm, + anchor=cues.grid_anchor, + duration=duration, + free_slots=free, + existing_times=existing_times, + max_cues=body.max_cues or ah.MAX_HOTCUES, + ) + if not specs: + return cues # no confident structure / no free slots — leave untouched + try: + store.place_hotcues(body.track_id, [AutoHotcue(**s) for s in specs]) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return _sync_cue_edit(body.track_id) + + @app.patch("/api/tracks/hotcue", response_model=TrackCues) def edit_hotcue_type(body: SetHotcueType) -> TrackCues: """Change the type of an existing hotcue (keeps its position).""" diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index c1b9715..b89d7f2 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -282,11 +282,18 @@ class PlaylistStore: return entry def set_hotcue( - self, track_id: str, slot: int, start_sec: float, cue_type: int, length_sec: float = 0.0 + self, + track_id: str, + slot: int, + start_sec: float, + cue_type: int, + length_sec: float = 0.0, + name: str | None = None, ) -> None: """Create (or reposition + retype) the hotcue in `slot` at `start_sec`. - `length_sec` > 0 makes it a loop (used with cue_type 5).""" + `length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the + cue label on create; when unset it falls back to Traktor's "n.n.".""" if not 0 <= slot <= 7: raise PlaylistError(f"Invalid hotcue slot: {slot}") if cue_type not in self.CREATABLE_TYPES: @@ -307,7 +314,7 @@ class PlaylistStore: entry.cue_v2 = [] entry.cue_v2.append( CueV2Type( - name="n.n.", # Traktor's default name for a manual cue + name=name or "n.n.", # Traktor's default name for a manual cue displ_order=0, type=cue_type, start=start_ms, @@ -320,6 +327,30 @@ class PlaylistStore: ) self.dirty = True + def place_hotcues( + self, track_id: str, specs: list, *, overwrite: bool = False + ) -> None: + """Batch-create hotcues from `specs` (each has .slot/.start/.name and + optional .type/.length). With `overwrite` False (the default), slots that + already hold a hotcue are skipped so hand-placed cues are never clobbered. + Used by Auto Hotcues.""" + with self._lock: + entry = self._entry_or_raise(track_id) + occupied = { + c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0 + } + for spec in specs: + if not overwrite and spec.slot in occupied: + continue + self.set_hotcue( + track_id, + spec.slot, + spec.start, + getattr(spec, "type", 0), + getattr(spec, "length", 0.0), + name=getattr(spec, "name", None), + ) + def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None: """Change the type of the existing hotcue in `slot` (keeps its position).""" if cue_type not in self.POINT_CUE_TYPES: diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index a33d461..8acd3cf 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -152,6 +152,20 @@ class SetHotcue(BaseModel): start: float # seconds type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop length: float = 0.0 # seconds (>0 for a loop hotcue) + name: str | None = None # cue label; defaults to Traktor's "n.n." when unset + + +class AutoHotcue(BaseModel): + slot: int # 0–7 + start: float # seconds + name: str | None = None # positional label (e.g. "Drop") + type: int = 0 # plain cue + length: float = 0.0 # seconds (>0 for a loop hotcue) + + +class AutoHotcuesRequest(BaseModel): + track_id: str + max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side class SetHotcueType(BaseModel): diff --git a/backend/requirements.txt b/backend/requirements.txt index 8551c76..ce709d3 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -5,6 +5,10 @@ uvicorn[standard]>=0.34 pydantic>=2.11 mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF) python-multipart>=0.0.9 # multipart form parsing for cover-art upload +# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python, +# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build. +librosa>=0.11 +scikit-learn>=1.5 # Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0), # NOT the stale PyPI release (3.1.0), which cannot parse v4 files. traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 1d140cf..6e335fb 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -292,5 +292,99 @@ with tempfile.TemporaryDirectory() as d: store2.save() check("revert BPM + anchor 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 ==") +with tempfile.TemporaryDirectory() as d: + from konduktor.schemas import AutoHotcue + from traktor_nml_utils import TraktorCollection + + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + + store = PlaylistStore(work) + entry = store._nml.collection.entry[0] + loc = entry.location + track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" + + def entry_span(data: bytes, file_name: str): + marker = f'FILE="{file_name}"'.encode() + i = data.find(marker) + start = data.rfind(b"", i) + len(b"") + return start, end + + # Establish a hand-placed hotcue as the baseline the batch must NOT overwrite. + used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0} + hand_slot = next(s for s in range(8) if s not in used) + store.set_hotcue(track_id, hand_slot, 12.0, 0, name="HAND-PLACED") + store.save() + original = work.read_bytes() + + # Batch: one spec targets the occupied slot (must be skipped), two fill free slots. + store2 = PlaylistStore(work) + e2 = store2._nml.collection.entry[0] + now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0} + free = [s for s in range(8) if s not in now_used][:2] + specs = [AutoHotcue(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")] + specs += [AutoHotcue(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)] + store2.place_hotcues(track_id, specs) + store2.save() + edited = work.read_bytes() + + check("file actually changed", original != edited) + + os_, oe = entry_span(original, loc.file) + es_, ee = entry_span(edited, loc.file) + check( + "everything outside the edited track's ENTRY is byte-identical", + original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:], + ) + n = diff_count(original[os_:oe], edited[es_:ee]) + check(f"edited ENTRY diff is small (<= 6 tag-lines for {len(free)} cues)", n <= 6, f"got {n}") + + reparsed = TraktorCollection(path=work) + e0 = reparsed.nml.collection.entry[0] + hand = next((c for c in (e0.cue_v2 or []) if c.hotcue == hand_slot), None) + check("hand-placed hotcue NOT overwritten (position)", hand is not None and abs(hand.start - 12000.0) < 1) + check("hand-placed hotcue NOT overwritten (name)", hand is not None and hand.name == "HAND-PLACED") + for i, s in enumerate(free): + c = next((c for c in (e0.cue_v2 or []) if c.hotcue == s), None) + check(f"auto hotcue slot {s} created", c is not None) + check(f"auto hotcue slot {s} name round-trips", c is not None and c.name == f"Auto {i}") + check( + f"auto hotcue slot {s} START in ms", + c is not None and abs(c.start - (30000.0 + i * 10000)) < 1, + ) + +# ---- Invariant G: select_hotcues placement logic (pure, no audio) ------ +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. +BPM, ANCHOR, DUR = 128.0, 0.0, 300.0 +# 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, + free_slots=[2, 3, 4, 5, 6, 7], existing_times=[], max_cues=8, +) +starts = [s["start"] for s in specs] +check("snaps to 30s phrase grid", all(abs(round(t / 30.0) * 30.0 - t) < 0.01 for t in starts), str(starts)) +check("fragmented 29.4/30.6 merge to one boundary (30.0)", starts.count(30.0) == 1, str(starts)) +check("only free slots used, in ascending order", [s["slot"] for s in specs] == sorted(s["slot"] for s in specs) and set(s["slot"] for s in specs) <= {2, 3, 4, 5, 6, 7}) +check("first cue named Intro", specs and specs[0]["name"] == "Intro") +check("last cue named Outro", specs and specs[-1]["name"] == "Outro") +check("names are unique (ordinal de-dupe)", len({s["name"] for s in specs}) == len(specs), str([s["name"] for s in specs])) + +# A hotcue already sitting on the 60s phrase must not get a duplicate. +specs2 = ah.select_hotcues( + raw, bpm=BPM, anchor=ANCHOR, 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) == []) + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2fc2322..41bbb7c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -260,7 +260,7 @@ export default function App() { )} {/* Prep strip spans the top of the window; the library sits below it. */} - +
diff --git a/frontend/src/api.ts b/frontend/src/api.ts index f1e32d9..233e9a2 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -249,13 +249,27 @@ export const api = { `${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, trackCues: (trackId: string) => getJSON(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`), - createHotcue: (trackId: string, slot: number, start: number, type: number, length = 0) => + createHotcue: ( + trackId: string, + slot: number, + start: number, + type: number, + length = 0, + name?: string, + ) => send('POST', '/api/tracks/hotcue', { track_id: trackId, slot, start, type, length, + name, + }), + // Backend analyses the audio and places structural hotcues into empty slots. + autoHotcues: (trackId: string, maxCues?: number) => + send('POST', '/api/tracks/auto-hotcues', { + track_id: trackId, + max_cues: maxCues, }), setHotcueType: (trackId: string, slot: number, type: number) => send('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }), diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index ffb098d..9422607 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -16,6 +16,8 @@ interface Props { /** Bumped by the library's per-row play button to load + auto-play. */ playRequest?: number onError?: (msg: string) => void + /** Neutral/success feedback (e.g. Auto Hotcues result). */ + onNotify?: (kind: 'success' | 'error', msg: string) => void } function fmt(secs: number): string { @@ -41,7 +43,7 @@ const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32] * Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the * scratch engine and both waveform views. */ -export function PrepStrip({ track, playRequest = 0, onError }: Props) { +export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) { const qc = useQueryClient() const [playing, setPlaying] = useState(false) const [previewing, setPreviewing] = useState(false) // momentary hold-to-play active @@ -72,6 +74,7 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) { const engagedRef = useRef(false) // scratch engine is dragging or coasting const pendingPlayRef = useRef(false) // a play was requested; start once ready const loadedIdRef = useRef(null) // trackId whose buffer is loaded + const [autoBusy, setAutoBusy] = useState(false) // Active momentary "cue preview": a hotcue OR the CUE button held while paused // plays from its point and stops on release, unless `latched` (play pressed // during the hold). `id` identifies the holder so its release matches. @@ -553,6 +556,36 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) { // Hotcue slot released (mouse/touch up, or key up). Ends its momentary preview. const onSlotRelease = (slot: number) => endPreview(`hc:${slot}`) + // Auto Hotcues: the backend analyses the track's audio (librosa structural + // segmentation), snaps boundaries to the beatgrid, and fills empty slots only. + // Requires a beatgrid (button disabled otherwise). + const canAutoCue = !!(cueData?.bpm && cueData.bpm > 0 && cueData.grid_anchor != null) + const runAutoHotcues = async () => { + if (!track || !canAutoCue || autoBusy) return + const hotcueCount = (c: TrackCues | null) => + c?.cues.filter((x) => x.hotcue >= 0).length ?? 0 + if (hotcueCount(cueData) >= 8) { + onError?.('No free hotcue slots — delete some first') + return + } + setAutoBusy(true) + try { + const before = hotcueCount(cueData) + const fresh = await api.autoHotcues(track.id) + applyCueEdit(fresh) + const placed = Math.max(0, hotcueCount(fresh) - before) + if (placed === 0) { + onNotify?.('error', 'No clear structure found — no hotcues placed') + } else { + onNotify?.('success', `Placed ${placed} auto hotcue${placed === 1 ? '' : 's'}`) + } + } catch (e) { + onError?.((e as Error).message) + } finally { + setAutoBusy(false) + } + } + const changeSelectedType = async (type: number) => { if (!track || selectedSlot == null) return try { @@ -863,6 +896,18 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) { )}
+