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
@@ -1,12 +1,12 @@
|
||||
// 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.
|
||||
// Never closed: a deck that goes away disconnects its own nodes.
|
||||
// mixed (and limited) before the speakers — two contexts cannot be connected.
|
||||
// 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 rubberbandUrl from './rubberband.wasm?url'
|
||||
|
||||
let ctx: AudioContext | null = null
|
||||
let master: GainNode | null = null
|
||||
let worklet: Promise<ArrayBuffer | null> | null = null
|
||||
|
||||
export function audioContext(): AudioContext {
|
||||
@@ -14,8 +14,6 @@ export function audioContext(): AudioContext {
|
||||
const AC: typeof AudioContext =
|
||||
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
|
||||
ctx = new AC({ latencyHint: 'interactive' })
|
||||
master = ctx.createGain()
|
||||
master.connect(ctx.destination)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
@@ -25,12 +23,6 @@ export function resumeAudio(): void {
|
||||
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
|
||||
* 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.
|
||||
|
||||
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 { extrapolate, type Loop, type Model } from './position'
|
||||
|
||||
@@ -27,13 +27,14 @@ export class DeckEngine {
|
||||
private onEnded: (() => void) | null = null
|
||||
private onScratchDone: ((playing: boolean) => void) | null = null
|
||||
|
||||
/** The worklet module loads asynchronously, once per app. */
|
||||
static async create(): Promise<DeckEngine> {
|
||||
/** The worklet module loads asynchronously, once per app. `destination` is
|
||||
* where the deck plays into: its mixer channel. */
|
||||
static async create(destination: AudioNode): Promise<DeckEngine> {
|
||||
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.node = new AudioWorkletNode(this.ctx, 'konduktor-deck', {
|
||||
numberOfInputs: 0,
|
||||
@@ -43,7 +44,7 @@ export class DeckEngine {
|
||||
})
|
||||
this.output = this.ctx.createGain()
|
||||
this.node.connect(this.output)
|
||||
this.output.connect(masterInput())
|
||||
this.output.connect(destination)
|
||||
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))
|
||||
}
|
||||
Reference in new issue
Block a user