Compare commits

...
3 Commits
Author SHA1 Message Date
patben8 1bd65ea707 Improved scratching engine 2026-11-05 11:57:43 +01:00
patben8 2afba4557c Paused decks now always scratch when jog wheel is moved 2026-11-05 11:33:45 +01:00
patben8 aaa7537d50 Filter FXs are now post-fader 2026-11-05 11:24:57 +01:00
9 changed files with 454 additions and 76 deletions

No files matched your search

+24 -8
View File
@@ -1552,8 +1552,10 @@ Two independent apps that talk over HTTP:
browse: All Tracks + the visible tree; a playlist opens as reached, a
folder opens on press). **Jog** (`useDeck`): touch = scratch through the
waveform-drag path, target sent straight to the worklet; no touch =
nudge (a per-frame bend, also in prep mode) while playing, scrub while
paused; scale `JOG_SEC_PER_TICK` × the mapping's sensitivity. **UI**:
nudge (a per-frame bend, also in prep mode) while playing; while paused
a turn SCRATCHES too (decided 2026-11-05: grabbed on the first tick,
released `JOG_SCRATCH_IDLE_MS` after the last, so a jog without a touch
sensor still cues by ear); fast scrub stays a seek; scale `JOG_SEC_PER_TICK` × the mapping's sensitivity. **UI**:
Settings ▸ MIDI Controllers… (`MidiSettings`: per controller, Shift, jog
sensitivity / fast scrub, every action × Normal / Shift with Learn,
encoding + Reversed per binding, Import / Export as
@@ -2853,9 +2855,21 @@ The prep strip plays every track through the **Web Audio API** (a plain
performance mode; [the discussion](.claude/discussions/discuss-performance-mode-2026-11-02.md)).
`deckCore.ts` renders a deck block by block: transport, seamless loops, the
stems in lockstep (ONE position for all), mute/solo as ramped gains,
varispeed (cubic interpolation) and scratch (the old ScriptProcessor's
drag/inertia feel; a release coasts and the deck PLAYS ON BY ITSELF, so there
is no gap). `deckProcessor.worklet.ts` wraps it (`?worker&url`, bundled
varispeed (cubic interpolation) and scratch (a release coasts and the deck
PLAYS ON BY ITSELF, so there is no gap). **Scratch is rebuilt for sound**
(2026-11-05): the hand's position arrives in STEPS (mouse ~60 Hz, a jog up
to one per block, bunched by the main thread), and chasing each step with a
one-pole made the speed swing ±67-83% at that rate — buzzing, with a click
each time it caught up (a hard mute at rest). Now the steps are joined into
a line played `handDelay` behind the newest (adapted to their spacing,
6-30 ms), followed by a critically damped spring (`SCRATCH_HZ` 45), so the
speed is continuous; volume follows speed; above 1x the source is averaged
over the span each frame covers (anti-aliasing); targets are RELATIVE to
the position given at the grab (`scratchBegin` / `scratchRegrab(sec)`), so a
stale main-thread position cannot jump it, and grabbing a playing deck
brakes from its speed. Measured (`deckCore.test.ts` "scratch sound"): speed
ripple 0 for even steps, 3% for jittery bursts; lag 13.5 ms (a jog every
block) to ~30 ms (mouse). `deckProcessor.worklet.ts` wraps it (`?worker&url`, bundled
self-contained); `deckEngine.ts` is the main thread's handle, with the old
PlaybackEngine's surface: commands are async, so it answers from a model
(last report + context clock, `position.ts`) that each command updates at
@@ -2882,7 +2896,9 @@ The prep strip plays every track through the **Web Audio API** (a plain
(LR4 crossovers at 250 Hz / 2.5 kHz, the low band through a 2.5 kHz
all-pass, so the bands sum flat — measured 0.0000 dB; Web Audio's
lowpass/highpass Q is in DB, Butterworth = -3.01, its allpass Q linear) →
FILTER FX (`FilterFx`, decided 2026-11-03 after Traktor's mixer: the
fader → FILTER FX, POST-fader (decided 2026-11-05: pulling the fader down
stops feeding the reverb / delay and their tails ring out rather than
being cut with it) (`FilterFx`, decided 2026-11-03 after Traktor's mixer: the
FILTER knob always filters — 4-pole, low-pass left / high-pass right, over
a RANGE: FULL (to 20 Hz / 20 kHz: a 100 Hz bass -56 dB at full left,
measured; one 12 dB stage left it at -28), MUSICAL (150 Hz / 8 kHz) or
@@ -2906,14 +2922,14 @@ The prep strip plays every track through the **Web Audio API** (a plain
knob, -54 at 60%). Resonance fades over the last stretch of the sweep (no
boom at 20 Hz). Each effect's one parameter is an APP SETTING, not a knob —
`mixerState.fx`; all built once and switched by gains) →
fader → crossfader (`xfadeGains(x, sharpness)`: each channel fades on a
crossfader (`xfadeGains(x, sharpness)`: each channel fades on a
quarter-cosine over the last `xfadeWidth` of the travel — the whole of it
at 0, constant power, -3 dB in the middle; 4% at 1, a cut; no dip in the
middle above ~0.52) → bus → limiter
(DynamicsCompressor at -1.5 dBFS 20:1 — Web Audio adds an automatic
MAKE-UP gain, +0.57 dB at -1/20:1, which let two loud decks peak at +0.3
dBFS until a gain after it took it back off) → speakers. Channel meters are
after the fader, before the crossfader. OUTSIDE performance mode the mixer
after the fader and FX, before the crossfader. OUTSIDE performance mode the mixer
is BYPASSED (A straight through, B silent, no limiter): prep listening is
unchanged. Controls live in `mixerState.ts` (an external store, not
persisted; a MIDI mapping would write the same setters); the curves in
+8 -3
View File
@@ -34,7 +34,8 @@ interface Props {
secPerView: number
onZoomChange: (secPerView: number) => void
onSeek: (t: number) => void
onScratchStart: () => void
/** Grab at `from` (s): later moves are relative to it. */
onScratchStart: (from: number) => void
onScratchMove: (t: number) => void
onScratchEnd: (t: number) => void
/** A stem track: one lane per stem instead of the three-band mix view. */
@@ -236,11 +237,15 @@ export function MainWaveform({
const rect = e.currentTarget.getBoundingClientRect()
const dx = e.clientX - d.startX
if (!d.moved && Math.abs(dx) > DRAG_THRESHOLD) {
// Measure from HERE and NOW: a playing deck has moved on since the
// press, and the threshold's pixels would be a jump.
d.moved = true
onScratchStart()
d.startX = e.clientX
d.startTime = currentTime
onScratchStart(currentTime)
}
if (d.moved) {
const t = Math.min(duration, Math.max(0, d.startTime - (dx / rect.width) * secPerView))
const t = Math.min(duration, Math.max(0, d.startTime - ((e.clientX - d.startX) / rect.width) * secPerView))
d.lastT = t
onScratchMove(t)
}
+60 -12
View File
@@ -56,6 +56,8 @@ const JOG_SEC_PER_TICK = 1.8 / 500
const JOG_NUDGE_PER_TICK = 0.004
const JOG_NUDGE_MAX = 0.1
const JOG_NUDGE_IDLE_FRAMES = 4
/** A paused deck's untouched jog scratches; this long without a tick lets go. */
const JOG_SCRATCH_IDLE_MS = 120
export interface DeckOptions {
/** The track loaded into this deck, if any. */
@@ -612,18 +614,23 @@ export function useDeck({
scratchRafRef.current = requestAnimationFrame(tick)
}
const onScratchStart = () => {
/** Grab the platter. Later targets are RELATIVE to `from` (default: the
* engine's position), which is returned — so a caller measuring its moves
* from a slightly stale position cannot make the deck jump. */
const onScratchStart = (from?: number): number | null => {
const eng = playbackRef.current
if (!eng || !eng.ready) return
if (!eng || !eng.ready) return null
const ref = from ?? eng.getPosition()
if (engagedRef.current) {
eng.scratchRegrab() // re-grab while coasting
return
eng.scratchRegrab(ref) // re-grab while coasting
return ref
}
wasPlayingRef.current = eng.playing
if (eng.playing) setPlaying(false)
eng.scratchBegin(eng.getPosition())
eng.scratchBegin(ref)
engagedRef.current = true
runScratchRaf()
return ref
}
const onScratchMove = (t: number) => {
@@ -647,11 +654,24 @@ export function useDeck({
// Touching the top SCRATCHES — the same engine path as dragging the
// waveform, the target sent straight to the worklet. A turn without touch
// NUDGES while playing (a momentary bend, as the phase meter's drag) and
// SCRUBS while paused; `scrub` (Shift + jog) moves fast, playing or not.
// SCRATCHES while paused too — the platter grabbed on the first tick and let
// go `JOG_SCRATCH_IDLE_MS` after the last, so a jog without a touch sensor
// still cues by ear; `scrub` (Shift + jog) moves fast, playing or not.
// Nudge and scrub are gathered per frame so a jog's flood of messages costs
// one render a frame. How many ticks a turn sends differs per controller,
// so the scale is a starting point times the mapping's sensitivity.
const jogRef = useRef({ touching: false, target: 0, nudge: 0, scrub: 0, raf: 0, idle: 0, bending: false })
const jogRef = useRef({
touching: false,
/** Scratching from an untouched turn on a paused deck (released when idle). */
turning: false,
turnTimer: 0,
target: 0,
nudge: 0,
scrub: 0,
raf: 0,
idle: 0,
bending: false,
})
const jogLatest = useRef({ seekManual, duration })
jogLatest.current = { seekManual, duration }
const flushJog = () => {
@@ -678,16 +698,30 @@ export function useDeck({
const scheduleJog = () => {
if (!jogRef.current.raf) jogRef.current.raf = requestAnimationFrame(flushJog)
}
useEffect(() => () => cancelAnimationFrame(jogRef.current.raf), [])
useEffect(
() => () => {
cancelAnimationFrame(jogRef.current.raf)
clearTimeout(jogRef.current.turnTimer)
},
[],
)
/** Hand a turn-scratch over to a touch (or end it), without releasing it. */
const endTurn = () => {
const j = jogRef.current
clearTimeout(j.turnTimer)
j.turning = false
}
const jogTouch = (on: boolean) => {
const j = jogRef.current
const eng = playbackRef.current
if (on) {
if (!eng || !eng.ready || j.touching) return
endTurn()
const ref = onScratchStart()
if (ref == null) return
j.touching = true
onScratchStart()
j.target = eng.getPosition()
j.target = ref
} else if (j.touching) {
j.touching = false
onScratchEnd(j.target)
@@ -708,8 +742,22 @@ export function useDeck({
scheduleJog()
return 'nudge'
}
j.scrub += ticks * JOG_SEC_PER_TICK * sensitivity
scheduleJog()
// Paused (or coasting from a scratch): grab the platter and scratch.
if (!j.turning || !engagedRef.current) {
const ref = onScratchStart()
if (ref == null) return null
j.turning = true
j.target = ref
}
j.target = Math.max(0, Math.min(duration, j.target + ticks * JOG_SEC_PER_TICK * sensitivity))
eng.scratchTarget(j.target)
clearTimeout(j.turnTimer)
j.turnTimer = window.setTimeout(() => {
j.turning = false
// Let go as a touch release does (a deck that was playing plays on);
// nothing if something else ended the scratch meanwhile.
if (!j.touching && engagedRef.current) playbackRef.current?.scratchRelease(wasPlayingRef.current)
}, JOG_SCRATCH_IDLE_MS)
return null
}
const scrub = (ticks: number, sensitivity: number) => {
+1 -1
View File
@@ -278,7 +278,7 @@ function Strip({
</div>
)
const meter = (
<div className="flex flex-col pb-3" title={`Channel ${ch} level (after its fader)`}>
<div className="flex flex-col pb-3" title={`Channel ${ch} level (after its fader and FX)`}>
<MeterBar fillRef={meterRef} />
</div>
)
+108
View File
@@ -203,6 +203,26 @@ describe('DeckCore scratch', () => {
expect(core.positionSec - before).toBeCloseTo((10 * QUANTUM) / SR, 6)
})
it('a re-grab that arrives after the coast settled grabs afresh (and echoes its id)', () => {
const core = new DeckCore(SR, null)
core.load(ramp(SR * 4))
core.scratchBegin(1, 7)
core.scratchTarget(1.1)
run(core, 50)
core.scratchRelease(false)
for (let b = 0; b < 3000 && core.scratching; b++) run(core, 1)
expect(core.scratching).toBe(false)
expect(core.scratchId).toBe(7)
// The caller has not heard scratchDone yet and thinks it is still coasting.
const p = core.positionSec
core.scratchRegrab(p, 8)
expect(core.scratching).toBe(true)
expect(core.scratchId).toBe(8)
core.scratchTarget(p + 0.2)
run(core, 200)
expect(core.positionSec).toBeGreaterThan(p + 0.15)
})
it('a release without resume settles paused', () => {
const core = new DeckCore(SR, null)
core.load(ramp(SR * 4))
@@ -216,6 +236,94 @@ describe('DeckCore scratch', () => {
})
})
describe('DeckCore scratch sound', () => {
const tone = (freq: number): DeckSource => {
const ch = sine(freq, 20)
return { stems: [[ch]], length: ch.length, sampleRate: SR }
}
/** Drag at `speed`, the hand's position arriving after each of `gaps`
* (blocks, cycled) — as a mouse or a jog delivers it, in steps. Returns
* the speed after every block and the output. */
function drag(core: DeckCore, speed: number, gaps: number[], blocks: number) {
const start = core.positionSec
const speeds: number[] = []
const out = new Float32Array(blocks * QUANTUM)
const l = new Float32Array(QUANTUM)
const r = new Float32Array(QUANTUM)
let next = gaps[0]
for (let b = 0, g = 0; b < blocks; b++) {
if (b === next) {
core.scratchTarget(start + (speed * b * QUANTUM) / SR)
next += gaps[++g % gaps.length]
}
core.render(l, r)
out.set(l, b * QUANTUM)
speeds.push(core.speed)
}
return { speeds, out }
}
const worst = (xs: number[], ref: number) => Math.max(...xs.map((x) => Math.abs(x - ref)))
const maxStep = (x: Float32Array) => {
let m = 0
for (let i = 1; i < x.length; i++) m = Math.max(m, Math.abs(x[i] - x[i - 1]))
return m
}
it('a steady hand moving in mouse-rate steps plays at a steady speed', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.scratchBegin(1)
const { speeds } = drag(core, 1, [6], 700) // a position every 17 ms
expect(worst(speeds.slice(200), 1)).toBeLessThan(0.03)
})
it('and in jittery bursts, as a busy main thread delivers a jog', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.scratchBegin(1)
const { speeds } = drag(core, 1, [1, 1, 4, 1, 7, 2, 1, 3, 5, 1], 700)
expect(worst(speeds.slice(200), 1)).toBeLessThan(0.1)
})
it('stopping the hand fades out — no click at rest', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.scratchBegin(1)
const moving = drag(core, 1, [6], 200)
const resting = run(core, 100)
// A 0.5 amplitude 440 Hz sine at 1x moves at most 0.031 a sample.
expect(maxStep(moving.out)).toBeLessThan(0.05)
expect(maxStep(resting)).toBeLessThan(0.05)
expect(Math.max(...resting.slice(-QUANTUM).map(Math.abs))).toBeLessThan(1e-3)
})
it('grabbing a playing deck neither jumps nor clicks, whatever position the caller had', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.play()
const before = run(core, 20)
const p = core.positionSec
core.scratchBegin(p + 0.04) // a stale main-thread estimate
core.scratchTarget(p + 0.04) // the hand has not moved
const after = run(core, 20)
expect(Math.abs(core.positionSec - p)).toBeLessThan(0.01)
const joined = new Float32Array(before.length + after.length)
joined.set(before)
joined.set(after, before.length)
expect(maxStep(joined)).toBeLessThan(0.05)
})
it('a fast scratch does not fold highs back down as noise', () => {
const core = new DeckCore(SR, null)
core.load(tone(15000))
core.scratchBegin(1)
const { out } = drag(core, 3, [1], 300) // 3x: 45 kHz, far past Nyquist
const tail = out.slice(150 * QUANTUM)
const rms = Math.sqrt(tail.reduce((a, x) => a + x * x, 0) / tail.length)
expect(rms).toBeLessThan(0.05) // the tone itself is 0.35 RMS
})
})
describe('DeckCore keylock', () => {
it('keeps the pitch while the tempo changes; plain varispeed does not', () => {
const tone = sine(440, 6)
+207 -34
View File
@@ -40,11 +40,33 @@ export type DeckEvent = 'ended' | 'scratchDone'
type Mode = 'stopped' | 'playing' | 'drag' | 'inertia'
type StretchState = 'off' | 'warming' | 'on'
// Scratch feel — the values the ScriptProcessor scratch engine was tuned with.
const GLIDE = 400 // samples: how tightly position chases the target while dragging
// Scratch. The hand's position arrives in STEPS (a mouse move, a jog message:
// 60 Hz to 1 kHz, bunched by the main thread), and chasing each step made the
// speed lurch at that rate — a buzzing, distorted scratch with a click each
// time it caught up. So the steps are first joined into a line, played a
// little BEHIND the newest (`delay`, adapted to how far apart they arrive), and
// the platter follows that line through a critically damped spring: its speed
// is continuous. Volume follows speed (no hard mute at rest), and above 1x the
// source is averaged over the span each output frame covers (anti-aliasing).
const RATE_CAP = 12 // max source samples per output frame (pitch ceiling)
const INERTIA_FRICTION = 0.9998 // per-frame easing toward the target velocity (~0.4 s)
const SETTLE_EPS = 0.02 // |velocity - target| below this = settled
/** The platter's spring (Hz): higher follows the hand tighter, lower smooths more. */
const SCRATCH_HZ = 45
/** Hand-line delay (s): at least a block or two, at most this. */
const HAND_DELAY_MIN = 0.006
const HAND_DELAY_MAX = 0.03
const HAND_DELAY_START = 0.012
/** Two hand positions further apart than this (s) = the hand paused. */
const HAND_PAUSE = 0.06
/** How fast the delay may change: 3% of playing time (inaudible). */
const HAND_DELAY_SLEW = 0.03
/** Speed (source samples per frame) at which a scratch is at full volume. */
const SCRATCH_FULL_SPEED = 0.05
/** The volume's follow time (s). */
const SCRATCH_ENV_TAU = 0.003
/** Hand positions kept (a 1 kHz jog over the longest delay is ~30). */
const HAND_POINTS = 256
/** Blocks of varispeed while the stretchers prime (~29 ms at 44.1 kHz). */
export const WARM_QUANTA = 10
@@ -84,10 +106,31 @@ export class DeckCore {
private gainBuf: Float32Array[] = []
// Scratch (source samples, and source samples per output frame).
private target = 0
private velocity = 0
private targetVelocity = 0
private resume = false
/** The caller's id for the current grab, echoed with its scratchDone. */
scratchId = 0
/** Output frames rendered so far: the hand positions' clock. */
private clock = 0
/** The hand's positions (clock frame, source sample), oldest first, a ring. */
private readonly handT = new Float64Array(HAND_POINTS)
private readonly handX = new Float64Array(HAND_POINTS)
private handHead = 0
private handLen = 0
/** Was the newest hand point sent (not a hold point added here)? */
private handLastReal = false
/** How far behind the clock the hand line is played (frames). */
private handDelay: number
/** Recent largest gap between hand positions (frames). */
private handGap = 0
/** The core's playhead minus the caller's position at the grab (samples):
* targets are relative, so a stale main-thread position cannot jump it. */
private handOffset = 0
/** Scratch volume, following speed. */
private env = 0
private readonly springW: number
private readonly envCoef: number
// Keylock.
private stretchers: Stretcher[] = []
@@ -119,6 +162,9 @@ export class DeckCore {
this.ctxRate = ctxRate
this.rb = rb
this.gainCoef = Math.exp(-1 / (GAIN_TAU * ctxRate))
this.springW = (2 * Math.PI * SCRATCH_HZ) / ctxRate
this.envCoef = 1 - Math.exp(-1 / (SCRATCH_ENV_TAU * ctxRate))
this.handDelay = HAND_DELAY_START * ctxRate
}
// ---- state -----------------------------------------------------------
@@ -238,24 +284,94 @@ export class DeckCore {
this.keylock = on
}
scratchBegin(sec: number): void {
/** Grab the platter. `sec` is where the CALLER thinks the playhead is: later
* targets move relative to it. Grabbing a playing deck starts from its own
* speed, so the stop is a quick brake rather than a click. */
scratchBegin(sec: number, id = this.scratchId + 1): void {
if (!this.len) return
this.scratchId = id
const p = sec * this.srcRate
if (this.mode === 'playing') {
this.velocity = this.step
this.env = 1
} else if (!this.scratching) {
this.velocity = 0
this.env = 0
}
// The caller's position is an estimate; trust our own unless far off.
if (Math.abs(p - this.pos) > 0.25 * this.srcRate || this.pos < 0) {
this.pos = Math.max(0, Math.min(p, this.len - 1))
}
this.mode = 'drag'
this.pos = Math.max(0, Math.min(sec * this.srcRate, this.len - 1))
this.target = this.pos
this.velocity = 0
this.sState = 'off'
this.grabHand(p)
}
/** Re-grab while the platter is still coasting: resume dragging from here. */
scratchRegrab(): void {
if (!this.scratching) return
/** Re-grab while the platter is still coasting: resume dragging from here.
* If the coast has already settled (its scratchDone still on its way to
* the caller), this is a fresh grab — ignoring it would leave the caller
* dragging a deck that no longer listens. */
scratchRegrab(sec?: number, id = this.scratchId + 1): void {
if (!this.len) return
if (!this.scratching) {
this.scratchBegin(sec ?? this.positionSec, id)
return
}
this.scratchId = id
this.mode = 'drag'
this.target = this.pos
this.grabHand(sec == null ? this.pos : sec * this.srcRate)
}
scratchTarget(sec: number): void {
this.target = Math.max(0, Math.min(this.len - 1, sec * this.srcRate))
if (!this.handLen) return
const x = Math.max(0, Math.min(this.len - 1, sec * this.srcRate + this.handOffset))
const now = this.clock
const last = (this.handHead + this.handLen - 1) % HAND_POINTS
const lt = this.handT[last]
// Several in one block: the newest wins (they share an arrival time).
if (now <= lt) {
this.handX[last] = x
return
}
const gap = now - lt
if (this.handLastReal && gap < HAND_PAUSE * this.ctxRate) this.handGap = Math.max(gap, this.handGap * 0.97)
// The line already reached the last point and is holding it: start the
// move from where it is now, so the step is spread over the delay.
if (lt < now - this.handDelay) this.pushHand(now - this.handDelay, this.handX[last])
this.pushHand(now, x)
this.handLastReal = true
}
private grabHand(callerPos: number): void {
this.handOffset = this.pos - callerPos
this.handHead = 0
this.handLen = 0
this.handGap = 0
this.pushHand(this.clock - this.handDelay, this.pos)
this.handLastReal = false
}
private pushHand(t: number, x: number): void {
if (this.handLen === HAND_POINTS) {
this.handHead = (this.handHead + 1) % HAND_POINTS
this.handLen--
}
const i = (this.handHead + this.handLen) % HAND_POINTS
this.handT[i] = t
this.handX[i] = x
this.handLen++
}
/** The hand line at clock frame `t` (points before it are dropped). */
private handAt(t: number): number {
while (this.handLen > 1 && this.handT[(this.handHead + 1) % HAND_POINTS] <= t) {
this.handHead = (this.handHead + 1) % HAND_POINTS
this.handLen--
}
const a = this.handHead
if (this.handLen < 2 || t <= this.handT[a]) return this.handX[a]
const b = (a + 1) % HAND_POINTS
return this.handX[a] + ((this.handX[b] - this.handX[a]) * (t - this.handT[a])) / (this.handT[b] - this.handT[a])
}
/** Release the platter: coast toward playing speed (resume) or a stop. The
@@ -279,6 +395,8 @@ export class DeckCore {
/** Render one block into `outL` / `outR` (QUANTUM frames). */
render(outL: Float32Array, outR: Float32Array): void {
const n = outL.length
const base = this.clock
this.clock += n
this.events.length = 0
if (!this.len || this.mode === 'stopped') {
outL.fill(0)
@@ -288,7 +406,7 @@ export class DeckCore {
}
this.advanceGains(n)
if (this.scratching) {
this.renderScratch(outL, outR, n)
this.renderScratch(outL, outR, n, base)
return
}
@@ -404,27 +522,13 @@ export class DeckCore {
}
}
private renderScratch(outL: Float32Array, outR: Float32Array, n: number): void {
private renderScratch(outL: Float32Array, outR: Float32Array, n: number, base: number): void {
const w = this.springW
const w2 = w * w
const sr = this.ctxRate
const wantDelay = Math.max(HAND_DELAY_MIN * sr, Math.min(HAND_DELAY_MAX * sr, this.handGap * 1.2 + QUANTUM))
for (let i = 0; i < n; i++) {
if (this.mode === 'drag') {
const diff = this.target - this.pos
if (Math.abs(diff) < 1) {
// Hand at rest on the platter: no movement, no sound.
this.velocity = 0
outL[i] = 0
outR[i] = 0
continue
}
let step = diff / GLIDE
if (step > RATE_CAP) step = RATE_CAP
else if (step < -RATE_CAP) step = -RATE_CAP
this.pos += step
this.velocity = this.velocity * 0.9 + step * 0.1 // smoothed, for release momentum
} else if (this.mode === 'inertia') {
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
this.pos += this.velocity
if (Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) this.settle()
} else {
if (!this.scratching) {
// Settled mid-block: the rest of it plays (or stays silent) normally.
if (this.mode === 'playing') {
this.frame(this.pos, i, false, outL, outR)
@@ -435,6 +539,31 @@ export class DeckCore {
}
continue
}
// Read, then advance — as the playing path does, so a grab or a settle
// neither skips nor repeats a sample.
const speed = Math.abs(this.velocity)
this.env += ((speed >= SCRATCH_FULL_SPEED ? 1 : speed / SCRATCH_FULL_SPEED) - this.env) * this.envCoef
this.scratchFrame(this.pos, this.velocity, i, outL, outR)
outL[i] *= this.env
outR[i] *= this.env
if (this.mode === 'drag') {
const d = wantDelay - this.handDelay
this.handDelay += d > HAND_DELAY_SLEW ? HAND_DELAY_SLEW : d < -HAND_DELAY_SLEW ? -HAND_DELAY_SLEW : d
const target = this.handAt(base + i - this.handDelay)
// Critically damped spring (semi-implicit Euler: stable at this w).
let v = this.velocity + w2 * (target - this.pos) - 2 * w * this.velocity
if (v > RATE_CAP) v = RATE_CAP
else if (v < -RATE_CAP) v = -RATE_CAP
this.velocity = v
this.pos += v
} else {
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
if (!this.resume && Math.abs(this.velocity) < SETTLE_EPS) this.velocity = 0
this.pos += this.velocity
if (this.resume && Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) this.settle()
// A paused release stops once it has faded out.
else if (!this.resume && this.velocity === 0 && this.env < 1e-3) this.settle()
}
// Clamp to the track; hitting an edge kills momentum.
if (this.pos < 0) {
this.pos = 0
@@ -445,10 +574,54 @@ export class DeckCore {
this.velocity = 0
if (this.mode === 'inertia') this.settle()
}
this.frame(this.pos, i, false, outL, outR)
}
}
/** Mix every stem at p for a platter moving v samples a frame: above 1x,
* the span it covered is averaged (blended in from 1x to 2x), so highs
* played past the Nyquist frequency do not fold back down as noise. */
private scratchFrame(p: number, v: number, i: number, outL: Float32Array, outR: Float32Array): void {
const av = Math.abs(v)
const box = av <= 1 ? 0 : av >= 2 ? 1 : av - 1
if (box === 0) {
this.frame(p, i, false, outL, outR)
return
}
const a = v > 0 ? p - v : p
const k = Math.ceil(av)
let l = 0
let r = 0
for (let s = 0; s < this.stems.length; s++) {
const g = this.gainBuf[s][i]
if (g < 1e-5) continue
const chs = this.stems[s]
const c0 = chs[0]
const c1 = chs.length > 1 ? chs[1] : null
const sl = this.span(c0, a, av, k)
const vl = box < 1 ? (1 - box) * this.read(c0, p, false) + box * sl : sl
l += vl * g
if (c1) {
const sr = this.span(c1, a, av, k)
r += (box < 1 ? (1 - box) * this.read(c1, p, false) + box * sr : sr) * g
} else r += vl * g
}
outL[i] = l
outR[i] = r
}
/** Mean of `ch` over [a, a + len] (trapezoid over k linear-read steps). */
private span(ch: Float32Array, a: number, len: number, k: number): number {
let sum = 0
for (let j = 0; j <= k; j++) {
const q = a + (len * j) / k
const qi = Math.floor(q)
const f = q - qi
const x = this.at(ch, qi, false) * (1 - f) + this.at(ch, qi + 1, false) * f
sum += j === 0 || j === k ? 0.5 * x : x
}
return sum / k
}
private settle(): void {
this.mode = this.resume ? 'playing' : 'stopped'
this.velocity = 0
+22 -6
View File
@@ -30,6 +30,8 @@ export class DeckEngine {
private _keylockAvailable = false
private onEnded: (() => void) | null = null
private onScratchDone: ((playing: boolean) => void) | null = null
/** The latest grab's id: a scratchDone for an earlier one is superseded. */
private scratchSeq = 0
/** The worklet module loads asynchronously, once per app. `destination` is
* where the deck plays into: its mixer channel. */
@@ -57,6 +59,20 @@ export class DeckEngine {
console.warn(msg.message)
return
}
if (msg.type === 'event' && msg.event === 'scratchDone') {
// NOT filtered by generation: a command sent while the coast settled (a
// pitch fader's trickle of rate changes) would drop it, leaving the deck
// "scratching" for good — every later grab a re-grab the audio thread
// ignores. Only a newer grab supersedes it.
if (msg.scratch !== this.scratchSeq) return
const current = msg.gen === this.gen
const playing = current ? msg.playing : this.m.playing
this.m = current
? { ...this.m, pos: msg.pos, time: this.ctx.currentTime, speed: playing ? this.rate : 0, playing, scratching: false }
: { ...this.m, scratching: false }
this.onScratchDone?.(playing)
return
}
if (msg.gen !== this.gen) return // a report from before the latest command
if (msg.type === 'state') {
this._keylockAvailable = msg.keylockAvailable
@@ -64,8 +80,7 @@ export class DeckEngine {
return
}
this.m = { ...this.m, pos: msg.pos, time: this.ctx.currentTime, speed: msg.playing ? this.rate : 0, playing: msg.playing, scratching: false }
if (msg.event === 'ended') this.onEnded?.()
else this.onScratchDone?.(msg.playing)
this.onEnded?.()
}
private send(cmd: DeckCommand, positional = true): void {
@@ -199,12 +214,13 @@ export class DeckEngine {
scratchBegin(sec: number): void {
resumeAudio()
this.m = { pos: sec, time: this.ctx.currentTime, speed: 0, playing: false, scratching: true }
this.send({ op: 'scratchBegin', sec })
this.send({ op: 'scratchBegin', sec, id: ++this.scratchSeq })
}
/** Re-grab while the platter is still coasting. */
scratchRegrab(): void {
this.send({ op: 'scratchRegrab' }, false)
/** Re-grab while the platter is still coasting; later targets move
* relative to `sec`. */
scratchRegrab(sec: number): void {
this.send({ op: 'scratchRegrab', sec, id: ++this.scratchSeq }, false)
}
scratchTarget(sec: number): void {
@@ -29,8 +29,8 @@ export type DeckCommand =
| { op: 'rate'; rate: number }
| { op: 'keylock'; on: boolean }
| { op: 'leadIn'; on: boolean }
| { op: 'scratchBegin'; sec: number }
| { op: 'scratchRegrab' }
| { op: 'scratchBegin'; sec: number; id: number }
| { op: 'scratchRegrab'; sec: number; id: number }
| { op: 'scratchTarget'; sec: number }
| { op: 'scratchRelease'; resume: boolean }
@@ -54,7 +54,15 @@ export interface DeckReport {
export type DeckOutbound =
| DeckReport
| { type: 'event'; event: 'ended' | 'scratchDone'; gen: number; pos: number; playing: boolean }
| {
type: 'event'
event: 'ended' | 'scratchDone'
gen: number
/** The grab (`scratchBegin` / `scratchRegrab` id) a scratchDone ends. */
scratch: number
pos: number
playing: boolean
}
| { type: 'error'; message: string }
class DeckProcessor extends AudioWorkletProcessor {
@@ -113,9 +121,9 @@ class DeckProcessor extends AudioWorkletProcessor {
case 'leadIn':
return core.setLeadIn(c.on)
case 'scratchBegin':
return core.scratchBegin(c.sec)
return core.scratchBegin(c.sec, c.id)
case 'scratchRegrab':
return core.scratchRegrab()
return core.scratchRegrab(c.sec, c.id)
case 'scratchTarget':
return core.scratchTarget(c.sec)
case 'scratchRelease':
@@ -148,6 +156,7 @@ class DeckProcessor extends AudioWorkletProcessor {
type: 'event',
event,
gen: this.gen,
scratch: this.core.scratchId,
pos: this.core.positionSec,
playing: this.core.playing,
})
+10 -7
View File
@@ -1,8 +1,11 @@
// The mixer's audio graph (performance mode, decided 2026-11-02). Both decks
// play into it; it follows the controls in `mixerState.ts`.
//
// deck → gain → 3-band isolator → filter FX → fader ─┬→ crossfader → bus
// deck → gain → 3-band isolator → fader → filter FX ─┬→ crossfader → bus
// └→ meter
//
// The filter FX is POST-fader, so pulling the fader down stops feeding the
// reverb / delay and their tails ring out instead of being cut with it.
// bus → limiter → master meter → speakers
//
// GAIN (`trim` in the state) starts at the track's own auto gain (the DJ app's, `Track.auto_gain_db`;
@@ -329,16 +332,16 @@ class Strip {
mlB.connect(this.bands[1]).connect(eqOut)
mhB.connect(this.bands[2]).connect(eqOut)
this.fx = new FilterFx(ctx)
eqOut.connect(this.fx.input)
this.fader = ctx.createGain()
this.fx.output.connect(this.fader)
eqOut.connect(this.fader)
this.fx = new FilterFx(ctx)
this.fader.connect(this.fx.input)
this.meter = ctx.createAnalyser()
this.meter.fftSize = 512
this.fader.connect(this.meter)
this.fx.output.connect(this.meter)
this.xfade = ctx.createGain()
this.wetGate = ctx.createGain()
this.fader.connect(this.xfade).connect(this.wetGate).connect(bus)
this.fx.output.connect(this.xfade).connect(this.wetGate).connect(bus)
this.dryGate = ctx.createGain()
this.input.connect(this.dryGate).connect(bus)
}
@@ -362,7 +365,7 @@ class Strip {
}
export interface MixerLevels {
/** Peak dBFS: each channel after its fader, and the master after the limiter. */
/** Peak dBFS: each channel after its fader and FX, and the master after the limiter. */
A: number
B: number
master: number