6 Commits
Author SHA1 Message Date
LucasDLTG 83d17add42 feat: disconnect dsps on window close 2026-10-06 22:23:53 +02:00
LucasDLTG 83cb602625 feat: update todo 2026-10-06 21:05:12 +02:00
LucasDLTG 98a71e3114 fix: dont render graphs on every poll 2026-10-06 21:01:37 +02:00
LucasDLTG e151ab4f26 fix: bugs using real hardware 2026-10-04 21:01:09 +02:00
LucasDLTG e28f61447f fix: q value 2026-10-02 22:48:47 +02:00
LucasDLTG 388552f1c4 fix: matrix gain 2026-10-02 20:38:23 +02:00
23 changed files with 1014 additions and 740 deletions
+7 -7
View File
@@ -7,11 +7,11 @@ This template should help get you started developing with Tauri, React and Types
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) - [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
# TODO # TODO
- Move meters polling logic outside dsp state because it causes re-render of everything tied to dsp constantly
- Check render to improve perfoormances
- Check in meter if clip bool is limit instead
- On close disconenct all ds^p
- Ma-trix gain block sometimes
- Q out of range
- Check end to end behavioour - Check in meter if clip bool is limit instead
- Check end to end behavioour
- Roll back on scroll when 2 scroll
- Save Configs to keep after reboot app.
+37 -30
View File
@@ -2,6 +2,7 @@ mod commands;
mod state; mod state;
use state::AppState; use state::AppState;
use tauri::Manager;
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
@@ -13,36 +14,42 @@ pub fn run() {
commands::remove_dsp408, commands::remove_dsp408,
commands::get_dsp_snapshot, commands::get_dsp_snapshot,
commands::get_dsp_state, commands::get_dsp_state,
commands::connect_dsp408, // 0x10 commands::connect_dsp408,
commands::disconnect_dsp408, // 0x11 commands::disconnect_dsp408,
commands::set_delay_unit, // 0x15 commands::set_delay_unit,
commands::recall_preset, // 0x20 commands::recall_preset,
commands::store_current_configuration, // 0x21 commands::store_current_configuration,
commands::factory_reset, // 0x23 commands::factory_reset,
commands::set_current_preset_name, // 0x26 commands::set_current_preset_name,
commands::copy_channel, // 0x2A commands::copy_channel,
commands::unlock_device, // Command `0x2D` commands::unlock_device,
commands::lock_device, // Command `0x2F` commands::lock_device,
commands::set_compressor, // 0x30 commands::set_compressor,
commands::set_low_pass, // 0x31 commands::set_low_pass,
commands::set_high_pass, // 0x32 commands::set_high_pass,
commands::set_peq_band, // 0x33 commands::set_peq_band,
commands::set_channel_gain, // 0x34 commands::set_channel_gain,
commands::set_mute, // 0x35 commands::set_mute,
commands::set_channel_inverse_gain, // 0x36 commands::set_channel_inverse_gain,
commands::set_delay, // 0x38 commands::set_delay,
commands::set_input_source, // 0x39 commands::set_input_source,
commands::set_matrix_routing, // 0x3A commands::set_matrix_routing,
commands::link_channels, // 0x3B commands::link_channels,
commands::set_bypass_peq, // 0x3C commands::set_bypass_peq,
commands::set_channel_name, // 0x3D commands::set_channel_name,
commands::set_gate, // 0x3E commands::set_gate,
commands::set_limiter, // 0x3F commands::set_limiter,
commands::get_meter_levels, // 0x40 commands::get_meter_levels,
commands::set_matrix_gain, // 0x41 commands::set_matrix_gain,
commands::set_geq_band, // 0x48 commands::set_geq_band,
commands::set_geq_bypass, // 0x49 commands::set_geq_bypass,
]) ])
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { .. } = event {
let state = window.app_handle().state::<AppState>();
state.shutdown();
}
})
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }
+12
View File
@@ -18,4 +18,16 @@ impl AppState {
next_id: Mutex::new(1), next_id: Mutex::new(1),
} }
} }
pub fn shutdown(&self) {
let devices = self.devices.lock().unwrap();
for device in devices.values() {
if let Ok(mut device) = device.lock() {
if device.dsp.connected() {
let _ = device.dsp.disconnect();
}
}
}
}
} }
+41 -18
View File
@@ -12,6 +12,23 @@ const PENDING_FALLBACK_MS = 1000;
type CommitResult = Promise<boolean | void> | boolean | void; type CommitResult = Promise<boolean | void> | boolean | void;
function useNonPassiveWheel(
ref: React.RefObject<HTMLElement | null>,
handler: (e: WheelEvent) => void
) {
const handlerRef = useRef(handler);
handlerRef.current = handler;
useEffect(() => {
const el = ref.current;
if (!el) return;
const listener = (e: WheelEvent) => handlerRef.current(e);
el.addEventListener('wheel', listener, { passive: false });
return () => el.removeEventListener('wheel', listener);
}, [ref]);
}
function StepperArrows({ function StepperArrows({
onUp, onUp,
onDown, onDown,
@@ -80,6 +97,17 @@ function ChoiceStepperList<T>({
const pendingValue = useRef<T | null>(null); const pendingValue = useRef<T | null>(null);
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null); const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const fallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null); const fallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
useNonPassiveWheel(inputRef, (e) => {
e.preventDefault();
if (e.deltaY < 0 && canUp) {
stepWheel(1);
} else if (e.deltaY > 0 && canDown) {
stepWheel(-1);
}
});
useEffect(() => { useEffect(() => {
if (interacting.current) { if (interacting.current) {
@@ -180,21 +208,13 @@ function ChoiceStepperList<T>({
return ( return (
<div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}> <div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}>
<input <input
ref={inputRef}
id={id} id={id}
className="choice-stepper__input" className="choice-stepper__input"
value={text} value={text}
disabled={disabled} disabled={disabled}
onChange={(e) => setText(e.target.value)} onChange={(e) => setText(e.target.value)}
onBlur={commitText} onBlur={commitText}
onWheel={(e) => {
e.preventDefault();
if (e.deltaY < 0 && canUp) {
stepWheel(1);
} else if (e.deltaY > 0 && canDown) {
stepWheel(-1);
}
}}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
e.currentTarget.blur(); e.currentTarget.blur();
@@ -256,6 +276,17 @@ function ChoiceStepperRange({
const pendingValue = useRef<number | null>(null); const pendingValue = useRef<number | null>(null);
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null); const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const fallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null); const fallbackTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
useNonPassiveWheel(inputRef, (e) => {
e.preventDefault();
if (e.deltaY < 0 && canUp) {
stepWheel(1);
} else if (e.deltaY > 0 && canDown) {
stepWheel(-1);
}
});
useEffect(() => { useEffect(() => {
if (interacting.current) { if (interacting.current) {
@@ -344,21 +375,13 @@ function ChoiceStepperRange({
return ( return (
<div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}> <div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}>
<input <input
ref={inputRef}
id={id} id={id}
className="choice-stepper__input" className="choice-stepper__input"
value={text} value={text}
disabled={disabled} disabled={disabled}
onChange={(e) => setText(e.target.value)} onChange={(e) => setText(e.target.value)}
onBlur={commitText} onBlur={commitText}
onWheel={(e) => {
e.preventDefault();
if (e.deltaY < 0 && canUp) {
stepWheel(1);
} else if (e.deltaY > 0 && canDown) {
stepWheel(-1);
}
}}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
e.currentTarget.blur(); e.currentTarget.blur();
@@ -92,6 +92,23 @@ function formatGainDb(value: number) {
return `${sign}${value.toFixed(1)} dB`; return `${sign}${value.toFixed(1)} dB`;
} }
export function useNonPassiveWheel(
ref: React.RefObject<Element | null>,
handler: (e: WheelEvent) => void
) {
const handlerRef = useRef(handler);
handlerRef.current = handler;
useEffect(() => {
const el = ref.current;
if (!el) return;
const listener = (e: Event) => handlerRef.current(e as WheelEvent);
el.addEventListener('wheel', listener, { passive: false });
return () => el.removeEventListener('wheel', listener);
}, [ref]);
}
type GainTooltipState = { type GainTooltipState = {
visible: boolean; visible: boolean;
x: number; x: number;
@@ -104,11 +121,13 @@ function SignalFlowMatrix({
setMatrixRouting, setMatrixRouting,
setMatrixGain, setMatrixGain,
setActiveSidebar, setActiveSidebar,
onGainPreview,
}: { }: {
dsp: DSP408; dsp: DSP408;
setMatrixRouting: (output: OutputChannel, inputs: InputChannel[]) => Promise<boolean>; setMatrixRouting: (output: OutputChannel, inputs: InputChannel[]) => Promise<boolean>;
setMatrixGain: (input: InputChannel, output: OutputChannel, gain: number) => Promise<boolean>; setMatrixGain: (input: InputChannel, output: OutputChannel, gain: number) => Promise<boolean>;
setActiveSidebar: React.Dispatch<React.SetStateAction<SidebarId>>; setActiveSidebar: React.Dispatch<React.SetStateAction<SidebarId>>;
onGainPreview: (input: InputChannel, output: OutputChannel, value: number | null) => void;
}) { }) {
const nInputs = INPUT_ORDER.length; const nInputs = INPUT_ORDER.length;
const nOutputs = OUTPUT_ORDER.length; const nOutputs = OUTPUT_ORDER.length;
@@ -137,9 +156,16 @@ function SignalFlowMatrix({
}); });
const hideTooltipTimer = useRef<ReturnType<typeof setTimeout> | null>(null); const hideTooltipTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const WHEEL_COMMIT_DELAY = 250;
// key = `${input}-${output}`
const pendingGains = useRef<Map<string, number>>(new Map());
const commitTimers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
useEffect(() => { useEffect(() => {
return () => { return () => {
if (hideTooltipTimer.current) clearTimeout(hideTooltipTimer.current); if (hideTooltipTimer.current) clearTimeout(hideTooltipTimer.current);
commitTimers.current.forEach(clearTimeout);
}; };
}, []); }, []);
@@ -151,28 +177,55 @@ function SignalFlowMatrix({
void setMatrixRouting(output, next); void setMatrixRouting(output, next);
}; };
const handleWheelGain = (e: React.WheelEvent, output: OutputChannel, input: InputChannel) => { const svgRef = useRef<SVGSVGElement>(null);
const handleWheelGain = (e: WheelEvent, output: OutputChannel, input: InputChannel) => {
e.preventDefault(); e.preventDefault();
const current = getGain(dsp, output, input);
const key = `${input}-${output}`;
// Base on the pending value if we're mid-wheel, otherwise the real state
const current = pendingGains.current.get(key) ?? getGain(dsp, output, input);
const delta = e.deltaY < 0 ? MATRIX_GAIN_STEP : -MATRIX_GAIN_STEP; const delta = e.deltaY < 0 ? MATRIX_GAIN_STEP : -MATRIX_GAIN_STEP;
const next = const next =
Math.round(Math.min(MATRIX_GAIN_MAX, Math.max(MATRIX_GAIN_MIN, current + delta)) * 10) / 10; Math.round(Math.min(MATRIX_GAIN_MAX, Math.max(MATRIX_GAIN_MIN, current + delta)) * 10) / 10;
void setMatrixGain(input, output, next);
// Show a small tooltip with the new gain value right next to the cursor, pendingGains.current.set(key, next);
// then let it fade away shortly after wheeling stops. onGainPreview(input, output, next);
// Debounced send: only the final value goes out once the wheel pauses
const existing = commitTimers.current.get(key);
if (existing) clearTimeout(existing);
commitTimers.current.set(
key,
setTimeout(async () => {
commitTimers.current.delete(key);
const value = pendingGains.current.get(key);
if (value === undefined) return;
await setMatrixGain(input, output, value);
// Only release if the user hasn't wheeled again while we were awaiting
if (pendingGains.current.get(key) === value) {
pendingGains.current.delete(key);
onGainPreview(input, output, null);
}
}, WHEEL_COMMIT_DELAY)
);
// Tooltip (unchanged, shows the pending value)
if (hideTooltipTimer.current) clearTimeout(hideTooltipTimer.current); if (hideTooltipTimer.current) clearTimeout(hideTooltipTimer.current);
setGainTooltip({ setGainTooltip({ visible: true, x: e.clientX, y: e.clientY, label: formatGainDb(next) });
visible: true,
x: e.clientX,
y: e.clientY,
label: formatGainDb(next),
});
hideTooltipTimer.current = setTimeout(() => { hideTooltipTimer.current = setTimeout(() => {
setGainTooltip((t) => ({ ...t, visible: false })); setGainTooltip((t) => ({ ...t, visible: false }));
}, GAIN_TOOLTIP_HOLD_MS); }, GAIN_TOOLTIP_HOLD_MS);
}; };
useNonPassiveWheel(svgRef, (e) => {
const hit = (e.target as Element).closest<SVGElement>('[data-wheel-route]');
if (!hit) return; // not over a connected line: let the page scroll normally
const { input, output } = hit.dataset;
if (!input || !output) return;
handleWheelGain(e, output as OutputChannel, input as InputChannel);
});
const routePairs = useMemo(() => { const routePairs = useMemo(() => {
const pairs: { input: InputChannel; output: OutputChannel; i: number; j: number }[] = []; const pairs: { input: InputChannel; output: OutputChannel; i: number; j: number }[] = [];
OUTPUT_ORDER.forEach((output, j) => { OUTPUT_ORDER.forEach((output, j) => {
@@ -196,6 +249,7 @@ function SignalFlowMatrix({
return ( return (
<div className="signal-flow"> <div className="signal-flow">
<svg <svg
ref={svgRef}
viewBox={`0 0 ${W} ${H}`} viewBox={`0 0 ${W} ${H}`}
preserveAspectRatio="xMidYMid meet" preserveAspectRatio="xMidYMid meet"
className="signal-flow__svg" className="signal-flow__svg"
@@ -221,7 +275,9 @@ function SignalFlowMatrix({
strokeWidth={LINE_HITBOX_WIDTH} strokeWidth={LINE_HITBOX_WIDTH}
style={{ cursor: 'pointer' }} style={{ cursor: 'pointer' }}
onClick={() => handleToggle(output, input)} onClick={() => handleToggle(output, input)}
onWheel={connected ? (e) => handleWheelGain(e, output, input) : undefined} data-wheel-route={connected ? '' : undefined}
data-input={input}
data-output={output}
/> />
{/* Visible line, purely decorative — no pointer events, so it never {/* Visible line, purely decorative — no pointer events, so it never
competes with the hitbox above for hover/click/wheel. */} competes with the hitbox above for hover/click/wheel. */}
@@ -0,0 +1,120 @@
import { memo, useCallback, useMemo } from 'react';
import { logSpace } from '../../utils/graph/curve';
import { GRAPH_X_MIN, GRAPH_X_MAX, GRAPH_Y_MIN, GRAPH_Y_MAX } from '../../constants';
import { PEQBand, PEQ, CrossoverFilter } from '../../types';
import { sumCurvePoints, sumPhaseCurvePoints } from '../../utils/graph/curve';
import { getPeqCurvePoints, getPeqPhasePoints } from '../../utils/graph/peq';
import { getCrossoverCurvePoints, getCrossoverPhasePoints } from '../../utils/graph/crossover';
import { drawCurves } from '../../utils/graph/draw';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
// Constant, so compute once instead of every render.
const GRAPH_FREQS = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
const formatTick = (v: number) => Math.round(v).toString();
type FilterGraphProps = {
bands: Record<PEQBand, PEQ>;
bypass: boolean;
hpFreq: number;
hpSlope: CrossoverFilter;
lpFreq: number;
lpSlope: CrossoverFilter;
};
export const MagnitudeGraph = memo(function MagnitudeGraph({
bands, bypass, hpFreq, hpSlope, lpFreq, lpSlope,
}: FilterGraphProps) {
const points = useMemo(
() =>
sumCurvePoints([
getPeqCurvePoints({ freqs: GRAPH_FREQS, bands }),
getCrossoverCurvePoints({
freqs: GRAPH_FREQS,
highPass: { frequency: hpFreq, filter_type: hpSlope },
lowPass: { frequency: lpFreq, filter_type: lpSlope },
}),
]),
[bands, hpFreq, hpSlope, lpFreq, lpSlope]
);
const draw = useCallback(
({ ctx, toPx }: any) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: GRAPH_Y_MIN,
yMax: GRAPH_Y_MAX,
curves: [{ points, style: { strokeColor: '#e5e7eb', dimmed: bypass } }],
});
},
[points, bypass]
);
return (
<LinearGraph
xMin={GRAPH_X_MIN}
xMax={GRAPH_X_MAX}
xScale="log"
yMin={GRAPH_Y_MIN}
yMax={GRAPH_Y_MAX}
yStep={3}
xLabel="Frequency - Hz"
yLabel="Magnituded - dB"
showGrid={true}
formatX={formatTick}
formatY={formatTick}
draw={draw}
/>
);
});
export const PhaseGraph = memo(function PhaseGraph({
bands, bypass, hpFreq, hpSlope, lpFreq, lpSlope,
}: FilterGraphProps) {
const points = useMemo(
() =>
sumPhaseCurvePoints([
getPeqPhasePoints({ freqs: GRAPH_FREQS, bands }),
getCrossoverPhasePoints({
freqs: GRAPH_FREQS,
highPass: { frequency: hpFreq, filter_type: hpSlope },
lowPass: { frequency: lpFreq, filter_type: lpSlope },
}),
]),
[bands, hpFreq, hpSlope, lpFreq, lpSlope]
);
const draw = useCallback(
({ ctx, toPx }: any) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: -180,
yMax: 180,
curves: [{ points, style: { strokeColor: '#e5e7eb', dimmed: bypass } }],
});
},
[points, bypass]
);
return (
<LinearGraph
xMin={GRAPH_X_MIN}
xMax={GRAPH_X_MAX}
xScale="log"
yMin={-180}
yMax={180}
yStep={45}
xLabel="Frequency - Hz"
yLabel="Phase - Deg"
showGrid={true}
formatX={formatTick}
formatY={formatTick}
draw={draw}
/>
);
});
@@ -17,8 +17,7 @@ import {
import { Channel, PEQBand, PEQFilter, PEQ, Crossover } from '../../types'; import { Channel, PEQBand, PEQFilter, PEQ, Crossover } from '../../types';
import { DSP408 as DSP } from '../../../../types'; import { DSP408 as DSP } from '../../../../types';
import { CrossoverFilter } from '../../types'; import { CrossoverFilter } from '../../types';
import { LinearGraph, LinearGraphHandle } from '../../../../components/LinearGraph/LinearGraph'; import { useRef, useState, useEffect, useMemo } from 'react';
import { useRef, useState, useEffect } from 'react';
import './ChannelSection.css'; import './ChannelSection.css';
import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup'; import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup';
import Button from '../../../../components/Button/Button'; import Button from '../../../../components/Button/Button';
@@ -26,15 +25,14 @@ import {
FREQUENCY_MAX, FREQUENCY_MAX,
FREQUENCY_MIN, FREQUENCY_MIN,
FREQUENCY_QUANTIZATION, FREQUENCY_QUANTIZATION,
GRAPH_X_MAX,
GRAPH_X_MIN,
GRAPH_Y_MAX,
GRAPH_Y_MIN,
} from '../../constants'; } from '../../constants';
import { drawCurves } from '../../utils/graph/draw'; import { MagnitudeGraph, PhaseGraph } from './ChannelGraph';
import { getPeqCurvePoints, getPeqPhasePoints } from '../../utils/graph/peq';
import { logSpace, sumCurvePoints, sumPhaseCurvePoints } from '../../utils/graph/curve'; function nearestQValue(q: number, values: readonly number[] = PEAK_Q_VALUES): number {
import { getCrossoverCurvePoints, getCrossoverPhasePoints } from '../../utils/graph/crossover'; return values.reduce((nearest, current) =>
Math.abs(current - q) < Math.abs(nearest - q) ? current : nearest
);
}
type GraphView = 'both' | 'magnitude' | 'phase'; type GraphView = 'both' | 'magnitude' | 'phase';
@@ -133,9 +131,11 @@ function PeqPanelSliders({
const qDisabled = PEQ_Q_UNUSED.has(peq.filter_type); const qDisabled = PEQ_Q_UNUSED.has(peq.filter_type);
const gainDisabled = !PEQ_GAIN_USED.has(peq.filter_type); const gainDisabled = !PEQ_GAIN_USED.has(peq.filter_type);
const nearestQ = nearestQValue(peq.q);
const commit = (overrides: Partial<PEQ>) => { const commit = (overrides: Partial<PEQ>) => {
const next = { ...peq, ...overrides }; const next = { ...peq, ...overrides };
return setPEQ(next.gain, next.frequency, next.q, next.filter_type, next.bypass); return setPEQ(next.gain, next.frequency, overrides.q ?? nearestQ, next.filter_type, next.bypass);
}; };
return ( return (
@@ -169,9 +169,9 @@ function PeqPanelSliders({
max={qMax} max={qMax}
values={PEAK_Q_VALUES} values={PEAK_Q_VALUES}
formatValue={(v) => v.toFixed(2)} formatValue={(v) => v.toFixed(2)}
value={peq.q} value={nearestQ}
onChange={(value) => commit({ q: value })} onChange={(value) => commit({ q: value })}
onInput={(value) => onLiveValue({ ...peq, q: value })} onInput={(value) => onLiveValue({ ...peq, q: nearestQValue(value) })}
disabled={qDisabled} disabled={qDisabled}
style={{ width: '100%', flex: '1 1 auto' }} style={{ width: '100%', flex: '1 1 auto' }}
/> />
@@ -318,9 +318,16 @@ function PeqBandList({
bandsOrder: PEQBand[]; bandsOrder: PEQBand[];
}) { }) {
const commit = (band: PEQBand, overrides: Partial<PEQ>) => { const commit = (band: PEQBand, overrides: Partial<PEQ>) => {
const peq = liveBands[band] ?? bands[band]; const live = liveBands[band] ?? bands[band];
const next = { ...peq, ...overrides }; const next = { ...live, ...overrides };
return setPEQ(band, next.gain, next.frequency, next.q, next.filter_type, next.bypass); return setPEQ(
band,
next.gain,
next.frequency,
nearestQValue(next.q),
next.filter_type,
next.bypass
);
}; };
return ( return (
@@ -340,6 +347,7 @@ function PeqBandList({
const [qMin, qMax] = PEQ_Q_RANGES[peq.filter_type]; const [qMin, qMax] = PEQ_Q_RANGES[peq.filter_type];
const qValues = PEAK_Q_VALUES.filter((q) => q >= qMin && q <= qMax); const qValues = PEAK_Q_VALUES.filter((q) => q >= qMin && q <= qMax);
const qValue = nearestQValue(peq.q, qValues.length ? qValues : PEAK_Q_VALUES);
const qDisabled = PEQ_Q_UNUSED.has(peq.filter_type); const qDisabled = PEQ_Q_UNUSED.has(peq.filter_type);
const gainDisabled = !PEQ_GAIN_USED.has(peq.filter_type); const gainDisabled = !PEQ_GAIN_USED.has(peq.filter_type);
@@ -376,7 +384,7 @@ function PeqBandList({
<ChoiceStepper <ChoiceStepper
className="peq-band-list__stepper" className="peq-band-list__stepper"
value={peq.q} value={qValue}
values={qValues} values={qValues}
formatLabel={(v) => v.toFixed(2)} formatLabel={(v) => v.toFixed(2)}
disabled={qDisabled} disabled={qDisabled}
@@ -401,7 +409,14 @@ function PeqBandList({
formatLabel={(v) => formatLabel={(v) =>
PEQ_FILTERS_LABEL.find((opt) => opt.value === v)?.label ?? String(v) PEQ_FILTERS_LABEL.find((opt) => opt.value === v)?.label ?? String(v)
} }
onChange={(value) => commit(band, { filter_type: value, q: 3.0 })} onChange={(value) => {
const [min, max] = PEQ_Q_RANGES[value];
const allowed = PEAK_Q_VALUES.filter((q) => q >= min && q <= max);
commit(band, {
filter_type: value,
q: nearestQValue(3.0, allowed.length ? allowed : PEAK_Q_VALUES),
});
}}
/> />
<Button <Button
@@ -459,8 +474,6 @@ function ChannelSection({
const [liveLpFreq, setLiveLpFreq] = useState<number>(FREQUENCY_MAX); const [liveLpFreq, setLiveLpFreq] = useState<number>(FREQUENCY_MAX);
const [livePeq, setLivePeq] = useState<Partial<Record<PEQBand, PEQ>>>({}); const [livePeq, setLivePeq] = useState<Partial<Record<PEQBand, PEQ>>>({});
const magnitudeGraphRef = useRef<LinearGraphHandle>(null);
// DSP values // DSP values
const isInput = 'Input' in channel; const isInput = 'Input' in channel;
@@ -499,7 +512,7 @@ function ChannelSection({
// Skip only if already flat — nothing to change. // Skip only if already flat — nothing to change.
if (current.gain === 0 && current.filter_type === PEQFilter.Peak) continue; if (current.gain === 0 && current.filter_type === PEQFilter.Peak) continue;
await commitPEQ(band, 0, current.frequency, current.q, PEQFilter.Peak, current.bypass); await commitPEQ(band, 0, current.frequency, nearestQValue(3.0, PEAK_Q_VALUES), PEQFilter.Peak, current.bypass);
} }
setResetting(false); setResetting(false);
@@ -566,17 +579,20 @@ function ChannelSection({
return success; return success;
}; };
// Diplay value (merge live and real) const displayPeq = useMemo(
const displayPeq: Record<PEQBand, PEQ> = { () => ({ ...ActivePeq.bands, ...livePeq }) as Record<PEQBand, PEQ>,
...ActivePeq.bands, [ActivePeq.bands, livePeq]
...livePeq, );
const graphProps = {
bands: displayPeq,
bypass: ActivePeq.bypass,
hpFreq: liveHpFreq,
hpSlope: ActiveHighPassFilter.slope,
lpFreq: liveLpFreq,
lpSlope: ActiveLowPassFilter.slope,
}; };
const highPassSpec = { frequency: liveHpFreq, filter_type: ActiveHighPassFilter.slope };
const lowPassSpec = { frequency: liveLpFreq, filter_type: ActiveLowPassFilter.slope };
const freqs = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
return ( return (
<> <>
<div className="channel-graph-section"> <div className="channel-graph-section">
@@ -588,84 +604,11 @@ function ChannelSection({
{(graphView === 'both' || graphView === 'magnitude') && ( {(graphView === 'both' || graphView === 'magnitude') && (
<div className="channel-graph-panel__magnitude-wrap"> <div className="channel-graph-panel__magnitude-wrap">
<LinearGraph <MagnitudeGraph {...graphProps} />
ref={magnitudeGraphRef}
xMin={GRAPH_X_MIN}
xMax={GRAPH_X_MAX}
xScale="log"
yMin={GRAPH_Y_MIN}
yMax={GRAPH_Y_MAX}
yStep={3}
xLabel="Frequency - Hz"
yLabel="Magnituded - dB"
showGrid={true}
formatX={(v) => Math.round(v).toString()}
formatY={(v) => Math.round(v).toString()}
draw={({ ctx, toPx }) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: GRAPH_Y_MIN,
yMax: GRAPH_Y_MAX,
curves: [
{
points: sumCurvePoints([
getPeqCurvePoints({ freqs, bands: displayPeq }),
getCrossoverCurvePoints({
freqs,
highPass: highPassSpec,
lowPass: lowPassSpec,
}),
]),
style: { strokeColor: '#e5e7eb', dimmed: ActivePeq.bypass },
},
],
});
}}
/>
</div> </div>
)} )}
{(graphView === 'both' || graphView === 'phase') && ( {(graphView === 'both' || graphView === 'phase') && <PhaseGraph {...graphProps} />}
<LinearGraph
xMin={GRAPH_X_MIN}
xMax={GRAPH_X_MAX}
xScale="log"
yMin={-180}
yMax={180}
yStep={45}
xLabel="Frequency - Hz"
yLabel="Phase - Deg"
showGrid={true}
formatX={(v) => Math.round(v).toString()}
formatY={(v) => Math.round(v).toString()}
draw={({ ctx, toPx }) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: GRAPH_Y_MIN,
yMax: GRAPH_Y_MAX,
curves: [
{
points: sumPhaseCurvePoints([
getPeqPhasePoints({ freqs, bands: displayPeq }),
getCrossoverPhasePoints({
freqs,
highPass: highPassSpec,
lowPass: lowPassSpec,
}),
]),
style: { strokeColor: '#e5e7eb', dimmed: ActivePeq.bypass },
},
],
});
}}
/>
)}
{ActivePeq.bypass && ( {ActivePeq.bypass && (
<div className="channel-bypass-overlay"> <div className="channel-bypass-overlay">
@@ -0,0 +1,122 @@
import { memo, useCallback, useMemo } from 'react';
import { Ratio } from '../../types';
import { RATIO_NUMERIC } from '../../constants';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
const formatTick = (v: number) => Math.round(v).toString();
// Compressor transfer curve, in dB.
//
// The knee is NOT a smooth/quadratic blend. It is three straight
// (piecewise-linear) segments:
// 1) input <= kneeStart -> 1:1 line (output = input)
// 2) kneeStart < input < kneeEnd -> a straight line connecting the
// point on segment (1) at kneeStart
// to the point on segment (3) at kneeEnd
// 3) input >= kneeEnd -> ratio line (output = threshold + (input-threshold)/ratio)
//
// kneeStart/kneeEnd are simply the threshold shifted down/up by half the
// knee width, so increasing "knee" widens the middle straight segment
// symmetrically around the threshold.
function compressorOutputDb(input: number, threshold: number, ratio: number, knee: number): number {
const kneeStart = threshold - knee / 2;
const kneeEnd = threshold + knee / 2;
// No knee: simple two-segment (hard-knee) curve.
if (knee <= 0) {
return input <= threshold ? input : threshold + (input - threshold) / ratio;
}
// Segment 1: below the knee, straight 1:1 line.
if (input <= kneeStart) {
return input;
}
// Segment 3: above the knee, straight ratio line.
if (input >= kneeEnd) {
return threshold + (input - threshold) / ratio;
}
// Segment 2: straight line between the two boundary points
// (kneeStart, kneeStart) and (kneeEnd, threshold + (kneeEnd - threshold) / ratio).
const y1 = kneeStart;
const y2 = threshold + (kneeEnd - threshold) / ratio;
const t = (input - kneeStart) / (kneeEnd - kneeStart);
return y1 + t * (y2 - y1);
}
export const CompressorGraph = memo(function CompressorGraph({
threshold,
ratio,
knee,
}: {
threshold: number;
ratio: Ratio;
knee: number;
}) {
const curvePoints = useMemo(() => {
const ratioNumeric = RATIO_NUMERIC[ratio];
const steps = 120;
const points: [number, number][] = [];
for (let i = 0; i <= steps; i++) {
const x = -100 + (120 * i) / steps;
points.push([x, compressorOutputDb(x, threshold, ratioNumeric, knee)]);
}
return points;
}, [threshold, ratio, knee]);
const draw = useCallback(
({ ctx, toPx }: any) => {
// Unity reference line
ctx.strokeStyle = '#6b7280';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
const [ux0, uy0] = toPx(-100, -100);
const [ux1, uy1] = toPx(20, 20);
ctx.beginPath();
ctx.moveTo(ux0, uy0);
ctx.lineTo(ux1, uy1);
ctx.stroke();
ctx.setLineDash([]);
// Threshold marker
ctx.strokeStyle = '#fbbf24';
ctx.lineWidth = 1;
ctx.setLineDash([2, 3]);
const [tx0, ty0] = toPx(threshold, -100);
const [tx1, ty1] = toPx(threshold, 20);
ctx.beginPath();
ctx.moveTo(tx0, ty0);
ctx.lineTo(tx1, ty1);
ctx.stroke();
ctx.setLineDash([]);
// Compression curve
ctx.strokeStyle = '#4ade80';
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
ctx.beginPath();
curvePoints.forEach(([x, y], i) => {
const [px, py] = toPx(x, y);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
},
[threshold, curvePoints]
);
return (
<LinearGraph
xMin={-100}
xMax={20}
yMin={-100}
yMax={20}
xLabel="in dB"
yLabel="out dB"
formatX={formatTick}
formatY={formatTick}
draw={draw}
/>
);
});
@@ -3,12 +3,12 @@ import VerticalSlider from '../../../../components/VerticalSlider/VerticalSlider
import { OutputChannel, Ratio } from '../../types'; import { OutputChannel, Ratio } from '../../types';
import { DSP408 as DSP } from '../../../../types'; import { DSP408 as DSP } from '../../../../types';
import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup'; import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup';
import { LinearGraph } from '../../../../components/LinearGraph/LinearGraph'; import { CompressorGraph } from './CompressorGraph';
import MeterBar from '../../../../components/MeterBar/MeterBar'; import MeterBar from '../../../../components/MeterBar/MeterBar';
import { useMemo, useState } from 'react'; import { useState } from 'react';
import ChoiceStepper from '../../../../components/ChoiceStepper/ChoiceStepper'; import ChoiceStepper from '../../../../components/ChoiceStepper/ChoiceStepper';
import './CompressorSection.css'; import './CompressorSection.css';
import { RATIO_ORDER, RATIO_LABEL, RATIO_NUMERIC, KNEE_VALUES } from '../../constants'; import { RATIO_ORDER, RATIO_LABEL, KNEE_VALUES } from '../../constants';
const COMPRESSOR_SLIDER_PARAMS = [ const COMPRESSOR_SLIDER_PARAMS = [
{ key: 'threshold', label: 'Threshold', min: -90, max: 20, step: 0.5, unit: ' dB' }, { key: 'threshold', label: 'Threshold', min: -90, max: 20, step: 0.5, unit: ' dB' },
@@ -112,45 +112,7 @@ function CompressorPanel({
); );
} }
// Compressor transfer curve, in dB.
//
// The knee is NOT a smooth/quadratic blend. It is three straight
// (piecewise-linear) segments:
// 1) input <= kneeStart -> 1:1 line (output = input)
// 2) kneeStart < input < kneeEnd -> a straight line connecting the
// point on segment (1) at kneeStart
// to the point on segment (3) at kneeEnd
// 3) input >= kneeEnd -> ratio line (output = threshold + (input-threshold)/ratio)
//
// kneeStart/kneeEnd are simply the threshold shifted down/up by half the
// knee width, so increasing "knee" widens the middle straight segment
// symmetrically around the threshold.
function compressorOutputDb(input: number, threshold: number, ratio: number, knee: number): number {
const kneeStart = threshold - knee / 2;
const kneeEnd = threshold + knee / 2;
// No knee: simple two-segment (hard-knee) curve.
if (knee <= 0) {
return input <= threshold ? input : threshold + (input - threshold) / ratio;
}
// Segment 1: below the knee, straight 1:1 line.
if (input <= kneeStart) {
return input;
}
// Segment 3: above the knee, straight ratio line.
if (input >= kneeEnd) {
return threshold + (input - threshold) / ratio;
}
// Segment 2: straight line between the two boundary points
// (kneeStart, kneeStart) and (kneeEnd, threshold + (kneeEnd - threshold) / ratio).
const y1 = kneeStart;
const y2 = threshold + (kneeEnd - threshold) / ratio;
const t = (input - kneeStart) / (kneeEnd - kneeStart);
return y1 + t * (y2 - y1);
}
function CompressorSection({ dsp, set_compressor }: { dsp: DSP; set_compressor: SetCompressorFn }) { function CompressorSection({ dsp, set_compressor }: { dsp: DSP; set_compressor: SetCompressorFn }) {
const outputs = [ const outputs = [
@@ -207,70 +169,15 @@ function CompressorSection({ dsp, set_compressor }: { dsp: DSP; set_compressor:
const activeOutputState = dsp.state.current_config.output_states[activeChannel]; const activeOutputState = dsp.state.current_config.output_states[activeChannel];
const activeComp = liveComp[activeChannel] ?? (activeOutputState.compressor as CompressorValues); const activeComp = liveComp[activeChannel] ?? (activeOutputState.compressor as CompressorValues);
const curvePoints = useMemo(() => {
const { threshold, ratio, knee } = activeComp;
const ratioNumeric = RATIO_NUMERIC[ratio];
const steps = 120;
const points: [number, number][] = [];
for (let i = 0; i <= steps; i++) {
const x = -100 + (100 * i) / steps;
points.push([x, compressorOutputDb(x, threshold, ratioNumeric, knee)]);
}
return points;
}, [activeComp.threshold, activeComp.ratio, activeComp.knee]);
return ( return (
<> <>
<div className="compressor-linear-graph-section"> <div className="compressor-linear-graph-section">
<div className="compressor-graph-panel"> <div className="compressor-graph-panel">
<div className="compressor-graph__title">{activeOutputState.name} - RMS Compressor</div> <div className="compressor-graph__title">{activeOutputState.name} - RMS Compressor</div>
<CompressorGraph
<LinearGraph threshold={activeComp.threshold}
xMin={-100} ratio={activeComp.ratio}
xMax={0} knee={activeComp.knee}
yMin={-100}
yMax={0}
xLabel="in dB"
yLabel="out dB"
formatX={(v) => Math.round(v).toString()}
formatY={(v) => Math.round(v).toString()}
draw={({ ctx, toPx }) => {
// Unity reference line
ctx.strokeStyle = '#6b7280';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
const [ux0, uy0] = toPx(-100, -100);
const [ux1, uy1] = toPx(0, 0);
ctx.beginPath();
ctx.moveTo(ux0, uy0);
ctx.lineTo(ux1, uy1);
ctx.stroke();
ctx.setLineDash([]);
// Threshold marker
ctx.strokeStyle = '#fbbf24';
ctx.lineWidth = 1;
ctx.setLineDash([2, 3]);
const [tx0, ty0] = toPx(activeComp.threshold, -100);
const [tx1, ty1] = toPx(activeComp.threshold, 0);
ctx.beginPath();
ctx.moveTo(tx0, ty0);
ctx.lineTo(tx1, ty1);
ctx.stroke();
ctx.setLineDash([]);
// Compression curve
ctx.strokeStyle = '#4ade80';
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
ctx.beginPath();
curvePoints.forEach(([x, y], i) => {
const [px, py] = toPx(x, y);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
}}
/> />
</div> </div>
@@ -0,0 +1,73 @@
import { memo, useCallback, useMemo } from 'react';
import { DelayUnit } from '../../types';
import { DELAY_RANGES } from '../../constants';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
import { DELAY_UNIT_LABEL } from '../../constants';
const formatY = (v: number) => v.toFixed(0);
type DelayRow = { label: string; delay: number };
const rowsEqual = (a: DelayRow[], b: DelayRow[]) =>
a.length === b.length &&
a.every((row, i) => row.label === b[i].label && row.delay === b[i].delay);
export const DelayGraph = memo(
function DelayGraph({
title,
rows,
unit,
}: {
title: string;
rows: DelayRow[];
unit: DelayUnit;
}) {
const [min, max] = DELAY_RANGES[unit];
const roundedMax = (Math.floor(max / 100) + 1) * 100;
const labelByX = useMemo(() => {
const map = new Map<number, string>();
rows.forEach((row, i) => map.set(i + 1, row.label));
return map;
}, [rows]);
const formatX = useCallback((v: number) => labelByX.get(Math.round(v)) ?? '', [labelByX]);
const draw = useCallback(
({ ctx, toPx, plot }: any) => {
const barWidth = (plot.width / rows.length) * 0.55;
rows.forEach((row, i) => {
const x = i + 1;
const [xPx, baseY] = toPx(x, min);
const [, topY] = toPx(x, row.delay);
ctx.fillStyle = '#4ade80';
ctx.fillRect(xPx - barWidth / 2, topY, barWidth, baseY - topY);
});
},
[rows, min]
);
return (
<div className="delay-graph-panel">
<div className="delay-graph-title">{title}</div>
<LinearGraph
xMin={0.5}
xMax={rows.length + 0.5}
xStep={1}
yMin={min}
yMax={roundedMax}
xLabel="Channel"
yLabel={DELAY_UNIT_LABEL[unit]}
showGrid={true}
formatX={formatX}
formatY={formatY}
draw={draw}
/>
</div>
);
},
(prev, next) =>
prev.title === next.title && prev.unit === next.unit && rowsEqual(prev.rows, next.rows)
);
@@ -3,16 +3,10 @@ import { InputChannel, Channel, OutputChannel, DelayUnit } from '../../types';
import { DSP408 as DSP } from '../../../../types'; import { DSP408 as DSP } from '../../../../types';
import Button from '../../../../components/Button/Button'; import Button from '../../../../components/Button/Button';
import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup'; import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup';
import { LinearGraph } from '../../../../components/LinearGraph/LinearGraph'; import { DelayGraph } from './DelayGraph';
import { useMemo, useState } from 'react'; import { useState } from 'react';
import './DelaySection.css'; import './DelaySection.css';
import { DELAY_RANGES } from '../../constants'; import { DELAY_RANGES, DELAY_UNIT_LABEL } from '../../constants';
const UNIT_LABEL: Record<DelayUnit, string> = {
[DelayUnit.Millisecond]: 'ms',
[DelayUnit.Meter]: 'm',
[DelayUnit.Feet]: 'ft',
};
const UNIT_ORDER: DelayUnit[] = [DelayUnit.Millisecond, DelayUnit.Meter, DelayUnit.Feet]; const UNIT_ORDER: DelayUnit[] = [DelayUnit.Millisecond, DelayUnit.Meter, DelayUnit.Feet];
@@ -60,7 +54,7 @@ function DelayPanel({
min={min} min={min}
max={max} max={max}
step={() => DELAY_STEP[unit]} step={() => DELAY_STEP[unit]}
unit={' ' + UNIT_LABEL[unit]} unit={' ' + DELAY_UNIT_LABEL[unit]}
value={state.delay} value={state.delay}
onInput={(value) => onLiveValue(channel, value)} onInput={(value) => onLiveValue(channel, value)}
onChange={(value) => setDelay(channel, value)} onChange={(value) => setDelay(channel, value)}
@@ -69,54 +63,6 @@ function DelayPanel({
); );
} }
function DelayGraph({
title,
rows,
unit,
}: {
title: string;
rows: { label: string; delay: number }[];
unit: DelayUnit;
}) {
const [min, max] = DELAY_RANGES[unit];
const roundedMax = (Math.floor(max / 100) + 1) * 100;
const labelByX = useMemo(() => {
const map = new Map<number, string>();
rows.forEach((row, i) => map.set(i + 1, row.label));
return map;
}, [rows]);
return (
<div className="delay-graph-panel">
<div className="delay-graph-title">{title}</div>
<LinearGraph
xMin={0.5}
xMax={rows.length + 0.5}
xStep={1}
yMin={min}
yMax={roundedMax}
xLabel="Channel"
yLabel={UNIT_LABEL[unit]}
showGrid={true}
formatX={(v) => labelByX.get(Math.round(v)) ?? ''}
formatY={(v) => v.toFixed(0)}
draw={({ ctx, toPx, plot }) => {
const barWidth = (plot.width / rows.length) * 0.55;
rows.forEach((row, i) => {
const x = i + 1;
const [xPx, baseY] = toPx(x, min);
const [, topY] = toPx(x, row.delay);
ctx.fillStyle = '#4ade80';
ctx.fillRect(xPx - barWidth / 2, topY, barWidth, baseY - topY);
});
}}
/>
</div>
);
}
function DelayUnitSelector({ function DelayUnitSelector({
unit, unit,
onSelect, onSelect,
@@ -140,7 +86,7 @@ function DelayUnitSelector({
minHeight: 0, minHeight: 0,
}} }}
> >
{UNIT_LABEL[u]} {DELAY_UNIT_LABEL[u]}
</Button> </Button>
))} ))}
</div> </div>
@@ -0,0 +1,144 @@
import { memo, useCallback, useMemo } from 'react';
import { GRAPH_FREQS, GRAPH_X_MAX, GRAPH_X_MIN, GRAPH_Y_MIN, Y_AXIS_STEP } from '../../constants';
import { Curve, CurvePoint } from '../../utils/graph/curve';
import { drawCurves } from '../../utils/graph/draw';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
// Expands [baseMin, baseMax] outward to fit whatever the curves actually
// contain (e.g. gain + geq + peq stacking past the nominal graph range),
// snapped to the axis step with one step of headroom so nothing touches
// the plot edge. Never shrinks below the base range.
function computeYAxisBounds(
curves: Curve[],
baseMin: number,
baseMax: number,
step: number
): { yMin: number; yMax: number } {
let dataMax = baseMax;
let dataMin = baseMin;
for (const curve of curves) {
for (const { y } of curve.points) {
if (y > dataMax) dataMax = y;
if (y < dataMin) dataMin = y;
}
}
const yMax = Math.ceil((dataMax + step) / step) * step;
const yMin = Math.floor((dataMin - step) / step) * step;
return { yMin, yMax };
}
// fill:false everywhere — with multiple overlapping curves the fill/fade
// just muddies things; stroke-only makes each channel/stage legible.
function buildCurvesForChannels<T extends string>(
channels: T[],
selected: Set<T>,
colors: Record<T, string>,
showStages: boolean,
getCurves: (channel: T) => ChannelCurves
): Curve[] {
const curves: Curve[] = [];
[...channels].reverse().forEach((channel) => {
if (!selected.has(channel)) return;
const { geq, peqCrossover, total } = getCurves(channel);
const color = colors[channel];
if (showStages) {
if (geq.length > 0) {
curves.push({
points: geq,
style: { strokeColor: color, fill: false, dimmed: true, lineWidth: 1 },
});
}
if (peqCrossover.length > 0) {
curves.push({
points: peqCrossover,
style: { strokeColor: color, fill: false, dimmed: true, lineWidth: 1 },
});
}
}
curves.push({ points: total, style: { strokeColor: color, fill: false, lineWidth: 2 } });
});
return curves;
}
const formatX = (v: number) => Math.round(v).toString();
export const formatOutputY = (v: number) => Math.round(v).toString();
export const formatInputY = (v: number) => {
if (v === 0) return '0';
if (v > 0) return v % 12 === 0 ? `+${Math.round(v)}` : '';
return Math.abs(v) % 15 === 0 ? Math.round(v).toString() : '';
};
export type ChannelCurves = {
geq: CurvePoint[];
peqCrossover: CurvePoint[];
total: CurvePoint[];
};
type ResponseGraphProps<T extends string, S> = {
channels: T[];
states: Record<T, S>;
selected: Set<T>;
colors: Record<T, string>;
showStages: boolean;
liveGains: Partial<Record<T, number>>;
getChannelCurves: (state: S, freqs: number[], liveGain: number | undefined) => ChannelCurves;
formatY: (v: number) => string;
};
function ResponseGraphInner<T extends string, S>({
channels,
states,
selected,
colors,
showStages,
liveGains,
getChannelCurves,
formatY,
}: ResponseGraphProps<T, S>) {
const curves = useMemo(
() =>
buildCurvesForChannels(channels, selected, colors, showStages, (ch) =>
getChannelCurves(states[ch], GRAPH_FREQS, liveGains[ch])
),
[channels, selected, colors, showStages, states, liveGains, getChannelCurves]
);
const { yMin, yMax } = useMemo(
() => computeYAxisBounds(curves, GRAPH_Y_MIN, 12, Y_AXIS_STEP),
[curves]
);
const draw = useCallback(
({ ctx, toPx }: any) => {
drawCurves({ ctx, toPx, xMin: GRAPH_X_MIN, xMax: GRAPH_X_MAX, yMin, yMax, curves });
},
[curves, yMin, yMax]
);
return (
<LinearGraph
xMin={GRAPH_X_MIN}
xMax={GRAPH_X_MAX}
xScale="log"
yMin={yMin}
yMax={yMax}
yStep={Y_AXIS_STEP}
xLabel="Hz"
yLabel="dB"
showGrid={true}
formatX={formatX}
formatY={formatY}
draw={draw}
/>
);
}
// memo() erases the generics, so cast it back.
export const ResponseGraph = memo(ResponseGraphInner) as typeof ResponseGraphInner;
@@ -6,52 +6,21 @@ import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup';
import './GainSection.css'; import './GainSection.css';
import { import {
GEQ_BANDS_LABEL, GEQ_BANDS_LABEL,
GRAPH_X_MAX,
GRAPH_X_MIN,
GRAPH_Y_MAX,
GRAPH_Y_MIN,
INPUT_ORDER, INPUT_ORDER,
OUTPUT_ORDER, OUTPUT_ORDER,
GEQ_CURVE_Q,
INPUT_COLORS,
OUTPUT_COLORS,
} from '../../constants'; } from '../../constants';
import { useState } from 'react'; import { useState } from 'react';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph'; import { CurvePoint, sumCurvePoints } from '../../utils/graph/curve';
import { drawCurves } from '../../utils/graph/draw';
import { Curve, CurvePoint, sumCurvePoints } from '../../utils/graph/curve';
import { getGeqCurvePoints } from '../../utils/graph/geq'; import { getGeqCurvePoints } from '../../utils/graph/geq';
import { getPeqCurvePoints } from '../../utils/graph/peq'; import { getPeqCurvePoints } from '../../utils/graph/peq';
import { getCrossoverCurvePoints } from '../../utils/graph/crossover'; import { getCrossoverCurvePoints } from '../../utils/graph/crossover';
import { logSpace } from '../../utils/graph/curve'; import { ChannelCurves, formatInputY, formatOutputY, ResponseGraph } from './GainGraph';
const CHANNEL_COLORS = [
'#4ade80',
'#60a5fa',
'#f472b6',
'#fbbf24',
'#a78bfa',
'#34d399',
'#f87171',
'#38bdf8',
];
const GEQ_CURVE_Q = 5;
const Y_AXIS_STEP = 3; // must match the graph's yStep
function buildColorMap<T extends string>(channels: T[]): Record<T, string> {
const map = {} as Record<T, string>;
channels.forEach((ch, i) => {
map[ch] = CHANNEL_COLORS[i % CHANNEL_COLORS.length];
});
return map;
}
// ---- Curve construction ----------------------------------------------- // ---- Curve construction -----------------------------------------------
type ChannelCurves = {
geq: CurvePoint[];
peqCrossover: CurvePoint[];
total: CurvePoint[];
};
function getGainCurvePoints(freqs: number[], gainDb: number): CurvePoint[] { function getGainCurvePoints(freqs: number[], gainDb: number): CurvePoint[] {
return freqs.map((x) => ({ x, y: gainDb })); return freqs.map((x) => ({ x, y: gainDb }));
} }
@@ -126,69 +95,6 @@ function getOutputChannelCurves(
return { geq: [], peqCrossover, total }; return { geq: [], peqCrossover, total };
} }
// fill:false everywhere — with multiple overlapping curves the fill/fade
// just muddies things; stroke-only makes each channel/stage legible.
function buildCurvesForChannels<T extends string>(
channels: T[],
selected: Set<T>,
colors: Record<T, string>,
showStages: boolean,
getCurves: (channel: T) => ChannelCurves
): Curve[] {
const curves: Curve[] = [];
[...channels].reverse().forEach((channel) => {
if (!selected.has(channel)) return;
const { geq, peqCrossover, total } = getCurves(channel);
const color = colors[channel];
if (showStages) {
if (geq.length > 0) {
curves.push({
points: geq,
style: { strokeColor: color, fill: false, dimmed: true, lineWidth: 1 },
});
}
if (peqCrossover.length > 0) {
curves.push({
points: peqCrossover,
style: { strokeColor: color, fill: false, dimmed: true, lineWidth: 1 },
});
}
}
curves.push({ points: total, style: { strokeColor: color, fill: false, lineWidth: 2 } });
});
return curves;
}
// Expands [baseMin, baseMax] outward to fit whatever the curves actually
// contain (e.g. gain + geq + peq stacking past the nominal graph range),
// snapped to the axis step with one step of headroom so nothing touches
// the plot edge. Never shrinks below the base range.
function computeYAxisBounds(
curves: Curve[],
baseMin: number,
baseMax: number,
step: number
): { yMin: number; yMax: number } {
let dataMax = baseMax;
let dataMin = baseMin;
for (const curve of curves) {
for (const { y } of curve.points) {
if (y > dataMax) dataMax = y;
if (y < dataMin) dataMin = y;
}
}
const yMax = Math.ceil((dataMax + step) / step) * step;
const yMin = Math.floor((dataMin - step) / step) * step;
return { yMin, yMax };
}
// ---- Panels ------------------------------------------------------------- // ---- Panels -------------------------------------------------------------
function GainPanel({ function GainPanel({
@@ -334,9 +240,6 @@ function GainSection({
setMute: (channel: Channel, muted: boolean) => Promise<boolean>; setMute: (channel: Channel, muted: boolean) => Promise<boolean>;
setInverse: (channel: Channel, inverted: boolean) => Promise<boolean>; setInverse: (channel: Channel, inverted: boolean) => Promise<boolean>;
}) { }) {
const inputColors = buildColorMap(INPUT_ORDER);
const outputColors = buildColorMap(OUTPUT_ORDER);
const [selectedInputs, setSelectedInputs] = useState<Set<InputChannel>>(new Set(INPUT_ORDER)); const [selectedInputs, setSelectedInputs] = useState<Set<InputChannel>>(new Set(INPUT_ORDER));
const [selectedOutputs, setSelectedOutputs] = useState<Set<OutputChannel>>(new Set(OUTPUT_ORDER)); const [selectedOutputs, setSelectedOutputs] = useState<Set<OutputChannel>>(new Set(OUTPUT_ORDER));
@@ -402,47 +305,6 @@ function GainSection({
}); });
}; };
const freqs = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
const inputCurves = buildCurvesForChannels(
INPUT_ORDER,
selectedInputs,
inputColors,
showInputStages,
(channel) =>
getInputChannelCurves(
dsp.state.current_config.input_states[channel],
freqs,
liveInputGains[channel]
)
);
const outputCurves = buildCurvesForChannels(
OUTPUT_ORDER,
selectedOutputs,
outputColors,
showOutputStages,
(channel) =>
getOutputChannelCurves(
dsp.state.current_config.output_states[channel],
freqs,
liveOutputGains[channel]
)
);
const { yMin: inputYMin, yMax: inputYMax } = computeYAxisBounds(
inputCurves,
GRAPH_Y_MIN,
12,
Y_AXIS_STEP
);
const { yMin: outputYMin, yMax: outputYMax } = computeYAxisBounds(
outputCurves,
GRAPH_Y_MIN,
GRAPH_Y_MAX,
Y_AXIS_STEP
);
return ( return (
<> <>
<div className="gain-linear-graph-section"> <div className="gain-linear-graph-section">
@@ -461,45 +323,20 @@ function GainSection({
<ChannelSelector <ChannelSelector
channels={INPUT_ORDER} channels={INPUT_ORDER}
labels={inputLabels} labels={inputLabels}
colors={inputColors} colors={INPUT_COLORS}
selected={selectedInputs} selected={selectedInputs}
onToggle={toggleInput} onToggle={toggleInput}
/> />
</div> </div>
<LinearGraph <ResponseGraph
xMin={GRAPH_X_MIN} channels={INPUT_ORDER}
xMax={GRAPH_X_MAX} states={dsp.state.current_config.input_states}
xScale="log" selected={selectedInputs}
yMin={inputYMin} colors={INPUT_COLORS}
yMax={inputYMax} showStages={showInputStages}
yStep={Y_AXIS_STEP} liveGains={liveInputGains}
xLabel="Hz" getChannelCurves={getInputChannelCurves}
yLabel="dB" formatY={formatInputY}
showGrid={true}
formatX={(v) => Math.round(v).toString()}
formatY={(v) => {
// Always label 0.
if (v === 0) return '0';
// Positive side: label every 12 dB.
if (v > 0) {
return v % 12 === 0 ? `+${Math.round(v)}` : '';
}
// Negative side: label every 15 dB.
return Math.abs(v) % 15 === 0 ? Math.round(v).toString() : '';
}}
draw={({ ctx, toPx }) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: inputYMin,
yMax: inputYMax,
curves: inputCurves,
});
}}
/> />
</div> </div>
@@ -519,34 +356,20 @@ function GainSection({
<ChannelSelector <ChannelSelector
channels={OUTPUT_ORDER} channels={OUTPUT_ORDER}
labels={outputLabels} labels={outputLabels}
colors={outputColors} colors={OUTPUT_COLORS}
selected={selectedOutputs} selected={selectedOutputs}
onToggle={toggleOutput} onToggle={toggleOutput}
/> />
</div> </div>
<LinearGraph <ResponseGraph
xMin={GRAPH_X_MIN} channels={OUTPUT_ORDER}
xMax={GRAPH_X_MAX} states={dsp.state.current_config.output_states}
xScale="log" selected={selectedOutputs}
yMin={outputYMin} colors={OUTPUT_COLORS}
yMax={outputYMax} showStages={showOutputStages}
yStep={Y_AXIS_STEP} liveGains={liveOutputGains}
xLabel="Hz" getChannelCurves={getOutputChannelCurves}
yLabel="dB" formatY={formatOutputY}
showGrid={true}
formatX={(v) => Math.round(v).toString()}
formatY={(v) => Math.round(v).toString()}
draw={({ ctx, toPx }) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: outputYMin,
yMax: outputYMax,
curves: outputCurves,
});
}}
/> />
</div> </div>
</div> </div>
@@ -0,0 +1,72 @@
import { memo, useCallback, useMemo } from 'react';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
const formatTick = (v: number) => Math.round(v).toString();
export const GateGraph = memo(function GateGraph({
threshold,
attack,
hold,
release,
}: {
threshold: number;
attack: number;
hold: number;
release: number;
}) {
const envelope = useMemo(() => {
const roll = Math.max(20, (attack + hold + release) * 0.08);
const t1 = roll;
const t2 = t1 + attack;
const t3 = t2 + hold;
const t4 = t3 + release;
const t5 = t4 + roll;
return { t0: 0, t1, t2, t3, t4, t5 };
}, [attack, hold, release]);
const draw = useCallback(
({ toPx, ctx }: any) => {
const { t0, t1, t2, t3, t4, t5 } = envelope;
ctx.strokeStyle = '#fbbf24';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
const [tx0, ty] = toPx(t0, threshold);
const [tx1] = toPx(t5, threshold);
ctx.beginPath();
ctx.moveTo(tx0, ty);
ctx.lineTo(tx1, ty);
ctx.stroke();
ctx.setLineDash([]);
ctx.strokeStyle = '#4ade80';
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
const points: [number, number][] = [
[t0, -90], [t1, -90], [t2, 0], [t3, 0], [t4, -90], [t5, -90],
];
ctx.beginPath();
points.forEach(([t, g], i) => {
const [px, py] = toPx(t, g);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
},
[envelope, threshold]
);
return (
<LinearGraph
xMin={envelope.t0}
xMax={envelope.t5}
yMin={-95}
yMax={5}
xLabel="ms"
yLabel="dB"
formatX={formatTick}
formatY={formatTick}
draw={draw}
/>
);
});
@@ -3,9 +3,9 @@ import VerticalSlider from '../../../../components/VerticalSlider/VerticalSlider
import { InputChannel } from '../../types'; import { InputChannel } from '../../types';
import { DSP408 as DSP } from '../../../../types'; import { DSP408 as DSP } from '../../../../types';
import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup'; import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup';
import { LinearGraph } from '../../../../components/LinearGraph/LinearGraph'; import { GateGraph } from './GateGraph';
import MeterBar from '../../../../components/MeterBar/MeterBar'; import MeterBar from '../../../../components/MeterBar/MeterBar';
import { useMemo, useState } from 'react'; import { useState } from 'react';
import './GateSection.css'; import './GateSection.css';
const GATE_PARAMS = [ const GATE_PARAMS = [
@@ -112,65 +112,16 @@ function GateSection({ dsp, set_gate }: { dsp: DSP; set_gate: SetGateFn }) {
const activeInputState = dsp.state.current_config.input_states[activeChannel]; const activeInputState = dsp.state.current_config.input_states[activeChannel];
const activeGate = liveGate[activeChannel] ?? activeInputState.gate; const activeGate = liveGate[activeChannel] ?? activeInputState.gate;
const envelope = useMemo(() => {
const { threshold, attack, hold, release } = activeGate;
const roll = Math.max(20, (attack + hold + release) * 0.08);
const t0 = 0;
const t1 = t0 + roll;
const t2 = t1 + attack;
const t3 = t2 + hold;
const t4 = t3 + release;
const t5 = t4 + roll;
return { threshold, t0, t1, t2, t3, t4, t5 };
}, [activeGate.threshold, activeGate.attack, activeGate.hold, activeGate.release]);
return ( return (
<> <>
<div className="gate-linear-graph-section"> <div className="gate-linear-graph-section">
<div className="gate-graph-panel"> <div className="gate-graph-panel">
<div className="gate-graph-title">Frequency Response</div> <div className="gate-graph-title">Gate Response</div>
<LinearGraph <GateGraph
xMin={envelope.t0} threshold={activeGate.threshold}
xMax={envelope.t5} attack={activeGate.attack}
yMin={-95} hold={activeGate.hold}
yMax={5} release={activeGate.release}
xLabel="ms"
yLabel="dB"
formatX={(v) => Math.round(v).toString()}
formatY={(v) => Math.round(v).toString()}
draw={({ toPx, ctx }) => {
const { threshold, t0, t1, t2, t3, t4, t5 } = envelope;
ctx.strokeStyle = '#fbbf24';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
const [tx0, ty] = toPx(t0, threshold);
const [tx1] = toPx(t5, threshold);
ctx.beginPath();
ctx.moveTo(tx0, ty);
ctx.lineTo(tx1, ty);
ctx.stroke();
ctx.setLineDash([]);
ctx.strokeStyle = '#4ade80';
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
const points: [number, number][] = [
[t0, -90],
[t1, -90],
[t2, 0],
[t3, 0],
[t4, -90],
[t5, -90],
];
ctx.beginPath();
points.forEach(([t, g], i) => {
const [px, py] = toPx(t, g);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
}}
/> />
</div> </div>
@@ -0,0 +1,73 @@
import { memo, useCallback, useMemo } from 'react';
import { logSpace } from '../../utils/graph/curve';
import { drawCurves } from '../../utils/graph/draw';
import { GRAPH_X_MIN, GRAPH_X_MAX, GRAPH_Y_MIN, GRAPH_Y_MAX, GEQ_CURVE_Q } from '../../constants';
import { DiscreteFrequency } from '../../types';
import { GEQ_BANDS_LABEL } from '../../constants';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
import { getGeqCurvePoints } from '../../utils/graph/geq';
import { LiveBands } from './GeqSection';
const GEQ_FREQS = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
export const GeqGraph = memo(function GeqGraph({
title,
gains,
bypass,
liveBands,
}: {
title: string;
gains: Record<DiscreteFrequency, number>;
bypass: boolean;
liveBands: LiveBands | undefined;
}) {
const curvePoints = useMemo(() => {
const values = GEQ_BANDS_LABEL.map(
({ frequency }) => liveBands?.[frequency] ?? gains[frequency] ?? 0
);
return getGeqCurvePoints({ freqs: GEQ_FREQS, values, q: GEQ_CURVE_Q });
}, [gains, liveBands]);
const draw = useCallback(
({ ctx, toPx }: any) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: GRAPH_Y_MIN,
yMax: GRAPH_Y_MAX,
curves: [
{
points: curvePoints,
style: { strokeColor: '#e5e7eb', dimmed: bypass },
},
],
});
},
[curvePoints, bypass]
);
return (
<div className="geq-graph-panel">
<div className="geq-graph-title">{title}</div>
<LinearGraph
xMin={GRAPH_X_MIN}
xMax={GRAPH_X_MAX}
xScale="log"
yMin={GRAPH_Y_MIN}
yMax={GRAPH_Y_MAX}
yStep={3}
xLabel="Band Hz"
yLabel="dB"
showGrid={true}
draw={draw}
/>
{bypass && (
<div className="geq-bypass-overlay">
<span>BYPASSED</span>
</div>
)}
</div>
);
});
@@ -3,26 +3,18 @@ import { InputChannel, DiscreteFrequency } from '../../types';
import { DSP408 as DSP } from '../../../../types'; import { DSP408 as DSP } from '../../../../types';
import Button from '../../../../components/Button/Button'; import Button from '../../../../components/Button/Button';
import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup'; import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup';
import { LinearGraph } from '../../../../components/LinearGraph/LinearGraph';
import { drawCurves } from '../../utils/graph/draw';
import { import {
INPUT_ORDER, INPUT_ORDER,
GRAPH_X_MIN,
GRAPH_X_MAX,
GRAPH_Y_MIN,
GRAPH_Y_MAX,
GEQ_GAIN_MIN, GEQ_GAIN_MIN,
GEQ_GAIN_MAX, GEQ_GAIN_MAX,
GEQ_GAIN_STEP, GEQ_GAIN_STEP,
GEQ_BANDS_LABEL, GEQ_BANDS_LABEL,
GEQ_CURVE_Q,
} from '../../constants'; } from '../../constants';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import './GeqSection.css'; import './GeqSection.css';
import { getGeqCurvePoints } from '../../utils/graph/geq'; import { GeqGraph } from './GeqGraph';
import { logSpace } from '../../utils/graph/curve';
type LiveBands = Partial<Record<DiscreteFrequency, number>>; export type LiveBands = Partial<Record<DiscreteFrequency, number>>;
type SetGeqBandFn = ( type SetGeqBandFn = (
input: InputChannel, input: InputChannel,
@@ -69,64 +61,6 @@ function GeqBandPanel({
); );
} }
function GeqGraph({
title,
channel,
dsp,
liveBands,
}: {
title: string;
channel: InputChannel;
dsp: DSP;
liveBands: LiveBands | undefined;
}) {
const geq = dsp.state.current_config.input_states[channel].geq;
const values = GEQ_BANDS_LABEL.map(
({ frequency }) => liveBands?.[frequency] ?? geq.gains[frequency] ?? 0
);
const freqs = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
return (
<div className="geq-graph-panel">
<div className="geq-graph-title">{title}</div>
<LinearGraph
xMin={GRAPH_X_MIN}
xMax={GRAPH_X_MAX}
xScale="log"
yMin={GRAPH_Y_MIN}
yMax={GRAPH_Y_MAX}
yStep={3}
xLabel="Band Hz"
yLabel="dB"
showGrid={true}
draw={({ ctx, toPx }) => {
drawCurves({
ctx,
toPx,
xMin: GRAPH_X_MIN,
xMax: GRAPH_X_MAX,
yMin: GRAPH_Y_MIN,
yMax: GRAPH_Y_MAX,
curves: [
{
points: getGeqCurvePoints({ freqs, values, q: GEQ_CURVE_Q }),
style: { strokeColor: '#e5e7eb', dimmed: geq.bypass },
},
],
});
}}
/>
{geq.bypass && (
<div className="geq-bypass-overlay">
<span>BYPASSED</span>
</div>
)}
</div>
);
}
function GeqChannelSelector({ function GeqChannelSelector({
channel, channel,
inputs, inputs,
@@ -298,8 +232,8 @@ function GeqSection({
<div className="geq-linear-graph-section"> <div className="geq-linear-graph-section">
<GeqGraph <GeqGraph
title={`${activeInputState.name} - GEQ`} title={`${activeInputState.name} - GEQ`}
channel={activeChannel} gains={activeGeq.gains}
dsp={dsp} bypass={activeGeq.bypass}
liveBands={activeLiveBands} liveBands={activeLiveBands}
/> />
</div> </div>
@@ -0,0 +1,76 @@
import { memo, useCallback, useMemo } from 'react';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
const formatTick = (v: number) => Math.round(v).toString();
// Hard-knee brickwall limiter transfer curve, in dB.
function limiterOutputDb(input: number, threshold: number): number {
return input <= threshold ? input : threshold;
}
export const LimiterGraph = memo(function LimiterGraph({ threshold }: { threshold: number }) {
const curvePoints = useMemo(() => {
const steps = 120;
const points: [number, number][] = [];
for (let i = 0; i <= steps; i++) {
const x = -60 + (60 * i) / steps;
points.push([x, limiterOutputDb(x, threshold)]);
}
return points;
}, [threshold]);
const draw = useCallback(
({ ctx, toPx }: any) => {
// Unity reference line
ctx.strokeStyle = '#6b7280';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
const [ux0, uy0] = toPx(-60, -60);
const [ux1, uy1] = toPx(0, 0);
ctx.beginPath();
ctx.moveTo(ux0, uy0);
ctx.lineTo(ux1, uy1);
ctx.stroke();
ctx.setLineDash([]);
// Threshold marker
ctx.strokeStyle = '#fbbf24';
ctx.lineWidth = 1;
ctx.setLineDash([2, 3]);
const [tx0, ty0] = toPx(threshold, -60);
const [tx1, ty1] = toPx(threshold, 0);
ctx.beginPath();
ctx.moveTo(tx0, ty0);
ctx.lineTo(tx1, ty1);
ctx.stroke();
ctx.setLineDash([]);
// Limiter curve
ctx.strokeStyle = '#f87171';
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
ctx.beginPath();
curvePoints.forEach(([x, y], i) => {
const [px, py] = toPx(x, y);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
},
[threshold, curvePoints]
);
return (
<LinearGraph
xMin={-60}
xMax={0}
yMin={-60}
yMax={0}
xLabel="in dB"
yLabel="out dB"
formatX={formatTick}
formatY={formatTick}
draw={draw}
/>
);
});
@@ -3,9 +3,9 @@ import VerticalSlider from '../../../../components/VerticalSlider/VerticalSlider
import { OutputChannel } from '../../types'; import { OutputChannel } from '../../types';
import { DSP408 as DSP } from '../../../../types'; import { DSP408 as DSP } from '../../../../types';
import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup'; import ChannelGroup from '../../../../components/ChannelGroup/ChannelGroup';
import { LinearGraph } from '../../../../components/LinearGraph/LinearGraph'; import { LimiterGraph } from './LimiterGraph';
import MeterBar from '../../../../components/MeterBar/MeterBar'; import MeterBar from '../../../../components/MeterBar/MeterBar';
import { useMemo, useState } from 'react'; import { useState } from 'react';
import './LimiterSection.css'; import './LimiterSection.css';
const LIMITER_SLIDER_PARAMS = [ const LIMITER_SLIDER_PARAMS = [
@@ -74,11 +74,6 @@ function LimiterPanel({
); );
} }
// Hard-knee brickwall limiter transfer curve, in dB.
function limiterOutputDb(input: number, threshold: number): number {
return input <= threshold ? input : threshold;
}
function LimiterSection({ dsp, set_limiter }: { dsp: DSP; set_limiter: SetLimiterFn }) { function LimiterSection({ dsp, set_limiter }: { dsp: DSP; set_limiter: SetLimiterFn }) {
const outputs = [ const outputs = [
OutputChannel.Out1, OutputChannel.Out1,
@@ -122,70 +117,12 @@ function LimiterSection({ dsp, set_limiter }: { dsp: DSP; set_limiter: SetLimite
const activeOutputState = dsp.state.current_config.output_states[activeChannel]; const activeOutputState = dsp.state.current_config.output_states[activeChannel];
const activeLim = liveLim[activeChannel] ?? (activeOutputState.limiter as LimiterValues); const activeLim = liveLim[activeChannel] ?? (activeOutputState.limiter as LimiterValues);
const curvePoints = useMemo(() => {
const { threshold } = activeLim;
const steps = 120;
const points: [number, number][] = [];
for (let i = 0; i <= steps; i++) {
const x = -60 + (60 * i) / steps;
points.push([x, limiterOutputDb(x, threshold)]);
}
return points;
}, [activeLim.threshold]);
return ( return (
<> <>
<div className="limiter-linear-graph-section"> <div className="limiter-linear-graph-section">
<div className="limiter-graph-panel"> <div className="limiter-graph-panel">
<div className="limiter-graph__title">{activeOutputState.name} - Limiter</div> <div className="limiter-graph__title">{activeOutputState.name} - Limiter</div>
<LimiterGraph threshold={activeLim.threshold} />
<LinearGraph
xMin={-60}
xMax={0}
yMin={-60}
yMax={0}
xLabel="in dB"
yLabel="out dB"
formatX={(v) => Math.round(v).toString()}
formatY={(v) => Math.round(v).toString()}
draw={({ ctx, toPx }) => {
// Unity reference line
ctx.strokeStyle = '#6b7280';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
const [ux0, uy0] = toPx(-60, -60);
const [ux1, uy1] = toPx(0, 0);
ctx.beginPath();
ctx.moveTo(ux0, uy0);
ctx.lineTo(ux1, uy1);
ctx.stroke();
ctx.setLineDash([]);
// Threshold marker
ctx.strokeStyle = '#fbbf24';
ctx.lineWidth = 1;
ctx.setLineDash([2, 3]);
const [tx0, ty0] = toPx(activeLim.threshold, -60);
const [tx1, ty1] = toPx(activeLim.threshold, 0);
ctx.beginPath();
ctx.moveTo(tx0, ty0);
ctx.lineTo(tx1, ty1);
ctx.stroke();
ctx.setLineDash([]);
// Limiter curve
ctx.strokeStyle = '#f87171';
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
ctx.beginPath();
curvePoints.forEach(([x, y], i) => {
const [px, py] = toPx(x, y);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
}}
/>
</div> </div>
<div className="limiter-meter-panel"> <div className="limiter-meter-panel">
@@ -13,6 +13,7 @@ import {
} from '../../constants'; } from '../../constants';
import { SidebarId } from '../../constants'; import { SidebarId } from '../../constants';
import SignalFlowMatrix from '../../../../components/SignalFlowMatrix/SignalFlowMatrix'; import SignalFlowMatrix from '../../../../components/SignalFlowMatrix/SignalFlowMatrix';
import { useState } from 'react';
import './Matrixsection.css'; import './Matrixsection.css';
const GAIN_VALUES: number[] = (() => { const GAIN_VALUES: number[] = (() => {
@@ -39,6 +40,12 @@ function getRoutedInputs(dsp: DSP, output: OutputChannel): InputChannel[] {
return getMatrixRoutes(dsp, output).connected; return getMatrixRoutes(dsp, output).connected;
} }
function snapToGain(g: number): number {
return GAIN_VALUES.reduce((best, v) =>
Math.abs(v - g) < Math.abs(best - g) ? v : best
);
}
function MatrixSection({ function MatrixSection({
dsp, dsp,
setMatrixRouting, setMatrixRouting,
@@ -68,6 +75,21 @@ function MatrixSection({
void setMatrixGain(input, output, gain); void setMatrixGain(input, output, gain);
}; };
const [liveGains, setLiveGains] = useState<Record<string, number>>({});
// value = number while wheeling, null once the commit is done
const previewGain = (input: InputChannel, output: OutputChannel, value: number | null) => {
const key = `${input}-${output}`;
setLiveGains((prev) => {
if (value === null) {
if (!(key in prev)) return prev;
const { [key]: _removed, ...rest } = prev;
return rest;
}
return { ...prev, [key]: value };
});
};
return ( return (
<> <>
<div className="matrix-flow"> <div className="matrix-flow">
@@ -76,6 +98,7 @@ function MatrixSection({
setMatrixRouting={setMatrixRouting} setMatrixRouting={setMatrixRouting}
setMatrixGain={setMatrixGain} setMatrixGain={setMatrixGain}
setActiveSidebar={setActiveSidebar} setActiveSidebar={setActiveSidebar}
onGainPreview={previewGain}
/> />
</div> </div>
<div className="matrix-section"> <div className="matrix-section">
@@ -90,7 +113,7 @@ function MatrixSection({
<div className="matrix-panel__rows"> <div className="matrix-panel__rows">
{INPUT_ORDER.map((input) => { {INPUT_ORDER.map((input) => {
const connected = isRouted(dsp, output, input); const connected = isRouted(dsp, output, input);
const gain = getLinkGain(dsp, output, input); const gain = liveGains[`${input}-${output}`] ?? getLinkGain(dsp, output, input);
return ( return (
<div className="matrix-panel__row" key={String(input)}> <div className="matrix-panel__row" key={String(input)}>
@@ -111,7 +134,7 @@ function MatrixSection({
<ChoiceStepper <ChoiceStepper
className="matrix-gain-stepper" className="matrix-gain-stepper"
value={gain} value={snapToGain(gain)}
values={GAIN_VALUES} values={GAIN_VALUES}
formatLabel={(v: number) => `${v > 0 ? '+' : ''}${v.toFixed(1)} dB`} formatLabel={(v: number) => `${v > 0 ? '+' : ''}${v.toFixed(1)} dB`}
onChange={(g) => handleGainChange(output, input, g)} onChange={(g) => handleGainChange(output, input, g)}
@@ -37,10 +37,8 @@ function MiscellaneousPanel({
const [isLinkModalOpen, setIsLinkModalOpen] = useState(false); const [isLinkModalOpen, setIsLinkModalOpen] = useState(false);
const [isCopyModalOpen, setIsCopyModalOpen] = useState(false); const [isCopyModalOpen, setIsCopyModalOpen] = useState(false);
const [inputSource, setInputSourceState] = useState<InputSource>({ const [liveInputSource, setLiveInputSource] = useState<InputSource | null>(null);
type: InputType.Analog, const inputSource = liveInputSource ?? dsp.state.current_config.input_source;
frequency: DiscreteFrequency.F20,
});
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [isPasswordVisible, setIsPasswordVisible] = useState(false); const [isPasswordVisible, setIsPasswordVisible] = useState(false);
@@ -51,18 +49,19 @@ function MiscellaneousPanel({
frequency: type === InputType.SineWave ? inputSource.frequency : DiscreteFrequency.F20, frequency: type === InputType.SineWave ? inputSource.frequency : DiscreteFrequency.F20,
}; };
setInputSourceState(nextSource); setLiveInputSource(nextSource);
await setInputSource(nextSource); const success = await setInputSource(nextSource);
if (success) setLiveInputSource(null);
}; };
const handleFrequencyChange = async (frequency: DiscreteFrequency) => { const handleFrequencyChange = async (frequency: DiscreteFrequency) => {
const nextSource: InputSource = { const nextSource: InputSource = { ...inputSource, frequency };
...inputSource,
frequency,
};
setInputSourceState(nextSource); setLiveInputSource(nextSource);
await setInputSource(nextSource); const success = await setInputSource(nextSource);
if (success) setLiveInputSource(null);
}; };
const handleFactoryReset = () => { const handleFactoryReset = () => {
+24
View File
@@ -8,6 +8,8 @@ import {
DelayUnit, DelayUnit,
Ratio, Ratio,
} from './types'; } from './types';
import { logSpace } from './utils/graph/curve';
import { buildColorMap } from './utils/graph/draw';
export const INPUT_ORDER: InputChannel[] = [ export const INPUT_ORDER: InputChannel[] = [
InputChannel.InA, InputChannel.InA,
@@ -255,6 +257,12 @@ export const DELAY_RANGES: Record<DelayUnit, [number, number]> = {
[DelayUnit.Feet]: [0, 766.329], [DelayUnit.Feet]: [0, 766.329],
}; };
export const DELAY_UNIT_LABEL: Record<DelayUnit, string> = {
[DelayUnit.Millisecond]: 'ms',
[DelayUnit.Meter]: 'm',
[DelayUnit.Feet]: 'ft',
};
// ------ Graph constants ------ // ------ Graph constants ------
const REAL_X_MIN = 20; const REAL_X_MIN = 20;
const REAL_X_MAX = 20000; const REAL_X_MAX = 20000;
@@ -268,6 +276,22 @@ export const GRAPH_X_MIN = Math.floor(Math.pow(10, logMin - logRange * X_LOG_PAD
export const GRAPH_X_MAX = Math.ceil(Math.pow(10, logMax + logRange * X_LOG_PADDING)); export const GRAPH_X_MAX = Math.ceil(Math.pow(10, logMax + logRange * X_LOG_PADDING));
export const GRAPH_Y_MIN = -21; export const GRAPH_Y_MIN = -21;
export const GRAPH_Y_MAX = 21; export const GRAPH_Y_MAX = 21;
export const Y_AXIS_STEP = 3;
export const CHANNEL_COLORS = [
'#4ade80',
'#60a5fa',
'#f472b6',
'#fbbf24',
'#a78bfa',
'#34d399',
'#f87171',
'#38bdf8',
];
export const INPUT_COLORS = buildColorMap(INPUT_ORDER);
export const OUTPUT_COLORS = buildColorMap(OUTPUT_ORDER);
export const GRAPH_FREQS = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
// ------ App ------ // ------ App ------
export type SidebarId = export type SidebarId =
+9
View File
@@ -1,3 +1,4 @@
import { CHANNEL_COLORS } from '../../constants';
import { CurvePoint, CurveStyle, Curve, DEFAULT_CURVE_COLORS, sumCurvePoints } from './curve'; import { CurvePoint, CurveStyle, Curve, DEFAULT_CURVE_COLORS, sumCurvePoints } from './curve';
export { sumCurvePoints }; export { sumCurvePoints };
@@ -96,3 +97,11 @@ export function drawCurves({ ctx, toPx, xMin, xMax, yMin, yMax, curves }: DrawCu
drawSingleCurve(ctx, toPx, curve.points, xMin, xMax, yMin, yMax, style); drawSingleCurve(ctx, toPx, curve.points, xMin, xMax, yMin, yMax, style);
} }
} }
export function buildColorMap<T extends string>(channels: T[]): Record<T, string> {
const map = {} as Record<T, string>;
channels.forEach((ch, i) => {
map[ch] = CHANNEL_COLORS[i % CHANNEL_COLORS.length];
});
return map;
}