Swirl and comb a sound with a Phaser and a Flanger node (#341)

sfxr's "phaser" is a comb filter, the sound plus a copy delayed by up
to 2.9 ms. That is a flanger, not the phaser a guitarist knows. Both
effects come in as nodes of their own, so each name fits its sound and
sfxr is covered in full. Both run on the FX worklet like the
Bitcrusher, because a feedback loop in Web Audio costs a render quantum
per round.

- Phaser: first-order allpasses (Stages 2, 4, 6, 8, 12) around
  Frequency, moved by a sine LFO Depth octaves wide at Rate Hz, with
  Feedback and Mix. An Envelope can move Frequency and Mix.
- Flanger: a delay line of Offset ms. Sweep moves it on in ms/s from
  the start of the voice, an LFO adds up to Depth ms. As in sfxr the
  delay is mirrored at 0, and it never goes past 20 ms. Feedback comes
  back exactly one delay later. An Envelope can move Offset and Mix.
- Mix 0 leaves the sound as it is, 1 is half sound and half copy. The
  notches are deepest there and the peaks stay at the sound's level.
  sfxr adds both at full, so its sound comes out 6 dB louder.
- The Flanger's processor gets the start of its voice and begins the
  sweep on that sample. stageNodes takes it as a new argument `at`.
- Explosion gets a Flanger in one draw out of two, with sfxr's offset
  and sweep and no LFO. Offset is offset^2 * 2.89 ms, Sweep is
  ramp^2 * 125 ms/s, signed so the direction holds.
- Randomize draws a Flanger's offset and sweep like sfxr. Its LFO and
  feedback and all of a Phaser are drawn within bounds of their own.
  Mix and Stages stay, as a Bitcrusher's Mix does. Mutate moves them
  too, and a 0 stays 0.
- New instrument preset Phased Pad: saw, Envelope, low-pass, Phaser of
  six stages. The other 14 are unchanged.
- The Bitcrusher's worklet setup is now shared with both nodes
  (workletNodes), its behaviour is unchanged.

Tests:
- Unit phaser (new): 8 green. Counter-check with clamping at 0 instead
  of mirroring and a flipped allpass coefficient: 3 red.
- Unit soundfx, sound-library, chip-presets: 45 / 76 / 14 green.
  Counter-checks: start time not passed on, phaser frequency eased
  linearly, sweep sign dropped, Phaser left out of Mutate, each red.
- Unit core, viewport, graph: 179 files, 2979 tests green.
- e2e 34 (melektaus-atx): ALL PASSED, 70 checks (1 new), first run.
  Chrome offline: 1 kHz notch RMS 0.0000 with two stages, 0.5657
  with four. Flanger echo after 48 samples, swept echo at 533/534.
  About 47 Phasers (12 stages) or 63 Flangers fill the audio thread.
- Gate (melektaus-atx): CHECK EXIT 0, 257 files, 3991 tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-07 12:11:54 +02:00
1 parent 29b604dc07
commit 01fd6e6464
13 files changed
+999 -48

No files matched your search

+86 -5
View File
@@ -10,9 +10,13 @@ import {
type FxPassFilter,
passOf,
SoundFxBitcrusher,
FLANGER_ROWS,
PHASER_ROWS,
SoundFxDelay,
SoundFxFilter,
SoundFxFlanger,
SoundFxMix,
SoundFxPhaser,
SoundFxPitch,
} from '../soundfx/nodes';
import {
@@ -30,7 +34,8 @@ import { HIGHEST_NOTE, LOWEST_NOTE } from './notes';
/**
* The Preset menu, Randomize and Mutate of the Instrument tab (#329), the way sfxr makes its sounds:
* its generators and its randomizer draw sfxr's settings, 0 to 1 as its sliders have them, which are
* then worked out into the numbers of a Chip, an Envelope, a Filter and a Bitcrusher. sfxr is
* then worked out into the numbers of a Chip, an Envelope, a Filter, a Bitcrusher and a Flanger (#341),
* which sfxr calls its phaser. sfxr is
* Copyright (c) 2007 Tomas Pettersson, MIT licence.
*
* Next to those sounds the menu has instruments to play tunes on: Chips that follow the note and hold
@@ -45,6 +50,7 @@ export type TonePreset =
| 'brass'
| 'detunedSaws'
| 'stringPad'
| 'phasedPad'
| 'organ'
| 'flute'
| 'bell'
@@ -62,6 +68,7 @@ export const TONE_PRESETS: readonly { value: TonePreset; label: string }[] = [
{ value: 'brass', label: 'Synth Brass' },
{ value: 'detunedSaws', label: 'Detuned Saws' },
{ value: 'stringPad', label: 'String Pad' },
{ value: 'phasedPad', label: 'Phased Pad' },
{ value: 'organ', label: 'Organ' },
{ value: 'flute', label: 'Flute' },
{ value: 'bell', label: 'Bell' },
@@ -112,6 +119,8 @@ interface Sfxr {
repeatSpeed: number;
arpSpeed: number;
arpMod: number;
phaOffset: number;
phaRamp: number;
}
const reset = (): Sfxr => ({
@@ -133,6 +142,8 @@ const reset = (): Sfxr => ({
repeatSpeed: 0,
arpSpeed: 0,
arpMod: 0,
phaOffset: 0,
phaRamp: 0,
});
/** sfxr's waves by their number there. */
@@ -192,6 +203,10 @@ function presetSfxr(preset: EffectPreset, random: Random): Sfxr {
if (r(2) === 0) p.repeatSpeed = 0.3 + f(0.5);
p.envSustain = 0.1 + f(0.3);
p.envDecay = f(0.5);
if (r(1)) {
p.phaOffset = -0.3 + f(0.9);
p.phaRamp = -f(0.3);
}
if (r(1)) {
p.vibStrength = f(0.7);
p.vibSpeed = f(0.6);
@@ -277,6 +292,9 @@ function randomSfxr(random: Random): Sfxr {
p.repeatSpeed = signed();
p.arpSpeed = signed();
p.arpMod = signed();
// Drawn last, not where sfxr has them, so the numbers before stay as they were.
p.phaOffset = signed() ** 3;
p.phaRamp = signed() ** 3;
return p;
}
@@ -331,6 +349,20 @@ function filterNumbers(p: Sfxr, filter: FxPassFilter): Record<'cutoff' | 'resona
return { cutoff: 17756 * Math.max(0, p.lpfFreq) ** 1.5, resonance: Math.abs(p.lpfResonance) };
}
/**
* sfxr's phaser as a Flanger: its delay is `offset²` of 1020 samples taken 8 times over, and moves
* `ramp²` of one of them every sample. Mirrored at 0 as it is, a sweep towards 0 is one with the
* other sign than the offset.
*/
function flangerNumbers(p: Sfxr): Record<'offset' | 'sweep', number> {
const taken = 8 * SFXR_RATE;
const away = Math.sign(p.phaOffset || 1) * Math.sign(p.phaRamp);
return {
offset: ((p.phaOffset ** 2 * 1020) / taken) * 1000,
sweep: (away * p.phaRamp ** 2 * SFXR_RATE * 1000) / taken,
};
}
/** A number held to its row and rounded to as many places as its step has. */
function heldTo(value: number, row: FlatDef<'number'>): number {
const places = Math.max(0, -Math.floor(Math.log10(row.step ?? 0.01)));
@@ -391,7 +423,7 @@ const everyNote: PropertyBag = { from: String(LOWEST_NOTE), to: String(HIGHEST_N
/**
* An effect preset as a whole graph (#329): every note plays one Chip, which ends by itself through
* an Envelope, a Filter and a Bitcrusher. The Chip keeps to the preset's own frequency, as sfxr does,
* an Envelope, a Filter, sfxr's phaser where it has one, and a Bitcrusher. The Chip keeps to the preset's own frequency, as sfxr does,
* so every key plays the same sound until "follow note" is turned on. Each call draws it anew.
*/
function effectGraph(preset: EffectPreset, random: Random): Graph {
@@ -406,11 +438,21 @@ function effectGraph(preset: EffectPreset, random: Random): Graph {
...held(chipNumbers(p), CHIP_ROWS),
});
s.wire(notes, 'any', chip, 'trigger');
const flanged: Step[] =
p.phaOffset !== 0 || p.phaRamp !== 0
? [
[
SoundFxFlanger.type,
held({ ...flangerNumbers(p), rate: 0, depth: 0, feedback: 0, mix: 1 }, FLANGER_ROWS),
],
]
: [];
return s.end(
s.line(
chip,
[INSTRUMENT_ENVELOPE, held(envelopeNumbers(p), ENVELOPE_ROWS)],
[SoundFxFilter.type, { filter, ...held(filterNumbers(p, filter), FILTER_ROWS) }],
...flanged,
[
SoundFxBitcrusher.type,
held({ bits: crushed ? 8 : 16, rate: crushed ? 22050 : 44100, mix: 1 }, CRUSH_ROWS),
@@ -448,6 +490,8 @@ const envelope = (attack: number, decay: number, sustain: number, release: numbe
const pass = (filter: FxPassFilter, cutoff: number, resonance = 0) =>
[SoundFxFilter.type, { filter, cutoff, resonance }] as const;
const pitch = (semitones: number) => [SoundFxPitch.type, { semitones }] as const;
const phaser = (stages: number, frequency: number, rate: number, depth: number, feedback: number) =>
[SoundFxPhaser.type, { stages: String(stages), frequency, rate, depth, feedback, mix: 1 }] as const;
const echo = (time: number, feedback: number, mix: number, pingPong = false) =>
[SoundFxDelay.type, { time, sync: 'beats', feedback, damping: 0.4, mix, pingPong }] as const;
@@ -587,6 +631,14 @@ const TONES: Record<Exclude<TonePreset, 'drumKit'>, (s: Sketch, notes: GraphNode
envelope(0.5, 0.5, 0.8, 1),
pass('lowpass', 2200, 0.1),
),
// A saw pad, slow to come, swirled by a phaser of six stages.
phasedPad: (s, notes) =>
s.line(
chipOn(s, notes, 0, 'saw', { vibratoDepth: 0.1, vibratoSpeed: 5 }),
envelope(0.3, 0.5, 0.8, 0.8),
pass('lowpass', 3000, 0.1),
phaser(6, 600, 0.3, 2.5, 0.5),
),
// A square and the square an octave up, held at full while the key is.
organ: (s, notes) => {
const low = chipOn(s, notes, 0, 'square');
@@ -661,6 +713,10 @@ function rowsOf(type: string): Record<string, FlatDef<'number'>> | null {
return FILTER_ROWS;
case SoundFxBitcrusher.type:
return CRUSH_ROWS;
case SoundFxPhaser.type:
return PHASER_ROWS;
case SoundFxFlanger.type:
return FLANGER_ROWS;
default:
return null;
}
@@ -684,15 +740,36 @@ function randomNumbers(node: GraphNode, random: Random): Record<string, number>
return held(filterNumbers(randomSfxr(random), passOf(node.params)), FILTER_ROWS);
case SoundFxBitcrusher.type:
return held({ bits: 4 + random() * 12, rate: 2000 * 24 ** random() }, CRUSH_ROWS);
case SoundFxPhaser.type:
return held(
{
frequency: 200 * 20 ** random(),
rate: 0.05 * 100 ** random(),
depth: 0.5 + random() * 3.5,
feedback: random() * 0.8,
},
PHASER_ROWS,
);
case SoundFxFlanger.type:
return held(
{
...flangerNumbers(randomSfxr(random)),
rate: 0.05 * 100 ** random(),
depth: random() * 4,
feedback: random() * 0.8,
},
FLANGER_ROWS,
);
default:
return null;
}
}
/**
* Randomize (#329): the numbers of every Chip, Envelope, Filter and Bitcrusher drawn anew, as sfxr's
* randomizer draws them. Waves, filter types, the Mix of a Bitcrusher and an Envelope's "from" and
* "to" stay, and so does everything else in the graph.
* Randomize (#329): the numbers of every Chip, Envelope, Filter, Bitcrusher, Phaser and Flanger
* (#341) drawn anew, as sfxr's randomizer draws them; a Phaser's, and a Flanger's LFO, which sfxr
* has not, within bounds of their own. Waves, filter types, the stages of a Phaser, every Mix and
* an Envelope's "from" and "to" stay, and so does everything else in the graph.
*/
export function randomizedParams(graph: Graph, random: Random = Math.random): ParamChange[] {
const changes: ParamChange[] = [];
@@ -726,6 +803,10 @@ const MUTATE: Readonly<Record<string, { octaves: number } | { by: number }>> = {
release: { by: 0.01 },
resonance: { by: 0.05 },
bits: { by: 0.5 },
offset: { by: 0.1 },
sweep: { by: 2 },
depth: { by: 0.2 },
feedback: { by: 0.05 },
};
/**
+19
View File
@@ -355,6 +355,25 @@ function bindStage(stage: FxStagePlan, bind: (amount: FxAmount) => FxAmount): Fx
if (stage.kind === 'envelope') return stage;
if (stage.kind === 'crush')
return { ...stage, bits: bind(stage.bits), rate: bind(stage.rate), mix: bind(stage.mix) };
if (stage.kind === 'phaser')
return {
...stage,
frequency: bind(stage.frequency),
rate: bind(stage.rate),
depth: bind(stage.depth),
feedback: bind(stage.feedback),
mix: bind(stage.mix),
};
if (stage.kind === 'flanger')
return {
...stage,
offset: bind(stage.offset),
sweep: bind(stage.sweep),
rate: bind(stage.rate),
depth: bind(stage.depth),
feedback: bind(stage.feedback),
mix: bind(stage.mix),
};
return {
...stage,
time: bind(stage.time),
+177 -2
View File
@@ -5,6 +5,7 @@ import type { PropertyBag } from '../model/Properties';
import { DEFAULT_TEMPO, heldTempo, secondsOfQuarters } from '../music/time';
import type { FlatDef } from '../properties/PropertySchema';
import type { ChipShape, ChipWave } from './chip';
import { PHASER_STAGES } from './phaser';
export { SOUND_FX_INPUT, SOUND_FX_OUTPUT };
@@ -25,7 +26,35 @@ export type FxStage =
| FxPass
| { kind: 'envelope'; envelope: FxEnvelope }
| FxDelay
| FxCrush;
| FxCrush
| FxPhaser
| FxFlanger;
/** A Phaser (#341): its allpass stages, where they turn, how fast and how far an LFO moves them. */
export interface FxPhaser {
kind: 'phaser';
stages: number;
frequency: number;
rate: number;
depth: number;
feedback: number;
mix: number;
frequencyMod?: FxMod;
mixMod?: FxMod;
}
/** A Flanger (#341): its delay in ms, how it sweeps and swings, all as its worklet takes them. */
export interface FxFlanger {
kind: 'flanger';
offset: number;
sweep: number;
rate: number;
depth: number;
feedback: number;
mix: number;
offsetMod?: FxMod;
mixMod?: FxMod;
}
/** A Bitcrusher (#322): bits, the rate in Hz it holds the sound at, and how much of it is heard. */
export interface FxCrush {
@@ -176,7 +205,12 @@ export type FxStagePlan =
mix: FxAmount;
pingPong: boolean;
}
| { kind: 'crush'; bits: FxAmount; rate: FxAmount; mix: FxAmount };
| { kind: 'crush'; bits: FxAmount; rate: FxAmount; mix: FxAmount }
| ({ kind: 'phaser'; stages: number } & Record<
'frequency' | 'rate' | 'depth' | 'feedback' | 'mix',
FxAmount
>)
| ({ kind: 'flanger' } & Record<'offset' | 'sweep' | 'rate' | 'depth' | 'feedback' | 'mix', FxAmount>);
/** A chain with its parameters still open: compiled once, filled in for every voice by `fxChainOf`. */
export type FxPlan =
@@ -533,6 +567,113 @@ export const SoundFxBitcrusher: SoundFxNodeDef = {
},
};
const PHASER_FREQUENCY = { ...numberRow('frequency', 'Frequency (Hz)', 20, 20000, 1), default: 800 };
const PHASER_RATE = { ...numberRow('rate', 'Rate (Hz)', 0, 10, 0.01), default: 0.5 };
const PHASER_DEPTH = { ...numberRow('depth', 'Depth (oct)', 0, 6, 0.1), default: 2 };
const PHASER_FEEDBACK = { ...numberRow('feedback', 'Feedback', 0, 0.95, 0.01), default: 0.4 };
const PHASER_MIX = { ...numberRow('mix', 'Mix', 0, 1, 0.01), default: 1 };
export const PHASER_ROWS = {
frequency: PHASER_FREQUENCY,
rate: PHASER_RATE,
depth: PHASER_DEPTH,
feedback: PHASER_FEEDBACK,
mix: PHASER_MIX,
};
const PHASER_STAGE_ROW = {
key: 'stages',
label: 'Stages',
kind: 'enum' as const,
default: '4',
options: PHASER_STAGES.map((n) => ({ value: String(n), label: String(n) })),
};
export function phaserStagesOf(settings: PropertyBag): number {
const stages = Number(settings[PHASER_STAGE_ROW.key] ?? PHASER_STAGE_ROW.default);
return PHASER_STAGES.find((n) => n === stages) ?? 4;
}
export const SoundFxPhaser: SoundFxNodeDef = {
type: 'SoundFxPhaser',
label: 'Phaser',
category: 'sound',
description:
'Sweeps notches through the sound, the swirl of a phaser pedal. "stages" is how many allpass stages the sound passes: every two make one notch, so 4 has two. They sit around "frequency" and an LFO moves them up and down, "depth" octaves wide, "rate" times a second. "feedback" sharpens the notches into a ring. "mix" 0 leaves the sound as it is, 1 is half sound and half phased, where the notches are deepest; it never gets louder. In an instrument an Envelope can move frequency and mix while a note plays.',
inputs: [
audioIn,
followingIn(PHASER_FREQUENCY),
numberIn(PHASER_RATE),
numberIn(PHASER_DEPTH),
numberIn(PHASER_FEEDBACK),
followingIn(PHASER_MIX),
],
outputs: [audioOut],
params: [PHASER_STAGE_ROW],
emit: (sounds, amounts, settings) => {
const mix = held(amounts.mix, PHASER_MIX);
if (isNone(mix)) return arriving(sounds);
return withStages(arriving(sounds), [
{
kind: 'phaser',
stages: phaserStagesOf(settings),
frequency: held(amounts.frequency, PHASER_FREQUENCY),
rate: held(amounts.rate, PHASER_RATE),
depth: held(amounts.depth, PHASER_DEPTH),
feedback: held(amounts.feedback, PHASER_FEEDBACK),
mix,
},
]);
},
};
const FLANGER_OFFSET = { ...numberRow('offset', 'Offset (ms)', 0, 10, 0.01), default: 1 };
const FLANGER_SWEEP = numberRow('sweep', 'Sweep (ms/s)', -125, 125, 0.1);
const FLANGER_RATE = { ...numberRow('rate', 'Rate (Hz)', 0, 10, 0.01), default: 0.25 };
const FLANGER_DEPTH = { ...numberRow('depth', 'Depth (ms)', 0, 10, 0.01), default: 2 };
const FLANGER_FEEDBACK = { ...numberRow('feedback', 'Feedback', 0, 0.95, 0.01), default: 0.5 };
const FLANGER_MIX = { ...numberRow('mix', 'Mix', 0, 1, 0.01), default: 1 };
export const FLANGER_ROWS = {
offset: FLANGER_OFFSET,
sweep: FLANGER_SWEEP,
rate: FLANGER_RATE,
depth: FLANGER_DEPTH,
feedback: FLANGER_FEEDBACK,
mix: FLANGER_MIX,
};
export const SoundFxFlanger: SoundFxNodeDef = {
type: 'SoundFxFlanger',
label: 'Flanger',
category: 'sound',
description:
'Blends the sound with a copy of itself a few milliseconds late, which combs out a row of frequencies: the jet sound of a flanger, and what sfxr calls its phaser. "offset" is how late the copy is when the sound starts. "sweep" moves that on by so many ms a second, for as long as the sound plays; one sweeping down passes 0 and comes back up, as in sfxr. An LFO adds up to "depth" ms to it, "rate" times a second; at depth 0 the copy only sweeps. The copy is never more than 20 ms late. "feedback" sends it back in, for a sharper, ringing comb. "mix" 0 leaves the sound as it is, 1 is half sound and half copy, where the comb is deepest; it never gets louder. In an instrument an Envelope can move offset and mix while a note plays.',
inputs: [
audioIn,
followingIn(FLANGER_OFFSET),
numberIn(FLANGER_SWEEP),
numberIn(FLANGER_RATE),
numberIn(FLANGER_DEPTH),
numberIn(FLANGER_FEEDBACK),
followingIn(FLANGER_MIX),
],
outputs: [audioOut],
params: [],
emit: (sounds, amounts) => {
const mix = held(amounts.mix, FLANGER_MIX);
if (isNone(mix)) return arriving(sounds);
return withStages(arriving(sounds), [
{
kind: 'flanger',
offset: held(amounts.offset, FLANGER_OFFSET),
sweep: held(amounts.sweep, FLANGER_SWEEP),
rate: held(amounts.rate, FLANGER_RATE),
depth: held(amounts.depth, FLANGER_DEPTH),
feedback: held(amounts.feedback, FLANGER_FEEDBACK),
mix,
},
]);
},
};
/** Where damping 0 leaves the echoes and damping 1 takes them: evenly in octaves between. */
const UNDAMPED_HZ = 20000;
const DAMPED_HZ = 500;
@@ -551,6 +692,8 @@ export const SOUND_FX_NODES: readonly SoundFxNodeDef[] = [
SoundFxMix,
SoundFxDelay,
SoundFxBitcrusher,
SoundFxPhaser,
SoundFxFlanger,
];
/** An amount with the value handed in for its parameter, held to its row; a 0 there does nothing. */
@@ -642,6 +785,38 @@ function stagesOf(plan: FxPlan, params: FxParams, tempo: number): FxStage[] {
});
continue;
}
if (stage.kind === 'phaser') {
const frequencyMod = modOf(stage.frequency, params);
const mixMod = modOf(stage.mix, params);
stages.push({
kind: 'phaser',
stages: stage.stages,
frequency: amountOf(stage.frequency, params),
rate: amountOf(stage.rate, params),
depth: amountOf(stage.depth, params),
feedback: amountOf(stage.feedback, params),
mix: amountOf(stage.mix, params),
...(frequencyMod && { frequencyMod }),
...(mixMod && { mixMod }),
});
continue;
}
if (stage.kind === 'flanger') {
const offsetMod = modOf(stage.offset, params);
const mixMod = modOf(stage.mix, params);
stages.push({
kind: 'flanger',
offset: amountOf(stage.offset, params),
sweep: amountOf(stage.sweep, params),
rate: amountOf(stage.rate, params),
depth: amountOf(stage.depth, params),
feedback: amountOf(stage.feedback, params),
mix: amountOf(stage.mix, params),
...(offsetMod && { offsetMod }),
...(mixMod && { mixMod }),
});
continue;
}
const gain = amountOf(stage.gain, params);
const mod = modOf(stage.gain, params);
if (gain !== 0 || stage.gain.param !== undefined || mod)
+138
View File
@@ -0,0 +1,138 @@
/**
* The Phaser and the Flanger (#341) sample by sample, as their worklet runs them. Both blend the
* sound with a shifted copy of itself, so some frequencies cancel: `mix` 0 leaves the sound as it
* is, 1 is half and half, where the notches are deepest and the peaks stay at full. Each number may
* be one value for the whole block or one per sample, as an AudioParam hands it over.
*/
/** How many allpass stages a Phaser can have: every two make one notch. */
export const PHASER_STAGES = [2, 4, 6, 8, 12] as const;
export type PhaserNumbers = Readonly<
Record<'frequency' | 'rate' | 'depth' | 'feedback' | 'mix', Float32Array>
>;
export type FlangerNumbers = Readonly<
Record<'offset' | 'sweep' | 'rate' | 'depth' | 'feedback' | 'mix', Float32Array>
>;
/** Feedback past this would ring on for ever. */
const MAX_FEEDBACK = 0.95;
/**
* The classic phaser: a chain of first-order allpasses, each turning the phase by 90° at a
* frequency a sine LFO moves `depth` octaves wide around `frequency`. What leaves the chain is fed
* back into it by `feedback`, a sample later, which sharpens the notches.
*/
export class Phaser {
private readonly stages: number;
private lfo = 0;
/** Per channel: the last input and output of each stage, and what left the chain. */
private inputs: Float64Array[] = [];
private outputs: Float64Array[] = [];
private last: number[] = [];
constructor(
private readonly sampleRate: number,
stages: number,
) {
this.stages = PHASER_STAGES.includes(stages as never) ? stages : 4;
}
render(input: readonly Float32Array[], output: readonly Float32Array[], numbers: PhaserNumbers): void {
const length = output[0]?.length ?? 0;
const top = this.sampleRate * 0.45;
for (let i = 0; i < length; i++) {
const sweep = Math.sin(this.lfo);
this.lfo =
(this.lfo + (2 * Math.PI * Math.max(0, at(numbers.rate, i))) / this.sampleRate) % (2 * Math.PI);
const f = Math.max(
10,
Math.min(top, at(numbers.frequency, i) * 2 ** ((at(numbers.depth, i) / 2) * sweep)),
);
const t = Math.tan((Math.PI * f) / this.sampleRate);
const a = (t - 1) / (t + 1);
const feedback = clamp(at(numbers.feedback, i), -MAX_FEEDBACK, MAX_FEEDBACK);
const share = clamp(at(numbers.mix, i), 0, 1) / 2;
output.forEach((channel, c) => {
const dry = input[c]?.[i] ?? input[0]?.[i] ?? 0;
const xs = (this.inputs[c] ??= new Float64Array(this.stages));
const ys = (this.outputs[c] ??= new Float64Array(this.stages));
let v = dry + feedback * (this.last[c] ?? 0);
for (let s = 0; s < this.stages; s++) {
const y = a * v + xs[s]! - a * ys[s]!;
xs[s] = v;
ys[s] = y;
v = y;
}
this.last[c] = v;
channel[i] = dry + (v - dry) * share;
});
}
}
}
/** The longest a Flanger delays its copy, in ms; a delay past it stays there, as sfxr's does at its own end. */
export const FLANGER_MAX_MS = 20;
/**
* The flanger, which sfxr calls its phaser: the sound and a copy `offset` ms late. `sweep` moves
* that delay on by so many ms a second from the start of the sound, and an LFO adds up to `depth` ms
* to it, `rate` times a second. As in sfxr the delay is mirrored at 0, so one sweeping down passes
* through 0 and comes back up. `feedback` sends the copy back into the line.
*/
export class Flanger {
private readonly lines: Float32Array[] = [];
private write = 0;
private lfo = 0;
/** Ms the sweep has moved the delay by so far. */
private swept = 0;
constructor(private readonly sampleRate: number) {}
private get size(): number {
return Math.ceil((FLANGER_MAX_MS / 1000) * this.sampleRate) + 2;
}
render(input: readonly Float32Array[], output: readonly Float32Array[], numbers: FlangerNumbers): void {
const length = output[0]?.length ?? 0;
const size = this.size;
const msToSamples = this.sampleRate / 1000;
for (let i = 0; i < length; i++) {
const swing = (1 - Math.cos(this.lfo)) / 2;
this.lfo =
(this.lfo + (2 * Math.PI * Math.max(0, at(numbers.rate, i))) / this.sampleRate) % (2 * Math.PI);
const offset = at(numbers.offset, i);
const ms = Math.min(
FLANGER_MAX_MS,
Math.abs(offset + this.swept) + Math.max(0, at(numbers.depth, i)) * swing,
);
// Held where it can no longer move the delay, so it never drifts off into the far numbers.
this.swept = clamp(
this.swept + at(numbers.sweep, i) / this.sampleRate,
-2 * FLANGER_MAX_MS,
2 * FLANGER_MAX_MS,
);
const delay = Math.min(size - 2, ms * msToSamples);
const whole = Math.floor(delay);
const part = delay - whole;
const feedback = clamp(at(numbers.feedback, i), 0, MAX_FEEDBACK);
const share = clamp(at(numbers.mix, i), 0, 1) / 2;
output.forEach((channel, c) => {
const dry = input[c]?.[i] ?? input[0]?.[i] ?? 0;
const line = (this.lines[c] ??= new Float32Array(size));
// Read before this sample is written, so every echo of the feedback comes `delay` later.
const near = whole === 0 ? dry : line[(this.write - whole + size) % size]!;
const far = line[(this.write - whole - 1 + size) % size]!;
const late = near + (far - near) * part;
line[this.write] = dry + feedback * late;
channel[i] = dry + (late - dry) * share;
});
this.write = (this.write + 1) % size;
}
}
}
const clamp = (value: number, low: number, high: number) =>
Math.max(low, Math.min(high, Number.isFinite(value) ? value : 0));
const at = (values: Float32Array, i: number) => (values.length > 1 ? values[i]! : values[0]!);