Refactoring round 10: split SoundLibrary, fold sound duplicates (#85)
game-maker / gate (push) Successful in 4m3s
game-maker / suite (push) Successful in 14m52s

Refactoring round 10 covers everything since round 9 (808e1ee): 110
commits with about 47 000 new lines, nearly all of them sound, sound
FX, instruments, patterns and songs. Behaviour is unchanged.

Duplicate code (jscpd over src, 50 tokens, TypeScript only, measured
on 808e1ee and here alike: 47 clones / 426 lines before, 33 / 245
after; round 9 itself ended at 22 / 160 by this count):

- PreviewParams (new, editor/soundfx) is the header's parameter bar
  of the Sound FX and the Instrument tab: values, defaults, fields
  and the voices a moved field reaches. Both tabs had it line for
  line.
- fxWorklet: an Effect base runs the bit crusher, phaser, flanger,
  limiter, LFO and bus shifter, a Source base the pitch player and
  the Chip. Start is the one wait for a voice's first sample, which
  four processors wrote out each.
- nodes/shared has checkPort, detachedPort, fxParamsPort and
  letRingPort. The Play and Stop nodes of sounds, notes, patterns and
  songs spelled each port out, up to five times.
- parameterValues builds both Sound FX parameters and Instrument
  parameters, which differed in name and text only.
- SetLoopCommand sets the ruler loop of a pattern or a song. It
  replaces SetPatternLoopCommand and SetSongLoopCommand.
- addLink in music/routing is the one rule for a link that both the
  song routing and the Master routing keep.
- eqCurves works out each band and their sum for the EQ tab, which
  did that in its drawing code. It replaces eqCurveDb, which only a
  test called.
- Smaller ones: the eight neighbour directions of a tile cell, and
  drawFloatingBox for the shadowed box of Popup and FloatWindow.
- Left on purpose: Play pattern and Play song stay two parallel node
  definitions, and the smaller clones under ten lines stay.

Architecture:

- SoundLibrary.ts goes from 2897 to 2188 lines. What a stage of a
  sound FX becomes as Web Audio nodes, and how the knobs of a playing
  voice move, is now viewport/fxNodes.ts. None of it keeps state of
  the library.

Dead code (TS language service, references per export and member):

- soundRefIds, LFO_SHAPE_INDEX, TREMOLO_ROWS, VIBRATO_ROWS and
  REVERB_ROWS had no reader. The four routing node defs are
  registered without an unused exported name.
- soundFileOf and portTypeOf were called by tests only. The tests
  now ask findSound and portOf, which the editor uses. DRY moves
  from src into the one test that uses it.
- 51 values used only in their own file lose their `export`. Types
  and the node catalogues stay exported.
- Kept on purpose: neighboursOf is the cell by cell reading the
  indexed neighboursIn is checked against, and PitchShifter.latency
  is the test's one view of how late the shifter is.

Comments and docs:

- Seven comments told history ("no longer", "any more", "as
  before", "of before #354"). Nine comment blocks ran far past the
  line width. Proof that this changed no code: the bundle was md5
  identical, and the touched tests and e2e modules were identical
  after esbuild.
- README: sound FX, instrument, pattern, song and bus in the asset
  list, the pages Instruments, Patterns and Songs, 1919 checks.
- Wiki: see its own commit.

Tests:

  Gate (melektaus-atx)    274 files, 4236 tests, CHECK EXIT 0
  e2e 34, 64, 65          ALL PASSED, 180 checks
  Unit, touched areas     16 files, 804 tests

No check was added, the e2e sum stays at 1919. Counter-checks, each
put back by copy and compared with cmp:

- addLink without the loop rule: 2 tests fail, one per routing.
- eqCurves with the sum of the last band only: 1 test fails.
- Start in the worklet never waiting: e2e 34 fails in exactly the
  four checks that hang on a voice's first sample (Flanger, Tremolo,
  Chip, a pitched note planned ahead).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-09 15:31:33 +02:00
1 parent 76f5097a38
commit 25084f8576
72 files changed
+1369 -1458

No files matched your search

+18 -8
View File
@@ -1,14 +1,14 @@
/**
* Editing the notes of a pattern (#333). As with a curve, one gesture is one command: the whole list
* is written once the pointer lets go, so an undo takes the drag back. What is written is held to the
* rules of a note first (`heldPatternNotes`).
* rules of a note first (`heldPatternNotes`). The loop of a song's ruler is set the same way (#334).
*/
import type { PatternAsset } from '../model/Asset';
import type { PatternAsset, SongAsset } from '../model/Asset';
import { heldPatternNotes, type PatternNote } from '../music/pattern';
import { heldLoop, type LoopRange } from '../music/sequence';
import type { Project } from '../model/Project';
import type { Command } from './Command';
import { requirePattern } from './require';
import { requirePattern, requireSong } from './require';
export class SetPatternNotesCommand implements Command {
private previous: PatternNote[] = [];
@@ -35,20 +35,30 @@ export class SetPatternNotesCommand implements Command {
}
}
/** Sets the loop of the ruler, or takes it away (`null`): then the whole pattern is the loop. */
export class SetPatternLoopCommand implements Command {
/**
* Sets the loop of the ruler of a pattern or a song, or takes it away (`null`): then the whole of it
* is the loop.
*/
export class SetLoopCommand implements Command {
readonly label: string;
private previous: LoopRange | undefined;
constructor(
private readonly kind: 'pattern' | 'song',
private readonly assetId: string,
private readonly loop: LoopRange | null,
) {
this.label = loop ? 'Set loop' : 'Loop the whole pattern';
this.label = loop ? 'Set loop' : `Loop the whole ${kind}`;
}
private asset(project: Project): PatternAsset | SongAsset {
return this.kind === 'pattern'
? requirePattern(project, this.assetId)
: requireSong(project, this.assetId);
}
execute(project: Project): void {
const asset = requirePattern(project, this.assetId);
const asset = this.asset(project);
this.previous = asset.loop;
const held = heldLoop(this.loop);
if (held) asset.loop = { start: Math.round(held.start), end: Math.round(held.end) };
@@ -56,7 +66,7 @@ export class SetPatternLoopCommand implements Command {
}
undo(project: Project): void {
const asset = requirePattern(project, this.assetId);
const asset = this.asset(project);
if (this.previous) asset.loop = this.previous;
else delete asset.loop;
}
-28
View File
@@ -11,7 +11,6 @@ import { settleEmbedded } from '../music/embedded';
import { routedKind, sendsTapped } from '../music/projectRouting';
import { heldSend, heldSongGraph } from '../music/routing';
import { heldSongItems, heldSongTracks, type SongItem, type SongTrack } from '../music/song';
import { heldLoop, type LoopRange } from '../music/sequence';
import { type Removed, removeWhere, restoreAt } from '../util/list';
import { type Command, CommandError } from './Command';
import { requireEdge, requireSong } from './require';
@@ -109,30 +108,3 @@ export class SetSendCommand implements Command {
else delete edge.send;
}
}
/** Sets the loop of the ruler, or takes it away (`null`): then the whole song is the loop. */
export class SetSongLoopCommand implements Command {
readonly label: string;
private previous: LoopRange | undefined;
constructor(
private readonly assetId: string,
private readonly loop: LoopRange | null,
) {
this.label = loop ? 'Set loop' : 'Loop the whole song';
}
execute(project: Project): void {
const asset = requireSong(project, this.assetId);
this.previous = asset.loop;
const held = heldLoop(this.loop);
if (held) asset.loop = { start: Math.round(held.start), end: Math.round(held.end) };
else delete asset.loop;
}
undo(project: Project): void {
const asset = requireSong(project, this.assetId);
if (this.previous) asset.loop = this.previous;
else delete asset.loop;
}
}
+4 -5
View File
@@ -22,10 +22,6 @@ export function portOf(graph: Graph, side: PortSide, lookup: GraphLookup): PortD
return list?.find((p) => p.key === side.port);
}
export function portTypeOf(graph: Graph, side: PortSide, lookup: GraphLookup): PortType | undefined {
return portOf(graph, side, lookup)?.type;
}
/** Whether a drag from `from` may land on `to`, i.e. whether ConnectCommand would accept it. */
export function canConnect(graph: Graph, from: PortSide, to: PortSide, lookup: GraphLookup): boolean {
if (from.isOutput === to.isOutput || from.nodeId === to.nodeId) return false;
@@ -37,7 +33,10 @@ export function canConnect(graph: Graph, from: PortSide, to: PortSide, lookup: G
return portsMeet(out, inp) && !linked(graph, from, to) && !closesLoop(graph, outNode, inNode, lookup);
}
/** Whether a link from `outNode` into `inNode` would lead round to where it started, between nodes that forbid that (#350). */
/**
* Whether a link from `outNode` into `inNode` would lead round to where it started, between nodes
* that forbid that (#350).
*/
export function closesLoop(graph: Graph, outNode: string, inNode: string, lookup: GraphLookup): boolean {
const acyclic = (id: string) => {
const node = findNode(graph, id);
+1 -1
View File
@@ -48,7 +48,7 @@ const PLAY_NOTE = 'PlayNote';
export const BEHAVIOR_PARAM = 'behavior';
export const FUNCTION_PARAM = 'function';
export const VARIABLES_PARAM = 'variablesAsset';
export const SOUND_FX_PARAM = 'soundFxAsset';
const SOUND_FX_PARAM = 'soundFxAsset';
/** Whose parameters a `Sound FX parameters` node sets. */
export const SOUND_FX_SETTING: PropertyDef = {
+4 -10
View File
@@ -2,7 +2,7 @@ import { MIDDLE_C } from '../../../instrument/notes';
import { heldTempo } from '../../../music/time';
import type { NodeDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString } from '../../values';
import { exec, num, playedBusPort, soundFxPort, withDefault } from '../shared';
import { detachedPort, exec, fxParamsPort, num, playedBusPort, soundFxPort, withDefault } from '../shared';
import { fxParamsOf, tempoPort } from './PlaySound';
export const PlayNote: NodeDef = {
@@ -35,17 +35,11 @@ export const PlayNote: NodeDef = {
withDefault(num('velocity'), 1),
withDefault(num('volume'), 1),
withDefault(num('duration'), 0),
{
key: 'detached',
label: 'detached',
type: 'boolean',
default: false,
field: { key: 'detached', label: 'Detached (outlives this object)', kind: 'boolean', default: false },
},
{ key: 'fxParams', label: 'params', type: 'fxparams' },
detachedPort(),
fxParamsPort('fxParams', 'params'),
tempoPort(),
{ ...soundFxPort(), key: 'soundFx' },
{ key: 'soundFxParams', label: 'fx params', type: 'fxparams' },
fxParamsPort('soundFxParams'),
playedBusPort(),
],
outputs: [exec(), num('voice')],
+13 -16
View File
@@ -1,6 +1,15 @@
import type { NodeDef, PortDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString } from '../../values';
import { exec, num, playedBusPort, soundFxPort, withDefault } from '../shared';
import {
checkPort,
detachedPort,
exec,
fxParamsPort,
num,
playedBusPort,
soundFxPort,
withDefault,
} from '../shared';
import { fxParamsOf } from './PlaySound';
export const patternPort = (): PortDef => ({
@@ -30,22 +39,10 @@ export const PlayPattern: NodeDef = {
exec(),
patternPort(),
withDefault(num('volume'), 1),
{
key: 'loop',
label: 'loop',
type: 'boolean',
default: true,
field: { key: 'loop', label: 'Loop', kind: 'boolean', default: true },
},
{
key: 'detached',
label: 'detached',
type: 'boolean',
default: false,
field: { key: 'detached', label: 'Detached (outlives this object)', kind: 'boolean', default: false },
},
checkPort('loop', 'loop', 'Loop', true),
detachedPort(),
soundFxPort(),
{ key: 'fxParams', label: 'fx params', type: 'fxparams' },
fxParamsPort(),
playedBusPort(),
],
outputs: [exec(), num('playback')],
+13 -16
View File
@@ -1,6 +1,15 @@
import type { NodeDef, PortDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString } from '../../values';
import { exec, num, playedBusPort, soundFxPort, withDefault } from '../shared';
import {
checkPort,
detachedPort,
exec,
fxParamsPort,
num,
playedBusPort,
soundFxPort,
withDefault,
} from '../shared';
import { fxParamsOf } from './PlaySound';
export const songPort = (): PortDef => ({
@@ -31,22 +40,10 @@ export const PlaySong: NodeDef = {
songPort(),
withDefault(num('volume'), 1),
withDefault(num('fadeIn', 'fade in'), 0),
{
key: 'loop',
label: 'loop',
type: 'boolean',
default: true,
field: { key: 'loop', label: 'Loop', kind: 'boolean', default: true },
},
{
key: 'detached',
label: 'detached',
type: 'boolean',
default: false,
field: { key: 'detached', label: 'Detached (outlives this object)', kind: 'boolean', default: false },
},
checkPort('loop', 'loop', 'Loop', true),
detachedPort(),
soundFxPort(),
{ key: 'fxParams', label: 'fx params', type: 'fxparams' },
fxParamsPort(),
playedBusPort(),
],
outputs: [exec(), num('playback')],
+11 -15
View File
@@ -3,7 +3,16 @@ import { DEFAULT_TEMPO, heldTempo, MAX_TEMPO, MIN_TEMPO } from '../../../music/t
import type { FxParams } from '../../../soundfx/nodes';
import type { NodeDef, PortDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString, type Value } from '../../values';
import { exec, num, playedBusPort, soundFxPort, soundPort, withDefault } from '../shared';
import {
detachedPort,
exec,
fxParamsPort,
num,
playedBusPort,
soundFxPort,
soundPort,
withDefault,
} from '../shared';
/**
* Three answers, not two: a checkbox cannot say "leave it to the asset", and without that a sound
@@ -37,19 +46,6 @@ function loopChoice(value: Value | undefined): boolean | undefined {
return undefined;
}
/**
* The way out of the ownership rule, off by default. Needed for one shape that is common enough to
* deserve it: an object that plays its own death sound and destroys itself in the same flow – the
* voice would be cut off in the instant it started, because the behavior holding it is gone.
*/
const detachedPort = (): PortDef => ({
key: 'detached',
label: 'detached',
type: 'boolean',
default: false,
field: { key: 'detached', label: 'Detached (outlives this object)', kind: 'boolean', default: false },
});
export const PlaySound: NodeDef = {
type: 'PlaySound',
label: 'Play sound',
@@ -76,7 +72,7 @@ export const PlaySound: NodeDef = {
loopPort(),
detachedPort(),
soundFxPort(),
{ key: 'fxParams', label: 'fx params', type: 'fxparams' },
fxParamsPort(),
tempoPort(),
playedBusPort(),
],
@@ -1,7 +1,7 @@
import type { NodeDef } from '../../NodeRegistry';
import { asNumber, asString } from '../../values';
import { curvesOf, easingOfParams, easingParams, idleEasing } from '../easing';
import { busPort, exec, num } from '../shared';
import { busPort, exec, fxParamsPort, num } from '../shared';
import { fxParamsOf } from './PlaySound';
import { easeShareOf } from '../../../model/animation';
@@ -25,13 +25,7 @@ export const SetSoundFxParameters: NodeDef = {
'time: seconds the values take to get there, along the chosen easing and on the clock of the ' +
'sound itself, so a sweep sounds the same every time; 0 is a quick glide. Without a voice it changes ' +
'the sound FX of "bus" instead, the master or a bus asset, for everything heard on it.',
inputs: [
exec(),
{ ...num('voice'), inline: false },
{ key: 'fxParams', label: 'fx params', type: 'fxparams' },
num('time'),
busPort('None', true),
],
inputs: [exec(), { ...num('voice'), inline: false }, fxParamsPort(), num('time'), busPort('None', true)],
outputs: [exec()],
params: easingParams(),
idleParams: idleEasing,
+2 -8
View File
@@ -1,6 +1,6 @@
import type { NodeDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString } from '../../values';
import { exec, num } from '../shared';
import { exec, letRingPort, num } from '../shared';
import { patternPort } from './PlayPattern';
export const StopPattern: NodeDef = {
@@ -18,13 +18,7 @@ export const StopPattern: NodeDef = {
patternPort(),
// Not typed in: unconnected it is null, and only then does the pattern decide.
{ ...num('playback'), inline: false },
{
key: 'letRing',
label: 'let ring',
type: 'boolean',
default: false,
field: { key: 'letRing', label: 'Let ring', kind: 'boolean', default: false },
},
letRingPort(),
],
outputs: [exec()],
params: [],
+2 -8
View File
@@ -1,6 +1,6 @@
import type { NodeDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString } from '../../values';
import { exec, num, soundPort } from '../shared';
import { exec, letRingPort, num, soundPort } from '../shared';
export const StopSound: NodeDef = {
type: 'StopSound',
@@ -18,13 +18,7 @@ export const StopSound: NodeDef = {
soundPort(),
// Not typed in: unconnected it is null, and only then does the sound decide.
{ ...num('voice'), inline: false },
{
key: 'letRing',
label: 'let ring',
type: 'boolean',
default: false,
field: { key: 'letRing', label: 'Let ring', kind: 'boolean', default: false },
},
letRingPort(),
],
outputs: [exec()],
params: [],
@@ -1,37 +1,15 @@
import type { StructValue } from '../../../model/Properties';
import { INSTRUMENT_PARAMETER_VALUES, INSTRUMENT_SETTING, soundFxSourceOf } from '../../nested';
import { INSTRUMENT_PARAMETER_VALUES, INSTRUMENT_SETTING } from '../../nested';
import type { NodeDef } from '../../NodeRegistry';
import { asNumber } from '../../values';
import { parameterValues } from './SoundFxParameters';
/**
* Values for the parameters of one instrument (#331), picked like those of a sound FX: each one picked
* is a number input starting at the instrument's default. The bundle goes into the `params` input of
* a `Play note`, or the `fx params` of a `Set sound FX parameters` that changes a playing note.
* Values for the parameters of one instrument (#331), picked like those of a sound FX. The bundle
* goes into the `params` input of a `Play note`, or the `fx params` of a `Set sound FX parameters`
* that changes a playing note.
*/
export const InstrumentParameterValues: NodeDef = {
type: INSTRUMENT_PARAMETER_VALUES,
label: 'Instrument parameters',
category: 'data',
description:
'Values for the parameters of an instrument, for the "params" input of a Play note or the "fx params" of a Set sound FX parameters. Pick the parameters to set; one not picked keeps the default its Parameters node gives it, or on a playing note the value it has.',
inputs: [],
outputs: [{ key: 'params', label: 'params', type: 'fxparams' }],
params: [INSTRUMENT_SETTING],
declaresPorts: 'inputs',
portKinds: ['number'],
declaredPort: (port, node, _graph, lookup) => {
const declared = lookup.soundFx(soundFxSourceOf(node.params))?.params.find((p) => p.key === port.key);
const value = declared?.default ?? 0;
return {
key: port.key,
label: port.key,
type: 'number',
default: value,
field: { key: port.key, label: port.key, kind: 'number', default: value },
};
},
run: (_ctx, inputs, _params, def) => {
const values: StructValue = Object.fromEntries(def.inputs.map((p) => [p.key, asNumber(inputs[p.key])]));
return { outputs: { params: values } };
},
};
export const InstrumentParameterValues: NodeDef = parameterValues(
INSTRUMENT_PARAMETER_VALUES,
'Instrument parameters',
'Values for the parameters of an instrument, for the "params" input of a Play note or the "fx params" of a Set sound FX parameters. Pick the parameters to set; one not picked keeps the default its Parameters node gives it, or on a playing note the value it has.',
INSTRUMENT_SETTING,
);
+48 -30
View File
@@ -1,37 +1,55 @@
import type { StructValue } from '../../../model/Properties';
import type { PropertyDef } from '../../../properties/PropertySchema';
import { SOUND_FX_PARAMETERS, SOUND_FX_SETTING, soundFxSourceOf } from '../../nested';
import type { NodeDef } from '../../NodeRegistry';
import { asNumber } from '../../values';
/**
* Values for the parameters of one sound FX (#311), picked from those its Input declares the way a
* Variables node picks variables. Each picked one is a number input starting at the FX's default;
* the bundle goes into the `fx params` input of a `Play sound` or a `Set sound FX parameters`.
* A node that bundles values for the parameters of one sound FX or instrument, picked from those it
* declares the way a Variables node picks variables. Each picked one is a number input starting at
* the asset's default; the bundle goes into an `fx params` or `params` input.
*/
export const SoundFxParameters: NodeDef = {
type: SOUND_FX_PARAMETERS,
label: 'Sound FX parameters',
category: 'data',
description:
'Values for the parameters of a sound FX, for the "fx params" input of a Play sound, Play note, Play pattern, Play song or a Set sound FX parameters. Pick the parameters to set; one not picked keeps the default its Input gives it, or on a playing sound the value it has.',
inputs: [],
outputs: [{ key: 'params', label: 'params', type: 'fxparams' }],
params: [SOUND_FX_SETTING],
declaresPorts: 'inputs',
portKinds: ['number'],
declaredPort: (port, node, _graph, lookup) => {
const declared = lookup.soundFx(soundFxSourceOf(node.params))?.params.find((p) => p.key === port.key);
const value = declared?.default ?? 0;
return {
key: port.key,
label: port.key,
type: 'number',
default: value,
field: { key: port.key, label: port.key, kind: 'number', default: value },
};
},
run: (_ctx, inputs, _params, def) => {
const values: StructValue = Object.fromEntries(def.inputs.map((p) => [p.key, asNumber(inputs[p.key])]));
return { outputs: { params: values } };
},
};
export function parameterValues(
type: string,
label: string,
description: string,
setting: PropertyDef,
): NodeDef {
return {
type,
label,
category: 'data',
description,
inputs: [],
outputs: [{ key: 'params', label: 'params', type: 'fxparams' }],
params: [setting],
declaresPorts: 'inputs',
portKinds: ['number'],
declaredPort: (port, node, _graph, lookup) => {
const declared = lookup.soundFx(soundFxSourceOf(node.params))?.params.find((p) => p.key === port.key);
const value = declared?.default ?? 0;
return {
key: port.key,
label: port.key,
type: 'number',
default: value,
field: { key: port.key, label: port.key, kind: 'number', default: value },
};
},
run: (_ctx, inputs, _params, def) => {
const values: StructValue = Object.fromEntries(def.inputs.map((p) => [p.key, asNumber(inputs[p.key])]));
return { outputs: { params: values } };
},
};
}
/**
* Values for the parameters of one sound FX (#311), for the `fx params` input of a `Play sound` or a
* `Set sound FX parameters`.
*/
export const SoundFxParameters: NodeDef = parameterValues(
SOUND_FX_PARAMETERS,
'Sound FX parameters',
'Values for the parameters of a sound FX, for the "fx params" input of a Play sound, Play note, Play pattern, Play song or a Set sound FX parameters. Pick the parameters to set; one not picked keeps the default its Input gives it, or on a playing sound the value it has.',
SOUND_FX_SETTING,
);
+28 -7
View File
@@ -14,6 +14,15 @@ export const any = (key: string, label = key): PortDef => ({ key, label, type: '
export const withDefault = (port: PortDef, value: PropertyValue): PortDef => ({ ...port, default: value });
/** A boolean input that shows a check box while it is not connected. */
export const checkPort = (key: string, label: string, fieldLabel: string, value = false): PortDef => ({
key,
label,
type: 'boolean',
default: value,
field: { key, label: fieldLabel, kind: 'boolean', default: value },
});
/** A whole-number input (an index, a count): its field shows no decimals, the node floors it anyway. */
export const int = (key: string, value = 0, label = key): PortDef => ({
key,
@@ -58,13 +67,7 @@ export const PER_CELL_INPUT = 'perCell';
* Which pairs a collision event hears of a map's trigger tiles (#160): off, one per area of a tile –
* a pond is entered once –, on, one per cell.
*/
export const perCellPort = (): PortDef => ({
key: PER_CELL_INPUT,
label: 'per cell',
type: 'boolean',
default: false,
field: { key: PER_CELL_INPUT, label: 'Per cell (trigger tiles)', kind: 'boolean', default: false },
});
export const perCellPort = (): PortDef => checkPort(PER_CELL_INPUT, 'per cell', 'Per cell (trigger tiles)');
/**
* The trigger tile a collider lies on (#160) and its cell in the map, which is then `other`. No
@@ -127,6 +130,24 @@ export const busPort = (none: string, master: boolean): PortDef => ({
/** The `bus` input of a Play node: empty is the bus its asset names. */
export const playedBusPort = (): PortDef => busPort('From the asset', true);
/**
* The way out of the ownership rule, off by default. Needed for one shape that is common enough to
* deserve it: an object that plays its own death sound and destroys itself in the same flow – the
* voice would be cut off in the instant it started, because the behavior holding it is gone.
*/
export const detachedPort = (): PortDef =>
checkPort('detached', 'detached', 'Detached (outlives this object)');
/** Values for the parameters of a sound FX or an instrument, bundled by their node (#311, #331). */
export const fxParamsPort = (key = 'fxParams', label = 'fx params'): PortDef => ({
key,
label,
type: 'fxparams',
});
/** Whether a Stop node lets what it stops fall away in its release instead of cutting it. */
export const letRingPort = (): PortDef => checkPort('letRing', 'let ring', 'Let ring');
export function binaryMath(type: string, description: string, fn: (a: number, b: number) => number): NodeDef {
return {
type,
+7 -3
View File
@@ -434,8 +434,9 @@ 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, 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.
* 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 {
const p = presetSfxr(preset, random);
@@ -795,7 +796,10 @@ export function randomizedParams(graph: Graph, random: Random = Math.random): Pa
return changes;
}
/** How far Mutate moves a number at most: a share of an octave where it is heard as a ratio, else a step and a tenth of it. */
/**
* How far Mutate moves a number at most: a share of an octave where it is heard as a ratio, else a
* step and a tenth of it.
*/
const MUTATE: Readonly<Record<string, { octaves: number } | { by: number }>> = {
frequency: { octaves: 0.25 },
minFrequency: { octaves: 0.25 },
+1 -1
View File
@@ -7,7 +7,7 @@ import type { FxEnvelope, FxMod } from '../soundfx/nodes';
export const SETTLE = Math.log(1000);
/** Seconds a release takes at least, so a note ending on a release of 0 does not click. */
export const SHORTEST_RELEASE = 0.01;
const SHORTEST_RELEASE = 0.01;
export function releaseTime(envelope: FxEnvelope): number {
return Math.max(SHORTEST_RELEASE, envelope.release);
+2 -2
View File
@@ -79,7 +79,7 @@ export function singleNotes(params: PropertyBag): boolean {
}
/** What a note is called on its output and in a piano roll: its own name, else its note name. */
export function noteLabel(params: PropertyBag, note: number): string {
function noteLabel(params: PropertyBag, note: number): string {
return textOf(params[noteNameKey(note)] ?? '').trim() || noteName(note);
}
@@ -120,7 +120,7 @@ const ROOT = noteRow('root', 'Root', MIDDLE_C);
const FOLLOW = { key: 'followNote', label: 'Follow note', kind: 'boolean' as const, default: true };
/** How a Sample plays while its note is held and once it is let go. */
export type SamplePlay = 'gate' | 'oneshot' | 'loop' | 'release';
export const SAMPLE_PLAYS: { value: SamplePlay; label: string }[] = [
const SAMPLE_PLAYS: { value: SamplePlay; label: string }[] = [
{ value: 'gate', label: 'Gate' },
{ value: 'oneshot', label: 'One-shot' },
{ value: 'loop', label: 'Loop' },
+2 -12
View File
@@ -10,8 +10,8 @@ export function isSoundFile(name: string): boolean {
return FILE_PATTERN.test(name);
}
export const CLIP_SEPARATOR = ' / ';
export const DEFAULT_CLIP_NAME = 'Clip';
const CLIP_SEPARATOR = ' / ';
const DEFAULT_CLIP_NAME = 'Clip';
export function clipsOf(asset: SoundAsset): readonly SoundClip[] {
return asset.clips ?? [];
@@ -58,11 +58,6 @@ export function renewClipIds(copy: Asset, ids: Map<string, string>): void {
}
}
/** Every id that means "this sound": the sound itself and each of its clips. */
export function soundRefIds(asset: SoundAsset): string[] {
return [asset.id, ...clipsOf(asset).map((c) => c.id)];
}
/** "Kick" for the sound, "Kick / Clip 1" for a clip of it. */
export function soundRefName(ref: SoundRef, soundName = ref.asset.name): string {
return ref.clip ? `${soundName}${CLIP_SEPARATOR}${ref.clip.name}` : soundName;
@@ -86,11 +81,6 @@ export function uniqueClipName(asset: SoundAsset, name: string, ignoreId = ''):
);
}
/** The file a `sound` value points at, empty when the id is unset or no longer resolves. */
export function soundFileOf(project: Project, id: string): string {
return findSound(project, id)?.asset.file ?? '';
}
/** The shape of the ramp at a cut edge (#345), from silence to full; the end runs it backwards. */
export type FadeCurve = 'linear' | 'equalPower' | 'sCurve' | 'exponential' | 'logarithmic';
+6 -10
View File
@@ -120,6 +120,11 @@ export function neighboursOf(
): Neighbours {
const same = (dx: number, dy: number): boolean =>
inGrid(props, x + dx, y + dy) && cellAt(layer, x + dx, y + dy) === tileId;
return joinedBy(same);
}
/** The eight neighbours, each joined where `same` finds the same tile that far off. */
function joinedBy(same: (dx: number, dy: number) => boolean): Neighbours {
return {
n: same(0, -1),
e: same(1, 0),
@@ -175,16 +180,7 @@ export function neighboursIn(cells: LayerCells, x: number, y: number, tileId: st
const ny = y + dy;
return nx >= 0 && ny >= 0 && nx < columns && ny < rows && at.get(ny * columns + nx) === tileId;
};
return {
n: same(0, -1),
e: same(1, 0),
s: same(0, 1),
w: same(-1, 0),
ne: same(1, -1),
se: same(1, 1),
sw: same(-1, 1),
nw: same(-1, -1),
};
return joinedBy(same);
}
/** One cell as it is drawn: where it sits, which tile it is and which quarters build it. */
+1 -1
View File
@@ -19,7 +19,7 @@ import { PATTERN_SIGN_KEY, PATTERN_TEMPO_KEY, patternInstrument } from './patter
import { type SongItem, songMeter, songTempo, type SongTrack } from './song';
import { signOf } from './time';
export const EMBEDDABLE_TYPES: readonly AssetType[] = ['sound', 'pattern', 'soundfx'];
const EMBEDDABLE_TYPES: readonly AssetType[] = ['sound', 'pattern', 'soundfx'];
/**
* The rows of an embedded asset that do nothing in a song: how it repeats is the song's. A pattern
+2 -2
View File
@@ -72,7 +72,7 @@ export function patternTempo(props: PropertyBag): number {
return heldTempo(typeof tempo === 'number' ? tempo : NaN);
}
export function patternBars(props: PropertyBag): number {
function patternBars(props: PropertyBag): number {
return wholeNumber(props[PATTERN_BARS_KEY], DEFAULT_BARS, 1, MAX_BARS);
}
@@ -116,7 +116,7 @@ export function patternSequence(asset: PatternAsset): Sequence {
}
/** Notes in the order they are played, the lower one first where two start together. */
export function byStart(a: PatternNote, b: PatternNote): number {
function byStart(a: PatternNote, b: PatternNote): number {
return a.tick - b.tick || a.note - b.note;
}
+5 -17
View File
@@ -4,7 +4,7 @@
* that comes gets a node of its own and the links most others of its type have, one that goes takes
* its node along.
*/
import { createEmptyGraph, type Graph, type GraphEdge, type GraphNode, reaches } from '../graph/Graph';
import { createEmptyGraph, type Graph, type GraphEdge, type GraphNode } from '../graph/Graph';
import { newId } from '../ids';
import type { Asset } from '../model/Asset';
import type { AssetType } from '../model/AssetTypes';
@@ -13,10 +13,10 @@ import type { Project } from '../model/Project';
import { MASTER_BUS } from '../properties/buses';
import { type Removed, removeWhere, restoreAt } from '../util/list';
import { isEmbedded } from './embedded';
import { heldSend } from './routing';
import { addLink, heldSend } from './routing';
import { ROUTED_ASSET, ROUTED_KIND, ROUTED_MASTER, ROUTED_NAME } from './routingNodes';
export const ROUTED_TYPES: readonly AssetType[] = ['sound', 'instrument', 'pattern', 'song', 'bus'];
const ROUTED_TYPES: readonly AssetType[] = ['sound', 'instrument', 'pattern', 'song', 'bus'];
/** What has its own sound FX and level on a bus of its own, and so may send from before them. */
const TAPPED_TYPES: readonly AssetType[] = ['bus', 'song'];
@@ -96,30 +96,18 @@ export function heldRouting(graph: Graph | undefined, assets: readonly Asset[],
const kinds = new Map(nodes.map((node) => [node.id, routedKind(node)]));
const takesIn = (id: string) => id === MASTER_BUS || kinds.get(id) === 'bus';
const edges: GraphEdge[] = [];
const edgeIds = new Set<string>();
const lost = new Set<string>();
for (const edge of given.edges) {
const from = edge.from.node;
const to = edge.to.node;
const kind = kinds.get(from);
if (!kind || fresh.has(from) || edge.from.port !== 'out') continue;
if (!takesIn(to) || edge.to.port !== 'in') {
if (!takesIn(edge.to.node) || edge.to.port !== 'in') {
lost.add(from);
continue;
}
if (from === to || edgeIds.has(edge.id)) continue;
if (edges.some((e) => e.from.node === from && e.to.node === to)) continue;
if (to !== MASTER_BUS && reaches({ edges }, to, from)) continue;
edgeIds.add(edge.id);
const raw = heldSend(edge.send);
const send = raw && !sendsTapped(kind) ? heldSend({ ...raw, tap: 'post' }) : raw;
edges.push({
id: edge.id,
from: { node: from, port: 'out' },
to: { node: to, port: 'in' },
...(edge.folded && { folded: true }),
...(send && { send }),
});
addLink(edges, edge, send, MASTER_BUS);
}
const linked = new Set(edges.map((e) => e.from.node));
const toMaster = (from: string): GraphEdge => ({
+23 -17
View File
@@ -27,6 +27,26 @@ export const SEND_TAPS: readonly { value: SendTap; label: string }[] = [
{ value: 'preFx', label: 'Pre volume (Pre FX)' },
];
/**
* Adds a link from out to in, as `edge` runs, to `edges` – unless it is one to itself, a second one
* under the same id or between the same two nodes, or one that closes a loop. A link into `sink`,
* which sends on to nothing, never does.
*/
export function addLink(edges: GraphEdge[], edge: GraphEdge, send: EdgeSend | undefined, sink: string): void {
const from = edge.from.node;
const to = edge.to.node;
if (from === to || edges.some((e) => e.id === edge.id || (e.from.node === from && e.to.node === to)))
return;
if (to !== sink && reaches({ edges }, to, from)) return;
edges.push({
id: edge.id,
from: { node: from, port: 'out' },
to: { node: to, port: 'in' },
...(edge.folded && { folded: true }),
...(send && { send }),
});
}
/** What a link of the routing sends: as its `send` says, else at 0 dB after volume and pan. */
export function sendOf(edge: Pick<GraphEdge, 'send'>): EdgeSend {
return edge.send ?? { volume: 0, tap: 'post' };
@@ -73,24 +93,10 @@ export function heldSongGraph(graph: Graph | undefined, tracks: readonly SongTra
const ids = new Set(trackNodes.map((n) => n.id));
const edges: GraphEdge[] = [];
const edgeIds = new Set<string>();
for (const edge of given.edges) {
const from = edge.from.node;
const to = edge.to.node;
const toOutput = to === SONG_OUTPUT_ID;
if (!ids.has(from) || edge.from.port !== 'out' || edge.to.port !== 'in') continue;
if ((!toOutput && !ids.has(to)) || from === to || edgeIds.has(edge.id)) continue;
if (edges.some((e) => e.from.node === from && e.to.node === to)) continue;
if (!toOutput && reaches({ edges }, to, from)) continue;
edgeIds.add(edge.id);
const send = heldSend(edge.send);
edges.push({
id: edge.id,
from: { node: from, port: 'out' },
to: { node: to, port: 'in' },
...(edge.folded && { folded: true }),
...(send && { send }),
});
if (!ids.has(edge.from.node) || edge.from.port !== 'out' || edge.to.port !== 'in') continue;
if (edge.to.node !== SONG_OUTPUT_ID && !ids.has(edge.to.node)) continue;
addLink(edges, edge, heldSend(edge.send), SONG_OUTPUT_ID);
}
for (const id of fresh)
edges.push({ id: newId(), from: { node: id, port: 'out' }, to: { node: SONG_OUTPUT_ID, port: 'in' } });
+4 -4
View File
@@ -10,7 +10,7 @@ export const SONG_TRACK_NAME = 'name';
const audioIn: PortDef = { key: 'in', label: 'in', type: 'audio', many: true };
const audioOut: PortDef = { key: 'out', label: 'out', type: 'audio' };
export const SongTrackNode = registerNode({
registerNode({
type: SONG_TRACK,
label: 'Track',
category: 'sound',
@@ -24,7 +24,7 @@ export const SongTrackNode = registerNode({
derivePorts: ({ node }) => ({ label: textOf(node.params[SONG_TRACK_NAME] ?? '') || 'Track' }),
});
export const SongOutputNode = registerNode({
registerNode({
type: SONG_OUTPUT,
label: 'Output',
category: 'sound',
@@ -57,7 +57,7 @@ const KIND_WORDS: Record<string, string> = {
bus: 'Bus',
};
export const RoutedAssetNode = registerNode({
registerNode({
type: ROUTED_ASSET,
label: 'Asset',
category: 'sound',
@@ -78,7 +78,7 @@ export const RoutedAssetNode = registerNode({
},
});
export const RoutedMasterNode = registerNode({
registerNode({
type: ROUTED_MASTER,
label: 'Master',
category: 'sound',
+2 -2
View File
@@ -62,9 +62,9 @@ export const SONG_GRID_KEY = 'grid';
export const DEFAULT_SONG_GRID = '1/16';
export const SONG_GRID_OPTIONS = [{ value: 'bar', label: 'Bar' }, ...GRID_OPTIONS];
/** A new song has this many tracks. */
export const DEFAULT_TRACKS = 1;
const DEFAULT_TRACKS = 1;
/** A song is never shorter than this many bars, on the ruler or when it plays. */
export const MIN_BARS = 1;
const MIN_BARS = 1;
export const TRACK_MIN_DB = -60;
export const TRACK_MAX_DB = 12;
+1 -1
View File
@@ -9,7 +9,7 @@ import { newTrack, type SongTrack } from './song';
/** What a sound may weigh on the server, less a little for the header. */
export const MAX_TAKE_BYTES = 256 * 1024 * 1024 - 1024;
export const WAV_HEADER_BYTES = 44;
const WAV_HEADER_BYTES = 44;
/** A run of samples as the input gave them, from `frame` of the audio clock on. */
export interface TakeChunk {
+1 -1
View File
@@ -29,7 +29,7 @@ export function heldMeter(meter: Meter): Meter {
}
/** The time signatures a song or a pattern is written in (#363, #364), one row for both numbers. */
export const SIGNS: readonly string[] = [
const SIGNS: readonly string[] = [
'1/2',
'2/2',
'3/2',
+1 -1
View File
@@ -13,7 +13,7 @@ export const END_KEY = 'end';
/** Milliseconds the start and the end ramp over when they lie inside the file, so they do not click (#345). */
export const FADE_IN_KEY = 'fadeIn';
export const FADE_OUT_KEY = 'fadeOut';
export const DEFAULT_FADE_MS = 5;
const DEFAULT_FADE_MS = 5;
/** The shape of each ramp. */
export const FADE_IN_CURVE_KEY = 'fadeInCurve';
export const FADE_OUT_CURVE_KEY = 'fadeOutCurve';
+1 -1
View File
@@ -59,7 +59,7 @@ export function compressorMakeup(
}
/** How far a Limiter looks ahead: a peak is met by a gain that has come down over this long. */
export const LIMITER_LOOKAHEAD = 0.005;
const LIMITER_LOOKAHEAD = 0.005;
/** Samples a Limiter holds the sound back at this rate. */
export function limiterDelay(sampleRate: number): number {
+1 -4
View File
@@ -15,9 +15,6 @@ export const LFO_SHAPES: { value: LfoShape; label: string }[] = [
{ value: 'saw', label: 'Saw' },
];
/** The four shapes by a number, as the worklet takes them. */
export const LFO_SHAPE_INDEX: Record<LfoShape, number> = { sine: 0, triangle: 1, square: 2, saw: 3 };
/** An LFO at `phase` (0 to 1, one period): -1 to 1, each shape starting at 0 or rising from it. */
export function lfoAt(shape: LfoShape, phase: number): number {
const p = phase - Math.floor(phase);
@@ -74,7 +71,7 @@ export function lfoSwing(shape: LfoShape): number {
const speedUp = (depth: number) => 2 ** (Math.max(0, depth) / 12) - 1;
/** The longest a Vibrato's delay may get, and so what its line holds. */
export const VIBRATO_MAX_DELAY = 0.5;
const VIBRATO_MAX_DELAY = 0.5;
/**
* Seconds a Vibrato holds the sound back on average: as far as its delay swings out at the rate and
+10 -20
View File
@@ -269,8 +269,6 @@ export type FxChain =
/** How a Mix shares its two sounds out: `crossfade` (left out of a plan) or `both` at the middle. */
export type MixCurve = 'crossfade' | 'both';
export const DRY: FxChain = { pitch: 0, shifted: false, stages: [] };
/**
* A number of the graph as the compiler knows it: typed in, or a parameter of the Input that a
* `Play sound` may hand a value for (#311). `value` is what it is otherwise, and a parameter is held
@@ -423,7 +421,7 @@ const BYPASS = { key: 'bypass', label: 'Bypass', kind: 'boolean' as const, defau
const WET = { ...numberRow('wet', 'Wet', 0, 1, 0.01), default: 1 };
/** Whether a node is bypassed (#354): the graph is compiled as if it were not there. */
export const isBypassed = (settings: PropertyBag): boolean => settings[BYPASS.key] === true;
const isBypassed = (settings: PropertyBag): boolean => settings[BYPASS.key] === true;
/**
* An effect with a Bypass and a Wet (#354). Bypassed, it hands on what arrives. Its Wet (`blend`)
@@ -557,7 +555,7 @@ export const SoundFxPitch: SoundFxNodeDef = effect(
);
/** The five bands of the EQ: a shelf at either end and three peaks between them. */
export const EQ_BANDS: readonly { key: string; label: string; filter: FxFilter; frequency: number }[] = [
const EQ_BANDS: readonly { key: string; label: string; filter: FxFilter; frequency: number }[] = [
{ key: 'low', label: '80 Hz', filter: 'lowshelf', frequency: 80 },
{ key: 'lowMid', label: '250 Hz', filter: 'peaking', frequency: 250 },
{ key: 'mid', label: '1 kHz', filter: 'peaking', frequency: 1000 },
@@ -848,7 +846,7 @@ const PHASER_STAGE_ROW = {
options: PHASER_STAGES.map((n) => ({ value: String(n), label: String(n) })),
};
export function phaserStagesOf(settings: PropertyBag): number {
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;
}
@@ -971,7 +969,7 @@ const COMPRESS_ATTACK = { ...numberRow('attack', 'Attack (s)', 0, 1, 0.001), def
const COMPRESS_RELEASE = { ...numberRow('release', 'Release (s)', 0, 1, 0.001), default: 0.25 };
const MAKEUP = numberRow('makeup', 'Makeup (dB)', -24, 24, 0.5);
const AUTO_GAIN = numberRow('autoGain', 'Auto-gain', 0, 1, 0.01);
export const COMPRESS_ROWS = {
const COMPRESS_ROWS = {
threshold: COMPRESS_THRESHOLD,
ratio: COMPRESS_RATIO,
knee: COMPRESS_KNEE,
@@ -1013,7 +1011,7 @@ const LIMIT_THRESHOLD = { ...numberRow('threshold', 'Threshold (dB)', -60, 0, 0.
const CEILING = { ...numberRow('ceiling', 'Ceiling (dB)', -30, 0, 0.1), default: -1 };
const LIMIT_RELEASE = { ...numberRow('release', 'Release (s)', 0.001, 2, 0.001), default: 0.1 };
const LIMIT_AUTO_GAIN = { ...AUTO_GAIN, default: 1 };
export const LIMIT_ROWS = {
const LIMIT_ROWS = {
threshold: LIMIT_THRESHOLD,
ceiling: CEILING,
release: LIMIT_RELEASE,
@@ -1050,7 +1048,7 @@ const TONE = { ...numberRow('tone', 'Tone', 0, 1, 0.01), default: 1 };
const OUTPUT = numberRow('output', 'Output (dB)', -24, 24, 0.5);
const SATURATION_AUTO_GAIN = { ...AUTO_GAIN, default: 1 };
const SATURATION_MIX = { ...numberRow('mix', 'Wet', 0, 1, 0.01), default: 1 };
export const SATURATION_ROWS = {
const SATURATION_ROWS = {
drive: DRIVE,
tone: TONE,
output: OUTPUT,
@@ -1065,7 +1063,7 @@ const SATURATION_TYPE = {
options: SATURATION_TYPES,
};
export function saturationTypeOf(settings: PropertyBag): SaturationType {
function saturationTypeOf(settings: PropertyBag): SaturationType {
return SATURATION_TYPES.find((option) => option.value === settings[SATURATION_TYPE.key])?.value ?? 'soft';
}
@@ -1107,7 +1105,7 @@ const LFO_SHAPE = {
options: LFO_SHAPES,
};
export function lfoShapeOf(settings: PropertyBag): LfoShape {
function lfoShapeOf(settings: PropertyBag): LfoShape {
return LFO_SHAPES.find((option) => option.value === settings[LFO_SHAPE.key])?.value ?? 'sine';
}
@@ -1115,8 +1113,6 @@ const TREMOLO_RATE = { ...numberRow('rate', 'Rate (Hz)', 0, 20, 0.01), default:
const TREMOLO_DEPTH = { ...numberRow('depth', 'Depth (%)', 0, 100, 1), default: 50 };
const VIBRATO_RATE = { ...numberRow('rate', 'Rate (Hz)', 0.5, 20, 0.01), default: 5 };
const VIBRATO_DEPTH = { ...numberRow('depth', 'Depth (st)', 0, 4, 0.01), default: 0.5 };
export const TREMOLO_ROWS = { rate: TREMOLO_RATE, depth: TREMOLO_DEPTH };
export const VIBRATO_ROWS = { rate: VIBRATO_RATE, depth: VIBRATO_DEPTH };
export const SoundFxTremolo: SoundFxNodeDef = effect(
{
@@ -1174,14 +1170,8 @@ const REVERB_DECAY = { ...numberRow('decay', 'Decay (s)', 0.1, REVERB_MAX_DECAY,
const REVERB_DAMPING = { ...numberRow('damping', 'Damping', 0, 1, 0.01), default: 0.4 };
const PREDELAY = { ...numberRow('predelay', 'Pre-delay (s)', 0, 0.5, 0.001), default: 0.01 };
const REVERB_MIX = { ...numberRow('mix', 'Wet', 0, 1, 0.01), default: 0.3 };
export const REVERB_ROWS = {
decay: REVERB_DECAY,
damping: REVERB_DAMPING,
predelay: PREDELAY,
mix: REVERB_MIX,
};
export function reverbRoomOf(settings: PropertyBag): ReverbRoom {
function reverbRoomOf(settings: PropertyBag): ReverbRoom {
return REVERB_ROOMS.find((option) => option.value === settings[REVERB_ROOM.key])?.value ?? 'room';
}
@@ -1269,7 +1259,7 @@ function delaySeconds(time: number, beats: boolean, tempo: number): number {
return Math.min(DELAY_MAX, beats ? secondsOfQuarters(time, heldTempo(tempo)) : time);
}
export function envelopeOf(plan: FxEnvelopePlan, params: FxParams): FxEnvelope {
function envelopeOf(plan: FxEnvelopePlan, params: FxParams): FxEnvelope {
return {
id: plan.id,
attack: amountOf(plan.attack, params),
+17 -6
View File
@@ -98,7 +98,7 @@ export const isEqBandHeard = (band: EqBand): boolean => !hasGain(band.type) || b
export const eqStagesOf = (band: EqBand): number => (hasSlope(band.type) ? band.slope / 12 : 1);
/** The nominal rate the curve is drawn at; the context's own differs only near the very top. */
export const EQ_SAMPLE_RATE = 48000;
const EQ_SAMPLE_RATE = 48000;
interface Biquad {
b0: number;
@@ -207,9 +207,20 @@ export function eqBandDb(band: EqBand, frequency: number, rate = EQ_SAMPLE_RATE)
return eqBandResponse(band, rate)(frequency);
}
/** What all bands do together at a frequency, in dB. */
export function eqCurveDb(bands: readonly EqBand[], frequency: number, rate = EQ_SAMPLE_RATE): number {
let db = 0;
for (const band of bands) if (isEqBandHeard(band)) db += eqBandDb(band, frequency, rate);
return Math.max(FLOOR_DB, db);
/**
* What each band does at every one of `frequencies`, in dB, and what the bands that are heard do
* together: the lines the EQ tab draws. Each band's coefficients are worked out once.
*/
export function eqCurves(
bands: readonly EqBand[],
frequencies: readonly number[],
rate = EQ_SAMPLE_RATE,
): { bands: number[][]; sum: number[] } {
const sum = frequencies.map(() => 0);
const each = bands.map((band) => {
const dbs = frequencies.map(eqBandResponse(band, rate));
if (isEqBandHeard(band)) dbs.forEach((db, i) => (sum[i]! += db));
return dbs;
});
return { bands: each, sum };
}
+1 -1
View File
@@ -72,7 +72,7 @@ export class Phaser {
}
/** 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;
const FLANGER_MAX_MS = 20;
/**
* The flanger, which sfxr calls its phaser: the sound and a copy `offset` ms late. `sweep` moves
+1 -1
View File
@@ -11,7 +11,7 @@ const PULL = 0.1;
const ALIGNED = 0.05;
/** Samples in a frame at an output rate: about 43 ms, a few periods of a low note. */
export function pitchFrameSize(rate: number): number {
function pitchFrameSize(rate: number): number {
return 2 ** Math.round(Math.log2(rate * 0.043));
}