mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented deck transport controls
This commit is contained in:
1 parent
9df73ddcd2
commit
fe91a46bae
15 files changed
+1748
-41
No files matched your search
@@ -1370,8 +1370,24 @@ Two independent apps that talk over HTTP:
|
|||||||
letter, lit when focused), the two main waveforms STACKED at the one zoom
|
letter, lit when focused), the two main waveforms STACKED at the one zoom
|
||||||
past one playhead line (each lane a drop target for its own deck, ringed
|
past one playhead line (each lane a drop target for its own deck, ringed
|
||||||
while focused), the overviews side by side, then each deck's controls
|
while focused), the overviews side by side, then each deck's controls
|
||||||
`stacked` (pads on a row of their own; the tempo group folds below 52rem),
|
`stacked` (pads and the mode switches on a second row; the tempo group
|
||||||
a centre column between them for the mixer. App holds `decks: {A, B}`
|
folds below 44rem) and a TEMPO row (`DeckTempo`: KEY, SYNC, MASTER, the
|
||||||
|
phase meter, the pitch fader with its ±8/16/50 range, the tempo as heard),
|
||||||
|
each beside its overview, the MIXER between them. The pitch fader is the
|
||||||
|
deck's SPEED (`useDeck`'s `rate`, applied only while `tempoActive` — the
|
||||||
|
prep deck always plays at the file's tempo); the header's BPM stays the
|
||||||
|
GRID's. SYNC (`lib/sync.ts`, tested): a follower takes the MASTER's tempo
|
||||||
|
at the nearer octave (½/1/2), widening its range if it must, and while both
|
||||||
|
play its beats are re-aligned by a seek whenever they drift past 3% of a
|
||||||
|
beat (checked every 150 ms, at once when the follower starts); a flexible
|
||||||
|
grid follows the segment under the playhead; moving the follower's pitch by
|
||||||
|
hand releases it; SYNC on the master hands the master over. DRAGGING THE
|
||||||
|
PHASE METER bends the deck's speed while held (right faster, left slower,
|
||||||
|
squared up to ±5% at 80 px, Shift ×¼ — `sync.bendFor`; `useDeck.bend`
|
||||||
|
multiplies `rate`, so the readout and a follower see it), springing back
|
||||||
|
on release; bending a synced follower releases its SYNC. Measured in
|
||||||
|
the app: 175 synced to 125 lands at 125.00 within 0.005 beat and follows
|
||||||
|
the master's pitch. Leaving performance mode releases SYNC. App holds `decks: {A, B}`
|
||||||
(`DeckSlot`: track, origin, playRequest, cuesRefresh), `focusedDeck` and
|
(`DeckSlot`: track, origin, playRequest, cuesRefresh), `focusedDeck` and
|
||||||
`performance`; a load, Enter, a row's play button and a drop on the strip
|
`performance`; a load, Enter, a row's play button and a drop on the strip
|
||||||
go to the FOCUSED deck (A outside the mode), "Load to Deck A/B" to either,
|
go to the FOCUSED deck (A outside the mode), "Load to Deck A/B" to either,
|
||||||
@@ -2769,6 +2785,28 @@ The prep strip plays every track through the **Web Audio API** (a plain
|
|||||||
one block would be a dropout per hotcue. Aligned within ±3 ms, no drift over
|
one block would be a dropout per hotcue. Aligned within ±3 ms, no drift over
|
||||||
a minute (`deckCore.test.ts`, which drives the real `.wasm` in Node). At
|
a minute (`deckCore.test.ts`, which drives the real `.wasm` in Node). At
|
||||||
rate 1 the stretcher is bypassed.
|
rate 1 the stretcher is bypassed.
|
||||||
|
**The mixer** (`lib/audio/mixer.ts`, performance mode phase 4): each deck's
|
||||||
|
engine plays into its CHANNEL (`DeckEngine.create(mixer().input(ch))`):
|
||||||
|
trim (the track's `auto_gain_db` + the knob, ±12 dB) → a 3-band ISOLATOR
|
||||||
|
(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) →
|
||||||
|
the colour FX (Filter / Echo / Space / Noise / Crush, chosen PER CHANNEL,
|
||||||
|
one bipolar knob + one parameter, all built once and switched by gains) →
|
||||||
|
fader → crossfader (smooth = constant power, sharp) → 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
|
||||||
|
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
|
||||||
|
`mixerMath.ts` (tested). `components/mixer/`: `MixerPanel` (meters written
|
||||||
|
from one rAF loop, never through React state) and `Controls` (`Knob`,
|
||||||
|
`Fader`: drag, Shift = fine, wheel, double-click resets; not focusable, so
|
||||||
|
the deck keys never land on them). The graph itself was measured offline in
|
||||||
|
Chrome (tones in, levels out) — flat EQ, kills, crossfader, fader, trim,
|
||||||
|
filter and limiter all at their expected values.
|
||||||
**The PCM is TRANSFERRED to the worklet** (`waveform.DecodedAudio`, copied
|
**The PCM is TRANSFERRED to the worklet** (`waveform.DecodedAudio`, copied
|
||||||
out of the AudioBuffer once); the main thread keeps only a mono downmix for
|
out of the AudioBuffer once); the main thread keeps only a mono downmix for
|
||||||
the raw waveform. (The Firefox detach gotcha — playing an AudioBuffer
|
the raw waveform. (The Firefox detach gotcha — playing an AudioBuffer
|
||||||
|
|||||||
@@ -5,14 +5,20 @@ import { useDeckKeys, type DeckKeyTargets } from '../lib/deckKeys'
|
|||||||
import { useDropTarget, type DragPayload } from '../lib/drag'
|
import { useDropTarget, type DragPayload } from '../lib/drag'
|
||||||
import { Icon } from '../lib/icons'
|
import { Icon } from '../lib/icons'
|
||||||
import { usePrefsWriter } from '../lib/prefs'
|
import { usePrefsWriter } from '../lib/prefs'
|
||||||
|
import { mixer } from '../lib/audio/mixer'
|
||||||
|
import { alignedPosition, effectiveBpm, octaveFor, phaseOffset, syncRate, type DeckTempo as Tempo } from '../lib/sync'
|
||||||
import { DeckControls } from './deck/DeckControls'
|
import { DeckControls } from './deck/DeckControls'
|
||||||
import { DeckHeader } from './deck/DeckHeader'
|
import { DeckHeader } from './deck/DeckHeader'
|
||||||
import { DeckOverlays } from './deck/DeckOverlays'
|
import { DeckOverlays } from './deck/DeckOverlays'
|
||||||
|
import { DeckTempo } from './deck/DeckTempo'
|
||||||
import { DeckMainWave, DeckOverview, type DeckView } from './deck/DeckWaves'
|
import { DeckMainWave, DeckOverview, type DeckView } from './deck/DeckWaves'
|
||||||
import { useDeck, type Deck } from './deck/useDeck'
|
import { useDeck, type Deck } from './deck/useDeck'
|
||||||
import { MIN_SEC, MAX_SEC, DEFAULT_SEC } from './MainWaveform'
|
import { MIN_SEC, MAX_SEC, DEFAULT_SEC } from './MainWaveform'
|
||||||
|
import { MixerPanel } from './mixer/MixerPanel'
|
||||||
|
|
||||||
export type DeckId = 'A' | 'B'
|
export type DeckId = 'A' | 'B'
|
||||||
|
/** `performance.now()` — the global, which this file's `performance` prop shadows. */
|
||||||
|
const performance_now = () => globalThis.performance.now()
|
||||||
export const DECK_IDS: DeckId[] = ['A', 'B']
|
export const DECK_IDS: DeckId[] = ['A', 'B']
|
||||||
export const otherDeck = (id: DeckId): DeckId => (id === 'A' ? 'B' : 'A')
|
export const otherDeck = (id: DeckId): DeckId => (id === 'A' ? 'B' : 'A')
|
||||||
|
|
||||||
@@ -92,7 +98,7 @@ function useDeckView(): DeckView {
|
|||||||
* One deck normally. PERFORMANCE MODE (P, or the button beside Auto hotcues)
|
* One deck normally. PERFORMANCE MODE (P, or the button beside Auto hotcues)
|
||||||
* adds deck B: the two headers side by side, the two main waveforms stacked at
|
* adds deck B: the two headers side by side, the two main waveforms stacked at
|
||||||
* one zoom past one playhead line, the overviews side by side, then each
|
* one zoom past one playhead line, the overviews side by side, then each
|
||||||
* deck's controls (the mixer goes between them). Keys go to the FOCUSED deck
|
* deck's controls with the mixer between them. Keys go to the FOCUSED deck
|
||||||
* (click a deck), Alt/Option to the other. Deck B stays mounted while hidden,
|
* (click a deck), Alt/Option to the other. Deck B stays mounted while hidden,
|
||||||
* so leaving and coming back finds it as it was — paused on the way out.
|
* so leaving and coming back finds it as it was — paused on the way out.
|
||||||
*/
|
*/
|
||||||
@@ -119,6 +125,8 @@ export function PrepStrip({
|
|||||||
...common,
|
...common,
|
||||||
...decks.A,
|
...decks.A,
|
||||||
caps: caps.A,
|
caps: caps.A,
|
||||||
|
channel: 'A',
|
||||||
|
tempoActive: performance,
|
||||||
onPlayingChange: playingA,
|
onPlayingChange: playingA,
|
||||||
onEditTags: editTags(decks.A),
|
onEditTags: editTags(decks.A),
|
||||||
persist: true,
|
persist: true,
|
||||||
@@ -128,6 +136,8 @@ export function PrepStrip({
|
|||||||
...common,
|
...common,
|
||||||
...decks.B,
|
...decks.B,
|
||||||
caps: caps.B,
|
caps: caps.B,
|
||||||
|
channel: 'B',
|
||||||
|
tempoActive: performance,
|
||||||
onPlayingChange: playingB,
|
onPlayingChange: playingB,
|
||||||
onEditTags: editTags(decks.B),
|
onEditTags: editTags(decks.B),
|
||||||
persist: false,
|
persist: false,
|
||||||
@@ -142,6 +152,105 @@ export function PrepStrip({
|
|||||||
if (!performance) pauseB.current()
|
if (!performance) pauseB.current()
|
||||||
}, [performance])
|
}, [performance])
|
||||||
|
|
||||||
|
// The mixer: in circuit only in performance mode (prep listening stays as it
|
||||||
|
// was), each channel's trim starting at its track's own auto gain, and each
|
||||||
|
// deck's tempo for the echo.
|
||||||
|
useEffect(() => mixer().setActive(performance), [performance])
|
||||||
|
const gainA = decks.A.track?.auto_gain_db ?? null
|
||||||
|
const gainB = decks.B.track?.auto_gain_db ?? null
|
||||||
|
useEffect(() => mixer().setAutoGain('A', gainA ?? 0), [gainA])
|
||||||
|
useEffect(() => mixer().setAutoGain('B', gainB ?? 0), [gainB])
|
||||||
|
const bpmA = (a.activeMarker?.bpm ?? 0) * a.rate
|
||||||
|
const bpmB = (b.activeMarker?.bpm ?? 0) * b.rate
|
||||||
|
useEffect(() => mixer().setTempo('A', bpmA), [bpmA])
|
||||||
|
useEffect(() => mixer().setTempo('B', bpmB), [bpmB])
|
||||||
|
|
||||||
|
// ---- tempo master + SYNC -------------------------------------------------
|
||||||
|
// A synced deck follows the MASTER's tempo (at the nearer octave) and, while
|
||||||
|
// both play, its beats: re-aligned whenever they drift past 3% of a beat —
|
||||||
|
// after a hotcue, a jump, the follower starting. Moving its pitch fader by
|
||||||
|
// hand releases it. All from the grids (lib/sync.ts).
|
||||||
|
const [master, setMaster] = useState<DeckId>('A')
|
||||||
|
const [synced, setSynced] = useState<Record<DeckId, boolean>>({ A: false, B: false })
|
||||||
|
const live = useRef({ a, b, master, synced })
|
||||||
|
live.current = { a, b, master, synced }
|
||||||
|
const lastAlign = useRef<Record<DeckId, number>>({ A: 0, B: 0 })
|
||||||
|
const tempoOf = (d: Deck): Tempo => ({ grid: d.grid, pos: d.playheadNow(), rate: d.rate })
|
||||||
|
|
||||||
|
/** Bring follower `id` onto master `m`'s tempo, and its beats onto the
|
||||||
|
* master's when both play and `phase` (or a drift past the threshold). */
|
||||||
|
const follow = useCallback((id: DeckId, m: DeckId, force: boolean) => {
|
||||||
|
const { a, b } = live.current
|
||||||
|
const f = id === 'A' ? a : b
|
||||||
|
const md = m === 'A' ? a : b
|
||||||
|
const r = syncRate(tempoOf(md), tempoOf(f))
|
||||||
|
if (!r) return
|
||||||
|
if (Math.abs(r.rate - f.rate) > 1e-6) f.setRate(r.rate)
|
||||||
|
if (!f.playing || !md.playing) return
|
||||||
|
const now = performance_now()
|
||||||
|
if (!force && now - lastAlign.current[id] < 400) return
|
||||||
|
const ft = tempoOf(f)
|
||||||
|
const off = phaseOffset(tempoOf(md), ft, r.octave)
|
||||||
|
if (off == null || Math.abs(off) < (force ? 0.005 : 0.03)) return
|
||||||
|
lastAlign.current[id] = now
|
||||||
|
f.seek(alignedPosition(ft, off, r.octave))
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!performance) return
|
||||||
|
const t = setInterval(() => {
|
||||||
|
const { master, synced } = live.current
|
||||||
|
for (const id of DECK_IDS) if (synced[id] && id !== master) follow(id, master, false)
|
||||||
|
}, 150)
|
||||||
|
return () => clearInterval(t)
|
||||||
|
}, [performance, follow])
|
||||||
|
// A follower that starts playing lines up at once, not on the next tick.
|
||||||
|
useEffect(() => {
|
||||||
|
const { master, synced } = live.current
|
||||||
|
for (const id of DECK_IDS) if (synced[id] && id !== master) follow(id, master, true)
|
||||||
|
}, [a.playing, b.playing, follow])
|
||||||
|
// Leaving performance mode releases SYNC (the decks go back to their own tempo).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!performance) setSynced({ A: false, B: false })
|
||||||
|
}, [performance])
|
||||||
|
|
||||||
|
const toggleSync = (id: DeckId) => {
|
||||||
|
if (synced[id]) {
|
||||||
|
setSynced((s) => ({ ...s, [id]: false }))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// SYNC on the master hands the master to the other deck.
|
||||||
|
const m = master === id ? otherDeck(id) : master
|
||||||
|
if (m !== master) setMaster(m)
|
||||||
|
setSynced({ [id]: true, [m]: false } as Record<DeckId, boolean>)
|
||||||
|
follow(id, m, true)
|
||||||
|
}
|
||||||
|
const makeMaster = (id: DeckId) => {
|
||||||
|
setMaster(id)
|
||||||
|
setSynced((s) => ({ ...s, [id]: false }))
|
||||||
|
}
|
||||||
|
const syncBlocked = (id: DeckId): string | null => {
|
||||||
|
const m = master === id ? otherDeck(id) : master
|
||||||
|
if (!deckOf(id).grid) return 'This track has no beatgrid — Analyze it to sync'
|
||||||
|
if (!deckOf(m).track) return `Deck ${m} has nothing loaded to sync to`
|
||||||
|
if (!deckOf(m).grid) return `Deck ${m}'s track has no beatgrid to sync to`
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
/** This deck's beats against the other's, for the phase meter. */
|
||||||
|
const phaseOf = (id: DeckId) => () => {
|
||||||
|
const { a, b } = live.current
|
||||||
|
const me = id === 'A' ? a : b
|
||||||
|
const other = id === 'A' ? b : a
|
||||||
|
if (!me.playing || !other.playing) return null
|
||||||
|
const mine = tempoOf(me)
|
||||||
|
const theirs = tempoOf(other)
|
||||||
|
const em = effectiveBpm(mine)
|
||||||
|
const eo = effectiveBpm(theirs)
|
||||||
|
if (em == null || eo == null) return null
|
||||||
|
return phaseOffset(theirs, mine, octaveFor(eo, em))
|
||||||
|
}
|
||||||
|
|
||||||
const keys = useRef<DeckKeyTargets>({ focused: null, other: null })
|
const keys = useRef<DeckKeyTargets>({ focused: null, other: null })
|
||||||
keys.current = {
|
keys.current = {
|
||||||
focused: deckOf(lead).shortcuts,
|
focused: deckOf(lead).shortcuts,
|
||||||
@@ -193,10 +302,8 @@ export function PrepStrip({
|
|||||||
{id}
|
{id}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
// The centre column: the toggle above, the mixer (phase 4) below.
|
|
||||||
const centre = 'w-9 shrink-0'
|
|
||||||
return (
|
return (
|
||||||
<div className="glass flex h-[29rem] shrink-0 flex-col gap-2 p-4">
|
<div className="glass flex h-[32rem] shrink-0 flex-col gap-2 p-4">
|
||||||
<div className="flex shrink-0 items-center gap-3">
|
<div className="flex shrink-0 items-center gap-3">
|
||||||
{pane('A', <DeckHeader deck={a} compact badge={badge('A')} />)}
|
{pane('A', <DeckHeader deck={a} compact badge={badge('A')} />)}
|
||||||
{toggle}
|
{toggle}
|
||||||
@@ -205,15 +312,48 @@ export function PrepStrip({
|
|||||||
{DECK_IDS.map((id) => (
|
{DECK_IDS.map((id) => (
|
||||||
<DeckLane key={id} id={id} deck={deckOf(id)} view={view} focused={id === focused} drop={drop} onFocus={onFocus} />
|
<DeckLane key={id} id={id} deck={deckOf(id)} view={view} focused={id === focused} drop={drop} onFocus={onFocus} />
|
||||||
))}
|
))}
|
||||||
<div className="flex h-7 shrink-0 gap-3">
|
|
||||||
{pane('A', <DeckOverview deck={a} view={view} />)}
|
|
||||||
<div className={centre} />
|
|
||||||
{pane('B', <DeckOverview deck={b} view={view} />)}
|
|
||||||
</div>
|
|
||||||
<div className="flex shrink-0 gap-3">
|
<div className="flex shrink-0 gap-3">
|
||||||
{pane('A', <DeckControls deck={a} stacked />, 'flex min-w-0 flex-1')}
|
{pane(
|
||||||
<div className={centre} />
|
'A',
|
||||||
{pane('B', <DeckControls deck={b} stacked />, 'flex min-w-0 flex-1')}
|
<>
|
||||||
|
<div className="h-7">
|
||||||
|
<DeckOverview deck={a} view={view} />
|
||||||
|
</div>
|
||||||
|
<DeckControls deck={a} stacked />
|
||||||
|
<DeckTempo
|
||||||
|
deck={a}
|
||||||
|
master={master === 'A'}
|
||||||
|
synced={synced.A}
|
||||||
|
syncBlocked={syncBlocked('A')}
|
||||||
|
onSync={() => toggleSync('A')}
|
||||||
|
onMaster={() => makeMaster('A')}
|
||||||
|
onManualPitch={() => synced.A && setSynced((s) => ({ ...s, A: false }))}
|
||||||
|
phase={phaseOf('A')}
|
||||||
|
/>
|
||||||
|
</>,
|
||||||
|
'flex min-w-0 flex-1 flex-col gap-2',
|
||||||
|
)}
|
||||||
|
<MixerPanel autoGain={{ A: gainA, B: gainB }} />
|
||||||
|
{pane(
|
||||||
|
'B',
|
||||||
|
<>
|
||||||
|
<div className="h-7">
|
||||||
|
<DeckOverview deck={b} view={view} />
|
||||||
|
</div>
|
||||||
|
<DeckControls deck={b} stacked />
|
||||||
|
<DeckTempo
|
||||||
|
deck={b}
|
||||||
|
master={master === 'B'}
|
||||||
|
synced={synced.B}
|
||||||
|
syncBlocked={syncBlocked('B')}
|
||||||
|
onSync={() => toggleSync('B')}
|
||||||
|
onMaster={() => makeMaster('B')}
|
||||||
|
onManualPitch={() => synced.B && setSynced((s) => ({ ...s, B: false }))}
|
||||||
|
phase={phaseOf('B')}
|
||||||
|
/>
|
||||||
|
</>,
|
||||||
|
'flex min-w-0 flex-1 flex-col gap-2',
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<DeckOverlays deck={a} />
|
<DeckOverlays deck={a} />
|
||||||
<DeckOverlays deck={b} />
|
<DeckOverlays deck={b} />
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ const DIVIDER = <span aria-hidden className="h-7 w-px shrink-0 bg-line" />
|
|||||||
* bank would hit its minimum (with a lockable grid's extra Lock button, and the
|
* bank would hit its minimum (with a lockable grid's extra Lock button, and the
|
||||||
* Hot / Mem toggle's ~3rem with its gap), so move it with the controls.
|
* Hot / Mem toggle's ~3rem with its gap), so move it with the controls.
|
||||||
*
|
*
|
||||||
* `stacked` (half-width, in performance mode) gives the pads — or the grid or
|
* `stacked` (beside the mixer, in performance mode) puts the pads — or the grid
|
||||||
* memory strip — a row of their own under the rest, which then folds the tempo
|
* or memory strip — on a second row with the two mode switches, and folds the
|
||||||
* group below 52rem (measured in the app: row one needs ~50rem before the
|
* tempo group below 44rem (measured in the app: transport + loops + the tempo
|
||||||
* tempo group overflows).
|
* group need ~42rem).
|
||||||
*/
|
*/
|
||||||
export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?: boolean }) {
|
export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?: boolean }) {
|
||||||
const {
|
const {
|
||||||
@@ -240,14 +240,16 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
|
|||||||
{DIVIDER}
|
{DIVIDER}
|
||||||
{loopControls}
|
{loopControls}
|
||||||
<span className="flex-1" />
|
<span className="flex-1" />
|
||||||
{bankSwitch}
|
<TempoControls {...tempoProps} className="@max-[44rem]:hidden" />
|
||||||
{modeSwitch}
|
<TempoFold locked={tempoProps.locked} className="hidden @max-[44rem]:flex">
|
||||||
<TempoControls {...tempoProps} className="@max-[52rem]:hidden" />
|
|
||||||
<TempoFold locked={tempoProps.locked} className="hidden @max-[52rem]:flex">
|
|
||||||
<TempoControls {...tempoProps} />
|
<TempoControls {...tempoProps} />
|
||||||
</TempoFold>
|
</TempoFold>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex h-11 shrink-0 items-center">{strip}</div>
|
<div className="flex h-11 shrink-0 items-center gap-2">
|
||||||
|
{modeSwitch}
|
||||||
|
{bankSwitch}
|
||||||
|
{strip}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
import { bendFor, PITCH_RANGES } from '../../lib/sync'
|
||||||
|
import { Fader } from '../mixer/Controls'
|
||||||
|
import type { Deck } from './useDeck'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
deck: Deck
|
||||||
|
/** This deck is the tempo master (the one SYNC follows). */
|
||||||
|
master: boolean
|
||||||
|
synced: boolean
|
||||||
|
/** Why SYNC cannot engage (no grid on a deck), else null. */
|
||||||
|
syncBlocked: string | null
|
||||||
|
onSync: () => void
|
||||||
|
onMaster: () => void
|
||||||
|
/** Moving the pitch fader — or bending — by hand takes the deck out of SYNC. */
|
||||||
|
onManualPitch: () => void
|
||||||
|
/** This deck's beats against the other deck's, in beats (-0.5..0.5); null
|
||||||
|
* when either has no grid or is not playing. Read every frame. */
|
||||||
|
phase: () => number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
const lit = 'is-selected text-text'
|
||||||
|
const unlit = 'btn-glass text-muted'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A deck's tempo row in performance mode (decided 2026-11-02): keylock, SYNC,
|
||||||
|
* MASTER, the phase meter, the pitch fader with its range, and the tempo as
|
||||||
|
* heard. The pitch fader is the deck's SPEED — the grid's BPM is still edited
|
||||||
|
* in the header and Grid mode.
|
||||||
|
*/
|
||||||
|
export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster, onManualPitch, phase }: Props) {
|
||||||
|
const { pitch, setPitch, pitchRange, changeRange, rate, setBend, keylock, setKeylock, keylockAvailable, activeMarker, track } = deck
|
||||||
|
const bpm = activeMarker ? activeMarker.bpm * rate : null
|
||||||
|
const pct = pitch * pitchRange * 100
|
||||||
|
const nextRange = PITCH_RANGES[(PITCH_RANGES.indexOf(pitchRange) + 1) % PITCH_RANGES.length]
|
||||||
|
return (
|
||||||
|
<div className="flex h-9 shrink-0 items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setKeylock(!keylock)}
|
||||||
|
disabled={!keylockAvailable}
|
||||||
|
aria-pressed={keylock}
|
||||||
|
title={
|
||||||
|
keylockAvailable
|
||||||
|
? keylock
|
||||||
|
? 'Keylock on: a tempo change keeps the pitch'
|
||||||
|
: 'Keylock off: the pitch moves with the tempo, like a turntable'
|
||||||
|
: 'Keylock is unavailable (the time-stretcher did not load)'
|
||||||
|
}
|
||||||
|
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${keylock ? lit : unlit}`}
|
||||||
|
>
|
||||||
|
KEY
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={onSync}
|
||||||
|
disabled={!track || (!synced && syncBlocked != null)}
|
||||||
|
aria-pressed={synced}
|
||||||
|
title={syncBlocked ?? (synced ? 'Synced: following the master’s tempo and beats — click to release' : 'Match the master’s tempo and line the beats up')}
|
||||||
|
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${synced ? lit : unlit}`}
|
||||||
|
>
|
||||||
|
SYNC
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={onMaster}
|
||||||
|
disabled={!track}
|
||||||
|
aria-pressed={master}
|
||||||
|
title={master ? 'Tempo master: a synced deck follows this one' : 'Make this deck the tempo master'}
|
||||||
|
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${
|
||||||
|
master ? 'bg-gold/20 text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.6)]' : unlit
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
MASTER
|
||||||
|
</button>
|
||||||
|
<PhaseMeter
|
||||||
|
phase={phase}
|
||||||
|
disabled={!track}
|
||||||
|
onBend={(b) => {
|
||||||
|
if (b !== 1) onManualPitch()
|
||||||
|
setBend(b)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Fader
|
||||||
|
orientation="horizontal"
|
||||||
|
value={pitch}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
onChange={(v) => {
|
||||||
|
setPitch(Math.abs(v) < 0.01 ? 0 : v)
|
||||||
|
onManualPitch()
|
||||||
|
}}
|
||||||
|
label="Pitch"
|
||||||
|
describe={() => `Pitch ${fmtPct(pct)} (range ±${Math.round(pitchRange * 100)}%) — double-click to reset`}
|
||||||
|
className="min-w-16 flex-1"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => changeRange(nextRange)}
|
||||||
|
title={`Pitch range ±${Math.round(pitchRange * 100)}% — click for ±${Math.round(nextRange * 100)}%`}
|
||||||
|
className="btn-glass h-8 w-11 shrink-0 rounded-full font-mono text-[11px] text-muted"
|
||||||
|
>
|
||||||
|
±{Math.round(pitchRange * 100)}
|
||||||
|
</button>
|
||||||
|
<div className="well flex h-8 w-[6.5rem] shrink-0 flex-col items-end justify-center rounded-lg px-2 leading-none">
|
||||||
|
<span className="font-mono text-[13px] font-medium text-text">{bpm ? bpm.toFixed(2) : '—'}</span>
|
||||||
|
<span className={`font-mono text-[10px] ${pct === 0 ? 'text-faint' : 'text-muted'}`}>{fmtPct(pct)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fmtPct = (p: number) => `${p > 0 ? '+' : p < 0 ? '−' : '±'}${Math.abs(p).toFixed(2)}%`
|
||||||
|
|
||||||
|
/** Where this deck's beats fall against the other deck's: centre = in phase,
|
||||||
|
* right = ahead. Drawn every frame straight to the DOM. DRAG it to bend the
|
||||||
|
* deck's speed — right faster, left slower — and let go to spring back, the
|
||||||
|
* way a DJ nudges a platter to bring the beats together. */
|
||||||
|
function PhaseMeter({
|
||||||
|
phase,
|
||||||
|
onBend,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
phase: () => number | null
|
||||||
|
onBend: (bend: number) => void
|
||||||
|
disabled: boolean
|
||||||
|
}) {
|
||||||
|
const markRef = useRef<HTMLSpanElement>(null)
|
||||||
|
const dragX = useRef<number | null>(null)
|
||||||
|
const release = () => {
|
||||||
|
if (dragX.current == null) return
|
||||||
|
dragX.current = null
|
||||||
|
onBend(1)
|
||||||
|
}
|
||||||
|
const read = useRef(phase)
|
||||||
|
read.current = phase
|
||||||
|
useEffect(() => {
|
||||||
|
let raf = 0
|
||||||
|
const tick = () => {
|
||||||
|
const el = markRef.current
|
||||||
|
const p = read.current()
|
||||||
|
if (el) {
|
||||||
|
el.style.opacity = p == null ? '0' : '1'
|
||||||
|
if (p != null) {
|
||||||
|
el.style.left = `${(p + 0.5) * 100}%`
|
||||||
|
el.style.background = Math.abs(p) < 0.03 ? 'var(--color-mint)' : 'var(--color-gold)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
return () => cancelAnimationFrame(raf)
|
||||||
|
}, [])
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
if (disabled || e.button !== 0) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
dragX.current = e.clientX
|
||||||
|
}}
|
||||||
|
onPointerMove={(e) => dragX.current != null && onBend(bendFor(e.clientX - dragX.current, e.shiftKey))}
|
||||||
|
onPointerUp={release}
|
||||||
|
onPointerCancel={release}
|
||||||
|
onLostPointerCapture={release}
|
||||||
|
className={`well relative h-3 w-20 shrink-0 touch-none overflow-hidden rounded-full ${disabled ? '' : 'cursor-ew-resize'}`}
|
||||||
|
title="Phase: where this deck's beats fall against the other deck's (centre = together). Drag to bend the speed — right faster, left slower (Shift: finer)"
|
||||||
|
>
|
||||||
|
<span aria-hidden className="absolute inset-y-0.5 left-1/2 w-px bg-white/25" />
|
||||||
|
<span ref={markRef} className="absolute inset-y-0 w-1.5 -translate-x-1/2 rounded-full opacity-0" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -36,8 +36,11 @@ import { analyzeStems, analyzeWaveform, type WaveColumn } from '../../lib/wavefo
|
|||||||
import type { RawWave } from '../../lib/rawWave'
|
import type { RawWave } from '../../lib/rawWave'
|
||||||
import { setAmbientFromArt } from '../../lib/ambient'
|
import { setAmbientFromArt } from '../../lib/ambient'
|
||||||
import { DeckEngine } from '../../lib/audio/deckEngine'
|
import { DeckEngine } from '../../lib/audio/deckEngine'
|
||||||
|
import { mixer } from '../../lib/audio/mixer'
|
||||||
|
import type { Channel } from '../../lib/audio/mixerState'
|
||||||
import { resumeAudio } from '../../lib/audio/context'
|
import { resumeAudio } from '../../lib/audio/context'
|
||||||
import { STEM_KEYS, type DeckShortcuts } from '../../lib/deckKeys'
|
import { STEM_KEYS, type DeckShortcuts } from '../../lib/deckKeys'
|
||||||
|
import { PITCH_RANGES, rangeFor } from '../../lib/sync'
|
||||||
import { invalidateTrackLists } from '../../lib/trackQueries'
|
import { invalidateTrackLists } from '../../lib/trackQueries'
|
||||||
import { eventLabel } from '../AutoCueDialog'
|
import { eventLabel } from '../AutoCueDialog'
|
||||||
import type { MenuItem } from '../ContextMenu'
|
import type { MenuItem } from '../ContextMenu'
|
||||||
@@ -73,6 +76,11 @@ export interface DeckOptions {
|
|||||||
/** Opens Edit Tags for the loaded track — passed only where the library
|
/** Opens Edit Tags for the loaded track — passed only where the library
|
||||||
* will accept the edit, so the cover popup offers it only then. */
|
* will accept the edit, so the cover popup offers it only then. */
|
||||||
onEditTags?: (track: Track) => void
|
onEditTags?: (track: Track) => void
|
||||||
|
/** Performance mode: the pitch fader and keylock apply (else the deck plays
|
||||||
|
* at the file's own tempo). */
|
||||||
|
tempoActive?: boolean
|
||||||
|
/** The mixer channel this deck plays into (default A). */
|
||||||
|
channel?: Channel
|
||||||
/** Persist this deck's loop size and cue bank (deck A; default true). */
|
/** Persist this deck's loop size and cue bank (deck A; default true). */
|
||||||
persist?: boolean
|
persist?: boolean
|
||||||
/** Recolour the app from this deck's cover art (default true). */
|
/** Recolour the app from this deck's cover art (default true). */
|
||||||
@@ -90,6 +98,8 @@ export function useDeck({
|
|||||||
cuesRefresh = 0,
|
cuesRefresh = 0,
|
||||||
onPlayingChange,
|
onPlayingChange,
|
||||||
onEditTags,
|
onEditTags,
|
||||||
|
tempoActive = false,
|
||||||
|
channel = 'A',
|
||||||
persist = true,
|
persist = true,
|
||||||
leadsAmbient = true,
|
leadsAmbient = true,
|
||||||
}: DeckOptions) {
|
}: DeckOptions) {
|
||||||
@@ -198,7 +208,7 @@ export function useDeck({
|
|||||||
|
|
||||||
const getEngine = (): Promise<DeckEngine> => {
|
const getEngine = (): Promise<DeckEngine> => {
|
||||||
if (!enginePromiseRef.current) {
|
if (!enginePromiseRef.current) {
|
||||||
enginePromiseRef.current = DeckEngine.create().then((eng) => {
|
enginePromiseRef.current = DeckEngine.create(mixer().input(channel)).then((eng) => {
|
||||||
playbackRef.current = eng
|
playbackRef.current = eng
|
||||||
eng.setOnEnded(() => setPlaying(false))
|
eng.setOnEnded(() => setPlaying(false))
|
||||||
// The deck hands itself back after a scratch's coast settles.
|
// The deck hands itself back after a scratch's coast settles.
|
||||||
@@ -1181,6 +1191,39 @@ export function useDeck({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- tempo (performance mode) ---------------------------------------------
|
||||||
|
// The pitch fader (-1..1 of its range), the range, and keylock. Applied only
|
||||||
|
// while `tempoActive`: the prep deck always plays at the file's own tempo, so
|
||||||
|
// grid edits are made against the music as it is. Kept while hidden, so
|
||||||
|
// coming back to performance mode finds the fader where it was.
|
||||||
|
const [pitch, setPitchState] = useState(0)
|
||||||
|
const [pitchRange, setPitchRange] = useState(PITCH_RANGES[0])
|
||||||
|
const [keylock, setKeylock] = useState(true)
|
||||||
|
// A pitch BEND: a momentary push or drag on top of the fader (the phase
|
||||||
|
// meter's drag), 1 = none. Part of `rate`, so the readout and a follower see it.
|
||||||
|
const [bend, setBend] = useState(1)
|
||||||
|
const rate = tempoActive ? (1 + pitch * pitchRange) * bend : 1
|
||||||
|
useEffect(() => {
|
||||||
|
playbackRef.current?.setRate(rate)
|
||||||
|
}, [rate, ready])
|
||||||
|
useEffect(() => {
|
||||||
|
playbackRef.current?.setKeylock(keylock)
|
||||||
|
}, [keylock, ready])
|
||||||
|
const setPitch = (p: number) => setPitchState(Math.max(-1, Math.min(1, p)))
|
||||||
|
/** An exact rate (SYNC), widening the range when the fader cannot reach it.
|
||||||
|
* Never called mid-bend: a bend releases the deck's SYNC. */
|
||||||
|
const setRate = (r: number) => {
|
||||||
|
const range = rangeFor(r, pitchRange)
|
||||||
|
setPitchRange(range)
|
||||||
|
setPitchState((r - 1) / range)
|
||||||
|
}
|
||||||
|
/** A new range keeps the tempo where the fader can still reach it. */
|
||||||
|
const changeRange = (range: number) => {
|
||||||
|
setPitchState(Math.max(-1, Math.min(1, (pitch * pitchRange) / range)))
|
||||||
|
setPitchRange(range)
|
||||||
|
}
|
||||||
|
const keylockAvailable = playbackRef.current?.keylockAvailable ?? true
|
||||||
|
|
||||||
// ---- stems: mute / solo ------------------------------------------------------
|
// ---- stems: mute / solo ------------------------------------------------------
|
||||||
// What each stem plays at: a muted stem is 0. Both engines follow it (the
|
// What each stem plays at: a muted stem is 0. Both engines follow it (the
|
||||||
// scratch engine re-sums).
|
// scratch engine re-sums).
|
||||||
@@ -1418,6 +1461,18 @@ export function useDeck({
|
|||||||
runAnalyzeGrid,
|
runAnalyzeGrid,
|
||||||
toggleStem,
|
toggleStem,
|
||||||
shortcuts,
|
shortcuts,
|
||||||
|
seek,
|
||||||
|
pitch,
|
||||||
|
setPitch,
|
||||||
|
pitchRange,
|
||||||
|
changeRange,
|
||||||
|
rate,
|
||||||
|
setRate,
|
||||||
|
bend,
|
||||||
|
setBend,
|
||||||
|
keylock,
|
||||||
|
setKeylock,
|
||||||
|
keylockAvailable,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
// The mixer's controls: a rotary knob and a fader. Mouse-driven — drag (Shift
|
||||||
|
// for fine), scroll, double-click to reset — and NOT focusable, so the deck's
|
||||||
|
// keys (←/→, Space) never land on them by accident.
|
||||||
|
|
||||||
|
import { useRef, type PointerEvent, type WheelEvent } from 'react'
|
||||||
|
|
||||||
|
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))
|
||||||
|
|
||||||
|
/** Pixels of drag for the whole travel (Shift: five times finer). */
|
||||||
|
const DRAG_PX = 150
|
||||||
|
|
||||||
|
interface KnobProps {
|
||||||
|
value: number
|
||||||
|
min: number
|
||||||
|
max: number
|
||||||
|
/** Reset value (double-click); also where the arc starts on a bipolar knob. */
|
||||||
|
defaultValue: number
|
||||||
|
/** The arc grows from the centre (EQ, colour) rather than from the left. */
|
||||||
|
bipolar?: boolean
|
||||||
|
onChange: (v: number) => void
|
||||||
|
label: string
|
||||||
|
/** The tooltip, for the value it would show. */
|
||||||
|
describe: (v: number) => string
|
||||||
|
color?: string
|
||||||
|
size?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A point on the knob's circle at angle `deg` (0 = straight up). */
|
||||||
|
function polar(r: number, deg: number, c: number): [number, number] {
|
||||||
|
const rad = ((deg - 90) * Math.PI) / 180
|
||||||
|
return [c + r * Math.cos(rad), c + r * Math.sin(rad)]
|
||||||
|
}
|
||||||
|
|
||||||
|
function arc(r: number, from: number, to: number, c: number): string {
|
||||||
|
if (Math.abs(to - from) < 0.5) return ''
|
||||||
|
const [a, b] = from < to ? [from, to] : [to, from]
|
||||||
|
const [x1, y1] = polar(r, a, c)
|
||||||
|
const [x2, y2] = polar(r, b, c)
|
||||||
|
return `M ${x1} ${y1} A ${r} ${r} 0 ${b - a > 180 ? 1 : 0} 1 ${x2} ${y2}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Knob({
|
||||||
|
value,
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
defaultValue,
|
||||||
|
bipolar = false,
|
||||||
|
onChange,
|
||||||
|
label,
|
||||||
|
describe,
|
||||||
|
color = 'var(--color-accent)',
|
||||||
|
size = 26,
|
||||||
|
}: KnobProps) {
|
||||||
|
const drag = useRef<{ y: number; v: number } | null>(null)
|
||||||
|
const range = max - min
|
||||||
|
const angle = -135 + ((clamp(value, min, max) - min) / range) * 270
|
||||||
|
const start = bipolar ? -135 + ((defaultValue - min) / range) * 270 : -135
|
||||||
|
const c = size / 2
|
||||||
|
const r = c - 3
|
||||||
|
const [px, py] = polar(r - 4, angle, c)
|
||||||
|
|
||||||
|
const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
|
||||||
|
if (e.button !== 0) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
drag.current = { y: e.clientY, v: value }
|
||||||
|
}
|
||||||
|
const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {
|
||||||
|
const d = drag.current
|
||||||
|
if (!d) return
|
||||||
|
const px = e.shiftKey ? DRAG_PX * 5 : DRAG_PX
|
||||||
|
onChange(clamp(d.v + ((d.y - e.clientY) / px) * range, min, max))
|
||||||
|
}
|
||||||
|
const onWheel = (e: WheelEvent<HTMLDivElement>) => {
|
||||||
|
onChange(clamp(value - (e.deltaY / (e.shiftKey ? 2000 : 400)) * range, min, max))
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center gap-0.5" title={describe(value)}>
|
||||||
|
<div
|
||||||
|
role="slider"
|
||||||
|
aria-label={label}
|
||||||
|
aria-valuemin={min}
|
||||||
|
aria-valuemax={max}
|
||||||
|
aria-valuenow={value}
|
||||||
|
onPointerDown={onPointerDown}
|
||||||
|
onPointerMove={onPointerMove}
|
||||||
|
onPointerUp={() => (drag.current = null)}
|
||||||
|
onPointerCancel={() => (drag.current = null)}
|
||||||
|
onDoubleClick={() => onChange(defaultValue)}
|
||||||
|
onWheel={onWheel}
|
||||||
|
className="cursor-ns-resize touch-none select-none"
|
||||||
|
style={{ width: size, height: size }}
|
||||||
|
>
|
||||||
|
<svg width={size} height={size}>
|
||||||
|
<circle cx={c} cy={c} r={r} fill="rgb(0 0 0 / 0.36)" stroke="rgb(255 255 255 / 0.08)" />
|
||||||
|
<path d={arc(r, -135, 135, c)} fill="none" stroke="rgb(255 255 255 / 0.1)" strokeWidth={2.5} strokeLinecap="round" />
|
||||||
|
<path
|
||||||
|
d={arc(r, start, angle, c)}
|
||||||
|
fill="none"
|
||||||
|
stroke={color}
|
||||||
|
strokeWidth={2.5}
|
||||||
|
strokeLinecap="round"
|
||||||
|
style={{ filter: `drop-shadow(0 0 3px ${color})` }}
|
||||||
|
/>
|
||||||
|
<line x1={c} y1={c} x2={px} y2={py} stroke="var(--color-text)" strokeWidth={2} strokeLinecap="round" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<span className="text-[8.5px] font-semibold uppercase leading-none tracking-[0.08em] text-faint">{label}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FaderProps {
|
||||||
|
value: number
|
||||||
|
min: number
|
||||||
|
max: number
|
||||||
|
defaultValue: number
|
||||||
|
onChange: (v: number) => void
|
||||||
|
orientation: 'vertical' | 'horizontal'
|
||||||
|
label: string
|
||||||
|
describe: (v: number) => string
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A fader: grab anywhere on it and the cap follows the pointer. */
|
||||||
|
export function Fader({ value, min, max, defaultValue, onChange, orientation, label, describe, className = '' }: FaderProps) {
|
||||||
|
const vertical = orientation === 'vertical'
|
||||||
|
const t = (clamp(value, min, max) - min) / (max - min)
|
||||||
|
const set = (e: PointerEvent<HTMLDivElement>) => {
|
||||||
|
const box = e.currentTarget.getBoundingClientRect()
|
||||||
|
const f = vertical ? 1 - (e.clientY - box.top) / box.height : (e.clientX - box.left) / box.width
|
||||||
|
onChange(min + clamp(f, 0, 1) * (max - min))
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="slider"
|
||||||
|
aria-label={label}
|
||||||
|
aria-orientation={orientation}
|
||||||
|
aria-valuemin={min}
|
||||||
|
aria-valuemax={max}
|
||||||
|
aria-valuenow={value}
|
||||||
|
title={describe(value)}
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
if (e.button !== 0) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
set(e)
|
||||||
|
}}
|
||||||
|
onPointerMove={(e) => e.currentTarget.hasPointerCapture(e.pointerId) && set(e)}
|
||||||
|
onDoubleClick={() => onChange(defaultValue)}
|
||||||
|
className={`relative touch-none select-none ${vertical ? 'w-6 cursor-ns-resize' : 'h-6 cursor-ew-resize'} ${className}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`well absolute rounded-full ${vertical ? 'inset-y-1.5 left-1/2 w-1.5 -translate-x-1/2' : 'inset-x-1.5 top-1/2 h-1.5 -translate-y-1/2'}`}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={`btn-glass pointer-events-none absolute rounded-md ${
|
||||||
|
vertical ? 'left-0 h-3 w-6 -translate-y-1/2' : 'top-0 h-6 w-3 -translate-x-1/2'
|
||||||
|
}`}
|
||||||
|
style={vertical ? { top: `calc(0.375rem + ${(1 - t) * 100}% - ${(1 - t) * 0.75}rem)` } : { left: `calc(0.375rem + ${t * 100}% - ${t * 0.75}rem)` }}
|
||||||
|
>
|
||||||
|
<span className={`absolute bg-text/80 ${vertical ? 'inset-x-1 top-1/2 h-px' : 'inset-y-1 left-1/2 w-px'}`} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
import { useEffect, useRef, useState, type RefObject } from 'react'
|
||||||
|
import { mixer } from '../../lib/audio/mixer'
|
||||||
|
import { faderGain, filterSweep, echoBeats, eqGain, gainToDb, TRIM_RANGE_DB, EQ_CUT_DB } from '../../lib/audio/mixerMath'
|
||||||
|
import {
|
||||||
|
DEFAULT_CHANNEL,
|
||||||
|
FX_LABELS,
|
||||||
|
FX_PARAM,
|
||||||
|
FX_TYPES,
|
||||||
|
setChannel,
|
||||||
|
setMixer,
|
||||||
|
useMixer,
|
||||||
|
type Channel,
|
||||||
|
type FxType,
|
||||||
|
} from '../../lib/audio/mixerState'
|
||||||
|
import { Icon } from '../../lib/icons'
|
||||||
|
import { ContextMenu } from '../ContextMenu'
|
||||||
|
import { Fader, Knob } from './Controls'
|
||||||
|
|
||||||
|
/** The meters' scale (dBFS). */
|
||||||
|
const METER_FLOOR = -48
|
||||||
|
const METER_TOP = 3
|
||||||
|
|
||||||
|
const fmtDb = (db: number, places = 1) =>
|
||||||
|
!isFinite(db) ? '−∞ dB' : `${db > 0 ? '+' : db < 0 ? '−' : ''}${Math.abs(db).toFixed(places)} dB`
|
||||||
|
|
||||||
|
function describeFx(fx: FxType, c: number, param: number): string {
|
||||||
|
const a = Math.round(Math.abs(c) * 100)
|
||||||
|
if (Math.abs(c) < 0.02) return `${FX_LABELS[fx]}: off (turn left or right)`
|
||||||
|
switch (fx) {
|
||||||
|
case 'filter': {
|
||||||
|
const s = filterSweep(c)!
|
||||||
|
const hz = s.freq >= 1000 ? `${(s.freq / 1000).toFixed(1)} kHz` : `${Math.round(s.freq)} Hz`
|
||||||
|
return `Filter: ${s.type === 'lowpass' ? 'low-pass' : 'high-pass'} at ${hz}`
|
||||||
|
}
|
||||||
|
case 'echo':
|
||||||
|
return `Echo ${a}% · ${beatsLabel(echoBeats(param))} · ${c < 0 ? 'darker' : 'thinner'} repeats`
|
||||||
|
case 'space':
|
||||||
|
return `Space ${a}% · ${c < 0 ? 'darker' : 'thinner'}`
|
||||||
|
case 'noise':
|
||||||
|
return `Noise ${a}% · ${c < 0 ? 'low-pass' : 'high-pass'} sweep`
|
||||||
|
case 'crush':
|
||||||
|
return `Crush ${a}%`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function beatsLabel(b: number): string {
|
||||||
|
return b === 1 ? '1 beat' : b === 0.75 ? '3/4 beat' : b === 0.5 ? '1/2 beat' : b === 0.25 ? '1/4 beat' : '1/8 beat'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mixer, between the decks in performance mode (decided 2026-11-02): per
|
||||||
|
* channel TRIM (on top of the track's auto gain), HI / MID / LOW, a colour
|
||||||
|
* effect with its own selector and parameter, a fader and its meter; between
|
||||||
|
* them the master meter and the limiter's light; the crossfader beneath. The
|
||||||
|
* values live in `mixerState` and the audio in `mixer.ts`.
|
||||||
|
*/
|
||||||
|
export function MixerPanel({ autoGain }: { autoGain: Record<Channel, number | null> }) {
|
||||||
|
const meterRefs = {
|
||||||
|
A: useRef<HTMLDivElement>(null),
|
||||||
|
B: useRef<HTMLDivElement>(null),
|
||||||
|
master: useRef<HTMLDivElement>(null),
|
||||||
|
}
|
||||||
|
const limitRef = useRef<HTMLSpanElement>(null)
|
||||||
|
|
||||||
|
// One frame loop for every meter, writing the DOM directly — sixty React
|
||||||
|
// renders a second for three bars would be waste.
|
||||||
|
useEffect(() => {
|
||||||
|
let raf = 0
|
||||||
|
const held = { A: METER_FLOOR, B: METER_FLOOR, master: METER_FLOOR }
|
||||||
|
let limitUntil = 0
|
||||||
|
const tick = (now: number) => {
|
||||||
|
const lv = mixer().levels()
|
||||||
|
for (const k of ['A', 'B', 'master'] as const) {
|
||||||
|
const db = Math.max(METER_FLOOR, lv[k])
|
||||||
|
held[k] = db >= held[k] ? db : Math.max(db, held[k] - 0.6) // fall back ~36 dB/s
|
||||||
|
const el = meterRefs[k].current
|
||||||
|
if (el) {
|
||||||
|
el.style.height = `${((held[k] - METER_FLOOR) / (METER_TOP - METER_FLOOR)) * 100}%`
|
||||||
|
el.style.background =
|
||||||
|
held[k] > -1 ? 'var(--color-pink)' : held[k] > -9 ? 'var(--color-gold)' : 'var(--color-mint)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (lv.limiting > 0.5) limitUntil = now + 600
|
||||||
|
if (limitRef.current) limitRef.current.dataset.on = String(now < limitUntil)
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(tick)
|
||||||
|
return () => cancelAnimationFrame(raf)
|
||||||
|
// The refs are stable.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const crossfader = useMixer((s) => s.crossfader)
|
||||||
|
const curve = useMixer((s) => s.curve)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="well flex w-[24rem] shrink-0 flex-col gap-1.5 rounded-2xl px-2.5 pb-1.5 pt-2.5">
|
||||||
|
<div className="flex min-h-0 flex-1 items-stretch gap-2">
|
||||||
|
<Strip ch="A" autoGain={autoGain.A} meterRef={meterRefs.A} />
|
||||||
|
<div className="flex w-3 flex-col items-center gap-1" title="Master — after the limiter">
|
||||||
|
<MeterBar fillRef={meterRefs.master} />
|
||||||
|
<span
|
||||||
|
ref={limitRef}
|
||||||
|
data-on="false"
|
||||||
|
title="The limiter is holding the master below clipping"
|
||||||
|
className="text-[7.5px] font-bold leading-none tracking-[0.04em] text-faint/50 data-[on=true]:text-pink data-[on=true]:[text-shadow:0_0_6px_var(--color-pink)]"
|
||||||
|
>
|
||||||
|
LIM
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Strip ch="B" autoGain={autoGain.B} meterRef={meterRefs.B} mirrored />
|
||||||
|
</div>
|
||||||
|
<div className="flex h-6 shrink-0 items-center gap-2 px-1">
|
||||||
|
<span className="font-mono text-[11px] font-semibold text-muted">A</span>
|
||||||
|
<Fader
|
||||||
|
orientation="horizontal"
|
||||||
|
value={crossfader}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
onChange={(v) => setMixer({ crossfader: Math.abs(v) < 0.03 ? 0 : v })}
|
||||||
|
label="Crossfader"
|
||||||
|
describe={(v) =>
|
||||||
|
`Crossfader (${curve === 'smooth' ? 'smooth' : 'sharp'} curve) — ${
|
||||||
|
Math.abs(v) < 0.03 ? 'centre' : v < 0 ? `toward A ${Math.round(-v * 100)}%` : `toward B ${Math.round(v * 100)}%`
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<span className="font-mono text-[11px] font-semibold text-muted">B</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MeterBar({ fillRef }: { fillRef: RefObject<HTMLDivElement | null> }) {
|
||||||
|
return (
|
||||||
|
<div className="relative w-1.5 flex-1 overflow-hidden rounded-full bg-black/40">
|
||||||
|
<div ref={fillRef} className="absolute inset-x-0 bottom-0 h-0 rounded-full transition-[background-color] duration-150" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One channel: its knobs, then (toward the middle) its fader and meter. */
|
||||||
|
function Strip({
|
||||||
|
ch,
|
||||||
|
autoGain,
|
||||||
|
meterRef,
|
||||||
|
mirrored = false,
|
||||||
|
}: {
|
||||||
|
ch: Channel
|
||||||
|
autoGain: number | null
|
||||||
|
meterRef: RefObject<HTMLDivElement | null>
|
||||||
|
mirrored?: boolean
|
||||||
|
}) {
|
||||||
|
const s = useMixer((m) => m[ch])
|
||||||
|
const eqKill = useMixer((m) => m.eqKill)
|
||||||
|
const [fxMenu, setFxMenu] = useState<{ x: number; y: number } | null>(null)
|
||||||
|
const set = (patch: Parameters<typeof setChannel>[1]) => setChannel(ch, patch)
|
||||||
|
const describeEq = (band: string) => (v: number) => {
|
||||||
|
const g = eqGain(v, eqKill)
|
||||||
|
return `${band} ${Math.abs(v) < 0.01 ? 'flat' : g === 0 ? 'killed' : fmtDb(gainToDb(g))}${
|
||||||
|
v < 0 ? ` (full left: ${eqKill ? 'kill' : `${EQ_CUT_DB} dB`})` : ''
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
const eq = (band: 'high' | 'mid' | 'low', label: string, name: string) => (
|
||||||
|
<Knob
|
||||||
|
value={s[band]}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
bipolar
|
||||||
|
onChange={(v) => set({ [band]: Math.abs(v) < 0.03 ? 0 : v })}
|
||||||
|
label={label}
|
||||||
|
describe={describeEq(name)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
const knobs = (
|
||||||
|
<div className="grid grid-cols-4 content-between gap-x-1.5">
|
||||||
|
<Knob
|
||||||
|
value={s.trim}
|
||||||
|
min={-TRIM_RANGE_DB}
|
||||||
|
max={TRIM_RANGE_DB}
|
||||||
|
defaultValue={0}
|
||||||
|
bipolar
|
||||||
|
color="var(--color-text)"
|
||||||
|
onChange={(v) => set({ trim: Math.abs(v) < 0.3 ? 0 : v })}
|
||||||
|
label="Trim"
|
||||||
|
describe={(v) =>
|
||||||
|
`Trim ${fmtDb(v)}${autoGain != null ? ` on the track's auto gain (${fmtDb(autoGain)})` : ' (this track has no auto gain)'}`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{eq('high', 'Hi', 'High')}
|
||||||
|
{eq('mid', 'Mid', 'Mid')}
|
||||||
|
{eq('low', 'Low', 'Low')}
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
const r = e.currentTarget.getBoundingClientRect()
|
||||||
|
setFxMenu({ x: r.left, y: r.bottom + 4 })
|
||||||
|
}}
|
||||||
|
title="Which effect the COLOR knob drives"
|
||||||
|
className="btn-glass col-span-2 mt-0.5 flex h-6 items-center justify-center gap-0.5 self-start rounded-md text-[10px] font-semibold uppercase tracking-[0.06em] text-text"
|
||||||
|
>
|
||||||
|
{FX_LABELS[s.fx]}
|
||||||
|
<Icon name="chevronDown" size={11} />
|
||||||
|
</button>
|
||||||
|
<Knob
|
||||||
|
value={s.color}
|
||||||
|
min={-1}
|
||||||
|
max={1}
|
||||||
|
defaultValue={0}
|
||||||
|
bipolar
|
||||||
|
color="var(--color-gold)"
|
||||||
|
onChange={(v) => set({ color: Math.abs(v) < 0.02 ? 0 : v })}
|
||||||
|
label="Color"
|
||||||
|
describe={(v) => describeFx(s.fx, v, s.param)}
|
||||||
|
/>
|
||||||
|
<Knob
|
||||||
|
value={s.param}
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
defaultValue={DEFAULT_CHANNEL.param}
|
||||||
|
color="var(--color-gold)"
|
||||||
|
onChange={(v) => set({ param: v })}
|
||||||
|
label="Prm"
|
||||||
|
describe={(v) =>
|
||||||
|
`${FX_PARAM[s.fx]}: ${s.fx === 'echo' ? beatsLabel(echoBeats(v)) : `${Math.round(v * 100)}%`}`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
const fader = (
|
||||||
|
<div className="flex flex-col items-center gap-0.5">
|
||||||
|
<Fader
|
||||||
|
orientation="vertical"
|
||||||
|
value={s.fader}
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
defaultValue={1}
|
||||||
|
onChange={(v) => set({ fader: v })}
|
||||||
|
label={`Channel ${ch} fader`}
|
||||||
|
describe={(v) => `Channel ${ch}: ${fmtDb(gainToDb(faderGain(v)))}`}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<span className="font-mono text-[10px] font-semibold leading-none text-muted">{ch}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
const meter = (
|
||||||
|
<div className="flex flex-col pb-3" title={`Channel ${ch} level (after its fader)`}>
|
||||||
|
<MeterBar fillRef={meterRef} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
<div className={`flex min-w-0 flex-1 items-stretch gap-1.5 ${mirrored ? 'flex-row-reverse' : ''}`}>
|
||||||
|
{knobs}
|
||||||
|
{fader}
|
||||||
|
{meter}
|
||||||
|
{fxMenu && (
|
||||||
|
<ContextMenu
|
||||||
|
x={fxMenu.x}
|
||||||
|
y={fxMenu.y}
|
||||||
|
onClose={() => setFxMenu(null)}
|
||||||
|
items={[
|
||||||
|
{ heading: `Channel ${ch} · colour effect` },
|
||||||
|
...FX_TYPES.map((t) => ({
|
||||||
|
label: FX_LABELS[t],
|
||||||
|
hint: t === s.fx ? '✓' : undefined,
|
||||||
|
onClick: () => set({ fx: t }),
|
||||||
|
})),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
// The app's ONE AudioContext. Every deck plays into it, so the decks can be
|
// The app's ONE AudioContext. Every deck plays into it, so the decks can be
|
||||||
// mixed (and limited) before the speakers; two contexts cannot be connected.
|
// mixed (and limited) before the speakers — two contexts cannot be connected.
|
||||||
// Never closed: a deck that goes away disconnects its own nodes.
|
// Never closed: a deck that goes away disconnects its own nodes. The route to
|
||||||
|
// the speakers is the mixer's (mixer.ts).
|
||||||
|
|
||||||
import deckWorkletUrl from './deckProcessor.worklet.ts?worker&url'
|
import deckWorkletUrl from './deckProcessor.worklet.ts?worker&url'
|
||||||
import rubberbandUrl from './rubberband.wasm?url'
|
import rubberbandUrl from './rubberband.wasm?url'
|
||||||
|
|
||||||
let ctx: AudioContext | null = null
|
let ctx: AudioContext | null = null
|
||||||
let master: GainNode | null = null
|
|
||||||
let worklet: Promise<ArrayBuffer | null> | null = null
|
let worklet: Promise<ArrayBuffer | null> | null = null
|
||||||
|
|
||||||
export function audioContext(): AudioContext {
|
export function audioContext(): AudioContext {
|
||||||
@@ -14,8 +14,6 @@ export function audioContext(): AudioContext {
|
|||||||
const AC: typeof AudioContext =
|
const AC: typeof AudioContext =
|
||||||
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
||||||
ctx = new AC({ latencyHint: 'interactive' })
|
ctx = new AC({ latencyHint: 'interactive' })
|
||||||
master = ctx.createGain()
|
|
||||||
master.connect(ctx.destination)
|
|
||||||
}
|
}
|
||||||
return ctx
|
return ctx
|
||||||
}
|
}
|
||||||
@@ -25,12 +23,6 @@ export function resumeAudio(): void {
|
|||||||
void audioContext().resume()
|
void audioContext().resume()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Where decks connect: the master bus. */
|
|
||||||
export function masterInput(): AudioNode {
|
|
||||||
audioContext()
|
|
||||||
return master!
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the deck processor (once per context) and fetch Rubber Band's
|
* Register the deck processor (once per context) and fetch Rubber Band's
|
||||||
* module bytes for keylock. Resolves to null bytes when the module cannot be
|
* module bytes for keylock. Resolves to null bytes when the module cannot be
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
// ignored, so a stale position can never snap the playhead back.
|
// ignored, so a stale position can never snap the playhead back.
|
||||||
|
|
||||||
import type { DecodedAudio } from '../waveform'
|
import type { DecodedAudio } from '../waveform'
|
||||||
import { audioContext, loadDeckWorklet, masterInput, resumeAudio } from './context'
|
import { audioContext, loadDeckWorklet, resumeAudio } from './context'
|
||||||
import type { DeckCommand, DeckInbound, DeckOutbound } from './deckProcessor.worklet'
|
import type { DeckCommand, DeckInbound, DeckOutbound } from './deckProcessor.worklet'
|
||||||
import { extrapolate, type Loop, type Model } from './position'
|
import { extrapolate, type Loop, type Model } from './position'
|
||||||
|
|
||||||
@@ -27,13 +27,14 @@ export class DeckEngine {
|
|||||||
private onEnded: (() => void) | null = null
|
private onEnded: (() => void) | null = null
|
||||||
private onScratchDone: ((playing: boolean) => void) | null = null
|
private onScratchDone: ((playing: boolean) => void) | null = null
|
||||||
|
|
||||||
/** The worklet module loads asynchronously, once per app. */
|
/** The worklet module loads asynchronously, once per app. `destination` is
|
||||||
static async create(): Promise<DeckEngine> {
|
* where the deck plays into: its mixer channel. */
|
||||||
|
static async create(destination: AudioNode): Promise<DeckEngine> {
|
||||||
const wasm = await loadDeckWorklet()
|
const wasm = await loadDeckWorklet()
|
||||||
return new DeckEngine(wasm)
|
return new DeckEngine(wasm, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
private constructor(wasm: ArrayBuffer | null) {
|
private constructor(wasm: ArrayBuffer | null, destination: AudioNode) {
|
||||||
this.ctx = audioContext()
|
this.ctx = audioContext()
|
||||||
this.node = new AudioWorkletNode(this.ctx, 'konduktor-deck', {
|
this.node = new AudioWorkletNode(this.ctx, 'konduktor-deck', {
|
||||||
numberOfInputs: 0,
|
numberOfInputs: 0,
|
||||||
@@ -43,7 +44,7 @@ export class DeckEngine {
|
|||||||
})
|
})
|
||||||
this.output = this.ctx.createGain()
|
this.output = this.ctx.createGain()
|
||||||
this.node.connect(this.output)
|
this.node.connect(this.output)
|
||||||
this.output.connect(masterInput())
|
this.output.connect(destination)
|
||||||
this.node.port.onmessage = (e: MessageEvent<DeckOutbound>) => this.receive(e.data)
|
this.node.port.onmessage = (e: MessageEvent<DeckOutbound>) => this.receive(e.data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,431 @@
|
|||||||
|
// The mixer's audio graph (performance mode, decided 2026-11-02). Both decks
|
||||||
|
// play into it; it follows the controls in `mixerState.ts`.
|
||||||
|
//
|
||||||
|
// deck → trim → 3-band isolator → colour FX → fader ─┬→ crossfader → bus
|
||||||
|
// └→ meter
|
||||||
|
// bus → limiter → master meter → speakers
|
||||||
|
//
|
||||||
|
// TRIM starts at the track's own auto gain (the DJ app's, `Track.auto_gain_db`;
|
||||||
|
// none = 0 dB) plus the knob. The ISOLATOR splits at 250 Hz / 2.5 kHz with
|
||||||
|
// Linkwitz-Riley (LR4) crossovers, the low band through an all-pass matching
|
||||||
|
// the upper crossover, so the three bands sum back to flat — measured to 0.0001
|
||||||
|
// dB — and a band can be cut to silence (`eqKill`). Web Audio's lowpass /
|
||||||
|
// highpass Q is in dB (Butterworth = -3.01) while its allpass Q is linear.
|
||||||
|
// The LIMITER is a DynamicsCompressor set as one (-1.5 dBFS, 20:1, 1 ms), and
|
||||||
|
// `levels().limiting` is its gain reduction. Web Audio's compressor adds an
|
||||||
|
// automatic MAKE-UP gain — (1 / its gain at 0 dBFS)^0.6, +0.57 dB at -1 / 20:1
|
||||||
|
// — which raised everything in circuit and let two loud decks peak at +0.3
|
||||||
|
// dBFS (measured); a gain after it takes exactly that back off.
|
||||||
|
//
|
||||||
|
// Outside performance mode the mixer is BYPASSED: deck A goes straight to the
|
||||||
|
// speakers, as the prep deck always has, deck B is silent, and the limiter is
|
||||||
|
// out of the path — so prep listening is unchanged.
|
||||||
|
|
||||||
|
import { audioContext } from './context'
|
||||||
|
import {
|
||||||
|
dbToGain,
|
||||||
|
echoSeconds,
|
||||||
|
eqGain,
|
||||||
|
EQ_HIGH_HZ,
|
||||||
|
EQ_LOW_HZ,
|
||||||
|
faderGain,
|
||||||
|
filterSweep,
|
||||||
|
FX_CENTRE,
|
||||||
|
TRIM_RANGE_DB,
|
||||||
|
xfadeGains,
|
||||||
|
} from './mixerMath'
|
||||||
|
import { getMixerState, subscribeMixer, type Channel, type ChannelState, type FxType } from './mixerState'
|
||||||
|
|
||||||
|
/** Butterworth Q in Web Audio's lowpass/highpass units (dB). */
|
||||||
|
const BUTTERWORTH_DB = 20 * Math.log10(Math.SQRT1_2)
|
||||||
|
const LIMIT_DB = -1.5
|
||||||
|
const LIMIT_RATIO = 20
|
||||||
|
/** The compressor's automatic make-up gain (Web Audio spec: the inverse of its
|
||||||
|
* gain at 0 dBFS, to the power 0.6), in dB. */
|
||||||
|
const MAKEUP_DB = -0.6 * (LIMIT_DB + (0 - LIMIT_DB) / LIMIT_RATIO)
|
||||||
|
|
||||||
|
/** Parameter smoothing (s): fast enough to feel direct, slow enough not to click. */
|
||||||
|
const GLIDE = 0.012
|
||||||
|
|
||||||
|
function ramp(param: AudioParam, value: number, ctx: AudioContext, tau = GLIDE): void {
|
||||||
|
param.setTargetAtTime(value, ctx.currentTime, tau)
|
||||||
|
}
|
||||||
|
|
||||||
|
function biquad(ctx: AudioContext, type: BiquadFilterType, freq: number, q: number): BiquadFilterNode {
|
||||||
|
const f = ctx.createBiquadFilter()
|
||||||
|
f.type = type
|
||||||
|
f.frequency.value = freq
|
||||||
|
f.Q.value = q
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Two cascaded Butterworth sections: one LR4 half. */
|
||||||
|
function lr4(ctx: AudioContext, type: 'lowpass' | 'highpass', freq: number): [BiquadFilterNode, BiquadFilterNode] {
|
||||||
|
const a = biquad(ctx, type, freq, BUTTERWORTH_DB)
|
||||||
|
const b = biquad(ctx, type, freq, BUTTERWORTH_DB)
|
||||||
|
a.connect(b)
|
||||||
|
return [a, b]
|
||||||
|
}
|
||||||
|
|
||||||
|
function noiseBuffer(ctx: AudioContext, seconds: number): AudioBuffer {
|
||||||
|
const buf = ctx.createBuffer(2, Math.round(ctx.sampleRate * seconds), ctx.sampleRate)
|
||||||
|
for (let c = 0; c < 2; c++) {
|
||||||
|
const d = buf.getChannelData(c)
|
||||||
|
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1
|
||||||
|
}
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A reverb impulse: stereo noise decaying 60 dB over `seconds`. */
|
||||||
|
function impulse(ctx: AudioContext, seconds: number): AudioBuffer {
|
||||||
|
const buf = noiseBuffer(ctx, seconds)
|
||||||
|
const k = -6.9 / (seconds * ctx.sampleRate)
|
||||||
|
for (let c = 0; c < 2; c++) {
|
||||||
|
const d = buf.getChannelData(c)
|
||||||
|
for (let i = 0; i < d.length; i++) d[i] *= Math.exp(k * i)
|
||||||
|
}
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A bit-crusher's transfer curve at `bits` of resolution. */
|
||||||
|
function crushCurve(bits: number): Float32Array<ArrayBuffer> {
|
||||||
|
const n = 2048
|
||||||
|
const steps = 2 ** bits / 2
|
||||||
|
const curve = new Float32Array(n)
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const x = (i / (n - 1)) * 2 - 1
|
||||||
|
curve[i] = Math.round(x * steps) / steps
|
||||||
|
}
|
||||||
|
return curve
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One channel's colour effect: ONE knob, -1..1, out of the path at the centre;
|
||||||
|
* which effect it drives is the channel's own choice (decided 2026-11-02).
|
||||||
|
* Every effect is built once and switched by gains, so a change never clicks;
|
||||||
|
* echo and reverb tails ring out after the knob returns.
|
||||||
|
*/
|
||||||
|
class ColorFx {
|
||||||
|
readonly input: GainNode
|
||||||
|
readonly output: GainNode
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly dry: GainNode
|
||||||
|
// Filter (also the music's path for Crush's tone).
|
||||||
|
private readonly filter: BiquadFilterNode
|
||||||
|
private readonly filterWet: GainNode
|
||||||
|
// Echo: a send into a delay with filtered feedback.
|
||||||
|
private readonly echoSend: GainNode
|
||||||
|
private readonly delay: DelayNode
|
||||||
|
private readonly echoTone: BiquadFilterNode
|
||||||
|
private readonly feedback: GainNode
|
||||||
|
// Space: a send into a convolver.
|
||||||
|
private readonly spaceSend: GainNode
|
||||||
|
private readonly spaceTone: BiquadFilterNode
|
||||||
|
private readonly convolver: ConvolverNode
|
||||||
|
private spaceSize = -1
|
||||||
|
// Noise: filtered white noise mixed in.
|
||||||
|
private readonly noiseFilter: BiquadFilterNode
|
||||||
|
private readonly noiseGain: GainNode
|
||||||
|
// Crush.
|
||||||
|
private readonly crushDrive: GainNode
|
||||||
|
private readonly shaper: WaveShaperNode
|
||||||
|
private readonly crushWet: GainNode
|
||||||
|
private crushBits = -1
|
||||||
|
|
||||||
|
constructor(ctx: AudioContext) {
|
||||||
|
this.ctx = ctx
|
||||||
|
this.input = ctx.createGain()
|
||||||
|
this.output = ctx.createGain()
|
||||||
|
this.dry = ctx.createGain()
|
||||||
|
this.input.connect(this.dry).connect(this.output)
|
||||||
|
|
||||||
|
this.filter = biquad(ctx, 'lowpass', 20000, 0)
|
||||||
|
this.filterWet = ctx.createGain()
|
||||||
|
this.filterWet.gain.value = 0
|
||||||
|
this.input.connect(this.filter).connect(this.filterWet).connect(this.output)
|
||||||
|
|
||||||
|
this.echoSend = ctx.createGain()
|
||||||
|
this.echoSend.gain.value = 0
|
||||||
|
this.delay = ctx.createDelay(4)
|
||||||
|
this.echoTone = biquad(ctx, 'lowpass', 2500, 0)
|
||||||
|
this.feedback = ctx.createGain()
|
||||||
|
this.feedback.gain.value = 0.45
|
||||||
|
this.input.connect(this.echoSend).connect(this.delay)
|
||||||
|
this.delay.connect(this.echoTone).connect(this.feedback).connect(this.delay)
|
||||||
|
this.delay.connect(this.output)
|
||||||
|
|
||||||
|
this.spaceSend = ctx.createGain()
|
||||||
|
this.spaceSend.gain.value = 0
|
||||||
|
this.spaceTone = biquad(ctx, 'lowpass', 20000, 0)
|
||||||
|
this.convolver = ctx.createConvolver()
|
||||||
|
this.input.connect(this.spaceSend).connect(this.spaceTone).connect(this.convolver).connect(this.output)
|
||||||
|
|
||||||
|
const noise = ctx.createBufferSource()
|
||||||
|
noise.buffer = noiseBuffer(ctx, 2)
|
||||||
|
noise.loop = true
|
||||||
|
this.noiseFilter = biquad(ctx, 'lowpass', 20000, 0)
|
||||||
|
this.noiseGain = ctx.createGain()
|
||||||
|
this.noiseGain.gain.value = 0
|
||||||
|
noise.connect(this.noiseFilter).connect(this.noiseGain).connect(this.output)
|
||||||
|
noise.start()
|
||||||
|
|
||||||
|
this.crushDrive = ctx.createGain()
|
||||||
|
this.shaper = ctx.createWaveShaper()
|
||||||
|
this.crushWet = ctx.createGain()
|
||||||
|
this.crushWet.gain.value = 0
|
||||||
|
this.input.connect(this.crushDrive).connect(this.shaper).connect(this.crushWet).connect(this.output)
|
||||||
|
}
|
||||||
|
|
||||||
|
apply(type: FxType, color: number, param: number, bpm: number): void {
|
||||||
|
const ctx = this.ctx
|
||||||
|
const a = Math.min(1, Math.abs(color))
|
||||||
|
const on = a >= FX_CENTRE
|
||||||
|
// Whatever replaces the dry signal (filter, crush) fades in over the first
|
||||||
|
// few percent of the knob, so leaving the centre never jumps.
|
||||||
|
const take = on ? Math.min(1, a / 0.06) : 0
|
||||||
|
const sweep = filterSweep(color)
|
||||||
|
|
||||||
|
// Filter: the music itself, swept.
|
||||||
|
const filtering = type === 'filter' && sweep != null
|
||||||
|
if (filtering) {
|
||||||
|
if (this.filter.type !== sweep.type) this.filter.type = sweep.type
|
||||||
|
ramp(this.filter.frequency, sweep.freq, ctx)
|
||||||
|
ramp(this.filter.Q, param * 15, ctx)
|
||||||
|
}
|
||||||
|
ramp(this.filterWet.gain, filtering ? take : 0, ctx)
|
||||||
|
|
||||||
|
// Echo: send + feedback grow with the knob; left darker, right thinner.
|
||||||
|
const echoing = type === 'echo' && on
|
||||||
|
ramp(this.echoSend.gain, echoing ? a * 0.8 : 0, ctx)
|
||||||
|
ramp(this.feedback.gain, echoing ? 0.35 + 0.5 * a : 0.45, ctx, 0.05)
|
||||||
|
if (type === 'echo') {
|
||||||
|
ramp(this.delay.delayTime, echoSeconds(param, bpm), ctx, 0.05)
|
||||||
|
const tone = color < 0 ? 'lowpass' : 'highpass'
|
||||||
|
if (this.echoTone.type !== tone) this.echoTone.type = tone
|
||||||
|
ramp(this.echoTone.frequency, color < 0 ? 2500 : 600, ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Space: a reverb send; left darker, right thinner.
|
||||||
|
const spacing = type === 'space' && on
|
||||||
|
ramp(this.spaceSend.gain, spacing ? a : 0, ctx)
|
||||||
|
if (type === 'space') {
|
||||||
|
const size = Math.round((0.8 + param * 4) * 10) / 10
|
||||||
|
if (size !== this.spaceSize) {
|
||||||
|
this.spaceSize = size
|
||||||
|
this.convolver.buffer = impulse(ctx, size)
|
||||||
|
}
|
||||||
|
const tone = color < 0 ? 'lowpass' : 'highpass'
|
||||||
|
if (this.spaceTone.type !== tone) this.spaceTone.type = tone
|
||||||
|
ramp(this.spaceTone.frequency, color < 0 ? 1500 : 700, ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Noise: white noise swept the way the filter is, the music untouched.
|
||||||
|
const noising = type === 'noise' && sweep != null
|
||||||
|
if (noising) {
|
||||||
|
if (this.noiseFilter.type !== sweep.type) this.noiseFilter.type = sweep.type
|
||||||
|
ramp(this.noiseFilter.frequency, sweep.freq, ctx)
|
||||||
|
ramp(this.noiseFilter.Q, param * 15, ctx)
|
||||||
|
}
|
||||||
|
ramp(this.noiseGain.gain, noising ? a * 0.25 : 0, ctx)
|
||||||
|
|
||||||
|
// Crush: fewer bits as the knob opens (16 → 3), driven by the parameter.
|
||||||
|
const crushing = type === 'crush' && on
|
||||||
|
if (crushing) {
|
||||||
|
const bits = Math.round(16 - a * 13)
|
||||||
|
if (bits !== this.crushBits) {
|
||||||
|
this.crushBits = bits
|
||||||
|
this.shaper.curve = crushCurve(bits)
|
||||||
|
}
|
||||||
|
const drive = 1 + param * 3
|
||||||
|
ramp(this.crushDrive.gain, drive, ctx)
|
||||||
|
}
|
||||||
|
ramp(this.crushWet.gain, crushing ? take / (1 + param * 3) ** 0.5 : 0, ctx)
|
||||||
|
|
||||||
|
ramp(this.dry.gain, filtering || crushing ? 1 - take : 1, ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Strip {
|
||||||
|
readonly input: GainNode
|
||||||
|
readonly meter: AnalyserNode
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly trim: GainNode
|
||||||
|
private readonly bands: [GainNode, GainNode, GainNode]
|
||||||
|
private readonly fx: ColorFx
|
||||||
|
private readonly fader: GainNode
|
||||||
|
private readonly xfade: GainNode
|
||||||
|
/** In circuit (performance mode) vs straight through (prep). */
|
||||||
|
private readonly wetGate: GainNode
|
||||||
|
private readonly dryGate: GainNode
|
||||||
|
autoGainDb = 0
|
||||||
|
bpm = 0
|
||||||
|
|
||||||
|
constructor(ctx: AudioContext, bus: AudioNode) {
|
||||||
|
this.ctx = ctx
|
||||||
|
this.input = ctx.createGain()
|
||||||
|
this.trim = ctx.createGain()
|
||||||
|
this.input.connect(this.trim)
|
||||||
|
|
||||||
|
// Isolator: low = LR4 low-pass @250 then an all-pass @2.5k (the phase the
|
||||||
|
// other bands get from their LR4 pair there); mid = high-pass @250 then
|
||||||
|
// low-pass @2.5k; high = high-pass @250 then high-pass @2.5k.
|
||||||
|
const eqOut = ctx.createGain()
|
||||||
|
const [lpA, lpB] = lr4(ctx, 'lowpass', EQ_LOW_HZ)
|
||||||
|
const [hpA, hpB] = lr4(ctx, 'highpass', EQ_LOW_HZ)
|
||||||
|
const ap = biquad(ctx, 'allpass', EQ_HIGH_HZ, Math.SQRT1_2)
|
||||||
|
const [mlA, mlB] = lr4(ctx, 'lowpass', EQ_HIGH_HZ)
|
||||||
|
const [mhA, mhB] = lr4(ctx, 'highpass', EQ_HIGH_HZ)
|
||||||
|
this.bands = [ctx.createGain(), ctx.createGain(), ctx.createGain()]
|
||||||
|
this.trim.connect(lpA)
|
||||||
|
this.trim.connect(hpA)
|
||||||
|
lpB.connect(ap).connect(this.bands[0]).connect(eqOut)
|
||||||
|
hpB.connect(mlA)
|
||||||
|
hpB.connect(mhA)
|
||||||
|
mlB.connect(this.bands[1]).connect(eqOut)
|
||||||
|
mhB.connect(this.bands[2]).connect(eqOut)
|
||||||
|
|
||||||
|
this.fx = new ColorFx(ctx)
|
||||||
|
eqOut.connect(this.fx.input)
|
||||||
|
this.fader = ctx.createGain()
|
||||||
|
this.fx.output.connect(this.fader)
|
||||||
|
this.meter = ctx.createAnalyser()
|
||||||
|
this.meter.fftSize = 512
|
||||||
|
this.fader.connect(this.meter)
|
||||||
|
this.xfade = ctx.createGain()
|
||||||
|
this.wetGate = ctx.createGain()
|
||||||
|
this.fader.connect(this.xfade).connect(this.wetGate).connect(bus)
|
||||||
|
this.dryGate = ctx.createGain()
|
||||||
|
this.input.connect(this.dryGate).connect(bus)
|
||||||
|
}
|
||||||
|
|
||||||
|
apply(s: ChannelState, xfade: number, eqKill: boolean): void {
|
||||||
|
const ctx = this.ctx
|
||||||
|
const trimDb = this.autoGainDb + Math.max(-TRIM_RANGE_DB, Math.min(TRIM_RANGE_DB, s.trim))
|
||||||
|
ramp(this.trim.gain, dbToGain(trimDb), ctx)
|
||||||
|
ramp(this.bands[0].gain, eqGain(s.low, eqKill), ctx)
|
||||||
|
ramp(this.bands[1].gain, eqGain(s.mid, eqKill), ctx)
|
||||||
|
ramp(this.bands[2].gain, eqGain(s.high, eqKill), ctx)
|
||||||
|
this.fx.apply(s.fx, s.color, s.param, this.bpm)
|
||||||
|
ramp(this.fader.gain, faderGain(s.fader), ctx)
|
||||||
|
ramp(this.xfade.gain, xfade, ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
route(inCircuit: boolean, audible: boolean): void {
|
||||||
|
ramp(this.wetGate.gain, audible && inCircuit ? 1 : 0, this.ctx, 0.01)
|
||||||
|
ramp(this.dryGate.gain, audible && !inCircuit ? 1 : 0, this.ctx, 0.01)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MixerLevels {
|
||||||
|
/** Peak dBFS: each channel after its fader, and the master after the limiter. */
|
||||||
|
A: number
|
||||||
|
B: number
|
||||||
|
master: number
|
||||||
|
/** The limiter's gain reduction now (dB, >= 0). */
|
||||||
|
limiting: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Mixer {
|
||||||
|
private readonly ctx: AudioContext
|
||||||
|
private readonly strips: Record<Channel, Strip>
|
||||||
|
private readonly limiter: DynamicsCompressorNode
|
||||||
|
private readonly limWet: GainNode
|
||||||
|
private readonly limDry: GainNode
|
||||||
|
private readonly masterMeter: AnalyserNode
|
||||||
|
private readonly buf = new Float32Array(512)
|
||||||
|
private active = false
|
||||||
|
|
||||||
|
constructor(ctx: AudioContext) {
|
||||||
|
this.ctx = ctx
|
||||||
|
const bus = ctx.createGain()
|
||||||
|
this.limiter = ctx.createDynamicsCompressor()
|
||||||
|
this.limiter.threshold.value = LIMIT_DB
|
||||||
|
this.limiter.knee.value = 0
|
||||||
|
this.limiter.ratio.value = LIMIT_RATIO
|
||||||
|
this.limiter.attack.value = 0.001
|
||||||
|
this.limiter.release.value = 0.15
|
||||||
|
const unMakeup = ctx.createGain()
|
||||||
|
unMakeup.gain.value = dbToGain(-MAKEUP_DB)
|
||||||
|
const out = ctx.createGain()
|
||||||
|
this.limWet = ctx.createGain()
|
||||||
|
this.limDry = ctx.createGain()
|
||||||
|
bus.connect(this.limiter).connect(unMakeup).connect(this.limWet).connect(out)
|
||||||
|
bus.connect(this.limDry).connect(out)
|
||||||
|
this.masterMeter = ctx.createAnalyser()
|
||||||
|
this.masterMeter.fftSize = 512
|
||||||
|
out.connect(this.masterMeter)
|
||||||
|
out.connect(ctx.destination)
|
||||||
|
this.strips = { A: new Strip(ctx, bus), B: new Strip(ctx, bus) }
|
||||||
|
this.setActive(false)
|
||||||
|
subscribeMixer(() => this.apply())
|
||||||
|
this.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where deck `ch` plays into. */
|
||||||
|
input(ch: Channel): AudioNode {
|
||||||
|
return this.strips[ch].input
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Performance mode: both channels through the mixer and the limiter. Off:
|
||||||
|
* deck A straight to the speakers, deck B silent. */
|
||||||
|
setActive(on: boolean): void {
|
||||||
|
this.active = on
|
||||||
|
this.strips.A.route(on, true)
|
||||||
|
this.strips.B.route(on, on)
|
||||||
|
ramp(this.limWet.gain, on ? 1 : 0, this.ctx, 0.01)
|
||||||
|
ramp(this.limDry.gain, on ? 0 : 1, this.ctx, 0.01)
|
||||||
|
}
|
||||||
|
|
||||||
|
get isActive(): boolean {
|
||||||
|
return this.active
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The loaded track's own auto gain (dB; 0 when it has none). */
|
||||||
|
setAutoGain(ch: Channel, db: number): void {
|
||||||
|
this.strips[ch].autoGainDb = db
|
||||||
|
this.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The deck's tempo now — Echo's beat. */
|
||||||
|
setTempo(ch: Channel, bpm: number): void {
|
||||||
|
if (this.strips[ch].bpm === bpm) return
|
||||||
|
this.strips[ch].bpm = bpm
|
||||||
|
this.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
private apply(): void {
|
||||||
|
const s = getMixerState()
|
||||||
|
const [ga, gb] = xfadeGains(s.crossfader, s.curve)
|
||||||
|
this.strips.A.apply(s.A, ga, s.eqKill)
|
||||||
|
this.strips.B.apply(s.B, gb, s.eqKill)
|
||||||
|
}
|
||||||
|
|
||||||
|
private peak(meter: AnalyserNode): number {
|
||||||
|
meter.getFloatTimeDomainData(this.buf)
|
||||||
|
let p = 0
|
||||||
|
for (let i = 0; i < this.buf.length; i++) {
|
||||||
|
const v = Math.abs(this.buf[i])
|
||||||
|
if (v > p) p = v
|
||||||
|
}
|
||||||
|
return p > 0 ? 20 * Math.log10(p) : -Infinity
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read the meters (call once per frame). */
|
||||||
|
levels(): MixerLevels {
|
||||||
|
return {
|
||||||
|
A: this.peak(this.strips.A.meter),
|
||||||
|
B: this.peak(this.strips.B.meter),
|
||||||
|
master: this.peak(this.masterMeter),
|
||||||
|
limiting: Math.max(0, -this.limiter.reduction),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let instance: Mixer | null = null
|
||||||
|
|
||||||
|
/** The app's mixer, built on its AudioContext the first time it is asked for. */
|
||||||
|
export function mixer(): Mixer {
|
||||||
|
if (!instance) instance = new Mixer(audioContext())
|
||||||
|
return instance
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { echoBeats, echoSeconds, eqGain, faderGain, filterSweep, gainToDb, xfadeGains } from './mixerMath'
|
||||||
|
|
||||||
|
describe('eqGain', () => {
|
||||||
|
it('is flat at the centre, +6 dB at full right', () => {
|
||||||
|
expect(eqGain(0, false)).toBe(1)
|
||||||
|
expect(gainToDb(eqGain(1, false))).toBeCloseTo(6, 6)
|
||||||
|
expect(gainToDb(eqGain(0.5, true))).toBeCloseTo(3, 6)
|
||||||
|
})
|
||||||
|
it('cuts to -26 dB, DJM-style', () => {
|
||||||
|
expect(gainToDb(eqGain(-1, false))).toBeCloseTo(-26, 6)
|
||||||
|
expect(gainToDb(eqGain(-0.5, false))).toBeCloseTo(-13, 6)
|
||||||
|
})
|
||||||
|
it('kills to silence over the last fifth, continuously', () => {
|
||||||
|
expect(eqGain(-1, true)).toBe(0)
|
||||||
|
expect(eqGain(-0.8, true)).toBeCloseTo(eqGain(-0.8, false), 9)
|
||||||
|
expect(eqGain(-0.5, true)).toBe(eqGain(-0.5, false))
|
||||||
|
let prev = Infinity
|
||||||
|
for (let v = -0.7; v >= -1; v -= 0.01) {
|
||||||
|
const g = eqGain(v, true)
|
||||||
|
expect(g).toBeLessThanOrEqual(prev)
|
||||||
|
prev = g
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('xfadeGains', () => {
|
||||||
|
it('smooth: constant power, -3 dB each at the centre', () => {
|
||||||
|
for (const x of [-1, -0.4, 0, 0.3, 1]) {
|
||||||
|
const [a, b] = xfadeGains(x, 'smooth')
|
||||||
|
expect(a * a + b * b).toBeCloseTo(1, 9)
|
||||||
|
}
|
||||||
|
expect(gainToDb(xfadeGains(0, 'smooth')[0])).toBeCloseTo(-3.01, 2)
|
||||||
|
expect(xfadeGains(-1, 'smooth')).toEqual([1, expect.closeTo(0, 9)])
|
||||||
|
})
|
||||||
|
it('sharp: both full until the last tenth', () => {
|
||||||
|
expect(xfadeGains(0, 'sharp')).toEqual([1, 1])
|
||||||
|
expect(xfadeGains(0.9, 'sharp')).toEqual([1, 1])
|
||||||
|
expect(xfadeGains(1, 'sharp')).toEqual([0, 1])
|
||||||
|
expect(xfadeGains(-0.95, 'sharp')[1]).toBeCloseTo(0.5, 9)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('faderGain', () => {
|
||||||
|
it('runs 0 → 1 on an audio taper', () => {
|
||||||
|
expect(faderGain(0)).toBe(0)
|
||||||
|
expect(faderGain(1)).toBe(1)
|
||||||
|
expect(gainToDb(faderGain(0.7071))).toBeCloseTo(-6.02, 1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('filterSweep', () => {
|
||||||
|
it('is bypassed at the centre', () => {
|
||||||
|
expect(filterSweep(0)).toBeNull()
|
||||||
|
expect(filterSweep(0.01)).toBeNull()
|
||||||
|
})
|
||||||
|
it('low-passes left and high-passes right, on a log scale', () => {
|
||||||
|
expect(filterSweep(-1)).toEqual({ type: 'lowpass', freq: expect.closeTo(150, 6) })
|
||||||
|
expect(filterSweep(1)).toEqual({ type: 'highpass', freq: expect.closeTo(8000, 6) })
|
||||||
|
const half = filterSweep(-0.5)!
|
||||||
|
expect(half.freq).toBeCloseTo(Math.sqrt(20000 * 150), 3)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('echo', () => {
|
||||||
|
it('picks its length in beats from the parameter and follows the tempo', () => {
|
||||||
|
expect(echoBeats(0)).toBe(1 / 8)
|
||||||
|
expect(echoBeats(0.5)).toBe(1 / 2)
|
||||||
|
expect(echoBeats(1)).toBe(1)
|
||||||
|
expect(echoSeconds(1, 120)).toBeCloseTo(0.5, 9)
|
||||||
|
expect(echoSeconds(0.5, 128)).toBeCloseTo(60 / 128 / 2, 9)
|
||||||
|
expect(echoSeconds(1, 0)).toBeCloseTo(0.5, 9) // unknown tempo: 120
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// The mixer's control curves: how a knob or fader position becomes a gain or a
|
||||||
|
// filter setting. Pure, so they are tested on their own (mixerMath.test.ts);
|
||||||
|
// `mixer.ts` applies them to the audio graph.
|
||||||
|
|
||||||
|
export const dbToGain = (db: number): number => 10 ** (db / 20)
|
||||||
|
export const gainToDb = (g: number): number => (g > 0 ? 20 * Math.log10(g) : -Infinity)
|
||||||
|
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))
|
||||||
|
|
||||||
|
/** An EQ band's boost at full right. */
|
||||||
|
export const EQ_BOOST_DB = 6
|
||||||
|
/** An EQ band's cut at full left, DJM-style (the alternative is a full kill). */
|
||||||
|
export const EQ_CUT_DB = -26
|
||||||
|
/** The isolator's crossovers (Hz) — where the deck's waveform splits its bands. */
|
||||||
|
export const EQ_LOW_HZ = 250
|
||||||
|
export const EQ_HIGH_HZ = 2500
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An EQ knob (-1..1, centre = flat) as a linear gain. Right boosts to +6 dB.
|
||||||
|
* Left cuts in dB to -26 dB; with `kill`, the last fifth of the travel fades
|
||||||
|
* on from there to silence, so the band can disappear entirely.
|
||||||
|
*/
|
||||||
|
export function eqGain(v: number, kill: boolean): number {
|
||||||
|
v = clamp(v, -1, 1)
|
||||||
|
if (v >= 0) return dbToGain(EQ_BOOST_DB * v)
|
||||||
|
const g = dbToGain(-EQ_CUT_DB * v)
|
||||||
|
if (!kill || v > -0.8) return g
|
||||||
|
return g * ((1 + v) / 0.2)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The trim knob's range either side of the track's auto gain (dB). */
|
||||||
|
export const TRIM_RANGE_DB = 12
|
||||||
|
|
||||||
|
/** A channel fader (0..1) as a gain: an audio taper, -6 dB at ~0.7. */
|
||||||
|
export const faderGain = (f: number): number => clamp(f, 0, 1) ** 2
|
||||||
|
|
||||||
|
export type CrossfaderCurve = 'smooth' | 'sharp'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The crossfader (-1 = all A, 1 = all B) as the two channels' gains. Smooth is
|
||||||
|
* constant-power: both at -3 dB in the middle, for blends. Sharp keeps both at
|
||||||
|
* full until the last tenth of the travel, for cuts and scratching.
|
||||||
|
*/
|
||||||
|
export function xfadeGains(x: number, curve: CrossfaderCurve): [number, number] {
|
||||||
|
x = clamp(x, -1, 1)
|
||||||
|
if (curve === 'smooth') {
|
||||||
|
const t = ((x + 1) / 2) * (Math.PI / 2)
|
||||||
|
return [Math.cos(t), Math.sin(t)]
|
||||||
|
}
|
||||||
|
return [x <= 0.9 ? 1 : (1 - x) / 0.1, x >= -0.9 ? 1 : (1 + x) / 0.1]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The colour knob's dead centre: inside it, the effect is out of the path. */
|
||||||
|
export const FX_CENTRE = 0.02
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The filter at colour `c` (-1..1): left a low-pass falling from 20 kHz to
|
||||||
|
* 150 Hz, right a high-pass rising from 20 Hz to 8 kHz, both on a log scale so
|
||||||
|
* the sweep sounds even. Null at the centre (bypassed).
|
||||||
|
*/
|
||||||
|
export function filterSweep(c: number): { type: 'lowpass' | 'highpass'; freq: number } | null {
|
||||||
|
c = clamp(c, -1, 1)
|
||||||
|
if (Math.abs(c) < FX_CENTRE) return null
|
||||||
|
const a = Math.abs(c)
|
||||||
|
return c < 0
|
||||||
|
? { type: 'lowpass', freq: 20000 * (150 / 20000) ** a }
|
||||||
|
: { type: 'highpass', freq: 20 * (8000 / 20) ** a }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The echo's lengths in beats, picked by the parameter knob. */
|
||||||
|
export const ECHO_BEATS = [1 / 8, 1 / 4, 1 / 2, 3 / 4, 1]
|
||||||
|
|
||||||
|
export function echoBeats(param: number): number {
|
||||||
|
return ECHO_BEATS[Math.round(clamp(param, 0, 1) * (ECHO_BEATS.length - 1))]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Seconds of echo for `param` at `bpm` (120 when the tempo is unknown). */
|
||||||
|
export function echoSeconds(param: number, bpm: number): number {
|
||||||
|
return (echoBeats(param) * 60) / (bpm > 0 ? bpm : 120)
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// The mixer's controls, in one small external store read through
|
||||||
|
// useSyncExternalStore (as lib/drag.tsx is): the on-screen mixer and the audio
|
||||||
|
// graph both follow it, and a MIDI mapping later will write the same setters
|
||||||
|
// (decided 2026-11-02: mouse now, MIDI later). Not persisted: a session's
|
||||||
|
// mixer starts flat.
|
||||||
|
|
||||||
|
import { useSyncExternalStore } from 'react'
|
||||||
|
import type { CrossfaderCurve } from './mixerMath'
|
||||||
|
|
||||||
|
export type Channel = 'A' | 'B'
|
||||||
|
export const CHANNELS: Channel[] = ['A', 'B']
|
||||||
|
|
||||||
|
export const FX_TYPES = ['filter', 'echo', 'space', 'noise', 'crush'] as const
|
||||||
|
export type FxType = (typeof FX_TYPES)[number]
|
||||||
|
export const FX_LABELS: Record<FxType, string> = {
|
||||||
|
filter: 'Filter',
|
||||||
|
echo: 'Echo',
|
||||||
|
space: 'Space',
|
||||||
|
noise: 'Noise',
|
||||||
|
crush: 'Crush',
|
||||||
|
}
|
||||||
|
/** What each effect's parameter knob does. */
|
||||||
|
export const FX_PARAM: Record<FxType, string> = {
|
||||||
|
filter: 'Resonance',
|
||||||
|
echo: 'Echo length (beats)',
|
||||||
|
space: 'Reverb size',
|
||||||
|
noise: 'Noise resonance',
|
||||||
|
crush: 'Drive',
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChannelState {
|
||||||
|
/** dB either side of the track's auto gain. */
|
||||||
|
trim: number
|
||||||
|
/** EQ bands, -1..1 (centre flat). */
|
||||||
|
low: number
|
||||||
|
mid: number
|
||||||
|
high: number
|
||||||
|
fx: FxType
|
||||||
|
/** The colour knob, -1..1 (centre = effect off). */
|
||||||
|
color: number
|
||||||
|
/** The effect's parameter, 0..1. */
|
||||||
|
param: number
|
||||||
|
/** The channel fader, 0..1. */
|
||||||
|
fader: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MixerState {
|
||||||
|
A: ChannelState
|
||||||
|
B: ChannelState
|
||||||
|
/** -1 = all A, 1 = all B. */
|
||||||
|
crossfader: number
|
||||||
|
curve: CrossfaderCurve
|
||||||
|
/** EQ cuts to silence at full left (else to -26 dB). */
|
||||||
|
eqKill: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_CHANNEL: ChannelState = {
|
||||||
|
trim: 0,
|
||||||
|
low: 0,
|
||||||
|
mid: 0,
|
||||||
|
high: 0,
|
||||||
|
fx: 'filter',
|
||||||
|
color: 0,
|
||||||
|
param: 0.5,
|
||||||
|
fader: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
let state: MixerState = {
|
||||||
|
A: DEFAULT_CHANNEL,
|
||||||
|
B: DEFAULT_CHANNEL,
|
||||||
|
crossfader: 0,
|
||||||
|
curve: 'smooth',
|
||||||
|
eqKill: false,
|
||||||
|
}
|
||||||
|
const listeners = new Set<() => void>()
|
||||||
|
|
||||||
|
export function getMixerState(): MixerState {
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeMixer(fn: () => void): () => void {
|
||||||
|
listeners.add(fn)
|
||||||
|
return () => listeners.delete(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
function commit(next: MixerState): void {
|
||||||
|
state = next
|
||||||
|
for (const fn of listeners) fn()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setChannel(ch: Channel, patch: Partial<ChannelState>): void {
|
||||||
|
commit({ ...state, [ch]: { ...state[ch], ...patch } })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setMixer(patch: Partial<Pick<MixerState, 'crossfader' | 'curve' | 'eqKill'>>): void {
|
||||||
|
commit({ ...state, ...patch })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A slice of the mixer, re-rendering only when it changes. */
|
||||||
|
export function useMixer<T>(select: (s: MixerState) => T): T {
|
||||||
|
return useSyncExternalStore(subscribeMixer, () => select(state))
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { buildBeatGrid } from './beatgrid'
|
||||||
|
import { alignedPosition, bendFor, effectiveBpm, octaveFor, phaseOffset, rangeFor, syncRate, type DeckTempo } from './sync'
|
||||||
|
|
||||||
|
const grid = (start: number, bpm: number) => buildBeatGrid([{ start, bpm }])
|
||||||
|
const deck = (g: ReturnType<typeof buildBeatGrid>, pos: number, rate = 1): DeckTempo => ({ grid: g, pos, rate })
|
||||||
|
|
||||||
|
describe('tempo', () => {
|
||||||
|
it('effective BPM is the grid tempo times the rate', () => {
|
||||||
|
expect(effectiveBpm(deck(grid(0, 128), 10, 1.02))).toBeCloseTo(130.56, 9)
|
||||||
|
expect(effectiveBpm(deck(null, 10))).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('matches a follower to the master', () => {
|
||||||
|
const r = syncRate(deck(grid(0, 128), 5, 1.01), deck(grid(0, 124), 5))!
|
||||||
|
expect(r.octave).toBe(1)
|
||||||
|
expect(124 * r.rate).toBeCloseTo(128 * 1.01, 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('syncs half and double time at the nearer octave', () => {
|
||||||
|
expect(octaveFor(174, 87)).toBe(2)
|
||||||
|
expect(octaveFor(87, 172)).toBe(0.5)
|
||||||
|
expect(octaveFor(128, 126)).toBe(1)
|
||||||
|
const r = syncRate(deck(grid(0, 174), 0), deck(grid(0, 86), 0))!
|
||||||
|
expect(r.octave).toBe(2)
|
||||||
|
expect(r.rate).toBeCloseTo(174 / 172, 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a flexible grid syncs to the segment under the playhead', () => {
|
||||||
|
const flex = buildBeatGrid([
|
||||||
|
{ start: 0, bpm: 120 },
|
||||||
|
{ start: 30, bpm: 125 },
|
||||||
|
])
|
||||||
|
expect(syncRate(deck(grid(0, 125), 0), deck(flex, 10))!.rate).toBeCloseTo(125 / 120, 9)
|
||||||
|
expect(syncRate(deck(grid(0, 125), 0), deck(flex, 40))!.rate).toBeCloseTo(1, 9)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('phase', () => {
|
||||||
|
const beat = 60 / 120 // 0.5 s
|
||||||
|
it('is zero on the beat and signed within half a beat', () => {
|
||||||
|
const m = deck(grid(0, 120), 4 * beat)
|
||||||
|
expect(phaseOffset(m, deck(grid(0.1, 120), 0.1 + 7 * beat), 1)).toBeCloseTo(0, 9)
|
||||||
|
expect(phaseOffset(m, deck(grid(0, 120), 4 * beat + 0.25 * beat), 1)).toBeCloseTo(0.25, 9) // follower ahead
|
||||||
|
expect(phaseOffset(m, deck(grid(0, 120), 4 * beat - 0.1 * beat), 1)).toBeCloseTo(-0.1, 9)
|
||||||
|
expect(phaseOffset(m, deck(grid(0, 120), 4 * beat + 0.6 * beat), 1)).toBeCloseTo(-0.4, 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('aligning moves the follower by the smallest amount onto the master’s beat', () => {
|
||||||
|
const m = deck(grid(0, 120), 10 * beat + 0.3 * beat)
|
||||||
|
const f = deck(grid(0.2, 128), 50)
|
||||||
|
const off = phaseOffset(m, f, 1)!
|
||||||
|
const at = alignedPosition(f, off, 1)
|
||||||
|
expect(phaseOffset(m, { ...f, pos: at }, 1)).toBeCloseTo(0, 9)
|
||||||
|
expect(Math.abs(at - 50)).toBeLessThanOrEqual(0.5 * (60 / 128) + 1e-9)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('compares in master beats at double time', () => {
|
||||||
|
// Follower at 87 felt as 174: half a follower beat is a whole master beat.
|
||||||
|
const m = deck(grid(0, 174), 0)
|
||||||
|
const half = 0.5 * (60 / 87)
|
||||||
|
expect(phaseOffset(m, deck(grid(0, 87), half), 2)).toBeCloseTo(0, 9)
|
||||||
|
const f = deck(grid(0, 87), half + 0.1 * (60 / 87))
|
||||||
|
const off = phaseOffset(m, f, 2)!
|
||||||
|
expect(off).toBeCloseTo(0.2, 9)
|
||||||
|
expect(phaseOffset(m, { ...f, pos: alignedPosition(f, off, 2) }, 2)).toBeCloseTo(0, 9)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('rangeFor', () => {
|
||||||
|
it('widens the pitch range only as far as needed', () => {
|
||||||
|
expect(rangeFor(1.05, 0.08)).toBe(0.08)
|
||||||
|
expect(rangeFor(1.12, 0.08)).toBe(0.16)
|
||||||
|
expect(rangeFor(0.7, 0.08)).toBe(0.5)
|
||||||
|
expect(rangeFor(1.05, 0.5)).toBe(0.5)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('bendFor', () => {
|
||||||
|
it('is none at rest, ±5% at full drag, finer with Shift, squared in between', () => {
|
||||||
|
expect(bendFor(0, false)).toBe(1)
|
||||||
|
expect(bendFor(80, false)).toBeCloseTo(1.05, 9)
|
||||||
|
expect(bendFor(-200, false)).toBeCloseTo(0.95, 9)
|
||||||
|
expect(bendFor(40, false)).toBeCloseTo(1.0125, 9)
|
||||||
|
expect(bendFor(80, true)).toBeCloseTo(1.0125, 9)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// Beat sync between two decks (performance mode, decided 2026-11-02): SYNC
|
||||||
|
// matches a follower's tempo to the tempo MASTER's and lines its beats up, from
|
||||||
|
// the two beatgrids — the same marker-list math as everything else
|
||||||
|
// (`beatgrid.ts`), so a flexible grid syncs to the segment the playhead is in.
|
||||||
|
// Pure (sync.test.ts); PrepStrip runs it.
|
||||||
|
|
||||||
|
import type { BeatGrid } from './beatgrid'
|
||||||
|
|
||||||
|
export interface DeckTempo {
|
||||||
|
grid: BeatGrid | null
|
||||||
|
/** Playhead (s, track time). */
|
||||||
|
pos: number
|
||||||
|
/** Playback rate (1 = the file's own tempo). */
|
||||||
|
rate: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** BPM as heard: the grid's tempo where the playhead is, times the rate. */
|
||||||
|
export function effectiveBpm(d: DeckTempo): number | null {
|
||||||
|
return d.grid ? d.grid.bpmAt(d.pos) * d.rate : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How many master beats one follower beat is felt as: ½, 1 or 2 — whichever
|
||||||
|
* brings the two tempos closest (an 87 BPM grid against 174 syncs as double). */
|
||||||
|
export const OCTAVES = [0.5, 1, 2]
|
||||||
|
|
||||||
|
export function octaveFor(masterBpm: number, followerBpm: number): number {
|
||||||
|
let best = 1
|
||||||
|
let bestErr = Infinity
|
||||||
|
for (const m of OCTAVES) {
|
||||||
|
const err = Math.abs(Math.log(masterBpm / (followerBpm * m)))
|
||||||
|
if (err < bestErr - 1e-9) {
|
||||||
|
bestErr = err
|
||||||
|
best = m
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The rate that puts the follower on the master's tempo, and the octave it is
|
||||||
|
* matched at. Null without both grids.
|
||||||
|
*/
|
||||||
|
export function syncRate(master: DeckTempo, follower: DeckTempo): { rate: number; octave: number } | null {
|
||||||
|
const m = effectiveBpm(master)
|
||||||
|
if (m == null || !follower.grid) return null
|
||||||
|
const f = follower.grid.bpmAt(follower.pos)
|
||||||
|
const octave = octaveFor(m, f)
|
||||||
|
return { rate: m / (f * octave), octave }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a beat position sits between beats, 0..1. */
|
||||||
|
const frac = (x: number) => x - Math.floor(x)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How far the follower's beats are from the master's, in MASTER beats, in
|
||||||
|
* [-0.5, 0.5): positive = the follower is ahead. Null without both grids.
|
||||||
|
*/
|
||||||
|
export function phaseOffset(master: DeckTempo, follower: DeckTempo, octave: number): number | null {
|
||||||
|
if (!master.grid || !follower.grid) return null
|
||||||
|
const pm = frac(master.grid.beatIndexAt(master.pos))
|
||||||
|
const pf = frac(follower.grid.beatIndexAt(follower.pos) * octave)
|
||||||
|
let d = pf - pm
|
||||||
|
if (d >= 0.5) d -= 1
|
||||||
|
if (d < -0.5) d += 1
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The follower's playhead with its beats on the master's (the smallest move). */
|
||||||
|
export function alignedPosition(follower: DeckTempo, offset: number, octave: number): number {
|
||||||
|
const g = follower.grid!
|
||||||
|
return Math.max(0, g.timeOfBeat(g.beatIndexAt(follower.pos) - offset / octave))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The pitch ranges a deck offers (fraction of the tempo either way). */
|
||||||
|
export const PITCH_RANGES = [0.08, 0.16, 0.5]
|
||||||
|
|
||||||
|
/** The narrowest range that holds `rate`, so a sync never pins the fader. */
|
||||||
|
export function rangeFor(rate: number, current: number): number {
|
||||||
|
const need = Math.abs(rate - 1)
|
||||||
|
if (need <= current + 1e-9) return current
|
||||||
|
return PITCH_RANGES.find((r) => need <= r + 1e-9) ?? PITCH_RANGES[PITCH_RANGES.length - 1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- pitch bend (the phase meter's drag) ------------------------------------
|
||||||
|
|
||||||
|
/** The bend at full drag (±5%), reached at BEND_PX; Shift is four times finer. */
|
||||||
|
export const BEND_MAX = 0.05
|
||||||
|
export const BEND_PX = 80
|
||||||
|
|
||||||
|
/** A drag of `dx` px as a rate multiplier: squared, so small drags are fine
|
||||||
|
* nudges and a long one a firm push. Right = faster. */
|
||||||
|
export function bendFor(dx: number, fine: boolean): number {
|
||||||
|
const b = Math.max(-1, Math.min(1, dx / BEND_PX))
|
||||||
|
return 1 + BEND_MAX * b * Math.abs(b) * (fine ? 0.25 : 1)
|
||||||
|
}
|
||||||
Reference in new issue
Block a user