Fixed looping issues and tied it to hotcue system

This commit is contained in:
Ben committed 2026-07-04 20:02:32 +02:00
1 parent 9dc020140a
commit fdcae5e0f5
6 files changed
+103 -21

No files matched your search

+3 -1
View File
@@ -384,7 +384,9 @@ def _sync_cue_edit(track_id: str) -> TrackCues:
def create_hotcue(body: SetHotcue) -> TrackCues: def create_hotcue(body: SetHotcue) -> TrackCues:
"""Create (or reposition + retype) the hotcue in a slot at a position.""" """Create (or reposition + retype) the hotcue in a slot at a position."""
try: try:
require_store().set_hotcue(body.track_id, body.slot, body.start, body.type) require_store().set_hotcue(
body.track_id, body.slot, body.start, body.type, body.length
)
except PlaylistError as ex: except PlaylistError as ex:
raise HTTPException(400, str(ex)) raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id) return _sync_cue_edit(body.track_id)
+17 -10
View File
@@ -266,11 +266,12 @@ class PlaylistStore:
with self._lock: with self._lock:
return self._entry_by_key.get(track_id) return self._entry_by_key.get(track_id)
# ---- hotcues (beatgrid-independent point markers) ----------------- # ---- hotcues ------------------------------------------------------
# Only self-contained point types are editable here: 0 cue, 1 fade-in, # Creatable/editable types: 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop.
# 2 fade-out, 3 load. Loops (need a length) and grid markers (redefine the # A loop (type 5) carries a length; the point types don't. Grid markers
# beatgrid) are deliberately excluded. Cues are NML-only (not synced to files). # (type 4, redefine the beatgrid) are excluded. Cues are NML-only.
POINT_CUE_TYPES = {0, 1, 2, 3} POINT_CUE_TYPES = {0, 1, 2, 3} # types the dropdown can switch between
CREATABLE_TYPES = {0, 1, 2, 3, 5}
def _entry_or_raise(self, track_id: str) -> Entrytype: def _entry_or_raise(self, track_id: str) -> Entrytype:
entry = self._entry_by_key.get(track_id) entry = self._entry_by_key.get(track_id)
@@ -278,21 +279,27 @@ class PlaylistStore:
raise PlaylistError(f"Track not found: {track_id}") raise PlaylistError(f"Track not found: {track_id}")
return entry return entry
def set_hotcue(self, track_id: str, slot: int, start_sec: float, cue_type: int) -> None: def set_hotcue(
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`.""" self, track_id: str, slot: int, start_sec: float, cue_type: int, length_sec: float = 0.0
) -> None:
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`.
`length_sec` > 0 makes it a loop (used with cue_type 5)."""
if not 0 <= slot <= 7: if not 0 <= slot <= 7:
raise PlaylistError(f"Invalid hotcue slot: {slot}") raise PlaylistError(f"Invalid hotcue slot: {slot}")
if cue_type not in self.POINT_CUE_TYPES: if cue_type not in self.CREATABLE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}") raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock: with self._lock:
entry = self._entry_or_raise(track_id) entry = self._entry_or_raise(track_id)
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START in ms 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( existing = next(
(c for c in (entry.cue_v2 or []) if c.hotcue == slot), None (c for c in (entry.cue_v2 or []) if c.hotcue == slot), None
) )
if existing is not None: if existing is not None:
existing.start = start_ms existing.start = start_ms
existing.type = cue_type existing.type = cue_type
existing.len = len_ms
else: else:
if entry.cue_v2 is None: if entry.cue_v2 is None:
entry.cue_v2 = [] entry.cue_v2 = []
@@ -302,7 +309,7 @@ class PlaylistStore:
displ_order=0, displ_order=0,
type=cue_type, type=cue_type,
start=start_ms, start=start_ms,
len=0.0, len=len_ms,
repeats=-1, repeats=-1,
hotcue=slot, hotcue=slot,
color=None, color=None,
+2 -1
View File
@@ -137,7 +137,8 @@ class SetHotcue(BaseModel):
track_id: str track_id: str
slot: int # 0–7 slot: int # 0–7
start: float # seconds start: float # seconds
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop
length: float = 0.0 # seconds (>0 for a loop hotcue)
class SetHotcueType(BaseModel): class SetHotcueType(BaseModel):
+8 -2
View File
@@ -218,8 +218,14 @@ export const api = {
audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
trackCues: (trackId: string) => trackCues: (trackId: string) =>
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`), getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
createHotcue: (trackId: string, slot: number, start: number, type: number) => createHotcue: (trackId: string, slot: number, start: number, type: number, length = 0) =>
send<TrackCues>('POST', '/api/tracks/hotcue', { track_id: trackId, slot, start, type }), send<TrackCues>('POST', '/api/tracks/hotcue', {
track_id: trackId,
slot,
start,
type,
length,
}),
setHotcueType: (trackId: string, slot: number, type: number) => setHotcueType: (trackId: string, slot: number, type: number) =>
send<TrackCues>('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }), send<TrackCues>('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }),
deleteHotcue: (trackId: string, slot: number) => deleteHotcue: (trackId: string, slot: number) =>
+58 -3
View File
@@ -28,6 +28,8 @@ const CUE_TYPES: { value: number; label: string }[] = [
{ value: 2, label: 'Fade-Out' }, { value: 2, label: 'Fade-Out' },
{ value: 3, label: 'Load' }, { value: 3, label: 'Load' },
] ]
const LOOP_TYPE = 5
const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32]
/** /**
* The DJ-style "prep strip" across the top of the window: transport controls on * The DJ-style "prep strip" across the top of the window: transport controls on
@@ -178,6 +180,16 @@ export function PrepStrip({ track, onError }: Props) {
setCurrent(t) setCurrent(t)
} }
// User-driven seek from the waveforms: navigating away drops the active loop
// (otherwise it would just pull playback back into the loop region).
const seekManual = (t: number) => {
if (loopActive) {
playbackRef.current?.setLoopEnabled(false)
setLoopActive(false)
}
seek(t)
}
// ---- scratch ---------------------------------------------------------- // ---- scratch ----------------------------------------------------------
const finalizeScratch = () => { const finalizeScratch = () => {
cancelAnimationFrame(scratchRafRef.current) cancelAnimationFrame(scratchRafRef.current)
@@ -269,7 +281,16 @@ export function PrepStrip({ track, onError }: Props) {
const eng = playbackRef.current const eng = playbackRef.current
const bpm = cueData?.bpm ?? null const bpm = cueData?.bpm ?? null
if (!eng || !eng.ready || !bpm || bpm <= 0) return if (!eng || !eng.ready || !bpm || bpm <= 0) return
const start = snapTime(eng.getPosition()) // Pressing the size of the loop that's already playing disables it.
if (loopActive && activeBeats === beats) {
eng.setLoopEnabled(false)
setLoopActive(false)
setCurrent(eng.getPosition())
return
}
// Resizing an active loop keeps its start locked; only a fresh loop starts
// at the current playhead.
const start = loopActive && loopRegion ? loopRegion.start : snapTime(eng.getPosition())
engagLoop(start, start + beats * (60 / bpm), beats) engagLoop(start, start + beats * (60 / bpm), beats)
} }
@@ -306,17 +327,47 @@ export function PrepStrip({ track, onError }: Props) {
qc.invalidateQueries({ queryKey: ['playlist'] }) qc.invalidateQueries({ queryKey: ['playlist'] })
} }
// Map a loop length (seconds) back to a preset beat count for the size
// highlight, snapping to the nearest preset when it's close (float tolerance).
const beatsForLength = (length: number): number | null => {
const bpm = cueData?.bpm ?? null
if (!bpm || bpm <= 0) return null
const beats = length / (60 / bpm)
let best: number | null = null
let bestDiff = Infinity
for (const s of LOOP_SIZES) {
const diff = Math.abs(s - beats)
if (diff < bestDiff) {
bestDiff = diff
best = s
}
}
return best != null && bestDiff <= beats * 0.05 ? best : null
}
const onSlotClick = async (slot: number) => { const onSlotClick = async (slot: number) => {
if (!track) return if (!track) return
const cue = hotcueAt(slot) const cue = hotcueAt(slot)
if (cue) { if (cue) {
// A loop hotcue jumps to its start AND re-engages a loop of its length.
if (cue.type === LOOP_TYPE && cue.length > 0) {
seek(cue.start) seek(cue.start)
engagLoop(cue.start, cue.start + cue.length, beatsForLength(cue.length))
} else {
seek(cue.start)
}
setSelectedSlot(slot) setSelectedSlot(slot)
return return
} }
try { try {
// Setting a hotcue while a loop is active stores it as a loop hotcue.
if (loopActive && loopRegion) {
const len = loopRegion.end - loopRegion.start
applyCueEdit(await api.createHotcue(track.id, slot, loopRegion.start, LOOP_TYPE, len))
} else {
const t = snapTime(playbackRef.current?.getPosition() ?? current) const t = snapTime(playbackRef.current?.getPosition() ?? current)
applyCueEdit(await api.createHotcue(track.id, slot, t, 0)) applyCueEdit(await api.createHotcue(track.id, slot, t, 0))
}
setSelectedSlot(slot) setSelectedSlot(slot)
} catch (e) { } catch (e) {
onError?.((e as Error).message) onError?.((e as Error).message)
@@ -402,7 +453,7 @@ export function PrepStrip({ track, onError }: Props) {
bpm={cueData?.bpm ?? null} bpm={cueData?.bpm ?? null}
gridAnchor={cueData?.grid_anchor ?? null} gridAnchor={cueData?.grid_anchor ?? null}
loop={activeLoop} loop={activeLoop}
onSeek={seek} onSeek={seekManual}
onScratchStart={onScratchStart} onScratchStart={onScratchStart}
onScratchMove={onScratchMove} onScratchMove={onScratchMove}
onScratchEnd={onScratchEnd} onScratchEnd={onScratchEnd}
@@ -421,7 +472,7 @@ export function PrepStrip({ track, onError }: Props) {
duration={duration} duration={duration}
cues={cueData?.cues ?? []} cues={cueData?.cues ?? []}
loop={activeLoop} loop={activeLoop}
onSeek={seek} onSeek={seekManual}
/> />
)} )}
</div> </div>
@@ -451,6 +502,9 @@ export function PrepStrip({ track, onError }: Props) {
{selectedCue ? `Hotcue ${(selectedSlot ?? 0) + 1}` : 'No hotcue selected'} {selectedCue ? `Hotcue ${(selectedSlot ?? 0) + 1}` : 'No hotcue selected'}
</span> </span>
<div className="flex-1" /> <div className="flex-1" />
{selectedCue && selectedCue.type === LOOP_TYPE ? (
<span className="rounded border border-line px-2 py-0.5 text-mint">Loop</span>
) : (
<select <select
value={selectedCue ? selectedCue.type : ''} value={selectedCue ? selectedCue.type : ''}
disabled={!selectedCue} disabled={!selectedCue}
@@ -464,6 +518,7 @@ export function PrepStrip({ track, onError }: Props) {
</option> </option>
))} ))}
</select> </select>
)}
<button <button
onClick={deleteSelected} onClick={deleteSelected}
disabled={!selectedCue} disabled={!selectedCue}
+15 -4
View File
@@ -125,8 +125,19 @@ export class PlaybackEngine {
} }
} }
// Snapshot the true buffer position into (startOffset, startedAt) so the
// position model stays correct after the loop params change. Must be called
// BEFORE mutating loopOn/loopStart/loopEnd (it reads the current/old params).
private reanchor(): void {
if (this._playing && this.ctx) {
this.startOffset = this.getPosition()
this.startedAt = this.ctx.currentTime
}
}
/** Set the loop region and whether it's active. Bounds apply live if playing. */ /** Set the loop region and whether it's active. Bounds apply live if playing. */
setLoop(start: number, end: number, enabled: boolean): void { setLoop(start: number, end: number, enabled: boolean): void {
this.reanchor() // capture the real position under the OLD loop state first
this.loopStart = start this.loopStart = start
this.loopEnd = end this.loopEnd = end
this.loopOn = enabled this.loopOn = enabled
@@ -139,10 +150,10 @@ export class PlaybackEngine {
this.source.loop = false this.source.loop = false
} }
} }
// If the playhead is already past the loop, jump into it so it engages now. // If the playhead is already at/past the loop end, jump into it (the live
if (enabled && this._playing) { // node won't loop back on its own from beyond loopEnd).
const pos = this.getPosition() if (enabled && end > start && this.startOffset >= end) {
if (pos >= end) this.seek(start) this.seek(start)
} }
} }