Implemented looping

This commit is contained in:
Ben committed 2026-07-04 19:39:03 +02:00
1 parent f88f1932dc
commit 9dc020140a
12 files changed
+845 -141

No files matched your search

+55 -6
View File
@@ -30,6 +30,8 @@ from .schemas import (
RenamePlaylist,
SaveResult,
SetEntries,
SetHotcue,
SetHotcueType,
Stats,
Track,
TrackCues,
@@ -330,12 +332,7 @@ def track_audio(track_id: str) -> FileResponse:
return FileResponse(path, media_type=mime)
@app.get("/api/tracks/cues", response_model=TrackCues)
def track_cues(track_id: str) -> TrackCues:
"""Beatgrid + cue/loop markers for a track (read-only, from the NML)."""
entry = require_store().model_entry(track_id)
if entry is None:
raise HTTPException(404, "Track not found")
def _build_track_cues(entry) -> TrackCues:
grid_anchor: float | None = None
grid_bpm: float | None = None
cues: list[CuePoint] = []
@@ -361,6 +358,58 @@ def track_cues(track_id: str) -> TrackCues:
return TrackCues(bpm=bpm, grid_anchor=grid_anchor, cues=cues)
def _cues_for(track_id: str) -> TrackCues:
entry = require_store().model_entry(track_id)
if entry is None:
raise HTTPException(404, "Track not found")
return _build_track_cues(entry)
@app.get("/api/tracks/cues", response_model=TrackCues)
def track_cues(track_id: str) -> TrackCues:
"""Beatgrid + cue/loop markers for a track (read-only, from the NML)."""
return _cues_for(track_id)
def _sync_cue_edit(track_id: str) -> TrackCues:
"""After a hotcue edit, refresh the read projection and return fresh cues."""
store = require_store()
entry = store.model_entry(track_id)
if entry is not None:
require_service().replace_track(track_id, entry)
return _build_track_cues(entry) if entry is not None else TrackCues()
@app.post("/api/tracks/hotcue", response_model=TrackCues)
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)
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)."""
try:
require_store().set_hotcue_type(body.track_id, body.slot, body.type)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.delete("/api/tracks/hotcue", response_model=TrackCues)
def delete_hotcue(track_id: str, slot: int) -> TrackCues:
"""Remove the hotcue in a slot."""
try:
require_store().delete_hotcue(track_id, slot)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(track_id)
@app.put("/api/tracks/art")
async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict:
"""Stage replacement cover art for a track (written to the file on save)."""
+64
View File
@@ -31,6 +31,7 @@ from traktor_nml_utils import (
)
from traktor_nml_utils.models.collection import (
Albumtype,
CueV2Type,
Entrytype,
Infotype,
Nodetype,
@@ -265,6 +266,69 @@ class PlaylistStore:
with self._lock:
return self._entry_by_key.get(track_id)
# ---- hotcues (beatgrid-independent point markers) -----------------
# Only self-contained point types are editable here: 0 cue, 1 fade-in,
# 2 fade-out, 3 load. Loops (need a length) and grid markers (redefine the
# beatgrid) are deliberately excluded. Cues are NML-only (not synced to files).
POINT_CUE_TYPES = {0, 1, 2, 3}
def _entry_or_raise(self, track_id: str) -> Entrytype:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
return entry
def set_hotcue(self, track_id: str, slot: int, start_sec: float, cue_type: int) -> None:
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`."""
if not 0 <= slot <= 7:
raise PlaylistError(f"Invalid hotcue slot: {slot}")
if cue_type not in self.POINT_CUE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START in ms
existing = next(
(c for c in (entry.cue_v2 or []) if c.hotcue == slot), None
)
if existing is not None:
existing.start = start_ms
existing.type = cue_type
else:
if entry.cue_v2 is None:
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
name="n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
len=0.0,
repeats=-1,
hotcue=slot,
color=None,
grid=None,
)
)
self.dirty = True
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:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
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")
cue.type = cue_type
self.dirty = True
def delete_hotcue(self, track_id: str, slot: int) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot]
self.dirty = True
# ---- cover art -----------------------------------------------------
def set_track_art(self, track_id: str, data: bytes, mime: str) -> None:
with self._lock:
+13
View File
@@ -133,6 +133,19 @@ class TrackCues(BaseModel):
cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded)
class SetHotcue(BaseModel):
track_id: str
slot: int # 0–7
start: float # seconds
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load
class SetHotcueType(BaseModel):
track_id: str
slot: int
type: int
class EditState(BaseModel):
dirty: bool # unsaved in-memory playlist changes exist
nml_path: str
+51
View File
@@ -175,5 +175,56 @@ with tempfile.TemporaryDirectory() as d:
check("re-parses + genre persisted", e0.info.genre == "KONDUKTOR-FIDELITY-TEST")
check("rating persisted (4 stars => RANKING 204)", e0.info.ranking == 204)
# ---- Invariant D: a hotcue edit is fully localized ---------------------
print("== D. hotcue create touches only that track's ENTRY ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = PlaylistStore(work)
entry = store._nml.collection.entry[0]
loc = entry.location
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
# Use a free slot so we exercise the create path (not overwrite an existing).
used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None}
slot = next(s for s in range(8) if s not in used)
store.set_hotcue(track_id, slot, 42.5, 0)
store.save()
edited = work.read_bytes()
check("file actually changed", original != edited)
def entry_span(data: bytes, file_name: str):
marker = f'FILE="{file_name}"'.encode()
i = data.find(marker)
start = data.rfind(b"<ENTRY ", 0, i)
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
return start, end
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("edited ENTRY diff is tiny (<= 3 tag-lines)", n <= 3, f"got {n}")
from traktor_nml_utils import TraktorCollection
reparsed = TraktorCollection(path=work)
e0 = reparsed.nml.collection.entry[0]
new_cue = next((c for c in (e0.cue_v2 or []) if c.hotcue == slot), None)
check("re-parses + hotcue persisted", new_cue is not None)
check("hotcue START stored in ms", new_cue is not None and abs(new_cue.start - 42500.0) < 1)
# Create then delete must round-trip back to a byte-identical file.
store2 = PlaylistStore(work) # reload the edited file
store2.delete_hotcue(track_id, slot)
store2.save()
check("create+delete round-trips to the original bytes", work.read_bytes() == original)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+9
View File
@@ -218,6 +218,15 @@ export const api = {
audioUrl: (trackId: string) => `/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
trackCues: (trackId: string) =>
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
createHotcue: (trackId: string, slot: number, start: number, type: number) =>
send<TrackCues>('POST', '/api/tracks/hotcue', { track_id: trackId, slot, start, type }),
setHotcueType: (trackId: string, slot: number, type: number) =>
send<TrackCues>('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }),
deleteHotcue: (trackId: string, slot: number) =>
send<TrackCues>(
'DELETE',
`/api/tracks/hotcue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`,
),
uploadArt: async (trackId: string, file: File) => {
const fd = new FormData()
fd.append('track_id', trackId)
+48
View File
@@ -0,0 +1,48 @@
import type { CuePoint } from '../api'
import { contrastText, cueColor } from '../lib/cues'
interface Props {
cues: CuePoint[]
selectedSlot: number | null
onSlotClick: (slot: number) => void
}
const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–8
/**
* Traktor-style hotcue bar: all 8 hotcue slots, colour-coded by cue type when
* assigned (gray when empty). Clicking a slot selects it — the parent decides
* whether that creates a cue (empty slot) or jumps to it (assigned slot).
*/
export function HotcueBar({ cues, selectedSlot, onSlotClick }: Props) {
return (
<div className="flex h-8 shrink-0 items-stretch gap-px border-t border-line bg-ink-950">
{SLOTS.map((slot) => {
const cue = cues.find((c) => c.hotcue === slot) ?? null
const selected = selectedSlot === slot
const color = cue ? cueColor(cue) : null
return (
<button
key={slot}
onClick={() => onSlotClick(slot)}
title={
cue
? cue.name && cue.name !== 'n.n.'
? `${slot + 1}: ${cue.name}`
: `Hotcue ${slot + 1}`
: `Hotcue ${slot + 1} — click to set at playhead`
}
style={color ? { backgroundColor: color, color: contrastText(color) } : undefined}
className={
'flex flex-1 items-center justify-center text-xs font-semibold transition-[filter] hover:brightness-110 ' +
(color ? '' : 'text-faint hover:bg-ink-900 ') +
(selected ? 'ring-2 ring-inset ring-white/80' : '')
}
>
{slot + 1}
</button>
)
})}
</div>
)
}
+118
View File
@@ -0,0 +1,118 @@
import { useState } from 'react'
interface Props {
bpm: number | null // beat-loops need a grid; buttons disable without one
active: boolean // a loop is currently engaged
activeBeats: number | null // size of the active loop (null for a manual loop)
canToggle: boolean // a loop region exists to enable/disable
snap: boolean
onToggleSnap: () => void
onSetLoop: (beats: number) => void
onLoopIn: () => void
onLoopOut: () => void
onToggleActive: () => void
}
// Fixed beat-loop sizes, 1/32 → 32 beats.
const SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32]
const WINDOW = 6 // sizes shown at once (Traktor-style), shifted with the arrows
const DEFAULT_START = 3 // start on 1/4 … 8
function label(size: number): string {
return size < 1 ? `1/${Math.round(1 / size)}` : String(size)
}
export function LoopControls({
bpm,
active,
activeBeats,
canToggle,
snap,
onToggleSnap,
onSetLoop,
onLoopIn,
onLoopOut,
onToggleActive,
}: Props) {
const [start, setStart] = useState(DEFAULT_START)
const maxStart = SIZES.length - WINDOW
const visible = SIZES.slice(start, start + WINDOW)
const hasGrid = !!bpm && bpm > 0
const btn =
'flex h-6 min-w-8 items-center justify-center rounded px-1.5 text-xs font-semibold ' +
'border border-line text-muted hover:text-text disabled:opacity-30'
return (
<div className="flex h-9 shrink-0 items-center gap-1.5 border-t border-line bg-ink-900 px-3">
<button
onClick={onToggleSnap}
title="Snap to the nearest beat"
className={
'mr-1 rounded px-2 py-0.5 text-xs font-semibold uppercase tracking-wider ' +
(snap ? 'bg-accent text-ink-950' : 'border border-line text-muted hover:text-text')
}
>
Snap
</button>
<button
onClick={() => setStart((s) => Math.max(0, s - 1))}
disabled={start === 0}
className={btn}
title="Smaller sizes"
>
‹
</button>
{visible.map((size) => {
const isActive = active && activeBeats === size
return (
<button
key={size}
onClick={() => onSetLoop(size)}
disabled={!hasGrid}
title={hasGrid ? `${label(size)}-beat loop` : 'No beatgrid'}
className={
'flex h-6 min-w-9 items-center justify-center rounded px-1.5 text-xs font-semibold ' +
(isActive
? 'bg-mint text-ink-950'
: 'border border-line text-text hover:border-accent disabled:opacity-30')
}
>
{label(size)}
</button>
)
})}
<button
onClick={() => setStart((s) => Math.min(maxStart, s + 1))}
disabled={start === maxStart}
className={btn}
title="Larger sizes"
>
›
</button>
<div className="mx-1 h-5 w-px bg-line" />
<button onClick={onLoopIn} className={btn} title="Set loop in point at playhead">
IN
</button>
<button onClick={onLoopOut} className={btn} title="Set loop out point at playhead">
OUT
</button>
<button
onClick={onToggleActive}
disabled={!canToggle}
title={active ? 'Disable loop' : 'Enable loop'}
className={
'flex h-6 min-w-9 items-center justify-center rounded px-2 text-sm ' +
(active
? 'bg-mint text-ink-950'
: 'border border-line text-muted hover:text-text disabled:opacity-30')
}
>
⟳
</button>
</div>
)
}
+8 -3
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import type { CuePoint } from '../api'
import { drawBeatgrid, drawCues } from '../lib/cues'
import { drawBeatgrid, drawCues, drawLoop } from '../lib/cues'
import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props {
@@ -10,6 +10,7 @@ interface Props {
cues: CuePoint[]
bpm: number | null
gridAnchor: number | null
loop: { start: number; end: number } | null
onSeek: (t: number) => void
onScratchStart: () => void
onScratchMove: (t: number) => void
@@ -35,6 +36,7 @@ export function MainWaveform({
cues,
bpm,
gridAnchor,
loop,
onSeek,
onScratchStart,
onScratchMove,
@@ -70,12 +72,15 @@ export function MainWaveform({
const endSec = currentTime + half
paintWave(ctx, cols, w, h, startSec / duration, endSec / duration)
// Beatgrid, then cue markers (extrapolated across the visible window).
const timeToX = (t: number) => ((t - startSec) / secPerView) * w
// Loop band (under the grid/cues), then beatgrid, then cue markers.
if (loop) {
drawLoop(ctx, timeToX(loop.start), timeToX(loop.end), h, dpr)
}
if (bpm && gridAnchor != null) {
drawBeatgrid(ctx, bpm, gridAnchor, startSec, endSec, w, h, dpr)
}
if (cues.length) {
const timeToX = (t: number) => ((t - startSec) / secPerView) * w
drawCues(ctx, cues, w, h, dpr, timeToX, true)
}
}
+10 -5
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef } from 'react'
import type { CuePoint } from '../api'
import { drawCues } from '../lib/cues'
import { drawCues, drawLoop } from '../lib/cues'
import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props {
@@ -8,6 +8,7 @@ interface Props {
currentTime: number
duration: number
cues: CuePoint[]
loop: { start: number; end: number } | null
onSeek: (t: number) => void
}
@@ -16,13 +17,14 @@ interface Props {
* offscreen canvas) with a moving playhead + dimmed played region. Click to
* seek anywhere in the track.
*/
export function OverviewWaveform({ cols, currentTime, duration, cues, onSeek }: Props) {
export function OverviewWaveform({ cols, currentTime, duration, cues, loop, onSeek }: Props) {
const wrapRef = useRef<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null)
const cacheRef = useRef<HTMLCanvasElement | null>(null)
const timeRef = useRef(0)
const durRef = useRef(0)
const cuesRef = useRef<CuePoint[]>(cues)
const loopRef = useRef(loop)
const renderCache = useCallback(() => {
const canvas = canvasRef.current
@@ -53,8 +55,10 @@ export function OverviewWaveform({ cols, currentTime, duration, cues, onSeek }:
const px = Math.round((timeRef.current / dur) * w)
ctx.fillStyle = 'rgba(10,11,15,0.55)'
ctx.fillRect(0, 0, px, h)
// Cue markers (no beatgrid/labels in the overview).
const dpr = window.devicePixelRatio || 1
const lp = loopRef.current
if (lp) drawLoop(ctx, (lp.start / dur) * w, (lp.end / dur) * w, h, dpr)
// Cue markers (no beatgrid/labels in the overview).
drawCues(ctx, cuesRef.current, w, h, dpr, (t) => (t / dur) * w, false)
const pw = Math.max(2, Math.round(2 * dpr))
ctx.fillStyle = '#e6e9ef'
@@ -93,11 +97,12 @@ export function OverviewWaveform({ cols, currentTime, duration, cues, onSeek }:
draw()
}, [currentTime, duration, draw])
// Redraw when the cue set changes (new track).
// Redraw when the cue set or loop changes.
useEffect(() => {
cuesRef.current = cues
loopRef.current = loop
draw()
}, [cues, draw])
}, [cues, loop, draw])
const seek = (e: React.MouseEvent<HTMLDivElement>) => {
if (!duration) return
+262 -108
View File
@@ -1,7 +1,11 @@
import { useEffect, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { api, type Track, type TrackCues } from '../api'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine'
import { HotcueBar } from './HotcueBar'
import { LoopControls } from './LoopControls'
import { MainWaveform } from './MainWaveform'
import { OverviewWaveform } from './OverviewWaveform'
@@ -18,45 +22,74 @@ function fmt(secs: number): string {
return `${m}:${s.toString().padStart(2, '0')}`
}
const CUE_TYPES: { value: number; label: string }[] = [
{ value: 0, label: 'Cue' },
{ value: 1, label: 'Fade-In' },
{ value: 2, label: 'Fade-Out' },
{ value: 3, label: 'Load' },
]
/**
* The DJ-style "prep strip" across the top of the window: transport controls on
* the left, waveforms on the right (a scrolling zoomable main view above a
* whole-track overview). Playback is driven by a single hidden <audio> element
* streamed from the backend (range-enabled, so seeking works). The frequency-
* coloured waveform is analysed once here and shared by both views.
* whole-track overview), plus loop + hotcue controls. Playback runs through the
* Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the
* scratch engine and both waveform views.
*/
export function PrepStrip({ track, onError }: Props) {
const audioRef = useRef<HTMLAudioElement | null>(null)
const qc = useQueryClient()
const [playing, setPlaying] = useState(false)
const [current, setCurrent] = useState(0)
const [duration, setDuration] = useState(0)
const [loadError, setLoadError] = useState(false)
const [ready, setReady] = useState(false)
const [cols, setCols] = useState<WaveColumn[] | null>(null)
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const [cueData, setCueData] = useState<TrackCues | null>(null)
const [snap, setSnap] = useState(true)
const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
// Loop state (transient — persisted only when saved as a hotcue later).
const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null)
const [loopActive, setLoopActive] = useState(false)
const [activeBeats, setActiveBeats] = useState<number | null>(null)
const loopInRef = useRef<number | null>(null) // armed manual loop-in point
// Scratch engine (Web Audio) — holds the decoded buffer for the loaded track.
const audioCtxRef = useRef<AudioContext | null>(null)
const engineRef = useRef<ScratchEngine | null>(null)
const playbackRef = useRef<PlaybackEngine | null>(null)
const scratchRef = useRef<ScratchEngine | null>(null)
const wasPlayingRef = useRef(false)
const scratchRafRef = useRef(0)
const engagedRef = useRef(false) // engine is dragging or coasting
const engagedRef = useRef(false) // scratch engine is dragging or coasting
const trackId = track?.id ?? null
// When the loaded track changes, reset transport state. The <audio> src is
// bound declaratively below, so changing trackId swaps the source.
const getCtx = (): AudioContext => {
if (!audioCtxRef.current) {
audioCtxRef.current = new (window.AudioContext ??
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)()
}
void audioCtxRef.current.resume()
return audioCtxRef.current
}
// Reset transport + loop state when the loaded track changes.
useEffect(() => {
playbackRef.current?.pause()
setPlaying(false)
setCurrent(0)
setDuration(0)
setLoadError(false)
setReady(false)
setSelectedSlot(null)
setLoopRegion(null)
setLoopActive(false)
setActiveBeats(null)
loopInRef.current = null
}, [trackId])
// Analyse the waveform once per track; both waveform views share the result,
// and the decoded buffer is handed to the scratch engine (no second decode).
// Analyse once per track; the decoded buffer feeds both the playback and
// scratch engines (no re-decode) and both waveform views share the columns.
useEffect(() => {
engineRef.current = null
scratchRef.current = null
if (!trackId) {
setCols(null)
setWaveStatus('loading')
@@ -70,9 +103,17 @@ export function PrepStrip({ track, onError }: Props) {
if (cancelled) return
setCols(res.cols)
setWaveStatus('ready')
const eng = new ScratchEngine()
eng.load(res.buffer)
engineRef.current = eng
const sc = new ScratchEngine()
sc.load(res.buffer)
scratchRef.current = sc
const ctx = getCtx()
if (!playbackRef.current) {
playbackRef.current = new PlaybackEngine()
playbackRef.current.setOnEnded(() => setPlaying(false))
}
playbackRef.current.load(ctx, res.buffer)
setDuration(res.buffer.duration)
setReady(true)
})
.catch(() => {
if (!cancelled) setWaveStatus('error')
@@ -104,84 +145,61 @@ export function PrepStrip({ track, onError }: Props) {
}, [trackId])
const toggle = () => {
const el = audioRef.current
if (!el || !track) return
if (el.paused) {
el.play().catch(() => {
setLoadError(true)
const eng = playbackRef.current
if (!eng || !eng.ready) return
getCtx() // ensure the context resumes on this user gesture
if (eng.playing) {
eng.pause()
setPlaying(false)
})
} else {
el.pause()
eng.play()
setPlaying(true)
}
setCurrent(eng.getPosition())
}
// Smoothly advance the playhead while playing. HTMLAudioElement.currentTime
// only updates in coarse steps (tens of ms), which looks choppy when zoomed in,
// so we interpolate with the wall clock between the media clock's ticks and
// re-anchor whenever it actually advances.
// Follow the Web Audio clock while playing (high-res → smooth playhead).
useEffect(() => {
if (!playing) return
let raf = 0
let lastRaw = -1
let anchorAudio = 0
let anchorPerf = 0
const tick = () => {
const el = audioRef.current
if (el) {
const raw = el.currentTime
if (raw !== lastRaw) {
lastRaw = raw
anchorAudio = raw
anchorPerf = performance.now()
}
const est = anchorAudio + (performance.now() - anchorPerf) / 1000
setCurrent(duration ? Math.min(est, duration) : est)
}
const eng = playbackRef.current
if (eng) setCurrent(eng.getPosition())
raf = requestAnimationFrame(tick)
}
raf = requestAnimationFrame(tick)
return () => cancelAnimationFrame(raf)
}, [playing, duration])
}, [playing])
const seek = (t: number) => {
const el = audioRef.current
if (!el) return
el.currentTime = t
const eng = playbackRef.current
if (!eng) return
eng.seek(t)
setCurrent(t)
}
// ---- scratch (Web Audio) ----------------------------------------------
const getCtx = (): AudioContext => {
if (!audioCtxRef.current) {
audioCtxRef.current = new (window.AudioContext ??
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)()
}
void audioCtxRef.current.resume()
return audioCtxRef.current
}
// Once the platter has coasted to a stop (or up to normal speed), hand the
// position back to the <audio> element and resume if it had been playing.
// ---- scratch ----------------------------------------------------------
const finalizeScratch = () => {
cancelAnimationFrame(scratchRafRef.current)
engagedRef.current = false
const eng = engineRef.current
if (!eng) return
const finalSec = eng.end()
const el = audioRef.current
if (el) el.currentTime = finalSec
const sc = scratchRef.current
if (!sc) return
const finalSec = sc.end()
const pb = playbackRef.current
if (pb) pb.seek(finalSec)
setCurrent(finalSec)
if (wasPlayingRef.current && el) void el.play().catch(() => {})
if (wasPlayingRef.current && pb) {
pb.play()
setPlaying(true)
}
}
// Follow the engine's actual position each frame; finalize when it settles.
const runScratchRaf = () => {
cancelAnimationFrame(scratchRafRef.current)
const eng = engineRef.current!
const sc = scratchRef.current!
const tick = () => {
setCurrent(eng.getPositionSec())
if (eng.finished) {
setCurrent(sc.getPositionSec())
if (sc.finished) {
finalizeScratch()
return
}
@@ -191,43 +209,145 @@ export function PrepStrip({ track, onError }: Props) {
}
const onScratchStart = () => {
const eng = engineRef.current
// Re-grab while still coasting: keep the current position, resume dragging.
if (engagedRef.current && eng) {
eng.regrab()
const sc = scratchRef.current
if (engagedRef.current && sc) {
sc.regrab() // re-grab while coasting
return
}
const el = audioRef.current
wasPlayingRef.current = !!el && !el.paused
if (el && !el.paused) el.pause()
if (eng && eng.loaded) {
eng.begin(getCtx(), current)
const pb = playbackRef.current
wasPlayingRef.current = !!pb && pb.playing
if (pb && pb.playing) {
pb.pause()
setPlaying(false)
}
if (sc && sc.loaded) {
sc.begin(getCtx(), current)
engagedRef.current = true
runScratchRaf()
}
}
const onScratchMove = (t: number) => {
if (engagedRef.current) engineRef.current!.setTargetSec(t)
else setCurrent(t) // no decoded buffer yet → silent visual scrub
if (engagedRef.current) scratchRef.current!.setTargetSec(t)
else setCurrent(t)
}
const onScratchEnd = (t: number) => {
if (engagedRef.current) {
// Coast; runScratchRaf finalizes once the platter settles.
engineRef.current!.release(wasPlayingRef.current)
scratchRef.current!.release(wasPlayingRef.current)
} else {
const el = audioRef.current
if (el) el.currentTime = t
setCurrent(t)
if (wasPlayingRef.current && el) void el.play().catch(() => {})
seek(t)
if (wasPlayingRef.current) {
playbackRef.current?.play()
setPlaying(true)
}
}
}
const showWaves = track && !loadError && cols && waveStatus === 'ready'
// ---- loops ------------------------------------------------------------
// Snap a time to the nearest beat when Snap is on (needs a beatgrid).
const snapTime = (t: number) => {
const bpm = cueData?.bpm ?? null
const anchor = cueData?.grid_anchor ?? null
if (!snap || !bpm || bpm <= 0 || anchor == null) return Math.max(0, t)
const beat = 60 / bpm
return Math.max(0, anchor + Math.round((t - anchor) / beat) * beat)
}
const engagLoop = (start: number, end: number, beats: number | null) => {
const eng = playbackRef.current
if (!eng) return
eng.setLoop(start, end, true)
setLoopRegion({ start, end })
setLoopActive(true)
setActiveBeats(beats)
loopInRef.current = null
setCurrent(eng.getPosition())
}
const setBeatLoop = (beats: number) => {
const eng = playbackRef.current
const bpm = cueData?.bpm ?? null
if (!eng || !eng.ready || !bpm || bpm <= 0) return
const start = snapTime(eng.getPosition())
engagLoop(start, start + beats * (60 / bpm), beats)
}
const loopIn = () => {
const eng = playbackRef.current
if (!eng || !eng.ready) return
loopInRef.current = snapTime(eng.getPosition())
}
const loopOut = () => {
const eng = playbackRef.current
if (!eng || !eng.ready || loopInRef.current == null) return
const end = snapTime(eng.getPosition())
if (end <= loopInRef.current) return
engagLoop(loopInRef.current, end, null)
}
const toggleLoop = () => {
const eng = playbackRef.current
if (!eng || !loopRegion) return
const next = !loopActive
eng.setLoopEnabled(next)
setLoopActive(next)
setCurrent(eng.getPosition())
}
// ---- hotcues ----------------------------------------------------------
const hotcueAt = (slot: number) => cueData?.cues.find((c) => c.hotcue === slot) ?? null
const applyCueEdit = (fresh: TrackCues) => {
setCueData(fresh)
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['tracks'] })
qc.invalidateQueries({ queryKey: ['playlist'] })
}
const onSlotClick = async (slot: number) => {
if (!track) return
const cue = hotcueAt(slot)
if (cue) {
seek(cue.start)
setSelectedSlot(slot)
return
}
try {
const t = snapTime(playbackRef.current?.getPosition() ?? current)
applyCueEdit(await api.createHotcue(track.id, slot, t, 0))
setSelectedSlot(slot)
} catch (e) {
onError?.((e as Error).message)
}
}
const changeSelectedType = async (type: number) => {
if (!track || selectedSlot == null) return
try {
applyCueEdit(await api.setHotcueType(track.id, selectedSlot, type))
} catch (e) {
onError?.((e as Error).message)
}
}
const deleteSelected = async () => {
if (!track || selectedSlot == null) return
try {
applyCueEdit(await api.deleteHotcue(track.id, selectedSlot))
setSelectedSlot(null)
} catch (e) {
onError?.((e as Error).message)
}
}
const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null
const showWaves = track && cols && waveStatus === 'ready'
const activeLoop = loopActive && loopRegion ? loopRegion : null
return (
<div className="flex h-52 shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
<div className="flex h-72 shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
{/* Controls */}
<div className="flex w-72 shrink-0 flex-col justify-between bg-ink-900 px-4 py-3">
<div className="min-w-0">
@@ -248,7 +368,7 @@ export function PrepStrip({ track, onError }: Props) {
<div className="flex items-center gap-3">
<button
onClick={toggle}
disabled={!track || loadError}
disabled={!ready}
className="flex h-9 w-9 items-center justify-center rounded-full border border-line bg-ink-850 text-text hover:border-accent disabled:opacity-40 disabled:hover:border-line"
title={playing ? 'Pause' : 'Play'}
>
@@ -260,15 +380,15 @@ export function PrepStrip({ track, onError }: Props) {
</div>
</div>
{/* Waveforms: scrolling main view above a whole-track overview. */}
{/* Waveforms + loop/hotcue controls. */}
<div className="relative flex min-w-0 flex-1 flex-col bg-ink-900">
{!track ? (
<div className="flex flex-1 items-center justify-center text-xs text-faint">
Load a track to prep it
</div>
) : loadError ? (
) : waveStatus === 'error' ? (
<div className="flex flex-1 items-center justify-center text-xs text-pink">
Could not load audio — file may be missing or unsupported by the browser.
Could not load audio — file may be missing or an unsupported format.
</div>
) : (
<>
@@ -281,6 +401,7 @@ export function PrepStrip({ track, onError }: Props) {
cues={cueData?.cues ?? []}
bpm={cueData?.bpm ?? null}
gridAnchor={cueData?.grid_anchor ?? null}
loop={activeLoop}
onSeek={seek}
onScratchStart={onScratchStart}
onScratchMove={onScratchMove}
@@ -288,7 +409,7 @@ export function PrepStrip({ track, onError }: Props) {
/>
) : (
<div className="flex h-full items-center justify-center text-xs text-faint">
{waveStatus === 'error' ? 'Waveform unavailable' : 'Analysing waveform…'}
Analysing waveform…
</div>
)}
</div>
@@ -299,29 +420,62 @@ export function PrepStrip({ track, onError }: Props) {
currentTime={current}
duration={duration}
cues={cueData?.cues ?? []}
loop={activeLoop}
onSeek={seek}
/>
)}
</div>
<LoopControls
bpm={cueData?.bpm ?? null}
active={loopActive}
activeBeats={activeBeats}
canToggle={loopRegion != null}
snap={snap}
onToggleSnap={() => setSnap((s) => !s)}
onSetLoop={setBeatLoop}
onLoopIn={loopIn}
onLoopOut={loopOut}
onToggleActive={toggleLoop}
/>
<HotcueBar
cues={cueData?.cues ?? []}
selectedSlot={selectedSlot}
onSlotClick={onSlotClick}
/>
{/* Selected-hotcue editing: type + delete. */}
<div className="flex h-8 shrink-0 items-center gap-2 border-t border-line bg-ink-900 px-3 text-xs">
<span className="text-faint">
{selectedCue ? `Hotcue ${(selectedSlot ?? 0) + 1}` : 'No hotcue selected'}
</span>
<div className="flex-1" />
<select
value={selectedCue ? selectedCue.type : ''}
disabled={!selectedCue}
onChange={(e) => changeSelectedType(Number(e.target.value))}
className="rounded border border-line bg-ink-850 px-2 py-0.5 text-text outline-none focus:border-accent disabled:opacity-40"
>
{!selectedCue && <option value="">—</option>}
{CUE_TYPES.map((t) => (
<option key={t.value} value={t.value}>
{t.label}
</option>
))}
</select>
<button
onClick={deleteSelected}
disabled={!selectedCue}
title="Delete selected hotcue"
className="rounded border border-line px-2 py-0.5 text-muted hover:border-pink hover:text-pink disabled:opacity-40 disabled:hover:border-line disabled:hover:text-muted"
>
🗑
</button>
</div>
</>
)}
</div>
{track && (
<audio
ref={audioRef}
src={api.audioUrl(track.id)}
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
onEnded={() => setPlaying(false)}
onTimeUpdate={(e) => setCurrent(e.currentTarget.currentTime)}
onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}
onError={() => {
setLoadError(true)
onError?.('Could not load audio for this track')
}}
/>
)}
</div>
)
}
+55 -19
View File
@@ -1,18 +1,18 @@
import type { CuePoint } from '../api'
// Default marker colours by Traktor cue type, used when a cue has no explicit
// colour of its own.
// Marker colour by Traktor cue type. Type is authoritative here (the NML's
// stored per-cue colour is intentionally ignored) so each type reads consistently.
const TYPE_COLORS: Record<number, string> = {
0: '#4f8cff', // cue — accent blue
1: '#34d399', // fade-in — mint
2: '#34d399', // fade-out — mint
3: '#ffb020', // load — gold
5: '#f472b6', // loop — pink
0: '#3b82f6', // cue — blue
1: '#ff8c2f', // fade-in — orange
2: '#ff8c2f', // fade-out — orange
3: '#ffd60a', // load — yellow
5: '#22c55e', // loop — green
}
const OTHER_COLOR = '#8b93a3' // gray
export function cueColor(cue: CuePoint): string {
if (cue.color && /^#[0-9a-f]{6}$/i.test(cue.color)) return cue.color
return TYPE_COLORS[cue.type] ?? '#8b93a3'
return TYPE_COLORS[cue.type] ?? OTHER_COLOR
}
function withAlpha(hex: string, a: number): string {
@@ -22,6 +22,14 @@ function withAlpha(hex: string, a: number): string {
return `rgba(${r},${g},${b},${a})`
}
// Black or white text, whichever reads better on the given marker colour.
export function contrastText(hex: string): string {
const r = parseInt(hex.slice(1, 3), 16)
const g = parseInt(hex.slice(3, 5), 16)
const b = parseInt(hex.slice(5, 7), 16)
return 0.299 * r + 0.587 * g + 0.114 * b > 140 ? '#0a0b0f' : '#ffffff'
}
/**
* Draw cue/loop markers onto a canvas. `timeToX` maps a time (seconds) to a
* device-pixel x. With `labels`, a small numbered flag is drawn at the top for
@@ -37,7 +45,10 @@ export function drawCues(
labels: boolean,
): void {
const lineW = Math.max(2, Math.round(2 * dpr))
const flag = Math.round(13 * dpr)
const outline = Math.max(1, Math.round(dpr))
const flagW = Math.round(12 * dpr)
const flagH = Math.round(14 * dpr)
const half = Math.floor(lineW / 2)
for (const cue of cues) {
const color = cueColor(cue)
const x = Math.round(timeToX(cue.start))
@@ -46,24 +57,49 @@ export function drawCues(
if (cue.length > 0) {
const x2 = Math.round(timeToX(cue.start + cue.length))
if (x2 > 0 && x < w) {
ctx.fillStyle = withAlpha(color, 0.18)
ctx.fillStyle = withAlpha(color, 0.2)
ctx.fillRect(x, 0, Math.max(1, x2 - x), h)
}
}
if (x < -flag || x > w + flag) continue
ctx.fillStyle = color
ctx.fillRect(x - Math.floor(lineW / 2), 0, lineW, h)
if (x < -flagW || x > w + flagW) continue
if (labels && cue.hotcue >= 0) {
// Dark outline behind the line so it reads on any waveform colour.
ctx.fillStyle = 'rgba(0,0,0,0.7)'
ctx.fillRect(x - half - outline, 0, lineW + outline * 2, h)
ctx.fillStyle = color
ctx.fillRect(x, 0, flag, flag)
ctx.fillStyle = '#0a0b0f'
ctx.font = `${Math.round(9 * dpr)}px system-ui, sans-serif`
ctx.fillRect(x - half, 0, lineW, h)
if (labels) {
// A flag tab at the top for every cue (outlined), with the hotcue number.
ctx.fillStyle = 'rgba(0,0,0,0.7)'
ctx.fillRect(x - half - outline, 0, flagW + outline * 2, flagH + outline * 2)
ctx.fillStyle = color
ctx.fillRect(x - half, 0, flagW, flagH)
if (cue.hotcue >= 0) {
ctx.fillStyle = contrastText(color)
ctx.font = `bold ${Math.round(10 * dpr)}px system-ui, sans-serif`
ctx.textBaseline = 'top'
ctx.fillText(String(cue.hotcue + 1), x + Math.round(3 * dpr), Math.round(2 * dpr))
ctx.fillText(String(cue.hotcue + 1), x - half + Math.round(2 * dpr), Math.round(2 * dpr))
}
}
}
}
/** Draw the active loop region: a translucent green band with bright edges. */
export function drawLoop(
ctx: CanvasRenderingContext2D,
startX: number,
endX: number,
h: number,
dpr: number,
): void {
const edge = Math.max(1, Math.round(2 * dpr))
ctx.fillStyle = 'rgba(34,197,94,0.18)'
ctx.fillRect(startX, 0, Math.max(1, endX - startX), h)
ctx.fillStyle = 'rgba(34,197,94,0.95)'
ctx.fillRect(startX, 0, edge, h)
ctx.fillRect(endX - edge, 0, edge, h)
}
/**
+152
View File
@@ -0,0 +1,152 @@
// Web Audio playback for the prep deck. Plays the already-decoded AudioBuffer
// through an AudioBufferSourceNode, which gives sample-accurate, gapless loops
// via native loopStart/loopEnd — something an <audio> element can't do.
//
// A source node is one-shot, so play/seek recreate it; position is derived from
// the AudioContext clock (high-resolution, so the playhead is smooth without any
// wall-clock interpolation). Loop bounds can be changed on the live node, so
// enabling a loop mid-playback is seamless.
export class PlaybackEngine {
private ctx: AudioContext | null = null
private buffer: AudioBuffer | null = null
private gain: GainNode | null = null
private source: AudioBufferSourceNode | null = null
private startedAt = 0 // ctx time when the current source started
private startOffset = 0 // buffer position (s) at that moment / paused position
private _playing = false
private loopOn = false
private loopStart = 0
private loopEnd = 0
private onEnded: (() => void) | null = null
load(ctx: AudioContext, buffer: AudioBuffer): void {
this.ctx = ctx
this.buffer = buffer
if (!this.gain) {
this.gain = ctx.createGain()
this.gain.connect(ctx.destination)
}
this.stopSource()
this._playing = false
this.startOffset = 0
this.loopOn = false
}
setOnEnded(cb: () => void): void {
this.onEnded = cb
}
get ready(): boolean {
return !!this.buffer
}
get playing(): boolean {
return this._playing
}
get duration(): number {
return this.buffer?.duration ?? 0
}
get loopEnabled(): boolean {
return this.loopOn
}
getPosition(): number {
if (!this.buffer || !this.ctx || !this._playing) return this.startOffset
let pos = this.startOffset + (this.ctx.currentTime - this.startedAt)
if (this.loopOn && this.loopEnd > this.loopStart && pos >= this.loopEnd) {
const len = this.loopEnd - this.loopStart
pos = this.loopStart + ((pos - this.loopStart) % len)
}
return Math.min(pos, this.buffer.duration)
}
private startSource(offset: number): void {
if (!this.ctx || !this.buffer || !this.gain) return
const src = this.ctx.createBufferSource()
src.buffer = this.buffer
if (this.loopOn && this.loopEnd > this.loopStart) {
src.loop = true
src.loopStart = this.loopStart
src.loopEnd = this.loopEnd
}
src.connect(this.gain)
src.onended = () => {
if (this.source === src) {
// Natural end (our own stops null out onended first).
this._playing = false
this.source = null
this.onEnded?.()
}
}
const off = Math.max(0, Math.min(offset, this.buffer.duration - 0.001))
src.start(0, off)
this.source = src
this.startedAt = this.ctx.currentTime
this.startOffset = offset
this._playing = true
}
private stopSource(): void {
if (this.source) {
this.source.onended = null
try {
this.source.stop()
} catch {
/* already stopped */
}
this.source.disconnect()
this.source = null
}
}
play(): void {
if (!this.ctx || !this.buffer || this._playing) return
void this.ctx.resume()
let off = this.startOffset
if (off >= this.buffer.duration - 0.01) off = 0 // restart from top if at the end
this.startSource(off)
}
pause(): void {
if (!this._playing) return
this.startOffset = this.getPosition()
this.stopSource()
this._playing = false
}
seek(t: number): void {
const clamped = Math.max(0, Math.min(t, this.duration))
if (this._playing) {
this.stopSource()
this.startOffset = clamped
this.startSource(clamped)
} else {
this.startOffset = clamped
}
}
/** Set the loop region and whether it's active. Bounds apply live if playing. */
setLoop(start: number, end: number, enabled: boolean): void {
this.loopStart = start
this.loopEnd = end
this.loopOn = enabled
if (this.source) {
if (enabled && end > start) {
this.source.loop = true
this.source.loopStart = start
this.source.loopEnd = end
} else {
this.source.loop = false
}
}
// If the playhead is already past the loop, jump into it so it engages now.
if (enabled && this._playing) {
const pos = this.getPosition()
if (pos >= end) this.seek(start)
}
}
setLoopEnabled(enabled: boolean): void {
this.setLoop(this.loopStart, this.loopEnd, enabled)
}
}