Implemented beatgrid controls

This commit is contained in:
Ben committed 2026-07-04 21:12:25 +02:00
1 parent 14f5bf3774
commit 815b700075
8 files changed
+457 -23

No files matched your search

+35 -1
View File
@@ -25,6 +25,7 @@ from .schemas import (
FileTagOutcome, FileTagOutcome,
FsEntry, FsEntry,
FsListing, FsListing,
GridEdit,
OpenCollection, OpenCollection,
PlaylistNode, PlaylistNode,
RenamePlaylist, RenamePlaylist,
@@ -32,6 +33,7 @@ from .schemas import (
SetEntries, SetEntries,
SetHotcue, SetHotcue,
SetHotcueType, SetHotcueType,
SetLock,
Stats, Stats,
Track, Track,
TrackCues, TrackCues,
@@ -355,7 +357,9 @@ def _build_track_cues(entry) -> TrackCues:
) )
) )
bpm = grid_bpm if grid_bpm is not None else (entry.tempo.bpm if entry.tempo else None) bpm = grid_bpm if grid_bpm is not None else (entry.tempo.bpm if entry.tempo else None)
return TrackCues(bpm=bpm, grid_anchor=grid_anchor, cues=cues) return TrackCues(
bpm=bpm, grid_anchor=grid_anchor, locked=bool(entry.lock), cues=cues
)
def _cues_for(track_id: str) -> TrackCues: def _cues_for(track_id: str) -> TrackCues:
@@ -412,6 +416,36 @@ def delete_hotcue(track_id: str, slot: int) -> TrackCues:
return _sync_cue_edit(track_id) return _sync_cue_edit(track_id)
@app.patch("/api/tracks/grid", response_model=TrackCues)
def edit_grid(body: GridEdit) -> TrackCues:
"""Set the beatgrid BPM and/or move the grid marker (beat 1)."""
try:
require_store().set_grid(body.track_id, body.bpm, body.anchor)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.delete("/api/tracks/grid", response_model=TrackCues)
def remove_grid(track_id: str) -> TrackCues:
"""Delete the track's grid marker(s)."""
try:
require_store().delete_grid(track_id)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(track_id)
@app.patch("/api/tracks/lock", response_model=TrackCues)
def edit_lock(body: SetLock) -> TrackCues:
"""Toggle Traktor's LOCK flag on a track."""
try:
require_store().set_lock(body.track_id, body.locked)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
@app.put("/api/tracks/art") @app.put("/api/tracks/art")
async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) -> dict: 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).""" """Stage replacement cover art for a track (written to the file on save)."""
+65
View File
@@ -33,11 +33,13 @@ from traktor_nml_utils.models.collection import (
Albumtype, Albumtype,
CueV2Type, CueV2Type,
Entrytype, Entrytype,
GridType,
Infotype, Infotype,
Nodetype, Nodetype,
Playlisttype, Playlisttype,
Primarykeytype, Primarykeytype,
Subnodestype, Subnodestype,
Tempotype,
) )
from xsdata.formats.dataclass.serializers import XmlSerializer from xsdata.formats.dataclass.serializers import XmlSerializer
@@ -336,6 +338,69 @@ class PlaylistStore:
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot] entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot]
self.dirty = True self.dirty = True
# ---- beatgrid -----------------------------------------------------
@staticmethod
def _grid_marker(entry: Entrytype) -> CueV2Type | None:
return next(
(c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None), None
)
def set_grid(
self, track_id: str, bpm: float | None = None, anchor_sec: float | None = None
) -> None:
"""Set the beatgrid tempo (TEMPO + grid marker BPM) and/or move the grid
marker (beat 1). Creates a grid marker if the track has none."""
with self._lock:
entry = self._entry_or_raise(track_id)
marker = self._grid_marker(entry)
if bpm is not None:
if bpm <= 0:
raise PlaylistError(f"BPM must be positive: {bpm}")
if entry.tempo is None:
entry.tempo = Tempotype(bpm=bpm, bpm_quality=100.0)
else:
entry.tempo.bpm = bpm
if marker is not None and marker.grid is not None:
marker.grid.bpm = bpm
if anchor_sec is not None:
start_ms = max(0.0, anchor_sec * 1000.0)
if marker is not None:
marker.start = start_ms
else:
grid_bpm = bpm if bpm is not None else (entry.tempo.bpm if entry.tempo else None)
if grid_bpm is None:
raise PlaylistError("No BPM available to create a beatgrid")
if entry.cue_v2 is None:
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
name="AutoGrid",
displ_order=0,
type=4,
start=start_ms,
len=0.0,
repeats=-1,
hotcue=-1,
color=None,
grid=GridType(bpm=grid_bpm),
)
)
self.dirty = True
def delete_grid(self, track_id: str) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
entry.cue_v2 = [
c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is None
]
self.dirty = True
def set_lock(self, track_id: str, locked: bool) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
entry.lock = 1 if locked else None
self.dirty = True
# ---- cover art ----------------------------------------------------- # ---- cover art -----------------------------------------------------
def set_track_art(self, track_id: str, data: bytes, mime: str) -> None: def set_track_art(self, track_id: str, data: bytes, mime: str) -> None:
with self._lock: with self._lock:
+12
View File
@@ -130,9 +130,21 @@ class CuePoint(BaseModel):
class TrackCues(BaseModel): class TrackCues(BaseModel):
bpm: float | None = None # beatgrid BPM (from the grid marker; falls back to tempo) bpm: float | None = None # beatgrid BPM (from the grid marker; falls back to tempo)
grid_anchor: float | None = None # seconds — first grid marker (beat 1 of the grid) grid_anchor: float | None = None # seconds — first grid marker (beat 1 of the grid)
locked: bool = False # Traktor LOCK flag
cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded) cues: list[CuePoint] = [] # cue/loop markers (grid markers excluded)
class GridEdit(BaseModel):
track_id: str
bpm: float | None = None # set the beatgrid tempo
anchor: float | None = None # set the grid marker (beat 1) position, in seconds
class SetLock(BaseModel):
track_id: str
locked: bool
class SetHotcue(BaseModel): class SetHotcue(BaseModel):
track_id: str track_id: str
slot: int # 0–7 slot: int # 0–7
+66
View File
@@ -226,5 +226,71 @@ with tempfile.TemporaryDirectory() as d:
store2.save() store2.save()
check("create+delete round-trips to the original bytes", work.read_bytes() == original) check("create+delete round-trips to the original bytes", work.read_bytes() == original)
# ---- Invariant E: a beatgrid edit is fully localized -------------------
print("== E. grid/bpm edit 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)
# first entry that has both a tempo and a grid marker
entry = next(
e
for e in store._nml.collection.entry
if e.tempo and store._grid_marker(e) is not None
)
loc = entry.location
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
orig_bpm = entry.tempo.bpm
store.set_grid(track_id, bpm=orig_bpm / 2, anchor_sec=1.5)
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:],
)
from traktor_nml_utils import TraktorCollection
reparsed = TraktorCollection(path=work)
e0 = next(
e
for e in reparsed.nml.collection.entry
if e.location
and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id
)
m = store._grid_marker(e0)
check("tempo BPM halved + persisted", abs(e0.tempo.bpm - orig_bpm / 2) < 1e-3)
check("grid marker BPM matches tempo", m is not None and abs(m.grid.bpm - orig_bpm / 2) < 1e-3)
check("grid anchor moved to 1.5s (1500 ms)", m is not None and abs(m.start - 1500.0) < 1)
# Reverting BPM + anchor to the original values round-trips to the file.
orig_anchor_ms = store._grid_marker(
next(
e
for e in TraktorCollection(path=REAL).nml.collection.entry
if e.location
and f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}" == track_id
)
).start
store2 = PlaylistStore(work)
store2.set_grid(track_id, bpm=orig_bpm, anchor_sec=orig_anchor_ms / 1000.0)
store2.save()
check("revert BPM + anchor round-trips to original bytes", work.read_bytes() == original)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+7
View File
@@ -109,6 +109,7 @@ export interface CuePoint {
export interface TrackCues { export interface TrackCues {
bpm: number | null bpm: number | null
grid_anchor: number | null // seconds grid_anchor: number | null // seconds
locked: boolean
cues: CuePoint[] cues: CuePoint[]
} }
@@ -233,6 +234,12 @@ export const api = {
'DELETE', 'DELETE',
`/api/tracks/hotcue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, `/api/tracks/hotcue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`,
), ),
setGrid: (trackId: string, patch: { bpm?: number; anchor?: number }) =>
send<TrackCues>('PATCH', '/api/tracks/grid', { track_id: trackId, ...patch }),
deleteGrid: (trackId: string) =>
send<TrackCues>('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`),
setLock: (trackId: string, locked: boolean) =>
send<TrackCues>('PATCH', '/api/tracks/lock', { track_id: trackId, locked }),
uploadArt: async (trackId: string, file: File) => { uploadArt: async (trackId: string, file: File) => {
const fd = new FormData() const fd = new FormData()
fd.append('track_id', trackId) fd.append('track_id', trackId)
+157
View File
@@ -0,0 +1,157 @@
import { useRef, useState } from 'react'
interface Props {
bpm: number | null
locked: boolean
hasGrid: boolean
onSetBpm: (bpm: number) => void
onHalve: () => void
onDouble: () => void
onNudge: (deltaMs: number) => void
onSetHere: () => void
onReset: () => void
onToggleLock: () => void
onDeleteGrid: () => void
}
const BTN =
'flex flex-1 items-center justify-center rounded border border-line bg-ink-850 py-1 text-xs ' +
'font-semibold text-text transition-colors hover:border-accent disabled:opacity-30 ' +
'disabled:hover:border-line'
/**
* Beatgrid / tempo panel (Traktor grid-control equivalent): editable BPM, half/
* double, tap tempo, grid-phase nudge (±1/±10 ms), set beat 1 at the playhead,
* reset to the loaded values, lock, and delete grid.
*/
export function GridControls({
bpm,
locked,
hasGrid,
onSetBpm,
onHalve,
onDouble,
onNudge,
onSetHere,
onReset,
onToggleLock,
onDeleteGrid,
}: Props) {
const [editing, setEditing] = useState(false)
const [val, setVal] = useState('')
const tapsRef = useRef<number[]>([])
const commit = () => {
const n = parseFloat(val)
if (isFinite(n) && n > 0) onSetBpm(Math.round(n * 1000) / 1000)
setEditing(false)
}
const tap = () => {
const now = performance.now()
const taps = tapsRef.current
if (taps.length && now - taps[taps.length - 1] > 2000) taps.length = 0 // reset after a pause
taps.push(now)
if (taps.length > 8) taps.shift()
if (taps.length >= 2) {
const first = taps[0]
const avg = (now - first) / (taps.length - 1)
onSetBpm(Math.round((60000 / avg) * 1000) / 1000)
}
}
return (
<div className="flex flex-col gap-2">
{/* BPM readout / editor */}
<div className="text-center">
{editing ? (
<input
autoFocus
value={val}
onChange={(e) => setVal(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === 'Enter') commit()
if (e.key === 'Escape') setEditing(false)
}}
className="w-28 rounded bg-ink-850 py-0.5 text-center text-2xl font-semibold tabular-nums text-text outline-none"
/>
) : (
<button
onClick={() => {
setVal(bpm != null ? bpm.toFixed(3) : '')
setEditing(true)
}}
className="text-2xl font-semibold tabular-nums text-text hover:text-accent"
title="Click to type an exact BPM"
>
{bpm != null ? bpm.toFixed(2) : '––'}
</button>
)}
<div className="text-[10px] font-semibold uppercase tracking-wider text-faint">BPM</div>
</div>
{/* halve / double / tap / reset */}
<div className="flex gap-1">
<button className={BTN} onClick={onHalve} disabled={bpm == null} title="Halve BPM">
/2
</button>
<button className={BTN} onClick={onDouble} disabled={bpm == null} title="Double BPM">
×2
</button>
<button className={BTN} onClick={tap} title="Tap tempo">
TAP
</button>
<button className={BTN} onClick={onReset} title="Reset to loaded values">
Reset
</button>
</div>
{/* grid-phase nudge + set beat 1 */}
<div className="flex items-center gap-1">
<span className="mr-0.5 text-[10px] font-semibold uppercase tracking-wider text-faint">
Grid
</span>
<button className={BTN} onClick={() => onNudge(-10)} disabled={!hasGrid} title="−10 ms">
◀◀
</button>
<button className={BTN} onClick={() => onNudge(-1)} disabled={!hasGrid} title="−1 ms">
◀
</button>
<button className={BTN} onClick={onSetHere} title="Set beat 1 at the playhead">
SET
</button>
<button className={BTN} onClick={() => onNudge(1)} disabled={!hasGrid} title="+1 ms">
▶
</button>
<button className={BTN} onClick={() => onNudge(10)} disabled={!hasGrid} title="+10 ms">
▶▶
</button>
</div>
{/* lock / delete grid */}
<div className="flex gap-1">
<button
onClick={onToggleLock}
title={locked ? 'Unlock track' : 'Lock track'}
className={
'flex flex-1 items-center justify-center gap-1 rounded border py-1 text-xs font-semibold transition-colors ' +
(locked
? 'border-gold bg-gold/15 text-gold'
: 'border-line bg-ink-850 text-text hover:border-accent')
}
>
{locked ? '🔒 Locked' : '🔓 Lock'}
</button>
<button
className={BTN}
onClick={onDeleteGrid}
disabled={!hasGrid}
title="Delete beatgrid"
>
🗑 Grid
</button>
</div>
</div>
)
}
+84 -6
View File
@@ -4,6 +4,7 @@ import { api, type Track, type TrackCues } from '../api'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine' import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine' import { PlaybackEngine } from '../lib/playbackEngine'
import { GridControls } from './GridControls'
import { HotcueBar } from './HotcueBar' import { HotcueBar } from './HotcueBar'
import { LoopControls } from './LoopControls' import { LoopControls } from './LoopControls'
import { MainWaveform } from './MainWaveform' import { MainWaveform } from './MainWaveform'
@@ -55,8 +56,10 @@ export function PrepStrip({ track, onError }: Props) {
const [loopActive, setLoopActive] = useState(false) const [loopActive, setLoopActive] = useState(false)
const [activeBeats, setActiveBeats] = useState<number | null>(null) const [activeBeats, setActiveBeats] = useState<number | null>(null)
const loopInRef = useRef<number | null>(null) // armed manual loop-in point const loopInRef = useRef<number | null>(null) // armed manual loop-in point
const originalGridRef = useRef<{ bpm: number | null; anchor: number | null } | null>(null)
const audioCtxRef = useRef<AudioContext | null>(null) const audioCtxRef = useRef<AudioContext | null>(null) // playback
const scratchCtxRef = useRef<AudioContext | null>(null) // scratch (kept separate!)
const playbackRef = useRef<PlaybackEngine | null>(null) const playbackRef = useRef<PlaybackEngine | null>(null)
const scratchRef = useRef<ScratchEngine | null>(null) const scratchRef = useRef<ScratchEngine | null>(null)
const wasPlayingRef = useRef(false) const wasPlayingRef = useRef(false)
@@ -74,6 +77,18 @@ export function PrepStrip({ track, onError }: Props) {
return audioCtxRef.current return audioCtxRef.current
} }
// The scratch engine gets its OWN AudioContext: a ScriptProcessorNode is
// unreliable sharing a context with the playback source node (it goes silent
// once a source has played), so we keep them fully separate.
const getScratchCtx = (): AudioContext => {
if (!scratchCtxRef.current) {
scratchCtxRef.current = new (window.AudioContext ??
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)()
}
void scratchCtxRef.current.resume()
return scratchCtxRef.current
}
// Reset transport + loop state when the loaded track changes. // Reset transport + loop state when the loaded track changes.
useEffect(() => { useEffect(() => {
playbackRef.current?.pause() playbackRef.current?.pause()
@@ -91,6 +106,7 @@ export function PrepStrip({ track, onError }: Props) {
// Analyse once per track; the decoded buffer feeds both the playback and // Analyse once per track; the decoded buffer feeds both the playback and
// scratch engines (no re-decode) and both waveform views share the columns. // scratch engines (no re-decode) and both waveform views share the columns.
useEffect(() => { useEffect(() => {
scratchRef.current?.dispose()
scratchRef.current = null scratchRef.current = null
if (!trackId) { if (!trackId) {
setCols(null) setCols(null)
@@ -105,10 +121,11 @@ export function PrepStrip({ track, onError }: Props) {
if (cancelled) return if (cancelled) return
setCols(res.cols) setCols(res.cols)
setWaveStatus('ready') setWaveStatus('ready')
const ctx = getCtx()
const sc = new ScratchEngine() const sc = new ScratchEngine()
sc.load(res.buffer) sc.load(res.buffer)
sc.attach(getScratchCtx()) // own context; warm up so the first scratch isn't silent
scratchRef.current = sc scratchRef.current = sc
const ctx = getCtx()
if (!playbackRef.current) { if (!playbackRef.current) {
playbackRef.current = new PlaybackEngine() playbackRef.current = new PlaybackEngine()
playbackRef.current.setOnEnded(() => setPlaying(false)) playbackRef.current.setOnEnded(() => setPlaying(false))
@@ -136,7 +153,10 @@ export function PrepStrip({ track, onError }: Props) {
api api
.trackCues(trackId) .trackCues(trackId)
.then((d) => { .then((d) => {
if (!cancelled) setCueData(d) if (cancelled) return
setCueData(d)
// Remember the loaded grid values for "Reset".
originalGridRef.current = { bpm: d.bpm, anchor: d.grid_anchor }
}) })
.catch(() => { .catch(() => {
if (!cancelled) setCueData(null) if (!cancelled) setCueData(null)
@@ -233,7 +253,7 @@ export function PrepStrip({ track, onError }: Props) {
setPlaying(false) setPlaying(false)
} }
if (sc && sc.loaded) { if (sc && sc.loaded) {
sc.begin(getCtx(), current) sc.begin(getScratchCtx(), current)
engagedRef.current = true engagedRef.current = true
runScratchRaf() runScratchRaf()
} }
@@ -393,6 +413,48 @@ export function PrepStrip({ track, onError }: Props) {
} }
} }
// ---- beatgrid ---------------------------------------------------------
const gridBpm = cueData?.bpm ?? null
const gridAnchor = cueData?.grid_anchor ?? null
const editGrid = async (patch: { bpm?: number; anchor?: number }) => {
if (!track) return
try {
applyCueEdit(await api.setGrid(track.id, patch))
} catch (e) {
onError?.((e as Error).message)
}
}
const setBpm = (bpm: number) => editGrid({ bpm })
const halveBpm = () => gridBpm && editGrid({ bpm: gridBpm / 2 })
const doubleBpm = () => gridBpm && editGrid({ bpm: gridBpm * 2 })
const nudgeGrid = (deltaMs: number) => {
if (gridAnchor == null) return
editGrid({ anchor: Math.max(0, gridAnchor + deltaMs / 1000) })
}
const setGridHere = () => editGrid({ anchor: playbackRef.current?.getPosition() ?? current })
const resetGrid = () => {
const o = originalGridRef.current
if (!o) return
editGrid({ bpm: o.bpm ?? undefined, anchor: o.anchor ?? undefined })
}
const toggleLock = async () => {
if (!track) return
try {
applyCueEdit(await api.setLock(track.id, !cueData?.locked))
} catch (e) {
onError?.((e as Error).message)
}
}
const deleteGrid = async () => {
if (!track) return
try {
applyCueEdit(await api.deleteGrid(track.id))
} catch (e) {
onError?.((e as Error).message)
}
}
const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null
const showWaves = track && cols && waveStatus === 'ready' const showWaves = track && cols && waveStatus === 'ready'
const activeLoop = loopActive && loopRegion ? loopRegion : null const activeLoop = loopActive && loopRegion ? loopRegion : null
@@ -400,7 +462,7 @@ export function PrepStrip({ track, onError }: Props) {
return ( return (
<div className="flex h-72 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 */} {/* Controls */}
<div className="flex w-72 shrink-0 flex-col justify-between bg-ink-900 px-4 py-3"> <div className="flex w-72 shrink-0 flex-col gap-3 bg-ink-900 px-4 py-3">
<div className="min-w-0"> <div className="min-w-0">
{track ? ( {track ? (
<> <>
@@ -416,7 +478,23 @@ export function PrepStrip({ track, onError }: Props) {
)} )}
</div> </div>
<div className="flex items-center gap-3"> {track && (
<GridControls
bpm={gridBpm}
locked={cueData?.locked ?? false}
hasGrid={gridAnchor != null}
onSetBpm={setBpm}
onHalve={halveBpm}
onDouble={doubleBpm}
onNudge={nudgeGrid}
onSetHere={setGridHere}
onReset={resetGrid}
onToggleLock={toggleLock}
onDeleteGrid={deleteGrid}
/>
)}
<div className="mt-auto flex items-center gap-3">
<button <button
onClick={toggle} onClick={toggle}
disabled={!ready} disabled={!ready}
+31 -16
View File
@@ -7,11 +7,12 @@
// On release the engine coasts: it keeps the drag velocity and eases it toward a // On release the engine coasts: it keeps the drag velocity and eases it toward a
// target speed with friction (momentum/flywheel feel) — to a stop if playback was // target speed with friction (momentum/flywheel feel) — to a stop if playback was
// paused, or up to normal speed if it was playing. When it settles, `finished` // paused, or up to normal speed if it was playing. When it settles, `finished`
// flips true and the caller hands the position back to the <audio> element. // flips true and the caller hands the position back to the playback engine.
// //
// Uses a ScriptProcessorNode: deprecated but universally supported and runs on // The ScriptProcessorNode is created ONCE (via attach) and kept alive, sitting in
// the main thread, so `position`/`finished` are directly readable for visual // an 'idle' mode that outputs silence between scratches. Creating it fresh per
// sync. Moving to an AudioWorklet is the natural hardening step later. // scratch caused a start-up delay where a short drag was silent until the node
// began firing; a warmed-up persistent node produces sound immediately.
const BUFFER_SIZE = 512 const BUFFER_SIZE = 512
const GLIDE = 400 // samples: how tightly position chases the target while dragging const GLIDE = 400 // samples: how tightly position chases the target while dragging
@@ -19,7 +20,7 @@ const RATE_CAP = 12 // max samples advanced per output sample (pitch ceiling)
const INERTIA_FRICTION = 0.9998 // per-sample easing toward the target velocity (~0.4s spin-down) const INERTIA_FRICTION = 0.9998 // per-sample easing toward the target velocity (~0.4s spin-down)
const SETTLE_EPS = 0.02 // |velocity - target| below this → settled const SETTLE_EPS = 0.02 // |velocity - target| below this → settled
type Mode = 'drag' | 'inertia' | 'done' type Mode = 'idle' | 'drag' | 'inertia' | 'done'
export class ScratchEngine { export class ScratchEngine {
private channels: Float32Array[] = [] private channels: Float32Array[] = []
@@ -31,12 +32,15 @@ export class ScratchEngine {
private target = 0 // drag target, in source samples private target = 0 // drag target, in source samples
private velocity = 0 // source samples advanced per output sample private velocity = 0 // source samples advanced per output sample
private targetVelocity = 0 // inertia goal private targetVelocity = 0 // inertia goal
private mode: Mode = 'drag' private mode: Mode = 'idle'
load(buffer: AudioBuffer): void { load(buffer: AudioBuffer): void {
// COPY the PCM — do NOT hold getChannelData() views. When the playback engine
// plays this same AudioBuffer, the browser (Firefox) "acquires the content"
// and detaches those views to zero-length, which would silence the scratch.
this.channels = [] this.channels = []
for (let c = 0; c < buffer.numberOfChannels; c++) { for (let c = 0; c < buffer.numberOfChannels; c++) {
this.channels.push(buffer.getChannelData(c)) this.channels.push(new Float32Array(buffer.getChannelData(c)))
} }
this.length = buffer.length this.length = buffer.length
this.sr = buffer.sampleRate this.sr = buffer.sampleRate
@@ -54,14 +58,9 @@ export class ScratchEngine {
return this.position / this.sr return this.position / this.sr
} }
/** Enter scratch mode at the given position (creates the audio node if needed). */ /** Create the (persistent, idle) audio node once. Safe to call repeatedly. */
begin(ctx: AudioContext, positionSec: number): void { attach(ctx: AudioContext): void {
if (!this.loaded) return
this.ctxRate = ctx.sampleRate this.ctxRate = ctx.sampleRate
this.position = positionSec * this.sr
this.target = this.position
this.velocity = 0
this.mode = 'drag'
if (!this.node) { if (!this.node) {
const node = ctx.createScriptProcessor(BUFFER_SIZE, 0, 2) const node = ctx.createScriptProcessor(BUFFER_SIZE, 0, 2)
node.onaudioprocess = (e) => this.render(e) node.onaudioprocess = (e) => this.render(e)
@@ -70,6 +69,16 @@ export class ScratchEngine {
} }
} }
/** Enter scratch mode at the given position (node is already running). */
begin(ctx: AudioContext, positionSec: number): void {
if (!this.loaded) return
this.attach(ctx)
this.position = positionSec * this.sr
this.target = this.position
this.velocity = 0
this.mode = 'drag'
}
/** Re-grab while the platter is still coasting: resume dragging from here. */ /** Re-grab while the platter is still coasting: resume dragging from here. */
regrab(): void { regrab(): void {
this.mode = 'drag' this.mode = 'drag'
@@ -87,14 +96,19 @@ export class ScratchEngine {
this.mode = 'inertia' this.mode = 'inertia'
} }
/** Tear down the audio node; returns the final position (seconds). */ /** Leave scratch mode; the node stays alive (idle). Returns final position (s). */
end(): number { end(): number {
this.mode = 'idle'
return this.position / this.sr
}
/** Tear down the node (on track change / unmount). */
dispose(): void {
if (this.node) { if (this.node) {
this.node.disconnect() this.node.disconnect()
this.node.onaudioprocess = null this.node.onaudioprocess = null
this.node = null this.node = null
} }
return this.position / this.sr
} }
private sample(outs: Float32Array[], i: number, chN: number): void { private sample(outs: Float32Array[], i: number, chN: number): void {
@@ -138,6 +152,7 @@ export class ScratchEngine {
this.mode = 'done' this.mode = 'done'
} }
} else { } else {
// idle / done → silent (node stays alive and firing).
this.silence(outs, i, chN) this.silence(outs, i, chN)
continue continue
} }