Improved auto hot cue system

This commit is contained in:
patben8 committed 2026-09-24 13:53:42 +02:00
1 parent 6cc73267a6
commit 46ce3db916
12 files changed
+1199 -312

No files matched your search

+41 -4
View File
@@ -146,6 +146,42 @@ export interface TrackCues {
cues: CuePoint[]
}
/** A structural event an Auto Hotcues slot can be bound to (`core/structure.py`
* EVENTS; keep in lockstep with `schemas.AutoCueEvent`). */
export type AutoCueEvent =
| 'first_beat' | 'intro_end'
| 'build_1' | 'drop_1' | 'breakdown_1'
| 'build_2' | 'drop_2' | 'breakdown_2'
| 'build_3' | 'drop_3' | 'breakdown_3'
| 'outro' | 'last_beat'
export interface AutoCueSlot {
slot: number
event: AutoCueEvent
offset_beats: number
/** Replace a cue already in this slot. */
overwrite: boolean
}
/** 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). */
export type AutoCueStatus = 'placed' | 'not_found' | 'out_of_range' | 'occupied' | 'protected'
export interface AutoCueOutcome {
slot: number
event: AutoCueEvent
status: AutoCueStatus
start: number | null
name: string | null
}
export interface AutoHotcuesResult {
cues: TrackCues
outcomes: AutoCueOutcome[]
}
export interface CueCapabilities {
/** Whether cues can be created or changed. Symmetric with grid.editable: a
* platform can be writable overall while its cue store is not implemented. */
@@ -615,11 +651,12 @@ export const api = {
length,
name,
}),
// Backend analyses the audio and places structural hotcues into empty slots.
autoCues: (trackId: string, maxCues?: number) =>
send<TrackCues>('POST', '/api/tracks/cue/auto', {
// Analyses the track's structure on its beatgrid and places the template:
// one event (+ offset in beats) per slot. Every slot reports an outcome.
autoCues: (trackId: string, slots: AutoCueSlot[]) =>
send<AutoHotcuesResult>('POST', '/api/tracks/cue/auto', {
track_id: trackId,
max_cues: maxCues,
slots,
}),
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
autoGrid: (trackId: string) =>
+258
View File
@@ -0,0 +1,258 @@
import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
api,
type AutoCueEvent,
type AutoHotcuesResult,
type CuePoint,
type Track,
} from '../api'
import { formatDuration } from '../lib/format'
/**
* Auto Hotcues: bind each hotcue slot to a structural event plus an offset in
* beats, then analyse the track and place them all in one go.
*
* The template (event + offset per slot) is remembered in userprefs — a DJ cues
* every track the same way — but the per-slot "replace" ticks are NOT: whether
* to overwrite a hand-placed cue is a decision about THIS track, and a
* remembered tick would silently clobber the next track's cues.
*/
export const AUTO_CUE_EVENTS: { id: AutoCueEvent; label: string }[] = [
{ id: 'first_beat', label: 'First beat' },
{ id: 'intro_end', label: 'Intro end' },
{ id: 'build_1', label: 'Build 1' },
{ id: 'drop_1', label: 'Drop 1' },
{ id: 'breakdown_1', label: 'Breakdown 1' },
{ id: 'build_2', label: 'Build 2' },
{ id: 'drop_2', label: 'Drop 2' },
{ id: 'breakdown_2', label: 'Breakdown 2' },
{ id: 'build_3', label: 'Build 3' },
{ id: 'drop_3', label: 'Drop 3' },
{ id: 'breakdown_3', label: 'Breakdown 3' },
{ id: 'outro', label: 'Outro start' },
{ id: 'last_beat', label: 'Last beat' },
]
const EVENT_IDS = new Set<string>(AUTO_CUE_EVENTS.map((e) => e.id))
export const eventLabel = (id: AutoCueEvent) =>
AUTO_CUE_EVENTS.find((e) => e.id === id)?.label ?? id
interface Row {
event: AutoCueEvent | null
offset: number // beats
}
const DEFAULT_TEMPLATE: AutoCueEvent[] = [
'first_beat', 'build_1', 'drop_1', 'breakdown_1', 'build_2', 'drop_2', 'outro', 'last_beat',
]
const PREF_KEY = 'autoCueTemplate'
const MAX_OFFSET = 256
/** The remembered template, padded/truncated to this library's bank size.
* Anything malformed in prefs falls back to the default for that slot. */
function loadTemplate(prefs: Record<string, unknown> | undefined, slots: number): Row[] {
const saved = Array.isArray(prefs?.[PREF_KEY]) ? (prefs![PREF_KEY] as unknown[]) : null
return Array.from({ length: slots }, (_, i) => {
const r = saved?.[i] as { event?: unknown; offset_beats?: unknown } | undefined
if (saved && r && typeof r === 'object') {
const event = r.event === null ? null : EVENT_IDS.has(String(r.event)) ? (r.event as AutoCueEvent) : null
const off = typeof r.offset_beats === 'number' && isFinite(r.offset_beats) ? Math.round(r.offset_beats) : 0
return { event, offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, off)) }
}
return { event: DEFAULT_TEMPLATE[i] ?? null, offset: 0 }
})
}
interface Props {
track: Track
slotCount: number
slotLabel: (slot: number) => string
/** The track's current hotcues by slot, to mark occupied rows. */
existing: Map<number, CuePoint>
onClose: () => void
onDone: (result: AutoHotcuesResult) => void
onError: (msg: string) => void
}
export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const [rows, setRows] = useState<Row[] | null>(null)
const [replace, setReplace] = useState<Set<number>>(new Set())
const [busy, setBusy] = useState(false)
// Hydrate once from prefs (the query is normally already cached by PrepStrip).
useEffect(() => {
if (rows === null && (prefs.data || prefs.isError)) setRows(loadTemplate(prefs.data, slotCount))
}, [prefs.data, prefs.isError, rows, slotCount])
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !busy) onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [busy, onClose])
const setRow = (i: number, patch: Partial<Row>) =>
setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, ...patch } : r)))
const nudge = (i: number, by: number) =>
setRows((rs) =>
rs && rs.map((r, j) => (j === i ? { ...r, offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, r.offset + by)) } : r)),
)
const active = (rows ?? []).filter((r) => r.event !== null).length
const confirm = async () => {
if (!rows || busy || active === 0) return
setBusy(true)
const template = rows.map((r) => ({ event: r.event, offset_beats: r.offset }))
// Remember the template whatever the analysis finds: it describes how the
// user cues, not this track.
api
.patchPrefs({ [PREF_KEY]: template })
.then((p) => qc.setQueryData(['prefs'], p))
.catch(() => {})
try {
const result = await api.autoCues(
track.id,
rows.flatMap((r, slot) =>
r.event ? [{ slot, event: r.event, offset_beats: r.offset, overwrite: replace.has(slot) }] : [],
),
)
onDone(result)
onClose()
} catch (e) {
onError((e as Error).message)
setBusy(false)
}
}
return (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6" onClick={() => !busy && onClose()}>
<div
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div>
<div className="truncate text-xs text-muted">
{track.artist} — {track.title}
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-3">
<div className="mb-2 grid grid-cols-[2rem_1fr_9rem_7.5rem] gap-2 text-[10px] font-semibold uppercase tracking-wider text-faint">
<span>Slot</span>
<span>Event</span>
<span className="text-center">Offset (beats)</span>
<span>Existing cue</span>
</div>
{rows === null ? (
<div className="py-6 text-center text-sm text-muted">Loading…</div>
) : (
rows.map((r, slot) => {
const cue = existing.get(slot)
return (
<div key={slot} className="grid grid-cols-[2rem_1fr_9rem_7.5rem] items-center gap-2 py-1">
<span className="flex h-7 w-7 items-center justify-center rounded bg-ink-800 text-xs font-bold text-text">
{slotLabel(slot)}
</span>
<select
value={r.event ?? ''}
onChange={(e) => setRow(slot, { event: (e.target.value || null) as AutoCueEvent | null })}
className="h-7 rounded-md border border-line bg-ink-850 px-2 text-sm text-text"
>
<option value="">— Leave empty —</option>
{AUTO_CUE_EVENTS.map((ev) => (
<option key={ev.id} value={ev.id}>
{ev.label}
</option>
))}
</select>
<div className={`flex items-center gap-1 ${r.event ? '' : 'pointer-events-none opacity-30'}`}>
<button
onClick={() => nudge(slot, -4)}
title="4 beats earlier"
className="h-7 w-7 rounded-md border border-line bg-ink-850 text-sm text-muted hover:text-text"
>
−
</button>
<input
type="number"
value={r.offset}
step={1}
onChange={(e) => {
const v = Math.round(Number(e.target.value))
if (isFinite(v)) setRow(slot, { offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, v)) })
}}
className="h-7 w-12 rounded-md border border-line bg-ink-850 px-1 text-center text-sm tabular-nums text-text"
/>
<button
onClick={() => nudge(slot, 4)}
title="4 beats later"
className="h-7 w-7 rounded-md border border-line bg-ink-850 text-sm text-muted hover:text-text"
>
+
</button>
</div>
{cue ? (
cue.editable ? (
<label className="flex min-w-0 items-center gap-1.5 text-xs text-muted" title={cue.name ?? ''}>
<input
type="checkbox"
checked={replace.has(slot)}
disabled={!r.event}
onChange={(e) =>
setReplace((s) => {
const n = new Set(s)
if (e.target.checked) n.add(slot)
else n.delete(slot)
return n
})
}
/>
<span className="truncate">
Replace {cue.name || formatDuration(cue.start)}
</span>
</label>
) : (
<span className="truncate text-xs text-faint" title="This cue belongs to the beatgrid and is never replaced">
Grid cue (kept)
</span>
)
) : (
<span className="text-xs text-faint">Empty</span>
)}
</div>
)
})
)}
<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. Your slot setup is remembered for the next track.
</p>
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={onClose}
disabled={busy}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:text-text disabled:opacity-40"
>
Cancel
</button>
<button
onClick={confirm}
disabled={busy || rows === null || active === 0}
className="rounded-md bg-accent px-4 py-1.5 text-sm font-semibold text-ink-950 hover:brightness-110 disabled:opacity-40"
>
{busy ? 'Analyzing…' : `Analyze & place ${active} cue${active === 1 ? '' : 's'}`}
</button>
</div>
</div>
</div>
)
}
+48 -33
View File
@@ -1,6 +1,14 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type CueType, type GridMarker, type Track, type TrackCues } from '../api'
import {
api,
type AutoHotcuesResult,
type CuePoint,
type CueType,
type GridMarker,
type Track,
type TrackCues,
} from '../api'
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
import { slotLabeller, useCaps } from '../lib/capabilities'
import { CUE_TYPE_LABELS } from '../lib/cues'
@@ -8,6 +16,7 @@ import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine'
import { AutoCueDialog, eventLabel } from './AutoCueDialog'
import { BeatJumpControls, BEAT_JUMP_SIZES } from './BeatJumpControls'
import { GridControls } from './GridControls'
import { HotcueBar } from './HotcueBar'
@@ -99,7 +108,6 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
const engagedRef = useRef(false) // scratch engine is dragging or coasting
const pendingPlayRef = useRef(false) // a play was requested; start once ready
const loadedIdRef = useRef<string | null>(null) // trackId whose buffer is loaded
const [autoBusy, setAutoBusy] = useState(false)
const [gridBusy, setGridBusy] = 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
@@ -681,35 +689,31 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
// 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).
// Auto Hotcues: the button opens the slot-template dialog; the backend finds
// the track's structure on its beatgrid and places the template. Requires a
// beatgrid (button disabled otherwise) — every event is a bar on it.
const canAutoCue = grid != null
const runAutoHotcues = async () => {
if (!track || !canAutoCue || autoBusy) return
const [autoOpen, setAutoOpen] = useState(false)
const openAutoHotcues = () => {
if (!track || !canAutoCue) return
if (refuseCueEdit()) return
const hotcueCount = (c: TrackCues | null) =>
c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0
if (hotcueCount(cueData) >= slotCount) {
onError?.(`No free hotcue slots (${slotCount} of ${slotCount} used) — delete some first`)
return
}
setAutoBusy(true)
try {
const before = hotcueCount(cueData)
const fresh = await api.autoCues(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)
}
setAutoOpen(true)
}
const existingHotcues = useMemo(() => {
const m = new Map<number, CuePoint>()
for (const c of cueData?.cues ?? []) if (c.role === 'hotcue' && c.slot != null) m.set(c.slot, c)
return m
}, [cueData])
const autoHotcuesDone = (result: AutoHotcuesResult) => {
applyCueEdit(result.cues)
const by = (st: string) => result.outcomes.filter((o) => o.status === st)
const placed = by('placed').length
const missing = [...by('not_found'), ...by('out_of_range')].map((o) => eventLabel(o.event))
const kept = by('occupied').length + by('protected').length
const parts = [`Placed ${placed} hotcue${placed === 1 ? '' : 's'}`]
if (missing.length) parts.push(`not in this track: ${missing.join(', ')}`)
if (kept) parts.push(`${kept} occupied slot${kept === 1 ? '' : 's'} kept`)
onNotify?.(placed ? 'success' : 'error', parts.join(' · '))
}
const changeSelectedType = async (type: CueType) => {
@@ -1144,16 +1148,16 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
)}
</div>
<button
onClick={runAutoHotcues}
disabled={!canAutoCue || autoBusy}
onClick={openAutoHotcues}
disabled={!canAutoCue}
title={
canAutoCue
? 'Auto-place hotcues at detected phrase boundaries (empty slots only)'
? 'Place hotcues on the track\'s drops, breakdowns and other sections'
: 'Set a beatgrid first'
}
className="flex w-16 items-center justify-center gap-1 bg-ink-900 text-[11px] font-semibold uppercase tracking-wider text-muted transition-colors hover:bg-ink-800 hover:text-accent disabled:opacity-30 disabled:hover:bg-ink-900 disabled:hover:text-muted"
>
{autoBusy ? '…' : '✨ Auto'}
✨ Auto
</button>
<button
onClick={deleteSelected}
@@ -1167,6 +1171,17 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
</>
)}
</div>
{autoOpen && track && (
<AutoCueDialog
track={track}
slotCount={slotCount}
slotLabel={slotLabel}
existing={existingHotcues}
onClose={() => setAutoOpen(false)}
onDone={autoHotcuesDone}
onError={(msg) => onError?.(msg)}
/>
)}
</div>
)
}