mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
308 lines
11 KiB
TypeScript
308 lines
11 KiB
TypeScript
import { useEffect, useRef, useState, type RefObject } from 'react'
|
||
import { mixer } from '../../lib/audio/mixer'
|
||
import { delayBeatsAt, faderGain, filterSweep, eqGain, gainToDb, REVERB_GROWTH, sweepBeatsAt, TRIM_RANGE_DB, EQ_CUT_DB } from '../../lib/audio/mixerMath'
|
||
import {
|
||
FX_LABELS,
|
||
FX_SHORT,
|
||
FX_TYPES,
|
||
rangeFor,
|
||
setChannel,
|
||
setMixer,
|
||
useMixer,
|
||
type Channel,
|
||
type FxSettings,
|
||
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
|
||
|
||
/** Knob sizes (px): as large as the column allows — the EQ block is two
|
||
* across, the FILTER knob beside it larger. */
|
||
const EQ_KNOB = 40
|
||
const FILTER_KNOB = 48
|
||
|
||
const fmtDb = (db: number, places = 1) =>
|
||
!isFinite(db) ? '−∞ dB' : `${db > 0 ? '+' : db < 0 ? '−' : ''}${Math.abs(db).toFixed(places)} dB`
|
||
|
||
/** The FILTER knob's tooltip: where the filter is, and what rides with it. */
|
||
function describeFx(fx: FxType, c: number, set: FxSettings): string {
|
||
if (Math.abs(c) < 0.02) return `Filter${fx === 'filter' ? '' : ` + ${FX_LABELS[fx]}`}: off (turn left or right)`
|
||
const s = filterSweep(c, rangeFor(fx, set))!
|
||
const hz = s.freq >= 1000 ? `${(s.freq / 1000).toFixed(1)} kHz` : `${Math.round(s.freq)} Hz`
|
||
const filter = `${s.type === 'lowpass' ? 'low-pass' : 'high-pass'} at ${hz}`
|
||
const a = `${Math.round(Math.abs(c) * 100)}%`
|
||
switch (fx) {
|
||
case 'filter':
|
||
return `Filter: ${filter} · resonance ${Math.round(set.filterResonance * 100)}%`
|
||
case 'reverb':
|
||
return `Reverb ${a} (${set.reverbSize}–${set.reverbSize * REVERB_GROWTH} s, longer as it opens) + ${filter}`
|
||
case 'delay':
|
||
return `Delay ${a} (${beatsLabel(delayBeatsAt(set.delayBeats, Math.abs(c)))}) + ${filter}`
|
||
case 'crusher':
|
||
return `Bit crusher ${a} (drive ×${set.crusherDrive}) + ${filter}`
|
||
case 'flanger':
|
||
return `Flanger ${a} (a sweep every ${beatsLabel(sweepBeatsAt(set.flangerBeats, Math.abs(c)))}) + ${filter}`
|
||
}
|
||
}
|
||
|
||
function beatsLabel(b: number): string {
|
||
const fractions: Record<number, string> = { 0.125: '1/8', 0.25: '1/4', 0.5: '1/2', 0.75: '3/4' }
|
||
return `${fractions[b] ?? b} beat${b > 1 ? 's' : ''}`
|
||
}
|
||
|
||
/**
|
||
* The mixer, between the decks in performance mode (decided 2026-11-02): per
|
||
* channel GAIN (on top of the track's auto gain), HI / MID / LOW, the FILTER
|
||
* knob with the effect that rides with it (its picker above; each effect's one
|
||
* parameter is an app setting, in Settings ▸ Performance mode…), 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,
|
||
autoGainOn,
|
||
}: {
|
||
autoGain: Record<Channel, number | null>
|
||
/** The `useAutoGain` setting: off, the gain ignores the track's. */
|
||
autoGainOn: boolean
|
||
}) {
|
||
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)'
|
||
}
|
||
}
|
||
// Only while the master carries sound: on silence, Chrome's compressor
|
||
// reports a phantom reduction (14 dB, decaying over ~2 s, measured just
|
||
// after performance mode opens) that limits nothing.
|
||
if (lv.limiting > 0.5 && lv.master > -60) 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 sharpness = useMixer((s) => s.sharpness)
|
||
|
||
return (
|
||
<div className="well flex w-[26rem] 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={autoGainOn ? autoGain.A : undefined} 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={autoGainOn ? autoGain.B : undefined} meterRef={meterRefs.B} mirrored />
|
||
</div>
|
||
<div className="flex h-6 shrink-0 items-center justify-center gap-2 px-1">
|
||
<span className="font-mono text-[11px] font-semibold text-muted">A</span>
|
||
<Fader
|
||
midi="mixer.crossfader"
|
||
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 ${Math.round(sharpness * 100)}% sharp — Settings ▸ Performance mode…) — ${
|
||
Math.abs(v) < 0.03 ? 'centre' : v < 0 ? `toward A ${Math.round(-v * 100)}%` : `toward B ${Math.round(v * 100)}%`
|
||
}`
|
||
}
|
||
className="w-1/2"
|
||
/>
|
||
<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
|
||
/** The track's auto gain; null = it has none, undefined = the setting is off. */
|
||
autoGain: number | null | undefined
|
||
meterRef: RefObject<HTMLDivElement | null>
|
||
mirrored?: boolean
|
||
}) {
|
||
const s = useMixer((m) => m[ch])
|
||
const eqKill = useMixer((m) => m.eqKill)
|
||
const fxSettings = useMixer((m) => m.fx)
|
||
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
|
||
midi={`mixer.${ch}.${band}`}
|
||
value={s[band]}
|
||
min={-1}
|
||
max={1}
|
||
defaultValue={0}
|
||
bipolar
|
||
size={EQ_KNOB}
|
||
onChange={(v) => set({ [band]: Math.abs(v) < 0.03 ? 0 : v })}
|
||
label={label}
|
||
describe={describeEq(name)}
|
||
/>
|
||
)
|
||
// GAIN (the state's `trim`: on top of the track's auto gain) and the EQ as a
|
||
// 2×2 block; beside it, toward the fader, the Filter FX: the effect's picker
|
||
// above a larger FILTER knob (decided 2026-11-03).
|
||
const knobs = (
|
||
<div className={`flex items-center gap-2 self-center ${mirrored ? 'flex-row-reverse' : ''}`}>
|
||
<div className="grid grid-cols-2 gap-x-1.5 gap-y-1.5">
|
||
<Knob
|
||
midi={`mixer.${ch}.gain`}
|
||
value={s.trim}
|
||
min={-TRIM_RANGE_DB}
|
||
max={TRIM_RANGE_DB}
|
||
defaultValue={0}
|
||
bipolar
|
||
size={EQ_KNOB}
|
||
color="var(--color-text)"
|
||
onChange={(v) => set({ trim: Math.abs(v) < 0.3 ? 0 : v })}
|
||
label="Gain"
|
||
describe={(v) =>
|
||
`Gain ${fmtDb(v)}${
|
||
autoGain === undefined
|
||
? ' (auto gain off)'
|
||
: 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')}
|
||
</div>
|
||
<div className="flex flex-col items-center gap-2" style={{ width: FILTER_KNOB }}>
|
||
<button
|
||
data-midi-action={`mixer.${ch}.fxNext`}
|
||
onClick={(e) => {
|
||
const r = e.currentTarget.getBoundingClientRect()
|
||
setFxMenu({ x: r.left, y: r.bottom + 4 })
|
||
}}
|
||
title={s.fx === 'filter' ? 'Filter FX: the filter alone — pick an effect to ride with it' : `Filter FX: ${FX_LABELS[s.fx]} rides with the FILTER knob`}
|
||
className="btn-glass flex h-6 w-full items-center justify-center gap-px rounded-md text-[9.5px] font-semibold uppercase tracking-[0.04em] text-text"
|
||
>
|
||
{FX_SHORT[s.fx]}
|
||
<Icon name="chevronDown" size={9} />
|
||
</button>
|
||
<Knob
|
||
midi={`mixer.${ch}.filter`}
|
||
value={s.color}
|
||
min={-1}
|
||
max={1}
|
||
defaultValue={0}
|
||
bipolar
|
||
size={FILTER_KNOB}
|
||
color="var(--color-gold)"
|
||
onChange={(v) => set({ color: Math.abs(v) < 0.02 ? 0 : v })}
|
||
label="Filter"
|
||
describe={(v) => describeFx(s.fx, v, fxSettings)}
|
||
/>
|
||
</div>
|
||
</div>
|
||
)
|
||
const fader = (
|
||
<div className="flex flex-col items-center gap-0.5">
|
||
<Fader
|
||
midi={`mixer.${ch}.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 and FX)`}>
|
||
<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}
|
||
minWidth={0}
|
||
onClose={() => setFxMenu(null)}
|
||
items={[
|
||
...FX_TYPES.map((t) => ({
|
||
label: FX_LABELS[t],
|
||
hint: t === s.fx ? '✓' : undefined,
|
||
onClick: () => set({ fx: t }),
|
||
})),
|
||
]}
|
||
/>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|